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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
db6fe3a811da70c852fadd1af47c17dc239107ba | 598 | c | C | src/kernel/cpu.c | KostadinAlmishev/AnnOSTemp | 7390438faa155693ae7635ed332cbe32a778bbba | [
"MIT"
] | 5 | 2017-08-10T17:00:09.000Z | 2020-06-29T16:23:08.000Z | src/kernel/cpu.c | KostadinAlmishev/AnnOSTemp | 7390438faa155693ae7635ed332cbe32a778bbba | [
"MIT"
] | null | null | null | src/kernel/cpu.c | KostadinAlmishev/AnnOSTemp | 7390438faa155693ae7635ed332cbe32a778bbba | [
"MIT"
] | 3 | 2017-11-06T06:07:12.000Z | 2020-07-01T07:12:08.000Z | #include "kernel/cpu.h"
#include "stdlib/assert.h"
// TODO: append cpu (via spinlock)
static struct cpu_map cpu_map[CPU_MAX_CNT];
static struct cpu_context context[CPU_MAX_CNT];
cpuid_t cpu_id_by_hardware_id(hardware_cpuid_t id)
{
for (uint32_t i = 0; i < CPU_MAX_CNT; i++) {
if (cpu_map[i].real_id == id)
return i;
}
return CPU_ID_NONE;
}
cpuid_t cpu_get_id(void)
{
return 0;
}
struct cpu_context *cpu_context_by_id(cpuid_t id)
{
assert(id < CPU_MAX_CNT);
return &context[id];
}
struct cpu_context *cpu_context(void)
{
cpuid_t id = cpu_get_id();
return cpu_context_by_id(id);
}
| 17.588235 | 50 | 0.727425 |
67f809f264cc93e146ab0cedabf6bc7d107e5701 | 515 | h | C | core/LZerD/stats/align.h | tecdatalab/legacy | 9b5286d3375fff691a80ceb44172549e9a6bdee5 | [
"Apache-2.0"
] | null | null | null | core/LZerD/stats/align.h | tecdatalab/legacy | 9b5286d3375fff691a80ceb44172549e9a6bdee5 | [
"Apache-2.0"
] | 15 | 2019-06-17T16:13:39.000Z | 2022-02-27T05:23:59.000Z | db/Updater/generators/LZerD/stats/align.h | tecdatalab/biostructure | a30e907e83fa5bbfb934d951b7c663b622104fcc | [
"Apache-2.0"
] | null | null | null | // align.h
//
// prototypes for align.cc
//
// dw, 12/12/3
#include <gsl/gsl_matrix.h>
#include "pdb.h"
#include <map>
// find rigid body transformation z=Rx+t minimizing
// least squares error ||y-z||**2
// find rigid body transformation z=Rx+t minimizing
// least squares error ||y-z||**2
void align(gsl_matrix_const_view , gsl_matrix_const_view, gsl_matrix *, gsl_vector *, double *);
double align(vector<atom>&, vector<atom>&, map<int, int>&, int, vector<atom>&,
vector<atom>&, map<int, int>&, int);
| 24.52381 | 96 | 0.67767 |
9c33d36bca24972ccd50c593ae5b66507b7c638c | 598 | h | C | AWCoding/Feature/Other/Model/SkinManager.h | tospery/AWCoding | eb24c88024ec4f47782d4d11c821007ba348ed0a | [
"Apache-2.0"
] | null | null | null | AWCoding/Feature/Other/Model/SkinManager.h | tospery/AWCoding | eb24c88024ec4f47782d4d11c821007ba348ed0a | [
"Apache-2.0"
] | null | null | null | AWCoding/Feature/Other/Model/SkinManager.h | tospery/AWCoding | eb24c88024ec4f47782d4d11c821007ba348ed0a | [
"Apache-2.0"
] | null | null | null | //
// SkinManager.h
// AWCoding
//
// Created by 杨建祥 on 2018/2/27.
// Copyright © 2018年 艾维科思. All rights reserved.
//
#import "JXSkinManager.h"
#define SkinInstance ([SkinManager sharedInstance])
@interface SkinManager : JXSkinManager
- (void)configButtonStyle2:(UIButton *)button fontSize:(CGFloat)fontSize borderRadius:(CGFloat)borderRadius;
- (void)configButton:(UIButton *)button font:(UIFont *)font titleColor:(UIColor *)titleColor bgColor:(UIColor *)bgColor borderWidth:(CGFloat)borderWidth borderRadius:(CGFloat)borderRadius borderColor:(UIColor *)borderColor;
@end
| 29.9 | 223 | 0.745819 |
3b61c674d36fa57f3b860e1342eb07ea9c9f2c2f | 459 | h | C | 2 semester/AP/Labs/5/Code/Cards.h | kurpenok/Labs | 069c92b7964a1445d093313b38ebdc56318d2a73 | [
"MIT"
] | 1 | 2022-02-06T17:50:25.000Z | 2022-02-06T17:50:25.000Z | 2 semester/AP/Labs/5/Code/Cards.h | kurpenok/Labs | 069c92b7964a1445d093313b38ebdc56318d2a73 | [
"MIT"
] | null | null | null | 2 semester/AP/Labs/5/Code/Cards.h | kurpenok/Labs | 069c92b7964a1445d093313b38ebdc56318d2a73 | [
"MIT"
] | 1 | 2022-03-02T06:45:06.000Z | 2022-03-02T06:45:06.000Z | #pragma once
#include <iostream>
#include <ostream>
template<class T>
class Card {
private:
T data;
public:
Card(T&);
T getData();
friend std::ostream& operator<<(std::ostream& s, Card<T> c);
};
template<class T>
Card<T>::Card(T& data) {
this->data = data;
}
template<class T>
T Card<T>::getData() {
return data;
}
template<class T>
std::ostream& operator<<(std::ostream& s, Card<T> c) {
s << c.getData();
return s;
}
| 13.114286 | 64 | 0.601307 |
249f3a0ab181deac9260d2b20f1a34e4d61b1a19 | 173 | h | C | source/engine/script/CompilerUtils.h | dexter3k/Stranded2pp | 022df9becf9931f8437e81bb405bacf168884c8d | [
"MIT"
] | 1 | 2021-04-13T18:18:34.000Z | 2021-04-13T18:18:34.000Z | source/engine/script/CompilerUtils.h | SMemsky/Stranded2pp | 022df9becf9931f8437e81bb405bacf168884c8d | [
"MIT"
] | 2 | 2021-04-03T15:02:22.000Z | 2021-04-13T18:16:39.000Z | source/engine/script/CompilerUtils.h | SMemsky/Stranded2pp | 022df9becf9931f8437e81bb405bacf168884c8d | [
"MIT"
] | null | null | null | #pragma once
#include <list>
#include <string>
#include "Token.h"
namespace script
{
std::list<script::Token> tokenize(std::string const& source);
} // namespace script
| 14.416667 | 62 | 0.710983 |
6310090a48417534fb142aee58c4d20abb3b838c | 3,439 | h | C | include/error.h | mjaafar/dctlibrary | 700137c4de58c5a2cde44044214d23bfa96e603c | [
"MIT"
] | null | null | null | include/error.h | mjaafar/dctlibrary | 700137c4de58c5a2cde44044214d23bfa96e603c | [
"MIT"
] | null | null | null | include/error.h | mjaafar/dctlibrary | 700137c4de58c5a2cde44044214d23bfa96e603c | [
"MIT"
] | null | null | null | #ifndef _ERROR_H_
#define _ERROR_H_
/**
* \file error.h
* \brief error type
* \author mohamet.jaafar\@gmail.com
* \version 0.8
* \date first release
* \date modification mohamed.jaafar\@gmail.com 2008
*
* This file describe public error code structure and functions.
*
* ----------------------------------------
* Copyright (C) 2004 Mohamed JAAFAR
*
* 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.
*****************************************************************************/
/**
* \defgroup JPEG JPEG
* \{ */
/**
* \defgroup JPEG_CODEC JPEG_CODEC
* \{ */
/* =================================80======================================= */
/* INCLUDES */
/* =================================80======================================= */
/* =================================80======================================= */
/* DEFINES */
/* =================================80======================================= */
/** \brief ERROR read / write definition */
/** \brief ERROR_1 opening file error : file does not exist */
#define ERROR_1 (-1)
/** \brief ERROR_2 invalid file name (path) */
#define ERROR_2 (-2)
/** \brief ERROR_3 memory allocation error */
#define ERROR_3 (-3)
/** \brief ERROR_4 reading file error */
#define ERROR_4 (-4)
/** \brief ERROR_5 saving file error */
#define ERROR_5 (-5)
/** \brief ERROR_6 null pointer error */
#define ERROR_6 (-6)
/** \brief OK !!! */
#define OK (0)
#ifdef _USE_JOBS
/** \brief ERROR_7 null pointer (thread creation) error */
#define ERROR_7 (-7)
/** \brief ERROR_8 thread creation error */
#define ERROR_8 (-8)
/** \brief ERROR_9 msg queue init error */
#define ERROR_9 (-9)
/** \brief ERROR_10 msg queue error : full msg Queue */
#define ERROR_10 (-10)
#endif /*_USE_JOBS*/
/* =================================80======================================= */
/* FUNCTIONS */
/* =================================80======================================= */
// JPEG_CODEC
/** \} */
// JPEG
/** \} */
#endif // < _ERROR_H_
| 40.940476 | 80 | 0.413783 |
469e073e6da438178a08ef1cb64e9481a2583b15 | 137 | h | C | Tests/tests.h | Iskeletu/SimpleDB | 73429b63bb7c05617e2258c2bd33510044c1746c | [
"MIT"
] | 3 | 2021-12-10T03:09:01.000Z | 2021-12-27T17:24:22.000Z | Tests/tests.h | Iskeletu/SimpleDB | 73429b63bb7c05617e2258c2bd33510044c1746c | [
"MIT"
] | null | null | null | Tests/tests.h | Iskeletu/SimpleDB | 73429b63bb7c05617e2258c2bd33510044c1746c | [
"MIT"
] | null | null | null | //Header definition
#pragma once
#ifndef tests_h
#define tests_h
#define CATCH_CONFIG_MAIN
//Dependencies
#include "catch.hpp"
#endif | 11.416667 | 25 | 0.781022 |
f174540f06c238aa64d46a188e816791ebface6d | 2,070 | h | C | ITSMFT/ITS/ITSUpgradeRec/AliITSUCACell.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | ITSMFT/ITS/ITSUpgradeRec/AliITSUCACell.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | ITSMFT/ITS/ITSUpgradeRec/AliITSUCACell.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | #ifndef ALIITSUCACELL_H
#define ALIITSUCACELL_H
#include <vector>
class AliITSUCACell {
public:
AliITSUCACell(int xx = 0u,int yy = 0u, int zz = 0u, int dd0 = 0,
int dd1 = 0, float curv = 0.f, float n[3] = 0x0)
: f1OverR(curv), fd0(dd0), fd1(dd1), fN(), fVector()
{
fVector.reserve(4);
fVector.push_back(xx);
fVector.push_back(yy);
fVector.push_back(zz);
fVector.push_back(1u);
if(n) {
fN[0] = n[0];
fN[1] = n[1];
fN[2] = n[2];
}
}
int x() const { return fVector[0]; }
int y() const { return fVector[1]; }
int z() const { return fVector[2]; }
int d0() const { return fd0; }
int d1() const { return fd1; }
int GetLevel() const { return fVector[3]; }
float GetCurvature() const { return f1OverR; }
float* GetN() { return fN; }
void SetLevel(int lev) { fVector[3] = lev; }
int operator()(const int i) { return fVector[4 + i]; }
size_t NumberOfNeighbours() { return (fVector.size() - 4u); }
bool Combine(AliITSUCACell &neigh, int idd)
{
// From outside inward
if (this->y() == neigh.z() && this->x() == neigh.y()) // Cells sharing two points
{
fVector.push_back(idd);
if (neigh.GetLevel() + 1 > GetLevel())
{
SetLevel(neigh.GetLevel() + 1u);
}
return true;
}
return false;
}
private:
float f1OverR;
int fd0,fd1;
float fN[3];
std::vector<int> fVector;
};
class AliITSUCARoad {
public:
AliITSUCARoad() : Elements(), N(0)
{
ResetElements();
}
AliITSUCARoad(int layer, int idd) : Elements(), N()
{
ResetElements();
N = 1;
Elements[layer] = idd;
}
AliITSUCARoad(const AliITSUCARoad& copy) : Elements(), N(copy.N)
{
for ( int i=0; i<5; ++i )
{
Elements[i] = copy.Elements[i];
}
}
int &operator[] (const int &i) {
return Elements[i];
}
void ResetElements()
{
for ( int i=0; i<5; ++i )
Elements[i] = -1;
N = 0;
}
void AddElement(int i, int el)
{
++N;
Elements[i] = el;
}
int Elements[5];
int N;
};
#endif // ALIITSUCACELL_H
| 19.528302 | 83 | 0.567633 |
2b78f98a07edc2a283129bd2b4f61111436d1788 | 895 | h | C | HW2/common.h | tobielf/CSE530-Spring20 | 2c7309fbf28beb5f896797991b3e2de5d109ccd3 | [
"MIT"
] | null | null | null | HW2/common.h | tobielf/CSE530-Spring20 | 2c7309fbf28beb5f896797991b3e2de5d109ccd3 | [
"MIT"
] | null | null | null | HW2/common.h | tobielf/CSE530-Spring20 | 2c7309fbf28beb5f896797991b3e2de5d109ccd3 | [
"MIT"
] | null | null | null | /**
* @file common.h
* @brief shared structure definition and macro between kernel and user space
* @author Xiangyu Guo
*/
#ifndef __COMMON_H__
#define __COMMON_H__
#include <linux/ioctl.h>
typedef struct pins_setting {
int trigger_pin; /**< GPIO# of trigger pin */
int echo_pin; /**< GPIO# of echo pin */
} pins_setting_t;
typedef struct parameters_setting {
unsigned int m; /**< Number of samples */
unsigned int delta; /**< Interval of sampling */
} parameters_setting_t;
#define CONFIG_PINS _IOWR('d', 1, pins_setting_t *)
#define SET_PARAMETERS _IOW('d', 2, parameters_setting_t *)
typedef struct result_info {
unsigned long long measurement; /**< Distance measurement */
unsigned long long timestamp; /**< Time stamp (x86 TSC) */
} result_info_t;
#endif | 31.964286 | 77 | 0.626816 |
2be5cd168726dc6f51e5c4f4b9407829c89bd9f9 | 12,750 | c | C | ocrond.c | tomolt/ocron | c322cee5ce8045fef4c35ff95d11ebaf2ae95bea | [
"0BSD"
] | null | null | null | ocrond.c | tomolt/ocron | c322cee5ce8045fef4c35ff95d11ebaf2ae95bea | [
"0BSD"
] | null | null | null | ocrond.c | tomolt/ocron | c322cee5ce8045fef4c35ff95d11ebaf2ae95bea | [
"0BSD"
] | null | null | null | /* See LICENSE file for copyright and license details. */
/* Mostly Posix.1-2008 compatible, but also relies on the following extensions:
* reallocarray(3), ffsl(3), ffsll(3). */
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include "config.h"
#define VERSION "0.13"
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define VALID_HOUR(job, hour) ((job).hours >> (hour) & 1)
#define VALID_MDAY(job, mday) ((job).mdays >> (mday) & 1)
#define VALID_WDAY(job, wday) ((job).wdays >> (wday) & 1)
#define VALID_DAY(job, mday, wday) (VALID_MDAY(job, mday) || VALID_WDAY(job, wday))
#define VALID_MONTH(job, month) ((job).months >> (month) & 1)
#define VALID_DATE(job, mday, wday, month) (VALID_DAY(job, mday, wday) && VALID_MONTH(job, month))
#define JOBREACHED -2
struct Job
{
long long minutes;
time_t time;
char *command;
long hours;
long mdays;
pid_t pid;
short months;
short wdays;
short lineno;
};
static const char *no_aliases[] = { NULL };
static const char *months_aliases[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL
};
static const char *wdays_aliases[] = {
"Sun", "Mon", "Tue", "Wed",
"Thu", "Fri", "Sat", NULL
};
/* A queue containing all jobs. Implemented as a simple unordered array. */
static int capJobs;
static int numJobs;
static struct Job *jobs;
/* A pointer to the character that is currently examined
* by the crontab parser. Only used at startup. */
static char *text;
/* A pointer to the end of the line that we currently parse.
* Only used at startup. */
static char *eol;
/* General utility functions. */
/* Similar to read(2), but automatically restarts if less than count
* bytes were read or if EINTR, EAGAIN, or EWOULDBLOCK occurred. */
static int
readall(int fd, void *buf, size_t count)
{
ssize_t ret;
while (count > 0) {
ret = read(fd, buf, count);
if (ret < 0) {
if (errno != EINTR && errno != EAGAIN &&
errno != EWOULDBLOCK) return -1;
ret = 0;
}
buf += ret, count -= ret;
}
return 0;
}
/* Just like glibc's strchrnul(3), but portable.
* Essentially, it behaves just like strchr(3), but it will
* also return any NUL characters encountered along the way. */
static char *
pstrchrnul(const char *str, int ch)
{
while (*str && *str != ch) ++str;
/* Hacky, but mandated by the function signature. */
return (char *) str;
}
/* Returns 0 or 1 depending on whether year is a leap year in the Gregorian calendar or not.
* year must contain the actual year, without offset. */
static int
is_leap_year(int year)
{
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
/* Computes how many days there are in a particular month of the Gregorian calendar.
* month may be in the range 0 to 11 inclusive, and year must contain the actual year,
* without offset. */
static int
days_in_month(int month, int year)
{
return month != 1 ? 30 + ((month % 7 + 1) & 1) : 28 + is_leap_year(year);
}
/* Exit with a warning message. Should only be called during initialization! */
static void
die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsyslog(LOG_EMERG, fmt, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
static char *
read_file(const char *filename)
{
struct stat info;
char *contents;
int fd;
fd = open(filename, O_RDONLY);
if (fd < 0)
die("Can't open %s: %m", filename);
if (fstat(fd, &info) < 0)
die("Can't stat %s: %m", filename);
if ((contents = malloc(info.st_size + 1)) == NULL)
die("Out of memory.");
if (readall(fd, contents, info.st_size) < 0)
die("Can't read %s: %m", filename);
contents[info.st_size] = 0;
close(fd);
return contents;
}
/* Job time-finding algorithm. */
static void
update_job(int idx, time_t now)
{
struct tm tm;
struct Job job;
long long minutes_left;
long hours_left;
int today_alright, lookahead = 0;
job = jobs[idx];
localtime_r(&now, &tm);
tm.tm_sec = 0;
tm.tm_isdst = -1;
today_alright = VALID_DATE(job, tm.tm_mday, tm.tm_wday, tm.tm_mon);
/* Determine minute, and exit early if possible. */
assert(job.minutes != 0);
if (today_alright && VALID_HOUR(job, tm.tm_hour)) {
++tm.tm_min;
minutes_left = job.minutes & ~0ULL << tm.tm_min;
if (minutes_left != 0LL) {
tm.tm_min = ffsll(minutes_left) - 1;
goto finished;
}
}
tm.tm_min = ffsll(job.minutes) - 1;
/* Determine hour, and exit early if possible. */
assert(job.hours != 0);
if (today_alright) {
++tm.tm_hour;
hours_left = job.hours & ~0UL << tm.tm_hour;
if (hours_left != 0L) {
tm.tm_hour = ffsl(hours_left) - 1;
goto finished;
}
}
tm.tm_hour = ffsl(job.hours) - 1;
/* Determine day, month, and year. */
do {
if (++lookahead > (MAX_LOOKAHEAD)) {
syslog(LOG_WARNING, "Job '%s' exceeded the maximum lookahead and will be ignored.", job.command);
jobs[idx] = jobs[--numJobs];
return;
}
tm.tm_wday = (tm.tm_wday + 1) % 7;
if (++tm.tm_mday > days_in_month(tm.tm_mon, 1900 + tm.tm_year)) {
tm.tm_mday = 1;
if (++tm.tm_mon >= 12) {
tm.tm_mon = 0;
++tm.tm_year;
}
}
} while (!VALID_DATE(job, tm.tm_mday, tm.tm_wday, tm.tm_mon));
finished:
jobs[idx].time = mktime(&tm);
}
static int
closest_job(void)
{
int idx, next = 0;
if (!numJobs) return -1;
for (idx = 1; idx < numJobs; ++idx) {
if (jobs[idx].time < jobs[next].time)
next = idx;
}
return next;
}
/* Crontab parsing. */
static int
eat_char(char c)
{
int r;
r = *text == c;
if (r) ++text;
return r;
}
static int
skip_space(void)
{
if (!isblank(*text)) return -1;
do ++text; while (isblank(*text));
return 0;
}
static int
parse_number(int *number)
{
int num = 0;
if (!isdigit(*text)) return -1;
do {
num = num * 10 + *text++ - '0';
} while (isdigit(*text));
*number = num;
return 0;
}
static int
parse_value(const char *aliases[], int *number)
{
size_t len;
int i;
if (isdigit(*text)) {
if (parse_number(number) < 0) return -1;
return 0;
}
for (i = 0; aliases[i] != NULL; ++i) {
len = strlen(aliases[i]);
if (strncasecmp(text, aliases[i], len) == 0) {
text += len;
*number = i;
return 0;
}
}
return -1;
}
static int
parse_range(int min, int max, const char *aliases[], long long *field)
{
int first, last, step = 1, i;
if (eat_char('*')) {
if (eat_char('/')) {
if (parse_number(&step) < 0) return -1;
if (step < 1) return -1;
for (i = min; i <= max; i += step) {
*field |= 1ULL << i;
}
}
return 0;
} else {
if (parse_value(aliases, &first) < 0) return -1;
last = first;
if (eat_char('-')) {
if (parse_value(aliases, &last) < 0) return -1;
if (eat_char('/')) {
if (parse_number(&step) < 0) return -1;
}
}
if (first > last) return -1;
if (first < min) return -1;
if (last > max) return -1;
if (step < 1) return -1;
for (i = first; i <= last; i += step) {
*field |= 1ULL << i;
}
return 0;
}
}
static int
parse_field(int min, int max, const char *aliases[], long long *field)
{
*field = 0LL;
do {
if (parse_range(min, max, aliases, field) < 0) return -1;
} while (eat_char(','));
if (skip_space() < 0) return -1;
return 0;
}
static int
parse_command(char **command)
{
size_t len;
len = eol - text;
if (!len) return -1;
if ((*command = malloc(len + 1)) == NULL) {
die("Out of memory.");
}
memcpy(*command, text, len);
(*command)[len] = 0;
return 0;
}
static int
parse_line(int lineno)
{
struct Job job;
long long field;
memset(&job, 0, sizeof(job));
job.lineno = lineno;
/* We don't care if we actually find spaces here or not. */
skip_space();
/* Dismiss empty lines and comments. */
if (*text == '#') return 0;
if (!*text || *text == '\n') return 0;
if (parse_field(0, 59, no_aliases, &field) < 0) return -1;
job.minutes = field;
if (parse_field(0, 23, no_aliases, &field) < 0) return -1;
job.hours = field;
if (parse_field(1, 31, no_aliases, &field) < 0) return -1;
job.mdays = field;
if (parse_field(0, 11, months_aliases, &field) < 0) return -1;
job.months = field;
if (parse_field(0, 7, wdays_aliases, &field) < 0) return -1;
job.wdays = field;
if (parse_command(&job.command) < 0) return -1;
/* Fill in unrestricted fields. */
if (!job.minutes) job.minutes = ~0LL;
if (!job.hours) job.hours = ~0L;
if (!job.months) job.months = ~0;
job.wdays |= job.wdays >> 7 & 1;
if (!job.mdays && !job.wdays) {
job.mdays = ~0L;
}
/* Add the job to the list and we're done. */
if (numJobs >= capJobs) {
capJobs = capJobs ? 2 * capJobs : 4;
jobs = reallocarray(jobs, capJobs, sizeof(jobs[0]));
if (jobs == NULL) die("Out of memory.");
}
jobs[numJobs++] = job;
return 0;
}
static void
parse_file(const char *filename)
{
char *contents;
int lineno = 1;
contents = read_file(filename);
text = contents;
do {
eol = pstrchrnul(text, '\n');
if (parse_line(lineno) < 0) {
syslog(LOG_WARNING, "Line %d of %s will be ignored because of bad syntax.\n", lineno, filename);
}
text = eol + 1;
++lineno;
} while (*eol);
text = NULL;
free(contents);
}
static void
free_jobs(void)
{
int idx;
for (idx = 0; idx < numJobs; ++idx) {
free(jobs[idx].command);
}
free(jobs);
jobs = NULL;
numJobs = 0;
capJobs = 0;
}
/* Execute a job. */
static void
run_job(int idx)
{
pid_t pid;
/* Only execute the job if it isn't currently running. */
if (jobs[idx].pid) {
syslog(LOG_WARNING, "Job #%d won't be executed since it is still running.", jobs[idx].lineno);
return;
}
switch (pid = fork()) {
case -1:
syslog(LOG_EMERG, "Cannot start a new process: %m");
return;
case 0:
setpgid(0, 0);
execl(SHELL, SHELL, "-c", jobs[idx].command, NULL);
/* If we reach this line, execl() must have failed. */
exit(137);
default:
syslog(LOG_NOTICE, "Executing job #%d with pid %d.", jobs[idx].lineno, pid);
jobs[idx].pid = pid;
return;
}
}
/* Reap (and log) any zombie childs that have piled up since the last reap. */
static void
reap_zombies(void)
{
pid_t pid;
int status, idx;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
/* Log the return status of the child. */
if (WIFEXITED(status)) {
syslog(LOG_NOTICE, "pid %d returned with status %d.", pid, WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
syslog(LOG_WARNING, "pid %d terminated by signal %s.", pid, strsignal(WTERMSIG(status)));
} else if (WIFSTOPPED(status)) {
syslog(LOG_WARNING, "pid %d stopped by signal %s.", pid, strsignal(WSTOPSIG(status)));
} else continue;
/* Allow the returning job to be ran again.
* It's not a problem if we don't find a corresponding job. */
for (idx = 0; idx < numJobs; ++idx) {
if (jobs[idx].pid == pid) {
jobs[idx].pid = 0;
break;
}
}
}
}
int
main()
{
sigset_t signalMask;
struct timespec spec;
time_t begin;
int i, next, sig;
sigemptyset(&signalMask);
sigaddset(&signalMask, SIGCHLD);
sigaddset(&signalMask, SIGHUP);
sigaddset(&signalMask, SIGTERM);
sigaddset(&signalMask, SIGINT);
sigaddset(&signalMask, SIGQUIT);
sigprocmask(SIG_BLOCK, &signalMask, NULL);
openlog(LOGIDENT, LOG_CONS, LOG_CRON);
syslog(LOG_NOTICE, "ocron %s starting up with pid %d.", VERSION, getpid());
if (!(access(CRONTAB, F_OK) < 0)) {
parse_file(CRONTAB);
}
restart:
begin = time(NULL);
for (i = numJobs - 1; i >= 0; --i) update_job(i, begin);
next = closest_job();
for (;;) {
begin = time(NULL);
if (next < 0) {
sig = sigwaitinfo(&signalMask, NULL);
} else {
if (jobs[next].time > begin) {
spec.tv_sec = MIN(jobs[next].time - begin, (WAKEUP_PERIOD) * 60);
spec.tv_nsec = 0L;
sig = sigtimedwait(&signalMask, NULL, &spec);
} else {
sig = JOBREACHED;
}
}
switch (sig) {
case JOBREACHED:
if (begin - jobs[next].time <= (CATCHUP_LIMIT) * 60) {
run_job(next);
} else {
syslog(LOG_NOTICE, "Job #%d had to be skipped because it was too far "
"in the past. (Was the system time set forward?)", jobs[next].lineno);
}
update_job(next, time(NULL));
next = closest_job();
break;
case SIGCHLD:
reap_zombies();
break;
case SIGHUP:
syslog(LOG_NOTICE, "Reloading %s because we received a SIGHUP.", CRONTAB);
free_jobs();
if (!(access(CRONTAB, F_OK) < 0)) {
parse_file(CRONTAB);
}
goto restart;
case SIGTERM:
case SIGINT:
case SIGQUIT:
syslog(LOG_NOTICE, "Going down.");
free_jobs();
closelog();
exit(0);
case -1:
if (time(NULL) < begin) {
syslog(LOG_NOTICE, "Detected that the system time was set back. Recalculating.");
goto restart;
}
break;
default:
assert(0);
break;
}
}
}
| 21.646859 | 100 | 0.627608 |
601573094e99ac2bd396feff22874716fdaeb822 | 128 | c | C | lang/c/arm-eabi/static.c | liuyang1/test | a4560e0c9ffd0bc054d55bbcf12a894ab5b7d417 | [
"MIT"
] | 8 | 2015-06-07T13:25:48.000Z | 2022-03-22T23:14:50.000Z | lang/c/arm-eabi/static.c | liuyang1/test | a4560e0c9ffd0bc054d55bbcf12a894ab5b7d417 | [
"MIT"
] | 30 | 2016-01-29T01:36:41.000Z | 2018-09-19T07:01:22.000Z | lang/c/arm-eabi/static.c | liuyang1/test | a4560e0c9ffd0bc054d55bbcf12a894ab5b7d417 | [
"MIT"
] | null | null | null | #include <stdio.h>
static int func()
{
printf("call func\n");
return 0;
}
int main(void)
{
func();
return 0;
}
| 9.846154 | 26 | 0.546875 |
93f12753755a4ade4c4a74dc086f0631535796c8 | 851 | h | C | audiox/plug/iplug_factory.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 1 | 2017-08-11T19:12:24.000Z | 2017-08-11T19:12:24.000Z | audiox/plug/iplug_factory.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 11 | 2018-07-07T20:09:44.000Z | 2020-02-16T22:45:09.000Z | audiox/plug/iplug_factory.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | null | null | null | //------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#ifndef _SNAKEOIL_AUDIOX_API_IPLUG_FACTORY_H_
#define _SNAKEOIL_AUDIOX_API_IPLUG_FACTORY_H_
#include "iplug.h"
#include <snakeoil/audio/api/api_types.h>
#include <snakeoil/std/string/string.hpp>
namespace so_audiox
{
class SNAKEOIL_AUDIOX_API iplug_factory
{
public:
virtual so_audiox::iplug_ptr_t create_plug( so_audio::api_type const, so_audio::iapi_ptr_t,
so_audiox::iglobal_service_ptr_t, so_audiox::ilocal_service_ptr_t ) = 0 ;
virtual void_t destroy_plug( so_audiox::iplug_ptr_t ) = 0 ;
public:
virtual void_t destroy( void_t ) = 0 ;
};
so_typedef( iplug_factory ) ;
}
#endif | 27.451613 | 99 | 0.620447 |
2f26bc17433c5f336b2237aae1ecb28cb1b1647b | 9,933 | h | C | GM/VwEdtbrd.h | wsu-cb/cbwindows | 55d3797ed0c639b36fe3f677777fcc31e3449360 | [
"MIT"
] | 4 | 2020-06-22T16:59:51.000Z | 2020-06-28T19:35:23.000Z | GM/VwEdtbrd.h | wsu-cb/cbwindows | 55d3797ed0c639b36fe3f677777fcc31e3449360 | [
"MIT"
] | 59 | 2020-09-12T23:54:16.000Z | 2022-03-24T18:51:43.000Z | GM/VwEdtbrd.h | wsu-cb/cbwindows | 55d3797ed0c639b36fe3f677777fcc31e3449360 | [
"MIT"
] | 4 | 2020-06-22T13:37:40.000Z | 2021-01-29T12:42:54.000Z | // VwEdtbrd.h : interface of the CBrdEditView class
//
// Copyright (c) 1994-2020 By Dale L. Larson, 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.
//
/////////////////////////////////////////////////////////////////////////////
#ifndef _TILE_H
#include "Tile.h"
#endif
#ifndef _TOOLOBJS_H
#include "ToolObjs.h"
#endif
class CBrdEditView : public CScrollView
{
protected: // create from serialization only
CBrdEditView();
DECLARE_DYNCREATE(CBrdEditView)
void GetCellDrawBounds(CRect &oRct, CRect &oLim);
void FillMapCells(CDC* pDC, CRect &oLim);
void FrameMapCells(CDC* pDC, CRect &oLim);
CBoard* m_pBoard; // Pointer to document's board
CBoardManager* m_pBMgr;
// --------------- //
BOOL m_bOffScreen;
TileScale m_nZoom;
// --------------- //
UINT m_nCurToolID; // Current tool ID
UINT m_nLastToolID; // Previous tool ID
// Attributes
public:
CGamDoc* GetDocument();
TileScale GetCurrentScale() { return m_nZoom; }
CBoard* GetBoard() { return m_pBoard; }
// Current Colors etc...
COLORREF GetForeColor() { return m_pBMgr->GetForeColor(); }
COLORREF GetBackColor() { return m_pBMgr->GetBackColor(); }
UINT GetLineWidth() { return m_pBMgr->GetLineWidth(); }
void SetForeColor(COLORREF crFore) { m_pBMgr->SetForeColor(crFore); }
void SetBackColor(COLORREF crBack) { m_pBMgr->SetBackColor(crBack); }
// Operations
public:
void SetCellTile(TileID tid, CPoint pnt, BOOL bUpdate);
void SetCellColor(COLORREF crCell, CPoint pnt, BOOL bUpdate);
void SetBoardBackColor(COLORREF cr, BOOL bUpdate);
void SetDrawingTile(CDrawList* pDwg, TileID tid, CPoint pnt, BOOL bUpdate);
void DoCreateTextDrawingObject(CPoint point);
void DoEditTextDrawingObject(CText* pDObj);
void RestoreLastTool() { m_nCurToolID = m_nLastToolID; }
void ResetToDefaultTool();
virtual void OnPrepareDC(CDC* pDC, CPrintInfo* pInfo);
void PrepareScaledDC(CDC *pDC);
// Tools and Selection support
public:
CSelList m_selList; // List of selected objects.
CSelList* GetSelectList() { return &m_selList; }
void ClientToWorkspace(CPoint& point) const;
void ClientToWorkspace(CRect& rect) const;
void WorkspaceToClient(CPoint& point) const;
void WorkspaceToClient(CRect& rect) const;
void InvalidateWorkspaceRect(const CRect* pRect, BOOL bErase = FALSE);
CPoint GetWorkspaceDim();
void OnPrepareScaledDC(CDC *pDC);
void AdjustPoint(CPoint& pnt); // Limit and grid processing
void AdjustRect(CRect& rct);
CDrawObj* ObjectHitTest(CPoint point);
void AddDrawObject(CDrawObj::OwnerPtr pObj); // Add to active layer
void DeleteDrawObject(CDrawObj* pObj); // Delete from active layer
void SelectWithinRect(CRect rctNet, BOOL bInclIntersects = FALSE);
void SelectAllUnderPoint(CPoint point);
// --- Misc Draw object manipulations
void DeleteObjsInSelectList(BOOL bInvalidate = TRUE);
void MoveObjsInSelectList(BOOL bToFront, BOOL bInvalidate = TRUE);
void NudgeObjsInSelectList(int dX, int dY, BOOL forceScroll = FALSE); //DFM19991014
CDrawList* GetDrawList(BOOL bCanCreateList = TRUE);
// Implementation
protected:
// Grid and limiting support
BOOL IsGridizeActive();
void GridizeX(long& xPos);
void GridizeY(long& yPos);
void LimitPoint(POINT* pPnt);
void LimitRect(RECT* pRct);
void PixelToWorkspace(CPoint& point);
void CreateTextDrawingObject(CPoint pnt, FontID fid, COLORREF crText,
CString& m_strText, BOOL bInvalidate = TRUE);
void DoViewScale(TileScale nZoom);
void CenterViewOnWorkspacePoint(CPoint point);
BOOL DoMouseWheelFix(UINT fFlags, short zDelta, CPoint point);
public:
virtual ~CBrdEditView();
virtual void OnDraw(CDC* pDC); // overridden to draw this view
void SetupPalette(CDC *pDC);
void ResetPalette(CDC *pDC);
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual void OnInitialUpdate();
virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint);
// Printing support
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
// ------------ //
ToolType MapToolType(UINT nToolResID);
// Nudge and scroll functions
void HandleKeyDown ();
void HandleKeyUp ();
void HandleKeyLeft ();
void HandleKeyRight ();
void HandleKeyPageUp ();
void HandleKeyPageDown ();
void HandleKeyTop ();
void HandleKeyBottom ();
void ScrollDown();
void ScrollUp();
void ScrollLeft();
void ScrollRight();
void NudgeScrollDown();
void NudgeScrollUp();
void NudgeScrollLeft();
void NudgeScrollRight();
void NudgeDown();
void NudgeUp();
void NudgeLeft();
void NudgeRight();
void NudgescrollLeft();
void FastScrollDown();
void FastScrollUp();
void FastScrollLeft();
void FastScrollRight();
void FastNudgeScrollDown();
void FastNudgeScrollUp();
void FastNudgeScrollLeft();
void FastNudgeScrollRight();
void FastNudgeDown();
void FastNudgeUp();
void FastNudgeLeft();
void FastNudgeRight();
void FastNudgescrollLeft();
void PageDown();
void PageUp();
void PageLeft();
void PageRight();
void PageTop();
void PageBottom();
void PageFarLeft();
void PageFarRight();
// Generated message map functions
protected:
//{{AFX_MSG(CBrdEditView)
afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg LRESULT OnDragTileItem(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnSetColor(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnSetCustomColors(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnSetLineWidth(WPARAM wParam, LPARAM lParam);
afx_msg void OnOffscreen();
afx_msg void OnViewGridLines();
afx_msg void OnDwgToBack();
afx_msg void OnDwgToFront();
afx_msg BOOL OnToolPalette(UINT id);
afx_msg BOOL OnEditLayer(UINT id);
afx_msg void OnUpdateViewGridLines(CCmdUI* pCmdUI);
afx_msg void OnUpdateOffscreen(CCmdUI* pCmdUI);
afx_msg void OnUpdateEditLayer(CCmdUI* pCmdUI);
afx_msg void OnUpdateColorForeground(CCmdUI* pCmdUI);
afx_msg void OnUpdateColorBackground(CCmdUI* pCmdUI);
afx_msg void OnUpdateColorCustom(CCmdUI* pCmdUI);
afx_msg void OnUpdateLineWidth(CCmdUI* pCmdUI);
afx_msg void OnUpdateToolPalette(CCmdUI* pCmdUI);
afx_msg void OnUpdateDwgToFrontOrBack(CCmdUI* pCmdUI);
afx_msg void OnUpdateViewFullScale(CCmdUI* pCmdUI);
afx_msg void OnUpdateViewHalfScale(CCmdUI* pCmdUI);
afx_msg void OnDwgFont();
afx_msg void OnViewFullScale();
afx_msg void OnViewHalfScale();
afx_msg void OnViewSmallScale();
afx_msg void OnUpdateViewSmallScale(CCmdUI* pCmdUI);
afx_msg void OnUpdateIndicatorCellNum(CCmdUI* pCmdUI);
afx_msg void OnToolsBrdSnapGrid();
afx_msg void OnUpdateToolsBrdSnapGrid(CCmdUI* pCmdUI);
afx_msg void OnToolsBrdProps();
afx_msg void OnToolSetVisibleScale();
afx_msg void OnUpdateToolSetVisibleScale(CCmdUI* pCmdUI);
afx_msg void OnToolSuspendScaleVisibility();
afx_msg void OnUpdateToolSuspendScaleVsibility(CCmdUI* pCmdUI);
afx_msg void OnEditPaste();
afx_msg void OnUpdateEditPaste(CCmdUI* pCmdUI);
afx_msg void OnEditPasteBitmapFromFile();
afx_msg void OnUpdateEditPasteBitmapFromFile(CCmdUI* pCmdUI);
afx_msg void OnEditClear();
afx_msg void OnUpdateEditClear(CCmdUI* pCmdUI);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
afx_msg void OnEditCopy();
afx_msg void OnUpdateEditCopy(CCmdUI* pCmdUI);
afx_msg void OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnDwgDrawAboveGrid();
afx_msg void OnUpdateDwgDrawAboveGrid(CCmdUI* pCmdUI);
afx_msg void OnViewToggleScale();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in gmview.cpp
inline CGamDoc* CBrdEditView::GetDocument()
{ return (CGamDoc*) m_pDocument; }
#endif
| 37.342105 | 87 | 0.710963 |
9254fd11c6be90cba3d0391343ac7e718e2a157f | 865 | h | C | Slimetasia/ParticlePass.h | JasonWyx/Slimetasia | 5f69deb68da740d326c8514b881583f1e608e5d5 | [
"MIT"
] | null | null | null | Slimetasia/ParticlePass.h | JasonWyx/Slimetasia | 5f69deb68da740d326c8514b881583f1e608e5d5 | [
"MIT"
] | null | null | null | Slimetasia/ParticlePass.h | JasonWyx/Slimetasia | 5f69deb68da740d326c8514b881583f1e608e5d5 | [
"MIT"
] | null | null | null | #pragma once
#include <future>
#include "Camera.h"
class ParticlePass
{
public:
ParticlePass();
~ParticlePass();
void Render(Camera& camera);
void StartSortingParticleData(Camera& camera);
private:
GLuint m_VertexArray;
GLuint m_PositionBuffer;
GLuint m_ColorBuffer;
GLuint m_SizeBuffer;
GLuint m_FadeBuffer;
HShader m_ParticleBillboardShader;
HShader m_ParticleStencilShader;
std::future<void> m_DataSorted;
std::map<std::pair<GLuint, GLuint>, std::vector<Vector4>> m_SortedPositionData;
std::map<std::pair<GLuint, GLuint>, std::vector<Vector4>> m_SortedColorData;
std::map<std::pair<GLuint, GLuint>, std::vector<float>> m_SortedSizeData;
std::map<std::pair<GLuint, GLuint>, std::vector<float>> m_SortedFadeData;
static void SortParticleData(ParticlePass& particlePass, Camera& camera);
}; | 27.03125 | 83 | 0.724855 |
4f4cb04b57bfbd72a7ccbcdbb7daac21677c794b | 4,331 | c | C | uxmhf-rpi3/uapps/uapp-watchdog/uapp-watchdog.c | superymk/uberxmhf | 3cd28bfe565221a6073950de4a8da9b61e10614e | [
"RSA-MD"
] | 8 | 2020-03-19T18:49:02.000Z | 2022-03-19T22:00:30.000Z | uxmhf-rpi3/uapps/uapp-watchdog/uapp-watchdog.c | sirmammingtonham/uberxmhf | 84b17f1c107e38eed096cd21b264b3e4eb5b1c6e | [
"RSA-MD"
] | 3 | 2020-08-06T16:38:19.000Z | 2020-11-13T15:24:50.000Z | uxmhf-rpi3/uapps/uapp-watchdog/uapp-watchdog.c | sirmammingtonham/uberxmhf | 84b17f1c107e38eed096cd21b264b3e4eb5b1c6e | [
"RSA-MD"
] | 8 | 2020-02-21T15:06:54.000Z | 2021-03-30T14:56:24.000Z | /*
* @UBERXMHF_LICENSE_HEADER_START@
*
* uber eXtensible Micro-Hypervisor Framework (Raspberry Pi)
*
* Copyright 2018 Carnegie Mellon University. All Rights Reserved.
*
* NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING
* INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON
* UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
* AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR
* PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF
* THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF
* ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT
* INFRINGEMENT.
*
* Released under a BSD (SEI)-style license, please see LICENSE or
* contact permission@sei.cmu.edu for full terms.
*
* [DISTRIBUTION STATEMENT A] This material has been approved for public
* release and unlimited distribution. Please see Copyright notice for
* non-US Government use and distribution.
*
* Carnegie Mellon is registered in the U.S. Patent and Trademark Office by
* Carnegie Mellon University.
*
* @UBERXMHF_LICENSE_HEADER_END@
*/
/*
* Author: Amit Vasudevan (amitvasudevan@acm.org)
*
*/
/*
watchdog hypapp
author: amit vasudevan (amitvasudevan@acm.org)
*/
#include <types.h>
#include <arm8-32.h>
#include <bcm2837.h>
#include <uart.h>
#include <debug.h>
extern void uapp_watchdog_fiq_handler(void);
__attribute__((section(".data"))) volatile u32 *gpio;
bool led_on=false;
#define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
#define OUT_GPIO(g) *(gpio+((g)/10)) |= (1<<(((g)%10)*3))
#define GPIO_SET *(gpio+7) // sets bits which are 1 ignores bits which are 0
#define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
//////
// uapp watchdog timer_initialize
// initialize hypervisor timer functionality
//////
void uapp_watchdog_timer_initialize(u32 cpuid){
u32 cpsr;
u64 cntpct_val;
u32 cpu0_tintctl_value;
u32 loop_counter=0;
_XDPRINTFSMP_("%s[%u]: ENTER\n", __func__, cpuid);
//enable cpu0 timer interrupt control to generate FIQs
cpu0_tintctl_value = mmio_read32(LOCAL_TIMER_INT_CONTROL0);
_XDPRINTFSMP_("%s[%u]: cpu0_tintctl_value[before]=0x%08x, CNTHPFIQ=%u, CNTHPIRQ=%u\n",
__func__, cpuid,
cpu0_tintctl_value,
((cpu0_tintctl_value & (1UL << 6)) >> 6),
((cpu0_tintctl_value & (1UL << 2)) >> 2)
);
cpu0_tintctl_value &= ~(1UL << 2); //disable IRQs
cpu0_tintctl_value |= (1UL << 6); //enable FIQs
mmio_write32(LOCAL_TIMER_INT_CONTROL0, cpu0_tintctl_value);
cpu0_tintctl_value = mmio_read32(LOCAL_TIMER_INT_CONTROL0);
_XDPRINTFSMP_("%s[%u]: cpu0_tintctl_value[after]=0x%08x, CNTHPFIQ=%u, CNTHPIRQ=%u\n",
__func__, cpuid,
cpu0_tintctl_value,
((cpu0_tintctl_value & (1UL << 6)) >> 6),
((cpu0_tintctl_value & (1UL << 2)) >> 2)
);
//cpsr = sysreg_read_cpsr();
//_XDPRINTFSMP_("%s[%u]: CPSR[before]=0x%08x; CPSR.A=%u, CPSR.I=%u, CPSR.F=%u\n",
// __func__, cpuid, cpsr, ((cpsr & (1UL << 8)) >> 8),
// ((cpsr & (1UL << 7)) >> 7),
// ((cpsr & (1UL << 6)) >> 6) );
_XDPRINTFSMP_("%s[%u]: CNTHP_TVAL[initial]=%d\n", __func__, cpuid, sysreg_read_cnthp_tval());
sysreg_write_cnthp_tval(10*1024*1024);
_XDPRINTFSMP_("%s[%u]: CNTHP_TVAL[reset]=%d\n", __func__, cpuid, sysreg_read_cnthp_tval());
sysreg_write_cnthp_ctl(0x1);
_XDPRINTFSMP_("%s[%u]: CNTHP_TVAL[current]=%d\n", __func__, cpuid, sysreg_read_cnthp_tval());
_XDPRINTFSMP_("%s[%u]: CNTHP_CTL[current]=%d\n", __func__, cpuid, sysreg_read_cnthp_ctl());
//cpsr &= ~(1UL << 6); //clear CPSR.F to allow FIQs
//sysreg_write_cpsr(cpsr);
_XDPRINTFSMP_("%s[%u]: EXIT\n", __func__, cpuid);
}
void uapp_watchdog_fiqhandler(void){
uapp_watchdog_timerhandler();
//reset timer counter
sysreg_write_cnthp_tval(10*1024*1024);
}
void uapp_watchdog_timerhandler(void){
gpio = (u32 *)GPIO_BASE;
// set GPIO pin 7 as output
INP_GPIO(7); // must use INP_GPIO before we can use OUT_GPIO
OUT_GPIO(7);
if(led_on){
GPIO_CLR = (1 << 7);
led_on=false;
}else{
GPIO_SET = (1 << 7);
led_on=true;
}
//uart_puts("WATCHDOG EXCEPTION-- Resuming\n");
}
void uapp_watchdog_initialize(u32 cpuid){
if(cpuid == 0){
hypvtable_setentry(cpuid, 7, (u32)&uapp_watchdog_fiq_handler);
uapp_watchdog_timer_initialize(cpuid);
}
}
| 28.493421 | 94 | 0.70284 |
a205a5b91d751e461e96fbe2b5c99ee610678c66 | 256 | h | C | src/tritonsort/tests/themis_core/ThreadSafeQueueTest.h | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | 11 | 2015-12-14T05:35:17.000Z | 2021-11-08T22:02:32.000Z | src/tritonsort/tests/themis_core/ThreadSafeQueueTest.h | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | null | null | null | src/tritonsort/tests/themis_core/ThreadSafeQueueTest.h | anku94/themis_tritonsort | 68fd3e2f1c0b2947e187151a2e9717f6b9b0ed0d | [
"BSD-3-Clause"
] | 8 | 2015-12-22T19:31:16.000Z | 2020-12-15T12:09:00.000Z | #ifndef _TRITONSORT_THREADSAFEQUEUETEST_H
#define _TRITONSORT_THREADSAFEQUEUETEST_H
#include "third-party/googletest.h"
class ThreadSafeQueueTest : public ::testing::Test {
void SetUp();
void TearDown();
};
#endif //_TRITONSORT_THREADSAFEQUEUETEST_H
| 23.272727 | 52 | 0.804688 |
9af99e78d4fbeb32e6272109f30bb0eec29a8452 | 602 | h | C | src/txlookup.h | gandrewstone/bitcoin | 05de381c02eb4bfca94957733acadfa217527f25 | [
"MIT"
] | 535 | 2015-09-04T15:10:08.000Z | 2022-03-17T20:51:05.000Z | src/txlookup.h | gandrewstone/bitcoin | 05de381c02eb4bfca94957733acadfa217527f25 | [
"MIT"
] | 1,269 | 2016-01-31T20:21:24.000Z | 2022-03-16T01:20:08.000Z | src/txlookup.h | gandrewstone/bitcoin | 05de381c02eb4bfca94957733acadfa217527f25 | [
"MIT"
] | 295 | 2015-10-19T16:12:29.000Z | 2021-08-02T20:05:17.000Z | // Copyright (c) 2019-2020 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_TXLOOKUP_H
#include <cstdint>
static const int64_t TX_NOT_FOUND = -1;
class CBlock;
class uint256;
/// Finds the position of a transaction in a block.
/// \param ctor Optimized lookup if it's known that block has CTOR ordering
/// \return position in block, or negative value on error
int64_t FindTxPosition(const CBlock &block, const uint256 &txhash, bool ctor_optimized);
#endif
| 30.1 | 88 | 0.772425 |
b12b0c60e5f205d52338dd34480b8bac591beb9e | 561 | h | C | Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDEInterfaceBuilderKit/IBShadowBox.h | wokalski/Distraction-Free-Xcode-plugin | 54ab4b9d9825e8370855b7985d6ff39d64c19f25 | [
"MIT"
] | 25 | 2016-03-03T07:43:56.000Z | 2021-09-05T08:47:40.000Z | Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDEInterfaceBuilderKit/IBShadowBox.h | wokalski/Distraction-Free-Xcode-plugin | 54ab4b9d9825e8370855b7985d6ff39d64c19f25 | [
"MIT"
] | 8 | 2016-02-23T18:40:20.000Z | 2016-08-18T13:21:05.000Z | Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDEInterfaceBuilderKit/IBShadowBox.h | wokalski/Distraction-Free-Xcode-plugin | 54ab4b9d9825e8370855b7985d6ff39d64c19f25 | [
"MIT"
] | 4 | 2016-02-24T13:24:27.000Z | 2016-06-28T12:50:36.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSView.h"
@class NSShadow;
@interface IBShadowBox : NSView
{
NSShadow *shadow;
unsigned long long shadowedEdges;
}
@property(nonatomic) unsigned long long shadowedEdges; // @synthesize shadowedEdges;
- (void).cxx_destruct;
- (void)drawRect:(struct CGRect)arg1;
- (id)hitTest:(struct CGPoint)arg1;
@property(copy) NSShadow *shadow; // @synthesize shadow;
- (id)initWithFrame:(struct CGRect)arg1;
@end
| 21.576923 | 84 | 0.7041 |
7f304b394e5f3ce84c7182398ceca511ad7393bb | 2,710 | h | C | src/extra/seeno.h | DavidGriffith/uninvited | 2484b76c7d17e3304e9e5c94574d5f81bbfc7ec9 | [
"ClArtistic"
] | 9 | 2015-05-27T06:24:10.000Z | 2022-02-18T22:57:01.000Z | src/extra/seeno.h | whitten/uninvited | 2484b76c7d17e3304e9e5c94574d5f81bbfc7ec9 | [
"ClArtistic"
] | 1 | 2015-05-27T02:51:58.000Z | 2015-05-27T06:15:25.000Z | src/extra/seeno.h | whitten/uninvited | 2484b76c7d17e3304e9e5c94574d5f81bbfc7ec9 | [
"ClArtistic"
] | 2 | 2016-05-22T15:44:17.000Z | 2019-12-02T17:36:43.000Z | ! seeno.h for Inform 6 with library 6/10
!
! A library to change the standard Inform message "You can't see any such thing." to
! the more specific "You see no xxx yyy here." Note that this can repeat
! typing errors back to the player.
!
! Written by C Knight.
! Comments and bug reports welcomed: please see www.metebelis3.free-online.co.uk to email.
!
! Based on dunno.h (I don't know the word "kludge")
! version 1.1 - 2 Apr 2001 by Neil Cerutti (cerutti@together.net)
!
! To use this file, put the command
!
! Include "seeno.h";
!
! in your program's source code after including "parser".
!
! If you have defined your own ParserError() routine, you might instead call CantSeeError()
! routine in a LibraryMessages object (Inform Designer's Manual, 4th ed., section 25):
!
! Object LibraryMessages with before [;
! Miscellany: if (lm_n == 30) return CantSeeError();
! ];
!
! Version history 1.0 - 16 May 2003
! Version history 1.1 - 22 Sep 2003. Fixed TAKE ALL FROM X problem.
! Can override these constants by defining them before including the file:
Default SEENO_MSG1 "You see no "; ! or "You see nothing that can be described as ~"
Default SEENO_MSG2 " here.";
#ifdef ParserError;
#message "Warning: To use cantsee.h, call it from ParserError or LibraryMessages.";
#ifnot;
[ ParserError pe;
if (pe == CANTSEE_PE) return CantSeeError();
rfalse;
];
#endif;
[ CantSeeError wordnum word nwords stop pos end;
wordnum=saved_oops;
#ifdef TARGET_GLULX;
nwords=parse-->0;
#ifnot;
nwords=parse->1; ! end of line
#endif;
if (wordnum > 0)
{
#ifdef TARGET_GLULX;
word=parse-->(wordnum*3-2);
#ifnot;
word=parse-->(wordnum*2-1);
#endif;
! this most likely the result of TAKE ALL FROM X, in which case use the default message
if (word && (word->#dict_par1 & $80) ~= $80) rfalse;
print (string) SEENO_MSG1;
do { ! print at least one word, more if the noun phrase needs it
pos=WordAddress(wordnum); end = WordLength(wordnum) + pos;
for (: pos<end: pos++) ! print each character of word.
print (char) pos->0;
wordnum++;
if (wordnum > nwords) stop=1; ! end of line
else {
#ifdef TARGET_GLULX;
word=parse-->(wordnum*3-2);
#ifnot;
word=parse-->(wordnum*2-1);
#endif;
if (word) { ! recognised
if (word->#dict_par1 & $88 ~= $80) stop=1; ! not noun, or poss prep
if (word == AND1__WD or ',//' or './/'
or BUT1__WD or BUT2__WD) ! conjunction
stop=1;
}
} ! not end of line
if (~~stop) print " ";
} until (stop);
print_ret (string) SEENO_MSG2;
}
else rfalse;
];
! end seeno.h
| 30.795455 | 91 | 0.638007 |
3d1d91292847592e88f0e541e4d17aa697216f62 | 1,913 | h | C | include/linux/tc_act/tc_gact.h | gubaojian/headers | cafb2e3ea031be211e7f444a372cb3a6b4ed10b5 | [
"MIT"
] | null | null | null | include/linux/tc_act/tc_gact.h | gubaojian/headers | cafb2e3ea031be211e7f444a372cb3a6b4ed10b5 | [
"MIT"
] | null | null | null | include/linux/tc_act/tc_gact.h | gubaojian/headers | cafb2e3ea031be211e7f444a372cb3a6b4ed10b5 | [
"MIT"
] | null | null | null | /****************************************************************************
****************************************************************************
***
*** This header was automatically generated from a Linux kernel header
*** of the same name, to make information necessary for userspace to
*** call into the kernel available to libc. It contains only constants,
*** structures, and macros generated from the original header, and thus,
*** contains no copyrightable information.
***
*** To edit the content of this header, modify the corresponding
*** source file (e.g. under external/kernel-headers/original/) then
*** run bionic/libc/kernel/tools/update_all.py
***
*** Any manual change here will be lost the next time this script will
*** be run. You've been warned!
***
****************************************************************************
****************************************************************************/
#ifndef __LINUX_TC_GACT_H
#define __LINUX_TC_GACT_H
#include <linux/types.h>
#include <linux/pkt_cls.h>
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define TCA_ACT_GACT 5
struct tc_gact {
tc_gen;
};
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
struct tc_gact_p {
#define PGACT_NONE 0
#define PGACT_NETRAND 1
#define PGACT_DETERM 2
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define MAX_RAND (PGACT_DETERM + 1)
__u16 ptype;
__u16 pval;
int paction;
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
};
enum {
TCA_GACT_UNSPEC,
TCA_GACT_TM,
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
TCA_GACT_PARMS,
TCA_GACT_PROB,
TCA_GACT_PAD,
__TCA_GACT_MAX
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
};
#define TCA_GACT_MAX (__TCA_GACT_MAX - 1)
#endif
| 36.788462 | 78 | 0.605855 |
d246687f36e8de2e02fa2931caf5eef70159c26b | 244 | h | C | cmall/cmall/Products/NNProductListViewController.h | ddpisces33/cmall | 8c09dbc25663978a6452546f3b67ed8aea82a1de | [
"MIT"
] | null | null | null | cmall/cmall/Products/NNProductListViewController.h | ddpisces33/cmall | 8c09dbc25663978a6452546f3b67ed8aea82a1de | [
"MIT"
] | null | null | null | cmall/cmall/Products/NNProductListViewController.h | ddpisces33/cmall | 8c09dbc25663978a6452546f3b67ed8aea82a1de | [
"MIT"
] | null | null | null | //
// NNProductListViewController.h
// cmall
//
// Created by ddpisces on 15/8/6.
// Copyright (c) 2015年 NAONAO. All rights reserved.
//
#import "NNBaseViewController.h"
@interface NNProductListViewController : NNBaseViewController
@end
| 17.428571 | 61 | 0.737705 |
3233dc306e7e1ef2206e2a3410cf77f12934f8f4 | 9,947 | h | C | qemu_mode/qemu-2.10.0/roms/u-boot/arch/arm/include/asm/arch-rockchip/grf_rk3368.h | braymar/afl | a6b2dad6bbd9c9401814e088582bc04a074651eb | [
"Apache-2.0"
] | 1 | 2019-10-13T11:32:01.000Z | 2019-10-13T11:32:01.000Z | qemu_mode/qemu-2.10.0/roms/u-boot/arch/arm/include/asm/arch-rockchip/grf_rk3368.h | braymar/afl | a6b2dad6bbd9c9401814e088582bc04a074651eb | [
"Apache-2.0"
] | null | null | null | qemu_mode/qemu-2.10.0/roms/u-boot/arch/arm/include/asm/arch-rockchip/grf_rk3368.h | braymar/afl | a6b2dad6bbd9c9401814e088582bc04a074651eb | [
"Apache-2.0"
] | 1 | 2021-08-14T12:14:44.000Z | 2021-08-14T12:14:44.000Z | /* (C) Copyright 2016 Rockchip Electronics Co., Ltd
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef _ASM_ARCH_GRF_RK3368_H
#define _ASM_ARCH_GRF_RK3368_H
#include <common.h>
struct rk3368_grf {
u32 gpio1a_iomux;
u32 gpio1b_iomux;
u32 gpio1c_iomux;
u32 gpio1d_iomux;
u32 gpio2a_iomux;
u32 gpio2b_iomux;
u32 gpio2c_iomux;
u32 gpio2d_iomux;
u32 gpio3a_iomux;
u32 gpio3b_iomux;
u32 gpio3c_iomux;
u32 gpio3d_iomux;
u32 reserved[0x34];
u32 gpio1a_pull;
u32 gpio1b_pull;
u32 gpio1c_pull;
u32 gpio1d_pull;
u32 gpio2a_pull;
u32 gpio2b_pull;
u32 gpio2c_pull;
u32 gpio2d_pull;
u32 gpio3a_pull;
u32 gpio3b_pull;
u32 gpio3c_pull;
u32 gpio3d_pull;
u32 reserved1[0x34];
u32 gpio1a_drv;
u32 gpio1b_drv;
u32 gpio1c_drv;
u32 gpio1d_drv;
u32 gpio2a_drv;
u32 gpio2b_drv;
u32 gpio2c_drv;
u32 gpio2d_drv;
u32 gpio3a_drv;
u32 gpio3b_drv;
u32 gpio3c_drv;
u32 gpio3d_drv;
u32 reserved2[0x34];
u32 gpio1l_sr;
u32 gpio1h_sr;
u32 gpio2l_sr;
u32 gpio2h_sr;
u32 gpio3l_sr;
u32 gpio3h_sr;
u32 reserved3[0x1a];
u32 gpio_smt;
u32 reserved4[0x1f];
u32 soc_con0;
u32 soc_con1;
u32 soc_con2;
u32 soc_con3;
u32 soc_con4;
u32 soc_con5;
u32 soc_con6;
u32 soc_con7;
u32 soc_con8;
u32 soc_con9;
u32 soc_con10;
u32 soc_con11;
u32 soc_con12;
u32 soc_con13;
u32 soc_con14;
u32 soc_con15;
u32 soc_con16;
u32 soc_con17;
};
check_member(rk3368_grf, soc_con17, 0x444);
struct rk3368_pmu_grf {
u32 gpio0a_iomux;
u32 gpio0b_iomux;
u32 gpio0c_iomux;
u32 gpio0d_iomux;
u32 gpio0a_pull;
u32 gpio0b_pull;
u32 gpio0c_pull;
u32 gpio0d_pull;
u32 gpio0a_drv;
u32 gpio0b_drv;
u32 gpio0c_drv;
u32 gpio0d_drv;
u32 gpio0l_sr;
u32 gpio0h_sr;
};
check_member(rk3368_pmu_grf, gpio0h_sr, 0x34);
/*GRF_GPIO0C_IOMUX*/
enum {
GPIO0C7_SHIFT = 14,
GPIO0C7_MASK = 3 << GPIO0C7_SHIFT,
GPIO0C7_GPIO = 0,
GPIO0C7_LCDC_D19,
GPIO0C7_TRACE_D9,
GPIO0C7_UART1_RTSN,
GPIO0C6_SHIFT = 12,
GPIO0C6_MASK = 3 << GPIO0C6_SHIFT,
GPIO0C6_GPIO = 0,
GPIO0C6_LCDC_D18,
GPIO0C6_TRACE_D8,
GPIO0C6_UART1_CTSN,
GPIO0C5_SHIFT = 10,
GPIO0C5_MASK = 3 << GPIO0C5_SHIFT,
GPIO0C5_GPIO = 0,
GPIO0C5_LCDC_D17,
GPIO0C5_TRACE_D7,
GPIO0C5_UART1_SOUT,
GPIO0C4_SHIFT = 8,
GPIO0C4_MASK = 3 << GPIO0C4_SHIFT,
GPIO0C4_GPIO = 0,
GPIO0C4_LCDC_D16,
GPIO0C4_TRACE_D6,
GPIO0C4_UART1_SIN,
GPIO0C3_SHIFT = 6,
GPIO0C3_MASK = 3 << GPIO0C3_SHIFT,
GPIO0C3_GPIO = 0,
GPIO0C3_LCDC_D15,
GPIO0C3_TRACE_D5,
GPIO0C3_MCU_JTAG_TDO,
GPIO0C2_SHIFT = 4,
GPIO0C2_MASK = 3 << GPIO0C2_SHIFT,
GPIO0C2_GPIO = 0,
GPIO0C2_LCDC_D14,
GPIO0C2_TRACE_D4,
GPIO0C2_MCU_JTAG_TDI,
GPIO0C1_SHIFT = 2,
GPIO0C1_MASK = 3 << GPIO0C1_SHIFT,
GPIO0C1_GPIO = 0,
GPIO0C1_LCDC_D13,
GPIO0C1_TRACE_D3,
GPIO0C1_MCU_JTAG_TRTSN,
GPIO0C0_SHIFT = 0,
GPIO0C0_MASK = 3 << GPIO0C0_SHIFT,
GPIO0C0_GPIO = 0,
GPIO0C0_LCDC_D12,
GPIO0C0_TRACE_D2,
GPIO0C0_MCU_JTAG_TDO,
};
/*GRF_GPIO0D_IOMUX*/
enum {
GPIO0D7_SHIFT = 14,
GPIO0D7_MASK = 3 << GPIO0D7_SHIFT,
GPIO0D7_GPIO = 0,
GPIO0D7_LCDC_DCLK,
GPIO0D7_TRACE_CTL,
GPIO0D7_PMU_DEBUG5,
GPIO0D6_SHIFT = 12,
GPIO0D6_MASK = 3 << GPIO0D6_SHIFT,
GPIO0D6_GPIO = 0,
GPIO0D6_LCDC_DEN,
GPIO0D6_TRACE_CLK,
GPIO0D6_PMU_DEBUG4,
GPIO0D5_SHIFT = 10,
GPIO0D5_MASK = 3 << GPIO0D5_SHIFT,
GPIO0D5_GPIO = 0,
GPIO0D5_LCDC_VSYNC,
GPIO0D5_TRACE_D15,
GPIO0D5_PMU_DEBUG3,
GPIO0D4_SHIFT = 8,
GPIO0D4_MASK = 3 << GPIO0D4_SHIFT,
GPIO0D4_GPIO = 0,
GPIO0D4_LCDC_HSYNC,
GPIO0D4_TRACE_D14,
GPIO0D4_PMU_DEBUG2,
GPIO0D3_SHIFT = 6,
GPIO0D3_MASK = 3 << GPIO0D3_SHIFT,
GPIO0D3_GPIO = 0,
GPIO0D3_LCDC_D23,
GPIO0D3_TRACE_D13,
GPIO0D3_UART4_SIN,
GPIO0D2_SHIFT = 4,
GPIO0D2_MASK = 3 << GPIO0D2_SHIFT,
GPIO0D2_GPIO = 0,
GPIO0D2_LCDC_D22,
GPIO0D2_TRACE_D12,
GPIO0D2_UART4_SOUT,
GPIO0D1_SHIFT = 2,
GPIO0D1_MASK = 3 << GPIO0D1_SHIFT,
GPIO0D1_GPIO = 0,
GPIO0D1_LCDC_D21,
GPIO0D1_TRACE_D11,
GPIO0D1_UART4_RTSN,
GPIO0D0_SHIFT = 0,
GPIO0D0_MASK = 3 << GPIO0D0_SHIFT,
GPIO0D0_GPIO = 0,
GPIO0D0_LCDC_D20,
GPIO0D0_TRACE_D10,
GPIO0D0_UART4_CTSN,
};
/*GRF_GPIO2A_IOMUX*/
enum {
GPIO2A7_SHIFT = 14,
GPIO2A7_MASK = 3 << GPIO2A7_SHIFT,
GPIO2A7_GPIO = 0,
GPIO2A7_SDMMC0_D2,
GPIO2A7_JTAG_TCK,
GPIO2A6_SHIFT = 12,
GPIO2A6_MASK = 3 << GPIO2A6_SHIFT,
GPIO2A6_GPIO = 0,
GPIO2A6_SDMMC0_D1,
GPIO2A6_UART2_SIN,
GPIO2A5_SHIFT = 10,
GPIO2A5_MASK = 3 << GPIO2A5_SHIFT,
GPIO2A5_GPIO = 0,
GPIO2A5_SDMMC0_D0,
GPIO2A5_UART2_SOUT,
GPIO2A4_SHIFT = 8,
GPIO2A4_MASK = 3 << GPIO2A4_SHIFT,
GPIO2A4_GPIO = 0,
GPIO2A4_FLASH_DQS,
GPIO2A4_EMMC_CLKO,
GPIO2A3_SHIFT = 6,
GPIO2A3_MASK = 3 << GPIO2A3_SHIFT,
GPIO2A3_GPIO = 0,
GPIO2A3_FLASH_CSN3,
GPIO2A3_EMMC_RSTNO,
GPIO2A2_SHIFT = 4,
GPIO2A2_MASK = 3 << GPIO2A2_SHIFT,
GPIO2A2_GPIO = 0,
GPIO2A2_FLASH_CSN2,
GPIO2A1_SHIFT = 2,
GPIO2A1_MASK = 3 << GPIO2A1_SHIFT,
GPIO2A1_GPIO = 0,
GPIO2A1_FLASH_CSN1,
GPIO2A0_SHIFT = 0,
GPIO2A0_MASK = 3 << GPIO2A0_SHIFT,
GPIO2A0_GPIO = 0,
GPIO2A0_FLASH_CSN0,
};
/*GRF_GPIO2D_IOMUX*/
enum {
GPIO2D7_SHIFT = 14,
GPIO2D7_MASK = 3 << GPIO2D7_SHIFT,
GPIO2D7_GPIO = 0,
GPIO2D7_SDIO0_D3,
GPIO2D6_SHIFT = 12,
GPIO2D6_MASK = 3 << GPIO2D6_SHIFT,
GPIO2D6_GPIO = 0,
GPIO2D6_SDIO0_D2,
GPIO2D5_SHIFT = 10,
GPIO2D5_MASK = 3 << GPIO2D5_SHIFT,
GPIO2D5_GPIO = 0,
GPIO2D5_SDIO0_D1,
GPIO2D4_SHIFT = 8,
GPIO2D4_MASK = 3 << GPIO2D4_SHIFT,
GPIO2D4_GPIO = 0,
GPIO2D4_SDIO0_D0,
GPIO2D3_SHIFT = 6,
GPIO2D3_MASK = 3 << GPIO2D3_SHIFT,
GPIO2D3_GPIO = 0,
GPIO2D3_UART0_RTS0,
GPIO2D2_SHIFT = 4,
GPIO2D2_MASK = 3 << GPIO2D2_SHIFT,
GPIO2D2_GPIO = 0,
GPIO2D2_UART0_CTS0,
GPIO2D1_SHIFT = 2,
GPIO2D1_MASK = 3 << GPIO2D1_SHIFT,
GPIO2D1_GPIO = 0,
GPIO2D1_UART0_SOUT,
GPIO2D0_SHIFT = 0,
GPIO2D0_MASK = 3 << GPIO2D0_SHIFT,
GPIO2D0_GPIO = 0,
GPIO2D0_UART0_SIN,
};
/*GRF_GPIO3C_IOMUX*/
enum {
GPIO3C7_SHIFT = 14,
GPIO3C7_MASK = 3 << GPIO3C7_SHIFT,
GPIO3C7_GPIO = 0,
GPIO3C7_EDPHDMI_CECINOUT,
GPIO3C7_ISP_FLASHTRIGIN,
GPIO3C6_SHIFT = 12,
GPIO3C6_MASK = 3 << GPIO3C6_SHIFT,
GPIO3C6_GPIO = 0,
GPIO3C6_MAC_CLK,
GPIO3C6_ISP_SHUTTERTRIG,
GPIO3C5_SHIFT = 10,
GPIO3C5_MASK = 3 << GPIO3C5_SHIFT,
GPIO3C5_GPIO = 0,
GPIO3C5_MAC_RXER,
GPIO3C5_ISP_PRELIGHTTRIG,
GPIO3C4_SHIFT = 8,
GPIO3C4_MASK = 3 << GPIO3C4_SHIFT,
GPIO3C4_GPIO = 0,
GPIO3C4_MAC_RXDV,
GPIO3C4_ISP_FLASHTRIGOUT,
GPIO3C3_SHIFT = 6,
GPIO3C3_MASK = 3 << GPIO3C3_SHIFT,
GPIO3C3_GPIO = 0,
GPIO3C3_MAC_RXDV,
GPIO3C3_EMMC_RSTNO,
GPIO3C2_SHIFT = 4,
GPIO3C2_MASK = 3 << GPIO3C2_SHIFT,
GPIO3C2_MAC_MDC = 0,
GPIO3C2_ISP_SHUTTEREN,
GPIO3C1_SHIFT = 2,
GPIO3C1_MASK = 3 << GPIO3C1_SHIFT,
GPIO3C1_GPIO = 0,
GPIO3C1_MAC_RXD2,
GPIO3C1_UART3_RTSN,
GPIO3C0_SHIFT = 0,
GPIO3C0_MASK = 3 << GPIO3C0_SHIFT,
GPIO3C0_GPIO = 0,
GPIO3C0_MAC_RXD1,
GPIO3C0_UART3_CTSN,
GPIO3C0_GPS_RFCLK,
};
/*GRF_GPIO3D_IOMUX*/
enum {
GPIO3D7_SHIFT = 14,
GPIO3D7_MASK = 3 << GPIO3D7_SHIFT,
GPIO3D7_GPIO = 0,
GPIO3D7_SC_VCC18V,
GPIO3D7_I2C2_SDA,
GPIO3D7_GPUJTAG_TCK,
GPIO3D6_SHIFT = 12,
GPIO3D6_MASK = 3 << GPIO3D6_SHIFT,
GPIO3D6_GPIO = 0,
GPIO3D6_IR_TX,
GPIO3D6_UART3_SOUT,
GPIO3D6_PWM3,
GPIO3D5_SHIFT = 10,
GPIO3D5_MASK = 3 << GPIO3D5_SHIFT,
GPIO3D5_GPIO = 0,
GPIO3D5_IR_RX,
GPIO3D5_UART3_SIN,
GPIO3D4_SHIFT = 8,
GPIO3D4_MASK = 3 << GPIO3D4_SHIFT,
GPIO3D4_GPIO = 0,
GPIO3D4_MAC_TXCLKOUT,
GPIO3D4_SPI1_CSN1,
GPIO3D3_SHIFT = 6,
GPIO3D3_MASK = 3 << GPIO3D3_SHIFT,
GPIO3D3_GPIO = 0,
GPIO3D3_HDMII2C_SCL,
GPIO3D3_I2C5_SCL,
GPIO3D2_SHIFT = 4,
GPIO3D2_MASK = 3 << GPIO3D2_SHIFT,
GPIO3D2_GPIO = 0,
GPIO3D2_HDMII2C_SDA,
GPIO3D2_I2C5_SDA,
GPIO3D1_SHIFT = 2,
GPIO3D1_MASK = 3 << GPIO3D1_SHIFT,
GPIO3D1_GPIO = 0,
GPIO3D1_MAC_RXCLKIN,
GPIO3D1_I2C4_SCL,
GPIO3D0_SHIFT = 0,
GPIO3D0_MASK = 3 << GPIO3D0_SHIFT,
GPIO3D0_GPIO = 0,
GPIO3D0_MAC_MDIO,
GPIO3D0_I2C4_SDA,
};
/*GRF_SOC_CON11/12/13*/
enum {
MCU_SRAM_BASE_BIT27_BIT12_SHIFT = 0,
MCU_SRAM_BASE_BIT27_BIT12_MASK = GENMASK(15, 0),
};
/*GRF_SOC_CON12*/
enum {
MCU_EXSRAM_BASE_BIT27_BIT12_SHIFT = 0,
MCU_EXSRAM_BASE_BIT27_BIT12_MASK = GENMASK(15, 0),
};
/*GRF_SOC_CON13*/
enum {
MCU_EXPERI_BASE_BIT27_BIT12_SHIFT = 0,
MCU_EXPERI_BASE_BIT27_BIT12_MASK = GENMASK(15, 0),
};
/*GRF_SOC_CON14*/
enum {
MCU_EXPERI_BASE_BIT31_BIT28_SHIFT = 12,
MCU_EXPERI_BASE_BIT31_BIT28_MASK = GENMASK(15, 12),
MCU_EXSRAM_BASE_BIT31_BIT28_SHIFT = 8,
MCU_EXSRAM_BASE_BIT31_BIT28_MASK = GENMASK(11, 8),
MCU_SRAM_BASE_BIT31_BIT28_SHIFT = 4,
MCU_SRAM_BASE_BIT31_BIT28_MASK = GENMASK(7, 4),
MCU_CODE_BASE_BIT31_BIT28_SHIFT = 0,
MCU_CODE_BASE_BIT31_BIT28_MASK = GENMASK(3, 0),
};
#endif
| 22.555556 | 53 | 0.641098 |
9ab459b41b2164c9bf38b063edf96e28644751e1 | 1,270 | h | C | Pods/Headers/Public/SmartDeviceLink-iOS/SDLPerformInteractionResponse.h | amarenthe/mobile_weather_sdl | aa8115ab3719804f956fb26a3ca705968519570f | [
"BSD-3-Clause"
] | null | null | null | Pods/Headers/Public/SmartDeviceLink-iOS/SDLPerformInteractionResponse.h | amarenthe/mobile_weather_sdl | aa8115ab3719804f956fb26a3ca705968519570f | [
"BSD-3-Clause"
] | null | null | null | Pods/Headers/Public/SmartDeviceLink-iOS/SDLPerformInteractionResponse.h | amarenthe/mobile_weather_sdl | aa8115ab3719804f956fb26a3ca705968519570f | [
"BSD-3-Clause"
] | null | null | null | // SDLPerformInteractionResponse.h
//
#import "SDLRPCResponse.h"
@class SDLTriggerSource;
/**
* PerformInteraction Response is sent, when SDLPerformInteraction has been called
*
* @since SDL 1.0
*/
@interface SDLPerformInteractionResponse : SDLRPCResponse {
}
/**
* @abstract Constructs a new SDLPerformInteractionResponse object
*/
- (instancetype)init;
/**
* @abstract Constructs a new SDLPerformInteractionResponse object indicated by the dictionary parameter
* @param dict The dictionary to use
*/
- (instancetype)initWithDictionary:(NSMutableDictionary *)dict;
/**
* @abstract ID of the choice that was selected in response to PerformInteraction.
*
* @discussion Only is valid if general result is "success:true".
*
* Optional, Integer, 0 - 2,000,000,000
*/
@property (strong) NSNumber *choiceID;
/**
* @abstract Manually entered text selection, e.g. through keyboard
*
* @discussion Can be returned in lieu of choiceID, depending on trigger source
*
* Optional, Max length 500 chars
*/
@property (strong) NSString *manualTextEntry;
/**
* @abstract A *SDLTriggerSource* object which will be shown in the HMI
*
* @discussion Only is valid if resultCode is SUCCESS.
*/
@property (strong) SDLTriggerSource *triggerSource;
@end
| 22.678571 | 104 | 0.73937 |
36f170eb59da847a0f864720449e7bb107afd0cd | 5,936 | h | C | chrome/test/reliability/automated_ui_test_base.h | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 7 | 2015-05-20T22:41:35.000Z | 2021-11-18T19:07:59.000Z | chrome/test/reliability/automated_ui_test_base.h | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 1 | 2015-02-02T06:55:08.000Z | 2016-01-20T06:11:59.000Z | chrome/test/reliability/automated_ui_test_base.h | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 2 | 2015-12-08T00:37:41.000Z | 2017-04-06T05:34:05.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_TEST_RELIABILITY_AUTOMATED_UI_TEST_BASE_H_
#define CHROME_TEST_RELIABILITY_AUTOMATED_UI_TEST_BASE_H_
#include <string>
#include "chrome/test/ui/ui_test.h"
class WindowProxy;
class AutomatedUITestBase : public UITest {
protected:
AutomatedUITestBase();
virtual ~AutomatedUITestBase();
virtual void SetUp() OVERRIDE;
virtual void LogErrorMessage(const std::string &error);
virtual void LogWarningMessage(const std::string &warning);
virtual void LogInfoMessage(const std::string &info);
// Actions
// NOTE: This list is sorted alphabetically.
// All functions are synchronous unless specified with Async.
// Go back in active tab.
// Returns true if successful, false otherwise.
bool BackButton();
// Close the selected tab in the current browser window. The function will
// not try close the tab if it is the only tab of the last normal window, so
// the application is not got closed.
// Returns true if the tab is closed, false otherwise.
bool CloseActiveTab();
// Close the current browser window if it is not the only window left.
// (Closing the last window will get application closed.)
// Returns true if the window is closed, false otherwise.
bool CloseActiveWindow();
// Duplicates the current tab.
// Returns true if a duplicated tab is added.
bool DuplicateTab();
// Drags the active tab. The tab is dragged vertically to remove it from the
// tabstrip. Returns true if the tab is dragged, false otherwise.
// Note: returning true doesn't necessarily create a new window as the tab
// could be dragged in to another window.
bool DragTabOut();
// Drags the active tab.
// If |drag_right| is true, if there is a tab to the right of the active tab,
// the active tab is dragged to that tabs position. If |drag_right| is false,
// if there is a tab to the left of the active tab, the active tab is dragged
// to that tabs position. Returns true if the tab is dragged. If it returns
// false, the tab is not dragged, probably because no other tab exists to
// drag the active tab over.
bool DragActiveTab(bool drag_right);
// Activates "find in page" on the current page. Returns true on success.
bool FindInPage();
// Go forward in active tab.
// Returns true if successful, false otherwise.
bool ForwardButton();
// Opens an OffTheRecord browser window.
bool GoOffTheRecord();
// Navigates to the Home page.
// Returns true if call to activate the accelerator is successful.
bool Home();
// Navigates the activate tab to given url.
bool Navigate(const GURL& url);
// Opens a new tab in the active window using an accelerator.
// Returns true if a new tab is successfully opened.
bool NewTab();
// Opens a new browser window by calling automation()->OpenNewBrowserWindow.
// Then activates the tab opened in the new window.
// Returns true if window is successfully created.
// If optional parameter previous_browser is passed in, it is set to be the
// previous browser window when new window is successfully created, and the
// caller owns previous_browser.
bool OpenAndActivateNewBrowserWindow(
scoped_refptr<BrowserProxy>* previous_browser);
// Reload the active tab.
// Returns true if successful, false otherwise.
bool ReloadPage();
// Restores a previously closed tab.
// Returns true if the tab is successfully restored.
bool RestoreTab();
// Activates the next tab on the active browser window.
// Returns true on success.
bool SelectNextTab();
// Activates the previous tab on the active browser window.
// Returns true on success.
bool SelectPreviousTab();
// Displays the bookmark bar.
// Returns true on success.
bool ShowBookmarkBar();
// Opens the Downloads page in the current active browser window.
// Returns true on success.
bool ShowDownloads();
// Opens the History page in the current active browser window.
// Returns true on success.
bool ShowHistory();
// Runs the specified browser command in the current active browser.
// See Browser::ExecuteCommandWithDisposition() for the list of commands.
// Returns true if the call is successfully dispatched.
// Possible failures include the active window is not a browser window or
// the message to apply the accelerator fails.
bool RunCommandAsync(int browser_command);
// Runs the specified browser command in the current active browser, wait
// and return until the command has finished executing.
// See Browser::ExecuteCommandWithDisposition() for the list of commands.
// Returns true if the call is successfully dispatched and executed.
// Possible failures include the active window is not a browser window, or
// the message to apply the accelerator fails, or the command execution
// fails.
bool RunCommand(int browser_command);
void set_active_browser(BrowserProxy* browser) {
active_browser_ = browser;
}
BrowserProxy* active_browser() const { return active_browser_.get(); }
// Get the selected tab within the current active browser window, then
// create a corresponding TabProxy and transfer the ownership to caller.
// If success return the pointer to the newly created TabProxy and the
// caller owns the TabProxy. Return NULL otherwise.
scoped_refptr<TabProxy> GetActiveTab();
// Returns the WindowProxy associated with the given BrowserProxy
// (transferring ownership of the pointer to the caller) and brings that
// window to the top.
scoped_refptr<WindowProxy> GetAndActivateWindowForBrowser(
BrowserProxy* browser);
private:
scoped_refptr<BrowserProxy> active_browser_;
DISALLOW_COPY_AND_ASSIGN(AutomatedUITestBase);
};
#endif // CHROME_TEST_RELIABILITY_AUTOMATED_UI_TEST_BASE_H_
| 36.641975 | 79 | 0.743767 |
3c41e88e93a5f1ce612138dcc58eba344135d5f5 | 4,652 | h | C | System/Library/PrivateFrameworks/ITMLKit.framework/IKDOMElement.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/ITMLKit.framework/IKDOMElement.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/ITMLKit.framework/IKDOMElement.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:51:48 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/ITMLKit.framework/ITMLKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <ITMLKit/ITMLKit-Structs.h>
#import <ITMLKit/IKDOMNode.h>
#import <libobjc.A.dylib/IKJDOMParsingElement.h>
#import <libobjc.A.dylib/IKStyleableElement.h>
#import <libobjc.A.dylib/IKJSDOMElement.h>
#import <libobjc.A.dylib/_IKJSDOMElementProxy.h>
#import <libobjc.A.dylib/_IKJSDOMElement.h>
#import <libobjc.A.dylib/IKJSDOMParentNode.h>
@class NSString, IKViewElementStyleComposer, IKDOMNamedNodeMap, NSMutableDictionary, NSArray, NSDictionary, IKDOMHTMLCollection;
@interface IKDOMElement : IKDOMNode <IKJDOMParsingElement, IKStyleableElement, IKJSDOMElement, _IKJSDOMElementProxy, _IKJSDOMElement, IKJSDOMParentNode> {
NSMutableDictionary* _metadataDict;
NSArray* _cachedChildElements;
NSDictionary* _cachedAttributes;
IKViewElementStyleComposer* styleComposer;
IKDOMElement* __aliasOf;
}
@property (nonatomic,retain) NSString * innerHTML;
@property (nonatomic,retain) NSString * outerHTML;
@property (nonatomic,readonly) BOOL _isPrototypeElement;
@property (nonatomic,readonly) BOOL _isPartOfPrototypeElement;
@property (assign,setter=_setAliasOf:,nonatomic,__weak) IKDOMElement * _aliasOf; //@synthesize _aliasOf=__aliasOf - In the implementation block
@property (nonatomic,__weak,readonly) id<IKStyleableElement> parentStyleableElement;
@property (nonatomic,copy,readonly) NSString * elementName;
@property (nonatomic,retain) IKViewElementStyleComposer * styleComposer;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
@property (nonatomic,retain,readonly) NSString * tagName;
@property (nonatomic,copy,readonly) IKDOMNamedNodeMap * attributes;
@property (nonatomic,readonly) IKDOMHTMLCollection * children;
@property (nonatomic,readonly) IKDOMElement * firstElementChild;
@property (nonatomic,readonly) IKDOMElement * lastElementChild;
@property (nonatomic,readonly) unsigned long long childElementCount;
+(id)_filteredAttributes;
-(IKDOMHTMLCollection *)children;
-(id)_attributes;
-(id)objectForKeyedSubscript:(id)arg1 ;
-(long long)nodeType;
-(NSString *)tagName;
-(NSString *)elementName;
-(IKDOMNamedNodeMap *)attributes;
-(BOOL)hasAttribute:(id)arg1 ;
-(void)removeAttribute:(id)arg1 ;
-(unsigned long long)childElementCount;
-(id)nodeName;
-(id)textContent;
-(id)getAttribute:(id)arg1 ;
-(void)setObject:(id)arg1 forKeyedSubscript:(id)arg2 ;
-(NSString *)innerHTML;
-(id)getElementsByTagName:(id)arg1 ;
-(void)setTextContent:(id)arg1 ;
-(void)setInnerHTML:(NSString *)arg1 ;
-(BOOL)hasAttributes;
-(IKDOMElement *)firstElementChild;
-(IKDOMElement *)lastElementChild;
-(NSString *)outerHTML;
-(void)setOuterHTML:(NSString *)arg1 ;
-(void)setAttribute:(id)arg1 :(id)arg2 ;
-(id)childElementsByTagName:(id)arg1 ;
-(void)_setAliasOf:(id)arg1 ;
-(void)domib_setAppDataSet:(id)arg1 ;
-(id)domib_appDataSet;
-(void)domib_setItemsChangeSet:(id)arg1 ;
-(id)domib_itemsChangeSet;
-(void)domib_setVisibleIndexRange:(NSRange)arg1 ;
-(NSRange)domib_visibleIndexRange;
-(id)childElements;
-(id)ik_templateName;
-(void)childrenUpdatedWithUpdatedChildNodes:(id)arg1 notify:(BOOL)arg2 ;
-(void)setAttributeValue:(id)arg1 withName:(id)arg2 ;
-(void)_markUpdatedForChangeInAttribute:(id)arg1 fromValue:(id)arg2 toValue:(id)arg3 ;
-(IKDOMElement *)_aliasOf;
-(BOOL)_isPrototypeElement;
-(BOOL)_isPartOfPrototypeElement;
-(id<IKStyleableElement>)parentStyleableElement;
-(IKViewElementStyleComposer *)styleComposer;
-(void)setStyleComposer:(IKViewElementStyleComposer *)arg1 ;
-(id)asPrivateIKJSDOMElement;
-(id)childElementByTagName:(id)arg1 ;
-(void)domp_setPrototype:(id)arg1 ;
-(id)domp_prototype;
-(void)domp_setDerivativeDOMElementsBySelector:(id)arg1 ;
-(id)domp_derivativeDOMElementsBySelector;
-(void)insertAdjacentHTML:(id)arg1 :(id)arg2 ;
-(id)ik_templateElementCSSSelectorList;
-(id)domb_boundCSSRule;
-(void)domb_setDOMBindingController:(id)arg1 ;
-(id)domb_domBindingController;
-(void)domb_setDataBinding:(id)arg1 ;
-(id)domb_dataBinding;
-(void)domb_setMutationRuleSet:(id)arg1 ;
-(id)domb_mutationRuleSet;
-(void)domb_setBoundCSSRule:(id)arg1 ;
-(void)ikve_setPrototypesID:(id)arg1 ;
-(id)ikve_prototypesID;
-(void)ikve_setRulesID:(id)arg1 ;
-(id)ikve_rulesID;
-(void)dombs_setItems:(id)arg1 ;
-(id)dombs_items;
@end
| 40.103448 | 160 | 0.791273 |
2cc3fe8a4614d2cf5a6e8e97ddb2186a7ebb289e | 72 | h | C | qtmultimedia/include/QtMultimedia/qvideoencodersettingscontrol.h | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtmultimedia/include/QtMultimedia/qvideoencodersettingscontrol.h | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtmultimedia/include/QtMultimedia/qvideoencodersettingscontrol.h | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | #include "../../src/multimedia/controls/qvideoencodersettingscontrol.h"
| 36 | 71 | 0.791667 |
2ce305844dfa69f906758b2db2fc0d498d093282 | 1,079 | h | C | usr/libexec/sharingd/SDClassroomBrowser.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 11 | 2019-11-06T04:48:48.000Z | 2022-02-09T17:48:15.000Z | usr/libexec/sharingd/SDClassroomBrowser.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 1 | 2020-04-16T01:41:56.000Z | 2020-04-16T04:32:00.000Z | usr/libexec/sharingd/SDClassroomBrowser.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 3 | 2019-12-22T20:17:53.000Z | 2021-01-25T09:47:49.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 3:11:55 PM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /usr/libexec/sharingd
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@class NSArray, NSString;
@interface SDClassroomBrowser : NSObject {
NSArray* _nodes;
NSString* _clientBundleID;
}
@property (copy,readonly) NSArray * nodes; //@synthesize nodes=_nodes - In the implementation block
@property (copy) NSString * clientBundleID; //@synthesize clientBundleID=_clientBundleID - In the implementation block
+(id)sharedBrowser;
-(id)init;
-(void)start;
-(void)stop;
-(NSArray *)nodes;
-(void)setClientBundleID:(NSString *)arg1 ;
-(NSString *)clientBundleID;
-(void)potentiallyInvalidate;
-(void)startSendingItems:(id)arg1 withProperties:(id)arg2 toPersonWithID:(id)arg3 clientBundleID:(id)arg4 airDropClientDelegate:(id)arg5 ;
-(void)cancelSendingItemsToPersonWithID:(id)arg1 sessionID:(id)arg2 clientBundleID:(id)arg3 ;
@end
| 32.69697 | 138 | 0.747915 |
82ceec967f7141ac9b01ccd59b9b2098e8ddc4e0 | 633 | h | C | Friendly/Controllers/EntranceWorkflow/AddInterests Module/UserInterface/DataSource/FRAddInterestsDataSource.h | vikingdr/Friendly | ea690b061fc1dae59345f24d361dc032713e16de | [
"MIT"
] | null | null | null | Friendly/Controllers/EntranceWorkflow/AddInterests Module/UserInterface/DataSource/FRAddInterestsDataSource.h | vikingdr/Friendly | ea690b061fc1dae59345f24d361dc032713e16de | [
"MIT"
] | null | null | null | Friendly/Controllers/EntranceWorkflow/AddInterests Module/UserInterface/DataSource/FRAddInterestsDataSource.h | vikingdr/Friendly | ea690b061fc1dae59345f24d361dc032713e16de | [
"MIT"
] | null | null | null | //
// FRAddInterestsInteractor.h
// Friendly
//
// Created by Matthew James on 3.03.2016.
// Copyright (c) 2016 Accucode Inc. All rights reserved.
//
@class BSMemoryStorage;
@class FRInterestsModels, FRInterestsModel;
@protocol FRAddInterestsDataSourceDelegate <NSObject>
- (void)selectedInterest:(FRInterestsModel*)interest;
@end
@interface FRAddInterestsDataSource : NSObject
@property (nonatomic, strong) BSMemoryStorage* storage;
@property (nonatomic, weak) id<FRAddInterestsDataSourceDelegate> delegate;
- (void)setupStorageWithModel:(FRInterestsModels*)model;
- (void)addInterests:(FRInterestsModel*)interest;
@end
| 23.444444 | 74 | 0.78515 |
192ff13a0fa830409b5b36100a9f9b4091f624de | 51,264 | c | C | glib20/glib/gtimezone.c | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | 1 | 2021-02-24T13:01:00.000Z | 2021-02-24T13:01:00.000Z | glib20/glib/gtimezone.c | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | null | null | null | glib20/glib/gtimezone.c | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright © 2010 Codethink Limited
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
* Author: Ryan Lortie <desrt@desrt.ca>
*/
/* Prologue {{{1 */
#include "config.h"
#include "gtimezone.h"
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include "gmappedfile.h"
#include "gtestutils.h"
#include "gfileutils.h"
#include "gstrfuncs.h"
#include "ghash.h"
#include "gthread.h"
#include "gbytes.h"
#include "gslice.h"
#include "gdatetime.h"
#include "gdate.h"
#ifdef G_OS_WIN32
#define STRICT
#include <windows.h>
#endif
/**
* SECTION:timezone
* @title: GTimeZone
* @short_description: a structure representing a time zone
* @see_also: #GDateTime
*
* #GTimeZone is a structure that represents a time zone, at no
* particular point in time. It is refcounted and immutable.
*
* A time zone contains a number of intervals. Each interval has
* an abbreviation to describe it, an offet to UTC and a flag indicating
* if the daylight savings time is in effect during that interval. A
* time zone always has at least one interval -- interval 0.
*
* Every UTC time is contained within exactly one interval, but a given
* local time may be contained within zero, one or two intervals (due to
* incontinuities associated with daylight savings time).
*
* An interval may refer to a specific period of time (eg: the duration
* of daylight savings time during 2010) or it may refer to many periods
* of time that share the same properties (eg: all periods of daylight
* savings time). It is also possible (usually for political reasons)
* that some properties (like the abbreviation) change between intervals
* without other properties changing.
*
* #GTimeZone is available since GLib 2.26.
*/
/**
* GTimeZone:
*
* #GTimeZone is an opaque structure whose members cannot be accessed
* directly.
*
* Since: 2.26
**/
/* IANA zoneinfo file format {{{1 */
/* unaligned */
typedef struct { gchar bytes[8]; } gint64_be;
typedef struct { gchar bytes[4]; } gint32_be;
typedef struct { gchar bytes[4]; } guint32_be;
static inline gint64 gint64_from_be (const gint64_be be) {
gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
}
static inline gint32 gint32_from_be (const gint32_be be) {
gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
}
static inline guint32 guint32_from_be (const guint32_be be) {
guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
}
/* The layout of an IANA timezone file header */
struct tzhead
{
gchar tzh_magic[4];
gchar tzh_version;
guchar tzh_reserved[15];
guint32_be tzh_ttisgmtcnt;
guint32_be tzh_ttisstdcnt;
guint32_be tzh_leapcnt;
guint32_be tzh_timecnt;
guint32_be tzh_typecnt;
guint32_be tzh_charcnt;
};
struct ttinfo
{
gint32_be tt_gmtoff;
guint8 tt_isdst;
guint8 tt_abbrind;
};
/* A Transition Date structure for TZ Rules, an intermediate structure
for parsing MSWindows and Environment-variable time zones. It
Generalizes MSWindows's SYSTEMTIME struct.
*/
typedef struct
{
gint year;
gint mon;
gint mday;
gint wday;
gint week;
gint hour;
gint min;
gint sec;
} TimeZoneDate;
/* POSIX Timezone abbreviations are typically 3 or 4 characters, but
Microsoft uses 32-character names. We'll use one larger to ensure
we have room for the terminating \0.
*/
#define NAME_SIZE 33
/* A MSWindows-style time zone transition rule. Generalizes the
MSWindows TIME_ZONE_INFORMATION struct. Also used to compose time
zones from tzset-style identifiers.
*/
typedef struct
{
gint start_year;
gint32 std_offset;
gint32 dlt_offset;
TimeZoneDate dlt_start;
TimeZoneDate dlt_end;
gchar std_name[NAME_SIZE];
gchar dlt_name[NAME_SIZE];
} TimeZoneRule;
/* GTimeZone's internal representation of a Daylight Savings (Summer)
time interval.
*/
typedef struct
{
gint32 gmt_offset;
gboolean is_dst;
gchar *abbrev;
} TransitionInfo;
/* GTimeZone's representation of a transition time to or from Daylight
Savings (Summer) time and Standard time for the zone. */
typedef struct
{
gint64 time;
gint info_index;
} Transition;
/* GTimeZone structure */
struct _GTimeZone
{
gchar *name;
GArray *t_info; /* Array of TransitionInfo */
GArray *transitions; /* Array of Transition */
gint ref_count;
};
G_LOCK_DEFINE_STATIC (time_zones);
static GHashTable/*<string?, GTimeZone>*/ *time_zones;
#define MIN_TZYEAR 1916 /* Daylight Savings started in WWI */
#define MAX_TZYEAR 2999 /* And it's not likely ever to go away, but
there's no point in getting carried
away. */
/**
* g_time_zone_unref:
* @tz: a #GTimeZone
*
* Decreases the reference count on @tz.
*
* Since: 2.26
**/
void
g_time_zone_unref (GTimeZone *tz)
{
int ref_count;
again:
ref_count = g_atomic_int_get (&tz->ref_count);
g_assert (ref_count > 0);
if (ref_count == 1)
{
if (tz->name != NULL)
{
G_LOCK(time_zones);
/* someone else might have grabbed a ref in the meantime */
if G_UNLIKELY (g_atomic_int_get (&tz->ref_count) != 1)
{
G_UNLOCK(time_zones);
goto again;
}
g_hash_table_remove (time_zones, tz->name);
G_UNLOCK(time_zones);
}
if (tz->t_info != NULL)
{
gint idx;
for (idx = 0; idx < tz->t_info->len; idx++)
{
TransitionInfo *info = &g_array_index (tz->t_info, TransitionInfo, idx);
g_free (info->abbrev);
}
g_array_free (tz->t_info, TRUE);
}
if (tz->transitions != NULL)
g_array_free (tz->transitions, TRUE);
g_free (tz->name);
g_slice_free (GTimeZone, tz);
}
else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
ref_count,
ref_count - 1))
goto again;
}
/**
* g_time_zone_ref:
* @tz: a #GTimeZone
*
* Increases the reference count on @tz.
*
* Returns: a new reference to @tz.
*
* Since: 2.26
**/
GTimeZone *
g_time_zone_ref (GTimeZone *tz)
{
g_assert (tz->ref_count > 0);
g_atomic_int_inc (&tz->ref_count);
return tz;
}
/* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
/*
* parses strings of the form h or hh[[:]mm[[[:]ss]]] where:
* - h[h] is 0 to 23
* - mm is 00 to 59
* - ss is 00 to 59
*/
static gboolean
parse_time (const gchar *time_,
gint32 *offset)
{
if (*time_ < '0' || '9' < *time_)
return FALSE;
*offset = 60 * 60 * (*time_++ - '0');
if (*time_ == '\0')
return TRUE;
if (*time_ != ':')
{
if (*time_ < '0' || '9' < *time_)
return FALSE;
*offset *= 10;
*offset += 60 * 60 * (*time_++ - '0');
if (*offset > 23 * 60 * 60)
return FALSE;
if (*time_ == '\0')
return TRUE;
}
if (*time_ == ':')
time_++;
if (*time_ < '0' || '5' < *time_)
return FALSE;
*offset += 10 * 60 * (*time_++ - '0');
if (*time_ < '0' || '9' < *time_)
return FALSE;
*offset += 60 * (*time_++ - '0');
if (*time_ == '\0')
return TRUE;
if (*time_ == ':')
time_++;
if (*time_ < '0' || '5' < *time_)
return FALSE;
*offset += 10 * (*time_++ - '0');
if (*time_ < '0' || '9' < *time_)
return FALSE;
*offset += *time_++ - '0';
return *time_ == '\0';
}
static gboolean
parse_constant_offset (const gchar *name,
gint32 *offset)
{
if (g_strcmp0 (name, "UTC") == 0)
{
*offset = 0;
return TRUE;
}
if (*name >= '0' && '9' >= *name)
return parse_time (name, offset);
switch (*name++)
{
case 'Z':
*offset = 0;
return !*name;
case '+':
return parse_time (name, offset);
case '-':
if (parse_time (name, offset))
{
*offset = -*offset;
return TRUE;
}
default:
return FALSE;
}
}
static void
zone_for_constant_offset (GTimeZone *gtz, const gchar *name)
{
gint32 offset;
TransitionInfo info;
if (name == NULL || !parse_constant_offset (name, &offset))
return;
info.gmt_offset = offset;
info.is_dst = FALSE;
info.abbrev = g_strdup (name);
gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), 1);
g_array_append_val (gtz->t_info, info);
/* Constant offset, no transitions */
gtz->transitions = NULL;
}
#ifdef G_OS_UNIX
static GBytes*
zone_info_unix (const gchar *identifier)
{
gchar *filename;
GMappedFile *file = NULL;
GBytes *zoneinfo = NULL;
/* identifier can be a relative or absolute path name;
if relative, it is interpreted starting from /usr/share/zoneinfo
while the POSIX standard says it should start with :,
glibc allows both syntaxes, so we should too */
if (identifier != NULL)
{
const gchar *tzdir;
tzdir = getenv ("TZDIR");
if (tzdir == NULL)
tzdir = "/usr/share/zoneinfo";
if (*identifier == ':')
identifier ++;
if (g_path_is_absolute (identifier))
filename = g_strdup (identifier);
else
filename = g_build_filename (tzdir, identifier, NULL);
}
else
filename = g_strdup ("/etc/localtime");
file = g_mapped_file_new (filename, FALSE, NULL);
if (file != NULL)
{
zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
g_mapped_file_get_length (file),
(GDestroyNotify)g_mapped_file_unref,
g_mapped_file_ref (file));
g_mapped_file_unref (file);
}
g_free (filename);
return zoneinfo;
}
static void
init_zone_from_iana_info (GTimeZone *gtz, GBytes *zoneinfo)
{
gsize size;
guint index;
guint32 time_count, type_count;
guint8 *tz_transitions, *tz_type_index, *tz_ttinfo;
guint8 *tz_abbrs;
gsize timesize = sizeof (gint32);
const struct tzhead *header = g_bytes_get_data (zoneinfo, &size);
g_return_if_fail (size >= sizeof (struct tzhead) &&
memcmp (header, "TZif", 4) == 0);
if (header->tzh_version == '2')
{
/* Skip ahead to the newer 64-bit data if it's available. */
header = (const struct tzhead *)
(((const gchar *) (header + 1)) +
guint32_from_be(header->tzh_ttisgmtcnt) +
guint32_from_be(header->tzh_ttisstdcnt) +
8 * guint32_from_be(header->tzh_leapcnt) +
5 * guint32_from_be(header->tzh_timecnt) +
6 * guint32_from_be(header->tzh_typecnt) +
guint32_from_be(header->tzh_charcnt));
timesize = sizeof (gint64);
}
time_count = guint32_from_be(header->tzh_timecnt);
type_count = guint32_from_be(header->tzh_typecnt);
tz_transitions = ((guint8 *) (header) + sizeof (*header));
tz_type_index = tz_transitions + timesize * time_count;
tz_ttinfo = tz_type_index + time_count;
tz_abbrs = tz_ttinfo + sizeof (struct ttinfo) * type_count;
gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo),
type_count);
gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition),
time_count);
for (index = 0; index < type_count; index++)
{
TransitionInfo t_info;
struct ttinfo info = ((struct ttinfo*)tz_ttinfo)[index];
t_info.gmt_offset = gint32_from_be (info.tt_gmtoff);
t_info.is_dst = info.tt_isdst ? TRUE : FALSE;
t_info.abbrev = g_strdup ((gchar *) &tz_abbrs[info.tt_abbrind]);
g_array_append_val (gtz->t_info, t_info);
}
for (index = 0; index < time_count; index++)
{
Transition trans;
if (header->tzh_version == '2')
trans.time = gint64_from_be (((gint64_be*)tz_transitions)[index]);
else
trans.time = gint32_from_be (((gint32_be*)tz_transitions)[index]);
trans.info_index = tz_type_index[index];
g_assert (trans.info_index >= 0);
g_assert (trans.info_index < gtz->t_info->len);
g_array_append_val (gtz->transitions, trans);
}
}
#elif defined (G_OS_WIN32)
static void
copy_windows_systemtime (SYSTEMTIME *s_time, TimeZoneDate *tzdate)
{
tzdate->sec = s_time->wSecond;
tzdate->min = s_time->wMinute;
tzdate->hour = s_time->wHour;
tzdate->mon = s_time->wMonth;
tzdate->year = s_time->wYear;
tzdate->wday = s_time->wDayOfWeek ? s_time->wDayOfWeek : 7;
if (s_time->wYear)
{
tzdate->mday = s_time->wDay;
tzdate->wday = 0;
}
else
tzdate->week = s_time->wDay;
}
/* UTC = local time + bias while local time = UTC + offset */
static void
rule_from_windows_time_zone_info (TimeZoneRule *rule,
TIME_ZONE_INFORMATION *tzi)
{
/* Set offset */
if (tzi->StandardDate.wMonth)
{
rule->std_offset = -(tzi->Bias + tzi->StandardBias) * 60;
rule->dlt_offset = -(tzi->Bias + tzi->DaylightBias) * 60;
copy_windows_systemtime (&(tzi->DaylightDate), &(rule->dlt_start));
copy_windows_systemtime (&(tzi->StandardDate), &(rule->dlt_end));
}
else
{
rule->std_offset = -tzi->Bias * 60;
rule->dlt_start.mon = 0;
}
strncpy (rule->std_name, (gchar*)tzi->StandardName, NAME_SIZE - 1);
strncpy (rule->dlt_name, (gchar*)tzi->DaylightName, NAME_SIZE - 1);
}
static gchar*
windows_default_tzname (void)
{
const gchar *subkey =
"SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation";
HKEY key;
gchar *key_name = NULL;
if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
{
DWORD size = 0;
if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
NULL, &size) == ERROR_SUCCESS)
{
key_name = g_malloc ((gint)size);
if (RegQueryValueExA (key, "TimeZoneKeyName", NULL, NULL,
(LPBYTE)key_name, &size) != ERROR_SUCCESS)
{
g_free (key_name);
key_name = NULL;
}
}
RegCloseKey (key);
}
return key_name;
}
typedef struct
{
LONG Bias;
LONG StandardBias;
LONG DaylightBias;
SYSTEMTIME StandardDate;
SYSTEMTIME DaylightDate;
} RegTZI;
static void
system_time_copy (SYSTEMTIME *orig, SYSTEMTIME *target)
{
g_return_if_fail (orig != NULL);
g_return_if_fail (target != NULL);
target->wYear = orig->wYear;
target->wMonth = orig->wMonth;
target->wDayOfWeek = orig->wDayOfWeek;
target->wDay = orig->wDay;
target->wHour = orig->wHour;
target->wMinute = orig->wMinute;
target->wSecond = orig->wSecond;
target->wMilliseconds = orig->wMilliseconds;
}
static void
register_tzi_to_tzi (RegTZI *reg, TIME_ZONE_INFORMATION *tzi)
{
g_return_if_fail (reg != NULL);
g_return_if_fail (tzi != NULL);
tzi->Bias = reg->Bias;
system_time_copy (&(reg->StandardDate), &(tzi->StandardDate));
tzi->StandardBias = reg->StandardBias;
system_time_copy (&(reg->DaylightDate), &(tzi->DaylightDate));
tzi->DaylightBias = reg->DaylightBias;
}
static gint
rules_from_windows_time_zone (const gchar *identifier, TimeZoneRule **rules)
{
HKEY key;
gchar *subkey, *subkey_dynamic;
gchar *key_name = NULL;
const gchar *reg_key =
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
TIME_ZONE_INFORMATION tzi;
DWORD size;
gint rules_num = 0;
RegTZI regtzi, regtzi_prev;
*rules = NULL;
key_name = NULL;
if (!identifier)
key_name = windows_default_tzname ();
else
key_name = g_strdup (identifier);
if (!key_name)
return 0;
subkey = g_strconcat (reg_key, key_name, NULL);
subkey_dynamic = g_strconcat (subkey, "\\Dynamic DST", NULL);
if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
return 0;
size = sizeof tzi.StandardName;
if (RegQueryValueExA (key, "Std", NULL, NULL,
(LPBYTE)&(tzi.StandardName), &size) != ERROR_SUCCESS)
goto failed;
size = sizeof tzi.DaylightName;
if (RegQueryValueExA (key, "Dlt", NULL, NULL,
(LPBYTE)&(tzi.DaylightName), &size) != ERROR_SUCCESS)
goto failed;
RegCloseKey (key);
if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey_dynamic, 0,
KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
{
DWORD first, last;
int year, i;
gchar *s;
size = sizeof first;
if (RegQueryValueExA (key, "FirstEntry", NULL, NULL,
(LPBYTE) &first, &size) != ERROR_SUCCESS)
goto failed;
size = sizeof last;
if (RegQueryValueExA (key, "LastEntry", NULL, NULL,
(LPBYTE) &last, &size) != ERROR_SUCCESS)
goto failed;
rules_num = last - first + 2;
*rules = g_new0 (TimeZoneRule, rules_num);
for (year = first, i = 0; year <= last; year++)
{
s = g_strdup_printf ("%d", year);
size = sizeof regtzi;
if (RegQueryValueExA (key, s, NULL, NULL,
(LPBYTE) ®tzi, &size) != ERROR_SUCCESS)
{
g_free (*rules);
*rules = NULL;
break;
}
g_free (s);
if (year > first && memcmp (®tzi_prev, ®tzi, sizeof regtzi) == 0)
continue;
else
memcpy (®tzi_prev, ®tzi, sizeof regtzi);
register_tzi_to_tzi (®tzi, &tzi);
rule_from_windows_time_zone_info (&(*rules)[i], &tzi);
(*rules)[i++].start_year = year;
}
rules_num = i + 1;
failed:
RegCloseKey (key);
}
else if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey, 0,
KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
{
size = sizeof regtzi;
if (RegQueryValueExA (key, "TZI", NULL, NULL,
(LPBYTE) ®tzi, &size) == ERROR_SUCCESS)
{
rules_num = 2;
*rules = g_new0 (TimeZoneRule, 2);
register_tzi_to_tzi (®tzi, &tzi);
rule_from_windows_time_zone_info (&(*rules)[0], &tzi);
}
RegCloseKey (key);
}
g_free (subkey_dynamic);
g_free (subkey);
g_free (key_name);
if (*rules)
{
(*rules)[0].start_year = MIN_TZYEAR;
if ((*rules)[rules_num - 2].start_year < MAX_TZYEAR)
(*rules)[rules_num - 1].start_year = MAX_TZYEAR;
else
(*rules)[rules_num - 1].start_year = (*rules)[rules_num - 2].start_year + 1;
return rules_num;
}
else
return 0;
}
#endif
static void
find_relative_date (TimeZoneDate *buffer)
{
gint wday;
GDate date;
g_date_clear (&date, 1);
wday = buffer->wday;
/* Get last day if last is needed, first day otherwise */
if (buffer->mon == 13 || buffer->mon == 14) /* Julian Date */
{
g_date_set_dmy (&date, 1, 1, buffer->year);
if (wday >= 59 && buffer->mon == 13 && g_date_is_leap_year (buffer->year))
g_date_add_days (&date, wday);
else
g_date_add_days (&date, wday - 1);
buffer->mon = (int) g_date_get_month (&date);
buffer->mday = (int) g_date_get_day (&date);
buffer->wday = 0;
}
else /* M.W.D */
{
guint days;
guint days_in_month = g_date_days_in_month (buffer->mon, buffer->year);
GDateWeekday first_wday;
g_date_set_dmy (&date, 1, buffer->mon, buffer->year);
first_wday = g_date_get_weekday (&date);
if (first_wday > wday)
++(buffer->week);
/* week is 1 <= w <= 5, we need 0-based */
days = 7 * (buffer->week - 1) + wday - first_wday;
while (days > days_in_month)
days -= 7;
g_date_add_days (&date, days);
buffer->mday = g_date_get_day (&date);
}
}
/* Offset is previous offset of local time. Returns 0 if month is 0 */
static gint64
boundary_for_year (TimeZoneDate *boundary,
gint year,
gint32 offset)
{
TimeZoneDate buffer;
GDate date;
const guint64 unix_epoch_start = 719163L;
const guint64 seconds_per_day = 86400L;
if (!boundary->mon)
return 0;
buffer = *boundary;
if (boundary->year == 0)
{
buffer.year = year;
if (buffer.wday)
find_relative_date (&buffer);
}
g_assert (buffer.year == year);
g_date_clear (&date, 1);
g_date_set_dmy (&date, buffer.mday, buffer.mon, buffer.year);
return ((g_date_get_julian (&date) - unix_epoch_start) * seconds_per_day +
buffer.hour * 3600 + buffer.min * 60 + buffer.sec - offset);
}
static void
fill_transition_info_from_rule (TransitionInfo *info,
TimeZoneRule *rule,
gboolean is_dst)
{
gint offset = is_dst ? rule->dlt_offset : rule->std_offset;
gchar *name = is_dst ? rule->dlt_name : rule->std_name;
info->gmt_offset = offset;
info->is_dst = is_dst;
if (name)
info->abbrev = g_strdup (name);
else
info->abbrev = g_strdup_printf ("%+03d%02d",
(int) offset / 3600,
(int) abs (offset / 60) % 60);
}
static void
init_zone_from_rules (GTimeZone *gtz,
TimeZoneRule *rules,
gint rules_num)
{
guint type_count = 0, trans_count = 0, info_index = 0;
guint ri; /* rule index */
gboolean skip_first_std_trans = TRUE;
gint32 last_offset;
type_count = 0;
trans_count = 0;
/* Last rule only contains max year */
for (ri = 0; ri < rules_num - 1; ri++)
{
if (rules[ri].dlt_start.mon || rules[ri].dlt_end.mon)
{
guint rulespan = (rules[ri + 1].start_year - rules[ri].start_year);
guint transitions = rules[ri].dlt_start.mon > 0 ? 1 : 0;
transitions += rules[ri].dlt_end.mon > 0 ? 1 : 0;
type_count += rules[ri].dlt_start.mon > 0 ? 2 : 1;
trans_count += transitions * rulespan;
}
else
type_count++;
}
gtz->t_info = g_array_sized_new (FALSE, TRUE, sizeof (TransitionInfo), type_count);
gtz->transitions = g_array_sized_new (FALSE, TRUE, sizeof (Transition), trans_count);
last_offset = rules[0].std_offset;
for (ri = 0; ri < rules_num - 1; ri++)
{
if ((rules[ri].std_offset || rules[ri].dlt_offset) &&
rules[ri].dlt_start.mon == 0 && rules[ri].dlt_end.mon == 0)
{
TransitionInfo std_info;
/* Standard */
fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
g_array_append_val (gtz->t_info, std_info);
if (ri > 0 &&
((rules[ri - 1].dlt_start.mon > 12 &&
rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
{
/* The previous rule was a southern hemisphere rule that
starts the year with DST, so we need to add a
transition to return to standard time */
guint year = rules[ri].start_year;
gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
year, last_offset);
Transition std_trans = {std_time, info_index};
g_array_append_val (gtz->transitions, std_trans);
}
last_offset = rules[ri].std_offset;
++info_index;
skip_first_std_trans = TRUE;
}
else
{
const guint start_year = rules[ri].start_year;
const guint end_year = rules[ri + 1].start_year;
gboolean dlt_first;
guint year;
TransitionInfo std_info, dlt_info;
if (rules[ri].dlt_start.mon > 12)
dlt_first = rules[ri].dlt_start.wday > rules[ri].dlt_end.wday;
else
dlt_first = rules[ri].dlt_start.mon > rules[ri].dlt_end.mon;
/* Standard rules are always even, because before the first
transition is always standard time, and 0 is even. */
fill_transition_info_from_rule (&std_info, &(rules[ri]), FALSE);
fill_transition_info_from_rule (&dlt_info, &(rules[ri]), TRUE);
g_array_append_val (gtz->t_info, std_info);
g_array_append_val (gtz->t_info, dlt_info);
/* Transition dates. We hope that a year which ends daylight
time in a southern-hemisphere country (i.e., one that
begins the year in daylight time) will include a rule
which has only a dlt_end. */
for (year = start_year; year < end_year; year++)
{
gint32 dlt_offset = (dlt_first ? last_offset :
rules[ri].dlt_offset);
gint32 std_offset = (dlt_first ? rules[ri].std_offset :
last_offset);
/* NB: boundary_for_year returns 0 if mon == 0 */
gint64 std_time = boundary_for_year (&rules[ri].dlt_end,
year, dlt_offset);
gint64 dlt_time = boundary_for_year (&rules[ri].dlt_start,
year, std_offset);
Transition std_trans = {std_time, info_index};
Transition dlt_trans = {dlt_time, info_index + 1};
last_offset = (dlt_first ? rules[ri].dlt_offset :
rules[ri].std_offset);
if (dlt_first)
{
if (skip_first_std_trans)
skip_first_std_trans = FALSE;
else if (std_time)
g_array_append_val (gtz->transitions, std_trans);
if (dlt_time)
g_array_append_val (gtz->transitions, dlt_trans);
}
else
{
if (dlt_time)
g_array_append_val (gtz->transitions, dlt_trans);
if (std_time)
g_array_append_val (gtz->transitions, std_trans);
}
}
info_index += 2;
}
}
if (ri > 0 &&
((rules[ri - 1].dlt_start.mon > 12 &&
rules[ri - 1].dlt_start.wday > rules[ri - 1].dlt_end.wday) ||
rules[ri - 1].dlt_start.mon > rules[ri - 1].dlt_end.mon))
{
/* The previous rule was a southern hemisphere rule that
starts the year with DST, so we need to add a
transition to return to standard time */
TransitionInfo info;
guint year = rules[ri].start_year;
Transition trans;
fill_transition_info_from_rule (&info, &(rules[ri - 1]), FALSE);
g_array_append_val (gtz->t_info, info);
trans.time = boundary_for_year (&rules[ri - 1].dlt_end,
year, last_offset);
trans.info_index = info_index;
g_array_append_val (gtz->transitions, trans);
}
}
/*
* parses date[/time] for parsing TZ environment variable
*
* date is either Mm.w.d, Jn or N
* - m is 1 to 12
* - w is 1 to 5
* - d is 0 to 6
* - n is 1 to 365
* - N is 0 to 365
*
* time is either h or hh[[:]mm[[[:]ss]]]
* - h[h] is 0 to 23
* - mm is 00 to 59
* - ss is 00 to 59
*/
static gboolean
parse_mwd_boundary (gchar **pos, TimeZoneDate *boundary)
{
gint month, week, day;
if (**pos == '\0' || **pos < '0' || '9' < **pos)
return FALSE;
month = *(*pos)++ - '0';
if ((month == 1 && **pos >= '0' && '2' >= **pos) ||
(month == 0 && **pos >= '0' && '9' >= **pos))
{
month *= 10;
month += *(*pos)++ - '0';
}
if (*(*pos)++ != '.' || month == 0)
return FALSE;
if (**pos == '\0' || **pos < '1' || '5' < **pos)
return FALSE;
week = *(*pos)++ - '0';
if (*(*pos)++ != '.')
return FALSE;
if (**pos == '\0' || **pos < '0' || '6' < **pos)
return FALSE;
day = *(*pos)++ - '0';
if (!day)
day += 7;
boundary->year = 0;
boundary->mon = month;
boundary->week = week;
boundary->wday = day;
return TRUE;
}
/* Different implementations of tzset interpret the Julian day field
differently. For example, Linux specifies that it should be 1-based
(1 Jan is JD 1) for both Jn and n formats, while zOS and BSD
specify that a Jn JD is 1-based while an n JD is 0-based. Rather
than trying to follow different specs, we will follow GDate's
practice thatIn order to keep it simple, we will follow Linux's
practice. */
static gboolean
parse_julian_boundary (gchar** pos, TimeZoneDate *boundary,
gboolean ignore_leap)
{
gint day = 0;
GDate date;
while (**pos >= '0' && '9' >= **pos)
{
day *= 10;
day += *(*pos)++ - '0';
}
if (day < 1 || 365 < day)
return FALSE;
g_date_clear (&date, 1);
g_date_set_julian (&date, day);
boundary->year = 0;
boundary->mon = (int) g_date_get_month (&date);
boundary->mday = (int) g_date_get_day (&date);
boundary->wday = 0;
if (!ignore_leap && day >= 59)
boundary->mday++;
return TRUE;
}
static gboolean
parse_tz_boundary (const gchar *identifier,
TimeZoneDate *boundary)
{
gchar *pos;
pos = (gchar*)identifier;
/* Month-week-weekday */
if (*pos == 'M')
{
++pos;
if (!parse_mwd_boundary (&pos, boundary))
return FALSE;
}
/* Julian date which ignores Feb 29 in leap years */
else if (*pos == 'J')
{
++pos;
if (!parse_julian_boundary (&pos, boundary, FALSE))
return FALSE ;
}
/* Julian date which counts Feb 29 in leap years */
else if (*pos >= '0' && '9' >= *pos)
{
if (!parse_julian_boundary (&pos, boundary, TRUE))
return FALSE;
}
else
return FALSE;
/* Time */
if (*pos == '/')
{
gint32 offset;
if (!parse_time (++pos, &offset))
return FALSE;
boundary->hour = offset / 3600;
boundary->min = (offset / 60) % 60;
boundary->sec = offset % 3600;
return TRUE;
}
else
{
boundary->hour = 2;
boundary->min = 0;
boundary->sec = 0;
return *pos == '\0';
}
}
static gint
create_ruleset_from_rule (TimeZoneRule **rules, TimeZoneRule *rule)
{
*rules = g_new0 (TimeZoneRule, 2);
(*rules)[0].start_year = MIN_TZYEAR;
(*rules)[1].start_year = MAX_TZYEAR;
(*rules)[0].std_offset = -rule->std_offset;
(*rules)[0].dlt_offset = -rule->dlt_offset;
(*rules)[0].dlt_start = rule->dlt_start;
(*rules)[0].dlt_end = rule->dlt_end;
strcpy ((*rules)[0].std_name, rule->std_name);
strcpy ((*rules)[0].dlt_name, rule->dlt_name);
return 2;
}
static gboolean
parse_offset (gchar **pos, gint32 *target)
{
gchar *buffer;
gchar *target_pos = *pos;
gboolean ret;
while (**pos == '+' || **pos == '-' || **pos == ':' ||
(**pos >= '0' && '9' >= **pos))
++(*pos);
buffer = g_strndup (target_pos, *pos - target_pos);
ret = parse_constant_offset (buffer, target);
g_free (buffer);
return ret;
}
static gboolean
parse_identifier_boundary (gchar **pos, TimeZoneDate *target)
{
gchar *buffer;
gchar *target_pos = *pos;
gboolean ret;
while (**pos != ',' && **pos != '\0')
++(*pos);
buffer = g_strndup (target_pos, *pos - target_pos);
ret = parse_tz_boundary (buffer, target);
g_free (buffer);
return ret;
}
static gboolean
set_tz_name (gchar **pos, gchar *buffer, guint size)
{
gchar *name_pos = *pos;
guint len;
/* Name is ASCII alpha (Is this necessarily true?) */
while (g_ascii_isalpha (**pos))
++(*pos);
/* Name should be three or more alphabetic characters */
if (*pos - name_pos < 3)
return FALSE;
memset (buffer, 0, NAME_SIZE);
/* name_pos isn't 0-terminated, so we have to limit the length expressly */
len = *pos - name_pos > size - 1 ? size - 1 : *pos - name_pos;
strncpy (buffer, name_pos, len);
return TRUE;
}
static gboolean
parse_identifier_boundaries (gchar **pos, TimeZoneRule *tzr)
{
if (*(*pos)++ != ',')
return FALSE;
/* Start date */
if (!parse_identifier_boundary (pos, &(tzr->dlt_start)) || *(*pos)++ != ',')
return FALSE;
/* End date */
if (!parse_identifier_boundary (pos, &(tzr->dlt_end)))
return FALSE;
return TRUE;
}
/*
* Creates an array of TimeZoneRule from a TZ environment variable
* type of identifier. Should free rules afterwards
*/
static gint
rules_from_identifier (const gchar *identifier,
TimeZoneRule **rules)
{
gchar *pos;
TimeZoneRule tzr;
if (!identifier)
return 0;
pos = (gchar*)identifier;
memset (&tzr, 0, sizeof (tzr));
/* Standard offset */
if (!(set_tz_name (&pos, tzr.std_name, NAME_SIZE)) ||
!parse_offset (&pos, &(tzr.std_offset)))
return 0;
if (*pos == 0)
return create_ruleset_from_rule (rules, &tzr);
/* Format 2 */
if (!(set_tz_name (&pos, tzr.dlt_name, NAME_SIZE)))
return 0;
parse_offset (&pos, &(tzr.dlt_offset));
if (tzr.dlt_offset == 0) /* No daylight offset given, assume it's 1
hour earlier that standard */
tzr.dlt_offset = tzr.std_offset - 3600;
if (*pos == '\0')
#ifdef G_OS_WIN32
/* Windows allows us to use the US DST boundaries if they're not given */
{
int i;
guint rules_num = 0;
/* Use US rules, Windows' default is Pacific Standard Time */
if ((rules_num = rules_from_windows_time_zone ("Pacific Standard Time",
rules)))
{
for (i = 0; i < rules_num - 1; i++)
{
(*rules)[i].std_offset = - tzr.std_offset;
(*rules)[i].dlt_offset = - tzr.dlt_offset;
strcpy ((*rules)[i].std_name, tzr.std_name);
strcpy ((*rules)[i].dlt_name, tzr.dlt_name);
}
return rules_num;
}
else
return 0;
}
#else
return 0;
#endif
/* Start and end required (format 2) */
if (!parse_identifier_boundaries (&pos, &tzr))
return 0;
return create_ruleset_from_rule (rules, &tzr);
}
/* Construction {{{1 */
/**
* g_time_zone_new:
* @identifier: (nullable): a timezone identifier
*
* Creates a #GTimeZone corresponding to @identifier.
*
* @identifier can either be an RFC3339/ISO 8601 time offset or
* something that would pass as a valid value for the `TZ` environment
* variable (including %NULL).
*
* In Windows, @identifier can also be the unlocalized name of a time
* zone for standard time, for example "Pacific Standard Time".
*
* Valid RFC3339 time offsets are `"Z"` (for UTC) or
* `"±hh:mm"`. ISO 8601 additionally specifies
* `"±hhmm"` and `"±hh"`. Offsets are
* time values to be added to Coordinated Universal Time (UTC) to get
* the local time.
*
* In UNIX, the `TZ` environment variable typically corresponds
* to the name of a file in the zoneinfo database, or string in
* "std offset [dst [offset],start[/time],end[/time]]" (POSIX) format.
* There are no spaces in the specification. The name of standard
* and daylight savings time zone must be three or more alphabetic
* characters. Offsets are time values to be added to local time to
* get Coordinated Universal Time (UTC) and should be
* `"[±]hh[[:]mm[:ss]]"`. Dates are either
* `"Jn"` (Julian day with n between 1 and 365, leap
* years not counted), `"n"` (zero-based Julian day
* with n between 0 and 365) or `"Mm.w.d"` (day d
* (0 <= d <= 6) of week w (1 <= w <= 5) of month m (1 <= m <= 12), day
* 0 is a Sunday). Times are in local wall clock time, the default is
* 02:00:00.
*
* In Windows, the "tzn[+|–]hh[:mm[:ss]][dzn]" format is used, but also
* accepts POSIX format. The Windows format uses US rules for all time
* zones; daylight savings time is 60 minutes behind the standard time
* with date and time of change taken from Pacific Standard Time.
* Offsets are time values to be added to the local time to get
* Coordinated Universal Time (UTC).
*
* g_time_zone_new_local() calls this function with the value of the
* `TZ` environment variable. This function itself is independent of
* the value of `TZ`, but if @identifier is %NULL then `/etc/localtime`
* will be consulted to discover the correct time zone on UNIX and the
* registry will be consulted or GetTimeZoneInformation() will be used
* to get the local time zone on Windows.
*
* If intervals are not available, only time zone rules from `TZ`
* environment variable or other means, then they will be computed
* from year 1900 to 2037. If the maximum year for the rules is
* available and it is greater than 2037, then it will followed
* instead.
*
* See
* [RFC3339 §5.6](http://tools.ietf.org/html/rfc3339#section-5.6)
* for a precise definition of valid RFC3339 time offsets
* (the `time-offset` expansion) and ISO 8601 for the
* full list of valid time offsets. See
* [The GNU C Library manual](http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html)
* for an explanation of the possible
* values of the `TZ` environment variable. See
* [Microsoft Time Zone Index Values](http://msdn.microsoft.com/en-us/library/ms912391%28v=winembedded.11%29.aspx)
* for the list of time zones on Windows.
*
* You should release the return value by calling g_time_zone_unref()
* when you are done with it.
*
* Returns: the requested timezone
*
* Since: 2.26
**/
GTimeZone *
g_time_zone_new (const gchar *identifier)
{
GTimeZone *tz = NULL;
TimeZoneRule *rules;
gint rules_num;
G_LOCK (time_zones);
if (time_zones == NULL)
time_zones = g_hash_table_new (g_str_hash, g_str_equal);
if (identifier)
{
tz = g_hash_table_lookup (time_zones, identifier);
if (tz)
{
g_atomic_int_inc (&tz->ref_count);
G_UNLOCK (time_zones);
return tz;
}
}
tz = g_slice_new0 (GTimeZone);
tz->name = g_strdup (identifier);
tz->ref_count = 0;
zone_for_constant_offset (tz, identifier);
if (tz->t_info == NULL &&
(rules_num = rules_from_identifier (identifier, &rules)))
{
init_zone_from_rules (tz, rules, rules_num);
g_free (rules);
}
if (tz->t_info == NULL)
{
#ifdef G_OS_UNIX
GBytes *zoneinfo = zone_info_unix (identifier);
if (!zoneinfo)
zone_for_constant_offset (tz, "UTC");
else
{
init_zone_from_iana_info (tz, zoneinfo);
g_bytes_unref (zoneinfo);
}
#elif defined (G_OS_WIN32)
if ((rules_num = rules_from_windows_time_zone (identifier, &rules)))
{
init_zone_from_rules (tz, rules, rules_num);
g_free (rules);
}
}
if (tz->t_info == NULL)
{
if (identifier)
zone_for_constant_offset (tz, "UTC");
else
{
TIME_ZONE_INFORMATION tzi;
if (GetTimeZoneInformation (&tzi) != TIME_ZONE_ID_INVALID)
{
rules = g_new0 (TimeZoneRule, 2);
rule_from_windows_time_zone_info (&rules[0], &tzi);
memset (rules[0].std_name, 0, NAME_SIZE);
memset (rules[0].dlt_name, 0, NAME_SIZE);
rules[0].start_year = MIN_TZYEAR;
rules[1].start_year = MAX_TZYEAR;
init_zone_from_rules (tz, rules, 2);
g_free (rules);
}
}
#endif
}
if (tz->t_info != NULL)
{
if (identifier)
g_hash_table_insert (time_zones, tz->name, tz);
}
g_atomic_int_inc (&tz->ref_count);
G_UNLOCK (time_zones);
return tz;
}
/**
* g_time_zone_new_utc:
*
* Creates a #GTimeZone corresponding to UTC.
*
* This is equivalent to calling g_time_zone_new() with a value like
* "Z", "UTC", "+00", etc.
*
* You should release the return value by calling g_time_zone_unref()
* when you are done with it.
*
* Returns: the universal timezone
*
* Since: 2.26
**/
GTimeZone *
g_time_zone_new_utc (void)
{
return g_time_zone_new ("UTC");
}
/**
* g_time_zone_new_local:
*
* Creates a #GTimeZone corresponding to local time. The local time
* zone may change between invocations to this function; for example,
* if the system administrator changes it.
*
* This is equivalent to calling g_time_zone_new() with the value of
* the `TZ` environment variable (including the possibility of %NULL).
*
* You should release the return value by calling g_time_zone_unref()
* when you are done with it.
*
* Returns: the local timezone
*
* Since: 2.26
**/
GTimeZone *
g_time_zone_new_local (void)
{
return g_time_zone_new (getenv ("TZ"));
}
#define TRANSITION(n) g_array_index (tz->transitions, Transition, n)
#define TRANSITION_INFO(n) g_array_index (tz->t_info, TransitionInfo, n)
/* Internal helpers {{{1 */
/* NB: Interval 0 is before the first transition, so there's no
* transition structure to point to which TransitionInfo to
* use. Rule-based zones are set up so that TI 0 is always standard
* time (which is what's in effect before Daylight time got started
* in the early 20th century), but IANA tzfiles don't follow that
* convention. The tzfile documentation says to use the first
* standard-time (i.e., non-DST) tinfo, so that's what we do.
*/
inline static const TransitionInfo*
interval_info (GTimeZone *tz,
guint interval)
{
guint index;
g_return_val_if_fail (tz->t_info != NULL, NULL);
if (interval && tz->transitions && interval <= tz->transitions->len)
index = (TRANSITION(interval - 1)).info_index;
else
{
for (index = 0; index < tz->t_info->len; index++)
{
TransitionInfo *tzinfo = &(TRANSITION_INFO(index));
if (!tzinfo->is_dst)
return tzinfo;
}
index = 0;
}
return &(TRANSITION_INFO(index));
}
inline static gint64
interval_start (GTimeZone *tz,
guint interval)
{
if (!interval || tz->transitions == NULL || tz->transitions->len == 0)
return G_MININT64;
if (interval > tz->transitions->len)
interval = tz->transitions->len;
return (TRANSITION(interval - 1)).time;
}
inline static gint64
interval_end (GTimeZone *tz,
guint interval)
{
if (tz->transitions && interval < tz->transitions->len)
return (TRANSITION(interval)).time - 1;
return G_MAXINT64;
}
inline static gint32
interval_offset (GTimeZone *tz,
guint interval)
{
g_return_val_if_fail (tz->t_info != NULL, 0);
return interval_info (tz, interval)->gmt_offset;
}
inline static gboolean
interval_isdst (GTimeZone *tz,
guint interval)
{
g_return_val_if_fail (tz->t_info != NULL, 0);
return interval_info (tz, interval)->is_dst;
}
inline static gchar*
interval_abbrev (GTimeZone *tz,
guint interval)
{
g_return_val_if_fail (tz->t_info != NULL, 0);
return interval_info (tz, interval)->abbrev;
}
inline static gint64
interval_local_start (GTimeZone *tz,
guint interval)
{
if (interval)
return interval_start (tz, interval) + interval_offset (tz, interval);
return G_MININT64;
}
inline static gint64
interval_local_end (GTimeZone *tz,
guint interval)
{
if (tz->transitions && interval < tz->transitions->len)
return interval_end (tz, interval) + interval_offset (tz, interval);
return G_MAXINT64;
}
static gboolean
interval_valid (GTimeZone *tz,
guint interval)
{
if ( tz->transitions == NULL)
return interval == 0;
return interval <= tz->transitions->len;
}
/* g_time_zone_find_interval() {{{1 */
/**
* g_time_zone_adjust_time:
* @tz: a #GTimeZone
* @type: the #GTimeType of @time_
* @time_: a pointer to a number of seconds since January 1, 1970
*
* Finds an interval within @tz that corresponds to the given @time_,
* possibly adjusting @time_ if required to fit into an interval.
* The meaning of @time_ depends on @type.
*
* This function is similar to g_time_zone_find_interval(), with the
* difference that it always succeeds (by making the adjustments
* described below).
*
* In any of the cases where g_time_zone_find_interval() succeeds then
* this function returns the same value, without modifying @time_.
*
* This function may, however, modify @time_ in order to deal with
* non-existent times. If the non-existent local @time_ of 02:30 were
* requested on March 14th 2010 in Toronto then this function would
* adjust @time_ to be 03:00 and return the interval containing the
* adjusted time.
*
* Returns: the interval containing @time_, never -1
*
* Since: 2.26
**/
gint
g_time_zone_adjust_time (GTimeZone *tz,
GTimeType type,
gint64 *time_)
{
gint i;
guint intervals;
if (tz->transitions == NULL)
return 0;
intervals = tz->transitions->len;
/* find the interval containing *time UTC
* TODO: this could be binary searched (or better) */
for (i = 0; i <= intervals; i++)
if (*time_ <= interval_end (tz, i))
break;
g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
if (type != G_TIME_TYPE_UNIVERSAL)
{
if (*time_ < interval_local_start (tz, i))
/* if time came before the start of this interval... */
{
i--;
/* if it's not in the previous interval... */
if (*time_ > interval_local_end (tz, i))
{
/* it doesn't exist. fast-forward it. */
i++;
*time_ = interval_local_start (tz, i);
}
}
else if (*time_ > interval_local_end (tz, i))
/* if time came after the end of this interval... */
{
i++;
/* if it's not in the next interval... */
if (*time_ < interval_local_start (tz, i))
/* it doesn't exist. fast-forward it. */
*time_ = interval_local_start (tz, i);
}
else if (interval_isdst (tz, i) != type)
/* it's in this interval, but dst flag doesn't match.
* check neighbours for a better fit. */
{
if (i && *time_ <= interval_local_end (tz, i - 1))
i--;
else if (i < intervals &&
*time_ >= interval_local_start (tz, i + 1))
i++;
}
}
return i;
}
/**
* g_time_zone_find_interval:
* @tz: a #GTimeZone
* @type: the #GTimeType of @time_
* @time_: a number of seconds since January 1, 1970
*
* Finds an the interval within @tz that corresponds to the given @time_.
* The meaning of @time_ depends on @type.
*
* If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
* succeed (since universal time is monotonic and continuous).
*
* Otherwise @time_ is treated as local time. The distinction between
* %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
* the case that the given @time_ is ambiguous. In Toronto, for example,
* 01:30 on November 7th 2010 occurred twice (once inside of daylight
* savings time and the next, an hour later, outside of daylight savings
* time). In this case, the different value of @type would result in a
* different interval being returned.
*
* It is still possible for this function to fail. In Toronto, for
* example, 02:00 on March 14th 2010 does not exist (due to the leap
* forward to begin daylight savings time). -1 is returned in that
* case.
*
* Returns: the interval containing @time_, or -1 in case of failure
*
* Since: 2.26
*/
gint
g_time_zone_find_interval (GTimeZone *tz,
GTimeType type,
gint64 time_)
{
gint i;
guint intervals;
if (tz->transitions == NULL)
return 0;
intervals = tz->transitions->len;
for (i = 0; i <= intervals; i++)
if (time_ <= interval_end (tz, i))
break;
if (type == G_TIME_TYPE_UNIVERSAL)
return i;
if (time_ < interval_local_start (tz, i))
{
if (time_ > interval_local_end (tz, --i))
return -1;
}
else if (time_ > interval_local_end (tz, i))
{
if (time_ < interval_local_start (tz, ++i))
return -1;
}
else if (interval_isdst (tz, i) != type)
{
if (i && time_ <= interval_local_end (tz, i - 1))
i--;
else if (i < intervals && time_ >= interval_local_start (tz, i + 1))
i++;
}
return i;
}
/* Public API accessors {{{1 */
/**
* g_time_zone_get_abbreviation:
* @tz: a #GTimeZone
* @interval: an interval within the timezone
*
* Determines the time zone abbreviation to be used during a particular
* @interval of time in the time zone @tz.
*
* For example, in Toronto this is currently "EST" during the winter
* months and "EDT" during the summer months when daylight savings time
* is in effect.
*
* Returns: the time zone abbreviation, which belongs to @tz
*
* Since: 2.26
**/
const gchar *
g_time_zone_get_abbreviation (GTimeZone *tz,
gint interval)
{
g_return_val_if_fail (interval_valid (tz, (guint)interval), NULL);
return interval_abbrev (tz, (guint)interval);
}
/**
* g_time_zone_get_offset:
* @tz: a #GTimeZone
* @interval: an interval within the timezone
*
* Determines the offset to UTC in effect during a particular @interval
* of time in the time zone @tz.
*
* The offset is the number of seconds that you add to UTC time to
* arrive at local time for @tz (ie: negative numbers for time zones
* west of GMT, positive numbers for east).
*
* Returns: the number of seconds that should be added to UTC to get the
* local time in @tz
*
* Since: 2.26
**/
gint32
g_time_zone_get_offset (GTimeZone *tz,
gint interval)
{
g_return_val_if_fail (interval_valid (tz, (guint)interval), 0);
return interval_offset (tz, (guint)interval);
}
/**
* g_time_zone_is_dst:
* @tz: a #GTimeZone
* @interval: an interval within the timezone
*
* Determines if daylight savings time is in effect during a particular
* @interval of time in the time zone @tz.
*
* Returns: %TRUE if daylight savings time is in effect
*
* Since: 2.26
**/
gboolean
g_time_zone_is_dst (GTimeZone *tz,
gint interval)
{
g_return_val_if_fail (interval_valid (tz, interval), FALSE);
if (tz->transitions == NULL)
return FALSE;
return interval_isdst (tz, (guint)interval);
}
/* Epilogue {{{1 */
/* vim:set foldmethod=marker: */
| 27.86087 | 114 | 0.607502 |
d034384343c67f5e84cd0f232fc679216f6bc704 | 15,743 | h | C | src/openms/include/OpenMS/CHEMISTRY/NASequence.h | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 1 | 2022-03-23T09:45:02.000Z | 2022-03-23T09:45:02.000Z | src/openms/include/OpenMS/CHEMISTRY/NASequence.h | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 1 | 2018-04-02T18:07:10.000Z | 2018-04-02T18:07:10.000Z | src/openms/include/OpenMS/CHEMISTRY/NASequence.h | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 3 | 2018-01-10T19:50:48.000Z | 2021-11-12T15:56:13.000Z | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2021.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Samuel Wein $
// $Authors: Samuel Wein, Timo Sachsenberg, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CHEMISTRY/Ribonucleotide.h>
#include <vector>
#include <iosfwd>
namespace OpenMS
{
/**
* @brief Representation of a nucleic acid sequence
*
* NASequence represents nucleic acid sequences (RNA) in %OpenMS. Each NASequence consists
* of a vector of pointers to Ribonucleotides as well as RibonucleotideChainEnds representing
* the 5' and 3' ends of the sequence. Each Ribonucleotide has only a single instance.
* These are accessible through RibonucleotideDB. Modified Ribonucleotides are included in RibonucleotideDB
* and are expressed as the Modomics Short name surrounded by brackets when converted to string.
*
* @ingroup Chemistry
*/
class OPENMS_DLLAPI NASequence
{
/**
@brief an enum of all possible fragment ion types
*/
public:
enum NASFragmentType
{ //< NB: Not all fragments types are valid for all residue types, this class should probably get split
Full = 0, ///< with N-terminus and C-terminus
Internal, ///< internal, without any termini
FivePrime, ///< only 5' terminus
ThreePrime, ///< only 3' terminus
AIon, ///< MS:1001229 N-terminus up to the C-alpha/carbonyl carbon bond
BIon, ///< MS:1001224 N-terminus up to the peptide bond
CIon, ///< MS:1001231 N-terminus up to the amide/C-alpha bond
XIon, ///< MS:1001228 amide/C-alpha bond up to the C-terminus
YIon, ///< MS:1001220 peptide bond up to the C-terminus
ZIon, ///< MS:1001230 C-alpha/carbonyl carbon bond
Precursor, ///< MS:1001523 Precursor ion
BIonMinusH20, ///< MS:1001222 b ion without water
YIonMinusH20, ///< MS:1001223 y ion without water
BIonMinusNH3, ///< MS:1001232 b ion without ammonia
YIonMinusNH3, ///< MS:1001233 y ion without ammonia
NonIdentified, ///< MS:1001240 Non-identified ion
Unannotated, ///< no stored annotation
WIon, ///< W ion, added for nucleic acid support
AminusB, ///< A ion with base loss, added for nucleic acid support
DIon, ///< D ion, added for nucleic acid support
SizeOfNASFragmentType
};
using ConstRibonucleotidePtr = const Ribonucleotide*;
class Iterator;
/** @brief ConstIterator of NASequence class.
*
* References to the pointers are returned dereferenced.
* So we don't need to write (*iterator)->getCode(), but can simply use iterator->getCode().
*/
class OPENMS_DLLAPI ConstIterator
{
public:
typedef Ribonucleotide value_type;
typedef const value_type& const_reference;
typedef value_type& reference;
typedef const value_type* const_pointer;
typedef std::vector<const value_type*>::difference_type difference_type;
typedef const value_type* pointer;
typedef std::random_access_iterator_tag iterator_category;
/** @name Constructors and destructors
*/
//@{
/// default constructor
ConstIterator() = default;
/// detailed constructor with pointer to the vector and offset position
ConstIterator(const std::vector<const Ribonucleotide*>* vec_ptr,
difference_type position)
{
vector_ = vec_ptr;
position_ = position;
}
/// copy constructor
ConstIterator(const ConstIterator& rhs) :
vector_(rhs.vector_),
position_(rhs.position_)
{
}
/// copy constructor from Iterator
ConstIterator(const NASequence::Iterator& rhs) :
vector_(rhs.vector_),
position_(rhs.position_)
{
}
/// destructor
virtual ~ConstIterator() {}
//@}
/// assignment operator
ConstIterator& operator=(const ConstIterator& rhs)
{
if (this != &rhs)
{
position_ = rhs.position_;
vector_ = rhs.vector_;
}
return *this;
}
/** @name Operators
*/
//@{
/// dereference operator
const_reference operator*() const
{
return *(*vector_)[position_];
}
/// dereference operator
const_pointer operator->() const
{
return (*vector_)[position_];
}
/// forward jump operator
const ConstIterator operator+(difference_type diff) const
{
return ConstIterator(vector_, position_ + diff);
}
difference_type operator-(ConstIterator rhs) const
{
return position_ - rhs.position_;
}
/// backward jump operator
const ConstIterator operator-(difference_type diff) const
{
return ConstIterator(vector_, position_ - diff);
}
/// equality comparator
bool operator==(const ConstIterator& rhs) const
{
return (std::tie(vector_, position_) ==
std::tie(rhs.vector_, rhs.position_));
}
/// inequality operator
bool operator!=(const ConstIterator& rhs) const
{
return !(operator==(rhs));
}
/// increment operator
ConstIterator& operator++()
{
++position_;
return *this;
}
/// decrement operator
ConstIterator& operator--()
{
--position_;
return *this;
}
//@}
protected:
// pointer to the vector
const std::vector<const Ribonucleotide*>* vector_;
// position in the vector
difference_type position_;
};
/** @brief Iterator of NASequence class.
*
* References to the pointers are returned dereferenced.
* So we don't need to write (*iterator)->getCode(), but can simply use iterator->getCode().
*/
class OPENMS_DLLAPI Iterator
{
public:
friend class NASequence::ConstIterator;
typedef Ribonucleotide value_type;
typedef const value_type& const_reference;
typedef value_type& reference;
typedef const value_type* const_pointer;
typedef const value_type* pointer;
typedef std::vector<const value_type*>::difference_type difference_type;
/** @name Constructors and destructors
*/
//@{
Iterator() = default;
/// detailed constructor with pointer to the vector and offset position
Iterator(std::vector<const Ribonucleotide*>* vec_ptr,
difference_type position)
{
vector_ = vec_ptr;
position_ = position;
}
/// copy constructor
Iterator(const Iterator& rhs) :
vector_(rhs.vector_),
position_(rhs.position_)
{
}
/// destructor
virtual ~Iterator() {}
//@}
/// assignment operator
Iterator& operator=(const Iterator& rhs)
{
if (this != &rhs)
{
position_ = rhs.position_;
vector_ = rhs.vector_;
}
return *this;
}
/** @name Operators
*/
//@{
/// dereference operator
const_reference operator*() const
{
return *(*vector_)[position_];
}
/// dereference operator
const_pointer operator->() const
{
return (*vector_)[position_];
}
/// mutable dereference operator
pointer operator->()
{
return (*vector_)[position_];
}
/// forward jump operator
const Iterator operator+(difference_type diff) const
{
return Iterator(vector_, position_ + diff);
}
difference_type operator-(Iterator rhs) const
{
return position_ - rhs.position_;
}
/// backward jump operator
const Iterator operator-(difference_type diff) const
{
return Iterator(vector_, position_ - diff);
}
/// equality comparator
bool operator==(const Iterator& rhs) const
{
return (std::tie(vector_,position_) ==
std::tie(rhs.vector_, rhs.position_));
}
/// inequality operator
bool operator!=(const Iterator& rhs) const
{
return !this->operator==(rhs);
}
/// increment operator
Iterator& operator++()
{
++position_;
return *this;
}
/// decrement operator
Iterator& operator--()
{
--position_;
return *this;
}
//@}
protected:
std::vector<const Ribonucleotide*>* vector_;
// position in the vector
difference_type position_;
};
public:
/*
* Default constructors and assignment operators.
*/
NASequence() = default; /// default constructor
NASequence(const NASequence&) = default; ///< Copy constructor
NASequence(NASequence&&) = default; ///< Move constructor
NASequence& operator=(const NASequence&) & = default; ///< Copy assignment operator
NASequence& operator=(NASequence&&) & = default; ///< Move assignment operator
/// full constructor
NASequence(std::vector<const Ribonucleotide*> s,
const RibonucleotideChainEnd* five_prime,
const RibonucleotideChainEnd* three_prime);
virtual ~NASequence() = default; /// destructor
bool operator==(const NASequence& rhs) const; ///< element-wise equality
bool operator!=(const NASequence& rhs) const; ///< not quality
bool operator<(const NASequence& rhs) const; ///< less operator
/// getter / setter for sequence
void setSequence(const std::vector<const Ribonucleotide*>& seq);
const std::vector<const Ribonucleotide*>& getSequence() const
{
return seq_;
}
std::vector<const Ribonucleotide*>& getSequence()
{
return seq_;
}
/// getter / setter for ribonucleotide elements (easily wrapped using pyOpenMS)
void set(size_t index, const Ribonucleotide* r);
const Ribonucleotide* get(size_t index)
{
return seq_[index];
}
/// getter / setter for sequence elements (C++ container style)
inline const Ribonucleotide*& operator[](size_t index)
{
return seq_[index];
}
inline const Ribonucleotide* const& operator[](size_t index) const
{
return seq_[index];
}
bool empty() const;
size_t size() const;
void clear();
/// 5' and 3' modifications
bool hasFivePrimeMod() const;
void setFivePrimeMod(const RibonucleotideChainEnd* r);
const RibonucleotideChainEnd* getFivePrimeMod() const;
bool hasThreePrimeMod() const;
void setThreePrimeMod(const RibonucleotideChainEnd* r);
const RibonucleotideChainEnd* getThreePrimeMod() const;
/// iterators
inline Iterator begin()
{
return Iterator(&seq_, 0);
}
inline ConstIterator begin() const
{
return ConstIterator(&seq_, 0);
}
inline Iterator end()
{
return Iterator(&seq_, (Int) seq_.size());
}
inline ConstIterator end() const
{
return ConstIterator(&seq_, (Int) seq_.size());
}
inline ConstIterator cbegin() const
{
return ConstIterator(&seq_, 0);
}
inline ConstIterator cend() const
{
return ConstIterator(&seq_, (Int) seq_.size());
}
/// utility functions
double getMonoWeight(NASFragmentType type = Full, Int charge = 0) const;
double getAverageWeight(NASFragmentType type = Full, Int charge = 0) const;
EmpiricalFormula getFormula(NASFragmentType type = Full, Int charge = 0) const;
/// Return sequence prefix of the given length (not end index!)
NASequence getPrefix(Size length) const;
/// Return sequence suffix of the given length (not start index!)
NASequence getSuffix(Size length) const;
/// Return subsequence with given starting position and length
NASequence getSubsequence(Size start = 0, Size length = Size(-1)) const;
/**
@brief create NASequence object by parsing an OpenMS string
@param s Input string
@throws Exception::ParseError if an invalid string representation of a nucleic acid sequence is passed
*/
static NASequence fromString(const String& s);
/** @name Stream operators
writes a NASequence to an output stream
*/
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os,
const NASequence& seq);
/**
@brief create NASequence object by parsing a C string (character array)
@param s Input string
@throws Exception::ParseError if an invalid string representation of a nucleic acid sequence is passed
*/
static NASequence fromString(const char* s);
std::string toString() const ;
private:
//TODO: query RNA / DNA depending on type
static void parseString_(const String& s, NASequence& nas);
/**
@brief Parses modifications in square brackets
@param str_it Current position in the string to be parsed
@param str Full input string
@param aas Current AASequence object (will be modified with the correct ribo added)
@return Position at which to continue parsing
*/
//TODO: query RNA / DNA depending on type
static String::ConstIterator parseMod_(const String::ConstIterator str_it,
const String& str, NASequence& nas);
std::vector<const Ribonucleotide*> seq_;
const RibonucleotideChainEnd* five_prime_ = nullptr;
const RibonucleotideChainEnd* three_prime_ = nullptr;
};
}
| 30.391892 | 123 | 0.620276 |
d03e90f00dc267825436dcab2aa19437d1bd5a42 | 661 | c | C | port/hfermion-import.c | usqcd-software/clover | a92569b1af34afe9d7cc22f83a3305b5a743ed45 | [
"MIT"
] | 1 | 2020-08-24T06:44:29.000Z | 2020-08-24T06:44:29.000Z | port/hfermion-import.c | usqcd-software/clover | a92569b1af34afe9d7cc22f83a3305b5a743ed45 | [
"MIT"
] | null | null | null | port/hfermion-import.c | usqcd-software/clover | a92569b1af34afe9d7cc22f83a3305b5a743ed45 | [
"MIT"
] | null | null | null | #include <clover.h>
int
QX(import_half_fermion)(struct QX(HalfFermion) **half_fermion_ptr,
struct Q(State) *state,
double (*reader)(const int pos[4],
int color,
int dirac,
int re_im,
void *env),
void *env)
{
if (QX(allocate_half_fermion)(half_fermion_ptr, state) != 0)
return 1;
BEGIN_TIMING(state);
qx(x_import)(&state->even, (*half_fermion_ptr)->even, reader, env);
END_TIMING(state, 0, 0, 0);
return 0;
}
| 30.045455 | 69 | 0.447806 |
a96095f049698015e24237c5dbc34c7bd8905823 | 1,301 | h | C | install/halodi_msgs/include/halodi_msgs/msg/contact_point_command__rosidl_typesupport_fastrtps_c.h | AHGOverbeek/halodi-messages | 4286676cb85cc4d5b2684523c1482afc9eef6ec9 | [
"Apache-2.0"
] | null | null | null | install/halodi_msgs/include/halodi_msgs/msg/contact_point_command__rosidl_typesupport_fastrtps_c.h | AHGOverbeek/halodi-messages | 4286676cb85cc4d5b2684523c1482afc9eef6ec9 | [
"Apache-2.0"
] | 3 | 2020-11-05T14:53:41.000Z | 2021-04-27T13:40:47.000Z | install/halodi_msgs/include/halodi_msgs/msg/contact_point_command__rosidl_typesupport_fastrtps_c.h | AHGOverbeek/halodi-messages | 4286676cb85cc4d5b2684523c1482afc9eef6ec9 | [
"Apache-2.0"
] | 1 | 2021-10-05T14:08:08.000Z | 2021-10-05T14:08:08.000Z | // generated from rosidl_typesupport_fastrtps_c/resource/idl__rosidl_typesupport_fastrtps_c.h.em
// with input from halodi_msgs:msg/ContactPointCommand.idl
// generated code does not contain a copyright notice
#ifndef HALODI_MSGS__MSG__CONTACT_POINT_COMMAND__ROSIDL_TYPESUPPORT_FASTRTPS_C_H_
#define HALODI_MSGS__MSG__CONTACT_POINT_COMMAND__ROSIDL_TYPESUPPORT_FASTRTPS_C_H_
#include <stddef.h>
#include "rosidl_generator_c/message_type_support_struct.h"
#include "rosidl_typesupport_interface/macros.h"
#include "halodi_msgs/msg/rosidl_typesupport_fastrtps_c__visibility_control.h"
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_FASTRTPS_C_PUBLIC_halodi_msgs
size_t get_serialized_size_halodi_msgs__msg__ContactPointCommand(
const void * untyped_ros_message,
size_t current_alignment);
ROSIDL_TYPESUPPORT_FASTRTPS_C_PUBLIC_halodi_msgs
size_t max_serialized_size_halodi_msgs__msg__ContactPointCommand(
bool & full_bounded,
size_t current_alignment);
ROSIDL_TYPESUPPORT_FASTRTPS_C_PUBLIC_halodi_msgs
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, halodi_msgs, msg, ContactPointCommand)();
#ifdef __cplusplus
}
#endif
#endif // HALODI_MSGS__MSG__CONTACT_POINT_COMMAND__ROSIDL_TYPESUPPORT_FASTRTPS_C_H_
| 35.162162 | 124 | 0.883167 |
04a680d3852a105cd72bfdb459fe4e1cdd602a66 | 1,036 | c | C | zest5/zad2/slave.c | kamilok1965/operating-systems | 6686a6f3803ab6fe256e611b99bcc835e4abb21a | [
"MIT"
] | null | null | null | zest5/zad2/slave.c | kamilok1965/operating-systems | 6686a6f3803ab6fe256e611b99bcc835e4abb21a | [
"MIT"
] | null | null | null | zest5/zad2/slave.c | kamilok1965/operating-systems | 6686a6f3803ab6fe256e611b99bcc835e4abb21a | [
"MIT"
] | null | null | null | //
// Created by kamil on 17.04.18.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <zconf.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#define BUFFER_SIZE 512
int main(int argc, char **argv){
if(argc < 3){
printf("Too few arguments. Usage: slave <path> <count>\r\n");
exit(EXIT_FAILURE);
}
int fifo = open(argv[1], O_WRONLY);
if (fifo < 0) {
printf ("Error opening fifo\r\n");
exit(EXIT_FAILURE);
}
printf("PID: %i\r\n", getpid());
int n = atoi(argv[2]);
srand((unsigned int)time(NULL));
FILE *date;
char date_buffer[sizeof(char)*40];
char buffer[BUFFER_SIZE];
for(int i = 0; i < n; i++){
date = popen("date", "r");
fgets(date_buffer, sizeof(char)*40, date);
fclose(date);
sprintf(buffer, "%i - %s", getpid(), date_buffer);
write(fifo, buffer, strlen(buffer));
sleep((unsigned int)(rand() % 4 + 2));
}
close(fifo);
return 0;
} | 22.042553 | 69 | 0.563707 |
04a73715ebaa187ab9978ff9ec9fc6cb88306f87 | 563 | c | C | clang/test/Frontend/round-trip-cc1-args.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | clang/test/Frontend/round-trip-cc1-args.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang/test/Frontend/round-trip-cc1-args.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | // RUN: %clang_cc1 %s -no-round-trip-args -Rround-trip-cc1-args 2>&1 | FileCheck %s -check-prefix=CHECK-WITHOUT-ROUND-TRIP -allow-empty
// RUN: %clang_cc1 %s -round-trip-args 2>&1 | FileCheck %s -check-prefix=CHECK-ROUND-TRIP-WITHOUT-REMARKS -allow-empty
// RUN: %clang_cc1 %s -round-trip-args -Rround-trip-cc1-args 2>&1 | FileCheck %s -check-prefix=CHECK-ROUND-TRIP-WITH-REMARKS
// CHECK-WITHOUT-ROUND-TRIP-NOT: remark:
// CHECK-ROUND-TRIP-WITHOUT-REMARKS-NOT: remark:
// CHECK-ROUND-TRIP-WITH-REMARKS: remark: generated arguments #{{.*}} in round-trip: {{.*}}
| 70.375 | 135 | 0.717584 |
04b729aba7e03e4a030ee122edbe1bd820c8ea65 | 2,551 | h | C | Source/Resource.h | MissclickStudios/The-Mandalorian-Sands-of-Arvala | 346081b26409a33f129189dbcd5a830d6d58f7da | [
"MIT"
] | 1 | 2021-05-14T13:08:40.000Z | 2021-05-14T13:08:40.000Z | Source/Resource.h | MissclickStudios/The-Mandalorian-Sands-of-Arvala | 346081b26409a33f129189dbcd5a830d6d58f7da | [
"MIT"
] | null | null | null | Source/Resource.h | MissclickStudios/The-Mandalorian-Sands-of-Arvala | 346081b26409a33f129189dbcd5a830d6d58f7da | [
"MIT"
] | 1 | 2021-07-05T08:18:36.000Z | 2021-07-05T08:18:36.000Z | #ifndef __RESOURCE_H__
#define __RESOURCE_H__
#include <vector>
#include <string>
#include "Log.h"
#include "ImportSettings.h" // No need to centralize it, each resource will have their own settings.
#include "Macros.h"
class ParsonNode;
typedef unsigned int uint;
typedef unsigned __int32 uint32;
enum class ResourceType // IMPORTANT: Do not change the order of the Types! This will create a conflict with the saved files.
{
MODEL,
MESH,
MATERIAL,
TEXTURE,
FOLDER,
ANIMATION,
SCENE,
SHADER,
PARTICLE_SYSTEM,
PREFAB,
SCRIPT,
NAVMESH,
NONE
};
class MISSCLICK_API Resource
{
public:
Resource(ResourceType type);
virtual ~Resource();
virtual bool CleanUp();
virtual bool SaveMeta(ParsonNode& metaRoot) const;
virtual bool LoadMeta(const ParsonNode& metaRoot);
virtual inline ResourceType GetType() { return type; }
public:
ResourceType GetType() const; //
const char* GetTypeAsString() const; //
uint32 GetUID() const; //
void ForceUID(const uint32& UID); //
uint GetReferences() const; //
void SetReferences(const uint& references); //
void ModifyReferences(int modification); //
public:
const char* GetAssetsPath() const; //
const char* GetAssetsFile() const; //
const char* GetLibraryPath() const; //
const char* GetLibraryFile() const; //
void SetAssetsPath(const char* assetsPath); //
void SetAssetsFile(const char* assetsFile); //
void SetLibraryPath(const char* libraryPath); //
void SetLibraryFile(const char* libraryFile); //
void SetAssetsPathAndFile(const char* assetsPath, const char* assetsFile); //
void SetLibraryPathAndFile(); //
public:
bool hasForcedUID;
private:
ResourceType type;
uint32 uid; // UID for this Resource.
uint references;
std::string assetsPath; // Path of the file in the Assets directory. Will be used to avoid making duplicates.
std::string assetsFile; // File and extension string of the texture in the Assets directory.
std::string libraryPath; // Path of the file in the Library directory. Will be used to avoid making duplicates.
std::string libraryFile; // File and extension string of the texture in the Library directory.
ImportSettings importSettings;
};
#endif // !__RESOURCE_H__ | 28.988636 | 137 | 0.640925 |
04e3c1b6b2a374da3f9983a9cb431e075e457984 | 3,322 | c | C | demo/posix/main.c | dwtscript/dwt | ca0c0b0edb5cc6318f384121fe5630fc7fced598 | [
"MIT"
] | 1 | 2022-01-05T21:31:50.000Z | 2022-01-05T21:31:50.000Z | demo/posix/main.c | dwtscript/dwt | ca0c0b0edb5cc6318f384121fe5630fc7fced598 | [
"MIT"
] | 1 | 2022-03-27T14:13:42.000Z | 2022-03-27T14:13:42.000Z | demo/posix/main.c | dwtscript/dwt | ca0c0b0edb5cc6318f384121fe5630fc7fced598 | [
"MIT"
] | 1 | 2021-12-02T22:42:24.000Z | 2021-12-02T22:42:24.000Z | /* SPDX-FileCopyrightText: (c) 2021 Andrew Scott-Jones <andrew@dwtscript.org>
* SPDX-License-Identifier: MIT
*/
#include <dwt.h>
#include <dwt/config.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#define HEAP_SIZE (65536)
CFG_CHECK
enum
{
MODE_INTERACTIVE,
MODE_SCRIPT
};
static int mode = MODE_INTERACTIVE;
static int load_snapshot = 0;
static char *script_file = NULL;
void
parse_args(int argc, char **argv)
{
int opt = 0;
while ((opt = getopt(argc, argv, "si")) != -1)
{
switch (opt)
{
case 's':
load_snapshot = 1;
break;
default:
fprintf(stderr, "Usage: %s [-s] [file]\n", argv[0]);
break;
}
}
if (optind < argc)
{
script_file = argv[optind];
mode = MODE_SCRIPT;
}
}
static int
load_file(u8 **buffer, size_t *size, const char *filename)
{
FILE *script = fopen(filename, "r");
if (script == NULL)
{
return -1;
}
if (fseek(script, 0, SEEK_END) != 0)
{
fclose(script);
return -1;
}
int nr_bytes = ftell(script);
if (nr_bytes == -1)
{
fclose(script);
return -1;
}
else if (fseek(script, 0, SEEK_SET) != 0)
{
fclose(script);
return -1;
}
u8 *bytes = malloc(nr_bytes);
if (bytes == NULL)
{
fclose(script);
return -1;
}
for (int i = 0; i < nr_bytes; ++i)
{
int byte = fgetc(script);
bytes[i] = byte;
if (byte == EOF)
{
break;
}
}
fclose(script);
*buffer = bytes;
*size = nr_bytes;
return 0;
}
static void *code_heap = NULL;
static void *data_heap = NULL;
static int
alloc_heaps(void)
{
code_heap = malloc(HEAP_SIZE);
if (code_heap == NULL)
{
return -1;
}
data_heap = malloc(HEAP_SIZE);
if (data_heap == NULL)
{
free(code_heap);
return -1;
}
return 0;
}
static void
free_heaps(void)
{
if (code_heap != NULL)
{
free(code_heap);
}
if (data_heap != NULL)
{
free(data_heap);
}
}
static int
from_file(const char *filename)
{
u8 *buffer = NULL;
size_t nr_bytes = 0;
void *dwt = NULL;
int r = load_file(&buffer, &nr_bytes, filename);
if (r != 0)
{
return -1;
}
dwt = dwt_setup(code_heap, HEAP_SIZE, data_heap, HEAP_SIZE);
if (dwt == NULL)
{
free(buffer);
return -1;
}
r = dwt_script(dwt, buffer, nr_bytes);
free(buffer);
return r;
}
#if CONFIG_DWT_FEAT_REPL
static int
interactive(dwt_t dwt)
{
const size_t nr_bytes = 1024;
u8 *buffer = malloc(nr_bytes);
if (buffer == NULL)
{
return -1;
}
if (dwt == NULL)
{
dwt = dwt_setup(code_heap, HEAP_SIZE, data_heap, HEAP_SIZE);
}
if (dwt == NULL)
{
free(buffer);
return -1;
}
int r = dwt_prompt(dwt, buffer, nr_bytes);
free(buffer);
return r;
}
#endif
int
main(int argc, char **argv)
{
dwt_t dwt = NULL;
int r = 1;
(void) dwt;
parse_args(argc, argv);
r = alloc_heaps();
if (r != 0)
{
return 1;
}
if (load_snapshot)
{
dwt = dwt_load_filename(
"snapshot.dss",
code_heap,
HEAP_SIZE,
data_heap,
HEAP_SIZE);
}
else if (mode == MODE_SCRIPT)
{
r = from_file(script_file);
}
#if CONFIG_DWT_FEAT_REPL
if (mode == MODE_INTERACTIVE)
{
r = interactive(dwt);
}
#endif
free_heaps();
return r;
}
| 13.395161 | 77 | 0.577664 |
a602b49cfa34f221cc73a0b22ba9a6e6b9460b2d | 935 | h | C | widgets/WTabs.h | EmperDeon/Organizer | 94b7be51290027a15a68d7b2e98dd49840822a5d | [
"MIT"
] | 1 | 2017-09-27T11:56:00.000Z | 2017-09-27T11:56:00.000Z | widgets/WTabs.h | EmperDeon/Organizer | 94b7be51290027a15a68d7b2e98dd49840822a5d | [
"MIT"
] | null | null | null | widgets/WTabs.h | EmperDeon/Organizer | 94b7be51290027a15a68d7b2e98dd49840822a5d | [
"MIT"
] | null | null | null | /*
Copyright (c) 2017-2018 by Ilya Barykin
Released under the MIT License.
See the provided LICENSE.TXT file for details.
*/
#ifndef ORGANIZER_WTABWIDGET_H
#define ORGANIZER_WTABWIDGET_H
#include <QtWidgets/QTabWidget>
#include <tabs/Tab.h>
#include <tabs/TabsController.h>
#include <widgets/groups/WTGroups.h>
class WMain;
class TabsController;
class WTGroups;
class WTabs : public QTabWidget {
WMain *main;
TabsController *contr;
Tab *newTab = nullptr;
WTGroups *groups;
public:
explicit WTabs(WMain *m);
void tabClose();
void tabChange(int i);
Tab *getTab(int i) { return dynamic_cast<Tab *>(widget(i)); }
Tab *getCurrentTab() { return dynamic_cast<Tab *>(currentWidget()); }
void cycleGroup();
void groupBy(QString group = "");
void setGroupsMenu(QMenu *menu);
void tabMove(int from, int to);
friend class WTGroups;
};
#endif //ORGANIZER_WTABWIDGET_H
| 17.314815 | 73 | 0.695187 |
bd440d71e15110ff0cecc066f61013443f3bfabe | 3,221 | h | C | Celestial.framework/FigCaptureCalibrationContext.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 4 | 2021-10-06T12:15:26.000Z | 2022-02-21T02:26:00.000Z | Celestial.framework/FigCaptureCalibrationContext.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | null | null | null | Celestial.framework/FigCaptureCalibrationContext.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 1 | 2021-10-08T07:40:53.000Z | 2021-10-08T07:40:53.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/Celestial.framework/Celestial
*/
@interface FigCaptureCalibrationContext : NSObject {
NSString * _activityName;
unsigned long long _expectedDataSize;
NSString * _internalLogName;
int _interval;
NSMutableDictionary * _lastSuccessfulCalibrationData;
struct {
double x;
double y;
double z;
} _lastSuccessfulCalibrationMagneticField;
double _lastSuccessfulCalibrationTimeStamp;
int _minimumBatteryLevelToRun;
NSString * _preferenceString;
NSString * _propertyName;
NSArray * _supportedDevices;
}
@property (nonatomic, readonly) NSString *activityName;
@property (nonatomic, readonly) unsigned long long expectedDataSize;
@property (nonatomic, readonly) int interval;
@property (nonatomic, retain) NSDictionary *lastSuccessfulCalibrationData;
@property (nonatomic) struct { double x1; double x2; double x3; } lastSuccessfulCalibrationMagneticField;
@property (nonatomic) double lastSuccessfulCalibrationTimeStamp;
@property (nonatomic, readonly) int minimumBatteryLevelToRun;
@property (nonatomic, readonly) NSString *propertyName;
+ (id)calibrationDataStringForInternalLogging:(id)arg1;
+ (unsigned int)calibrationStatusFromRawStreamCalibrationData:(id)arg1;
+ (id)createRawStreamCalibrationDataWithFailureReasons:(int)arg1;
+ (void)initialize;
+ (void)printDebugInfoForRawStreamCalibrationData:(id)arg1;
+ (void)setStatusForCalibrationData:(id)arg1 status:(int)arg2;
- (id)_createDictionaryForFailureOutsideFirmwareWithReasons:(unsigned int)arg1;
- (unsigned int)_updateAndStashCalibrationData:(id)arg1 externalErrors:(unsigned int)arg2 hasFirmwareErrors:(bool)arg3 magneticFieldAttempts:(int)arg4 magneticField:(struct { double x1; double x2; double x3; })arg5;
- (void)_writeCalibrationDataToInternalLogFile:(id)arg1 magneticField:(struct { double x1; double x2; double x3; })arg2;
- (id)activityName;
- (id)calibrationDataHistory;
- (unsigned long long)expectedDataSize;
- (id)initWithPreferenceString:(id)arg1 withActivityName:(id)arg2 withPropertyName:(id)arg3 withExpectedDataSize:(unsigned long long)arg4 withInterval:(int)arg5 withMinimumBatteryLevel:(int)arg6 withInternalLogName:(id)arg7 supportedDeviceNames:(id)arg8;
- (id)initWithSupportedDeviceNames:(id)arg1;
- (int)interval;
- (id)lastSuccessfulCalibrationData;
- (struct { double x1; double x2; double x3; })lastSuccessfulCalibrationMagneticField;
- (double)lastSuccessfulCalibrationTimeStamp;
- (int)minimumBatteryLevelToRun;
- (id)propertyName;
- (void)pushCalibrationDataToHistory:(id)arg1 isRejected:(bool*)arg2;
- (void)reportForAggdLoggingWithCalibrationData:(id)arg1 isValid:(bool)arg2 magneticFieldMagnitude:(double)arg3;
- (void)setLastSuccessfulCalibrationData:(id)arg1;
- (void)setLastSuccessfulCalibrationMagneticField:(struct { double x1; double x2; double x3; })arg1;
- (void)setLastSuccessfulCalibrationTimeStamp:(double)arg1;
- (void)updateWithNewCalibrationData:(id)arg1 orExternalErrors:(unsigned int)arg2 magneticFieldAttempts:(int)arg3 magneticField:(struct { double x1; double x2; double x3; })arg4 isCalibrationValid:(bool*)arg5 calibrationStatus:(unsigned int*)arg6;
@end
| 52.803279 | 254 | 0.801304 |
64bcf70846f299875cb56b148aecf83246b1d8c6 | 2,021 | h | C | chrome/browser/ui/cocoa/location_bar/plus_decoration.h | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/cocoa/location_bar/plus_decoration.h | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/cocoa/location_bar/plus_decoration.h | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_COCOA_LOCATION_BAR_PLUS_DECORATION_H_
#define CHROME_BROWSER_UI_COCOA_LOCATION_BAR_PLUS_DECORATION_H_
#import <Cocoa/Cocoa.h>
#include "base/mac/scoped_nsobject.h"
#include "chrome/browser/ui/cocoa/location_bar/button_decoration.h"
#include "chrome/browser/ui/toolbar/action_box_button_controller.h"
@class ActionBoxMenuBubbleController;
class Browser;
class LocationBarViewMac;
// Note: this file is under development (see crbug.com/138118).
// Plus icon on the right side of the location bar.
class PlusDecoration : public ButtonDecoration,
public ActionBoxButtonController::Delegate {
public:
PlusDecoration(LocationBarViewMac* owner, Browser* browser);
virtual ~PlusDecoration();
// Helper to get where the action box menu and bubble point should be
// anchored. Similar to |PageActionDecoration| or |StarDecoration|.
NSPoint GetActionBoxAnchorPoint();
// Sets or clears a temporary icon for the button.
void ResetIcon();
void SetTemporaryIcon(int image_id);
// Implement |LocationBarDecoration|.
virtual bool AcceptsMousePress() OVERRIDE;
virtual bool OnMousePressed(NSRect frame) OVERRIDE;
virtual NSString* GetToolTip() OVERRIDE;
ActionBoxButtonController* action_box_button_controller() {
return &controller_;
}
private:
// Implement |ActionBoxButtonController::Delegate|.
virtual void ShowMenu(scoped_ptr<ActionBoxMenuModel> model) OVERRIDE;
// Owner of the decoration, used to obtain the menu.
LocationBarViewMac* owner_;
Browser* browser_;
ActionBoxButtonController controller_;
void SetIcons(int normal_id, int hover_id, int pressed_id);
base::scoped_nsobject<ActionBoxMenuBubbleController> menu_controller_;
DISALLOW_COPY_AND_ASSIGN(PlusDecoration);
};
#endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_PLUS_DECORATION_H_
| 32.079365 | 73 | 0.785255 |
26cfbe263b1288f09cd0f33fb47fe8d4874d5349 | 671 | h | C | libs/ofxLineaDeTiempo/include/ofx/LineaDeTiempo/Utils/FontUtils.h | roymacdonald/ofxLineaDeTiempo | 1a080c7d5533dc9b0e587bd1557506fe288f05e8 | [
"MIT"
] | 31 | 2020-04-29T06:11:54.000Z | 2021-11-10T19:14:09.000Z | libs/ofxLineaDeTiempo/include/ofx/LineaDeTiempo/Utils/FontUtils.h | roymacdonald/ofxLineaDeTiempo | 1a080c7d5533dc9b0e587bd1557506fe288f05e8 | [
"MIT"
] | 11 | 2020-07-27T17:12:05.000Z | 2021-12-01T16:33:18.000Z | libs/ofxLineaDeTiempo/include/ofx/LineaDeTiempo/Utils/FontUtils.h | roymacdonald/ofxLineaDeTiempo | 1a080c7d5533dc9b0e587bd1557506fe288f05e8 | [
"MIT"
] | null | null | null | //
// FontUtils.h
// example
//
// Created by Roy Macdonald on 4/11/20.
//
#pragma once
#include "ofTrueTypeFont.h"
namespace ofx {
namespace LineaDeTiempo {
static inline float getTextVCenteredPos( const ofRectangle& container, const ofTrueTypeFont& font)
{
return container.getCenter().y + (font.getAscenderHeight() + font.getDescenderHeight()) *0.5;
}
static inline void drawTextCentered(const std::string& text, const ofRectangle& container, const ofTrueTypeFont& font){
float y = getTextVCenteredPos(container, font);
float x = container.x + (container.width - font.stringWidth(text))*0.5;
font.drawString(text, x, y);
}
}} //ofx::LineaDeTiempo
| 22.366667 | 119 | 0.727273 |
1e30011414a4bf83c877a658adbf7794cd6d2745 | 10,442 | c | C | tests/api/test-dev-valstack-checked-size-call.c | wenq1/duktape | 5ed3eee19b291f3b3de0b212cc62c0aba0ab4ecb | [
"MIT"
] | 2 | 2019-10-15T06:01:16.000Z | 2019-12-21T14:32:50.000Z | tests/api/test-dev-valstack-checked-size-call.c | KiraanRK/esp32-duktape | 1b7fbcb8bd6bfc346d92df30ec099df7f13b03aa | [
"MIT"
] | null | null | null | tests/api/test-dev-valstack-checked-size-call.c | KiraanRK/esp32-duktape | 1b7fbcb8bd6bfc346d92df30ec099df7f13b03aa | [
"MIT"
] | null | null | null | /*
* Once a certain Duktape/C function invocation has "checked" the value
* stack to contain space for at least N elements, this reserve should
* not be reduced without warning.
*
* In Duktape 0.11.0 function calls (Ecmascript or Duktape/C) would
* essentially reset the "checked" stack size. This testcase demonstrates
* the issue and documents the desired behavior.
*/
/*===
*** test_ecma_call_success (duk_safe_call)
hello from ecma func
duk_call: 123
final top: 10001
==> rc=0, result='undefined'
*** test_ecma_call_error (duk_safe_call)
hello from ecma func
==> rc=1, result='Error: ecma thrown'
*** test_ecma_pcall_success (duk_safe_call)
hello from ecma func
duk_pcall: rc=0, value: 123
final top: 10001
==> rc=0, result='undefined'
*** test_ecma_pcall_error (duk_safe_call)
hello from ecma func
duk_pcall: rc=1, value: Error: ecma thrown
final top: 10001
==> rc=0, result='undefined'
*** test_c_call_success (duk_safe_call)
hello from my_func_success
duk_call: 234
final top: 10001
==> rc=0, result='undefined'
*** test_c_call_error1 (duk_safe_call)
hello from my_func_error1
==> rc=1, result='Error: error thrown by my_func_error1'
*** test_c_call_error2 (duk_safe_call)
hello from my_func_error2
==> rc=1, result='URIError: error (rc -7)'
*** test_c_pcall_success (duk_safe_call)
hello from my_func_success
duk_pcall: rc=0, value: 234
final top: 10001
==> rc=0, result='undefined'
*** test_c_pcall_error1 (duk_safe_call)
hello from my_func_error1
duk_pcall: rc=1, value: Error: error thrown by my_func_error1
final top: 10001
==> rc=0, result='undefined'
*** test_c_pcall_error2 (duk_safe_call)
hello from my_func_error2
duk_pcall: rc=1, value: URIError: error (rc -7)
final top: 10001
==> rc=0, result='undefined'
*** test_safe_call_success (duk_safe_call)
hello from my_safe_func_success
duk_safe_call: rc=0, value: 123
final top: 10001
==> rc=0, result='undefined'
*** test_safe_call_error1 (duk_safe_call)
hello from my_safe_func_error1
duk_safe_call: rc=1, value: Error: error thrown by my_safe_func_error1
final top: 10001
==> rc=0, result='undefined'
*** test_safe_call_error2 (duk_safe_call)
hello from my_safe_func_error2
duk_safe_call: rc=1, value: URIError: error (rc -7)
final top: 10001
==> rc=0, result='undefined'
===*/
#define STACK_REQUIRE 10000
static duk_ret_t my_func_success(duk_context *ctx) {
printf("hello from my_func_success\n");
duk_push_int(ctx, 234);
return 1;
}
static duk_ret_t my_func_error1(duk_context *ctx) {
printf("hello from my_func_error1\n");
duk_error(ctx, 123, "error thrown by my_func_error1");
return 0;
}
static duk_ret_t my_func_error2(duk_context *ctx) {
printf("hello from my_func_error2\n");
return DUK_RET_URI_ERROR;
}
static duk_ret_t my_safe_func_success(duk_context *ctx, void *udata) {
(void) udata;
printf("hello from my_safe_func_success\n");
duk_push_int(ctx, 123);
duk_push_int(ctx, 234);
return 2; /* caller wants 1 ret only, so 123 is effective */
}
static duk_ret_t my_safe_func_error1(duk_context *ctx, void *udata) {
(void) udata;
printf("hello from my_safe_func_error1\n");
duk_error(ctx, 123, "error thrown by my_safe_func_error1");
duk_push_int(ctx, 123);
duk_push_int(ctx, 234);
return 2; /* caller wants 1 ret only, so 123 is effective */
}
static duk_ret_t my_safe_func_error2(duk_context *ctx, void *udata) {
(void) udata;
printf("hello from my_safe_func_error2\n");
duk_push_int(ctx, 123);
duk_push_int(ctx, 234);
return DUK_RET_URI_ERROR;
}
static duk_ret_t test_ecma_call_success(duk_context *ctx, void *udata) {
duk_idx_t i;
(void) udata;
/* Ensure stack space for a lot of elements. */
duk_require_stack(ctx, STACK_REQUIRE + 1);
/* Make a function call. Call handling resizes the value stack
* back and forth. At the end, the value stack guaranteed size
* must include the STACK_REQUIRE checked above.
*/
duk_eval_string(ctx, "(function () { print('hello from ecma func'); return 123 })");
duk_call(ctx, 0 /*nargs*/);
printf("duk_call: %s\n", duk_safe_to_string(ctx, -1));
/* It would be quite awkward for user code to have no stack
* guarantees at this point, i.e. require the user code to
* call duk_require_stack(ctx, STACK_REQUIRE) again here.
*/
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_ecma_call_error(duk_context *ctx, void *udata) {
duk_idx_t i;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_eval_string(ctx, "(function () { print('hello from ecma func'); throw Error('ecma thrown'); })");
duk_call(ctx, 0 /*nargs*/);
printf("duk_call: %s\n", duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_ecma_pcall_success(duk_context *ctx, void *udata) {
duk_idx_t i;
duk_int_t rc;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_eval_string(ctx, "(function () { print('hello from ecma func'); return 123; })");
rc = duk_pcall(ctx, 0 /*nargs*/);
printf("duk_pcall: rc=%ld, value: %s\n", (long) rc, duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_ecma_pcall_error(duk_context *ctx, void *udata) {
duk_idx_t i;
duk_int_t rc;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_eval_string(ctx, "(function () { print('hello from ecma func'); throw Error('ecma thrown'); })");
rc = duk_pcall(ctx, 0 /*nargs*/);
printf("duk_pcall: rc=%ld, value: %s\n", (long) rc, duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_c_call_success(duk_context *ctx, void *udata) {
duk_idx_t i;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_push_c_function(ctx, my_func_success, 0);
duk_call(ctx, 0 /*nargs*/);
printf("duk_call: %s\n", duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_c_call_error1(duk_context *ctx, void *udata) {
duk_idx_t i;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_push_c_function(ctx, my_func_error1, 0);
duk_call(ctx, 0 /*nargs*/);
printf("duk_call: %s\n", duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_c_call_error2(duk_context *ctx, void *udata) {
duk_idx_t i;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_push_c_function(ctx, my_func_error2, 0);
duk_call(ctx, 0 /*nargs*/);
printf("duk_call: %s\n", duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_c_pcall_success(duk_context *ctx, void *udata) {
duk_idx_t i;
duk_int_t rc;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_push_c_function(ctx, my_func_success, 0);
rc = duk_pcall(ctx, 0 /*nargs*/);
printf("duk_pcall: rc=%ld, value: %s\n", (long) rc, duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_c_pcall_error1(duk_context *ctx, void *udata) {
duk_idx_t i;
duk_int_t rc;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_push_c_function(ctx, my_func_error1, 0);
rc = duk_pcall(ctx, 0 /*nargs*/);
printf("duk_pcall: rc=%ld, value: %s\n", (long) rc, duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_c_pcall_error2(duk_context *ctx, void *udata) {
duk_idx_t i;
duk_int_t rc;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
duk_push_c_function(ctx, my_func_error2, 0);
rc = duk_pcall(ctx, 0 /*nargs*/);
printf("duk_pcall: rc=%ld, value: %s\n", (long) rc, duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_safe_call_success(duk_context *ctx, void *udata) {
duk_idx_t i;
duk_int_t rc;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
rc = duk_safe_call(ctx, my_safe_func_success, NULL, 0 /*nargs*/, 1 /*nrets*/);
printf("duk_safe_call: rc=%ld, value: %s\n", (long) rc, duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_safe_call_error1(duk_context *ctx, void *udata) {
duk_idx_t i;
duk_int_t rc;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
rc = duk_safe_call(ctx, my_safe_func_error1, NULL, 0 /*nargs*/, 1 /*nrets*/);
printf("duk_safe_call: rc=%ld, value: %s\n", (long) rc, duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
static duk_ret_t test_safe_call_error2(duk_context *ctx, void *udata) {
duk_idx_t i;
duk_int_t rc;
(void) udata;
duk_require_stack(ctx, STACK_REQUIRE + 1);
rc = duk_safe_call(ctx, my_safe_func_error2, NULL, 0 /*nargs*/, 1 /*nrets*/);
printf("duk_safe_call: rc=%ld, value: %s\n", (long) rc, duk_safe_to_string(ctx, -1));
for (i = 0; i < STACK_REQUIRE; i++) {
duk_push_int(ctx, 123);
}
printf("final top: %ld\n", (long) duk_get_top(ctx));
return 0;
}
void test(duk_context *ctx) {
TEST_SAFE_CALL(test_ecma_call_success);
TEST_SAFE_CALL(test_ecma_call_error);
TEST_SAFE_CALL(test_ecma_pcall_success);
TEST_SAFE_CALL(test_ecma_pcall_error);
TEST_SAFE_CALL(test_c_call_success);
TEST_SAFE_CALL(test_c_call_error1);
TEST_SAFE_CALL(test_c_call_error2);
TEST_SAFE_CALL(test_c_pcall_success);
TEST_SAFE_CALL(test_c_pcall_error1);
TEST_SAFE_CALL(test_c_pcall_error2);
TEST_SAFE_CALL(test_safe_call_success);
TEST_SAFE_CALL(test_safe_call_error1);
TEST_SAFE_CALL(test_safe_call_error2);
}
| 26.105 | 102 | 0.709634 |
1ea0d7d8226f4ad9a1aa9803ebb85bd04f3c6fa9 | 6,493 | h | C | client/local_output_cache.h | xswz8015/goma_client | b0064de5f02694595792f4f38b5ec2ae81cf589d | [
"BSD-3-Clause"
] | null | null | null | client/local_output_cache.h | xswz8015/goma_client | b0064de5f02694595792f4f38b5ec2ae81cf589d | [
"BSD-3-Clause"
] | null | null | null | client/local_output_cache.h | xswz8015/goma_client | b0064de5f02694595792f4f38b5ec2ae81cf589d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Goma 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 DEVTOOLS_GOMA_CLIENT_LOCAL_OUTPUT_CACHE_H_
#define DEVTOOLS_GOMA_CLIENT_LOCAL_OUTPUT_CACHE_H_
#include <cstdint>
#include <string>
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "atomic_stats_counter.h"
#include "autolock_timer.h"
#include "compiler_specific.h"
#include "goma_hash.h"
#include "linked_unordered_map.h"
#include "worker_thread_manager.h"
MSVC_PUSH_DISABLE_WARNING_FOR_PROTO()
#include "client/local_output_cache_data.pb.h"
#include "lib/goma_data.pb.h"
MSVC_POP_WARNING()
namespace devtools_goma {
class LocalOutputCacheStats;
// LocalOutputCache is a cache that ExecReq -> output files.
class LocalOutputCache {
public:
struct GarbageCollectionStat {
size_t num_removed = 0; // # of garbage collected entries
size_t num_failed = 0; // failed to remove
std::int64_t removed_bytes = 0; // total removed bytes
};
static bool IsEnabled() { return instance_ != nullptr; }
static LocalOutputCache* instance() { return instance_; }
// When |server| is nullptr, GC won't run. This will be useful
// for testing.
static void Init(std::string cache_dir,
WorkerThreadManager* wm,
int max_cache_amount_in_mb,
int threshold_cache_amount_in_mb,
size_t max_cache_items,
size_t threshold_cache_items);
static void Quit();
LocalOutputCache(const LocalOutputCache&) = delete;
LocalOutputCache(LocalOutputCache&&) = delete;
LocalOutputCache& operator=(const LocalOutputCache&) = delete;
LocalOutputCache& operator=(LocalOutputCache&&) = delete;
// Creates cache key from |req|.
static std::string MakeCacheKey(const ExecReq& req);
// SaveOutput copies output files to cache.
// |trace_id| is just used for logging.
bool SaveOutput(const std::string& key,
const ExecReq* req,
const ExecResp* resp,
const std::string& trace_id);
// Finds cache with |key|.
// Returns true when a cache is found and read correctly. In this case,
// |resp| will be filled with output data.
// Otherwise, false is returned.
// |trace_id| is just used for logging.
bool Lookup(const std::string& key,
ExecResp* resp,
const std::string& trace_id);
// Dumps stats.
void DumpStatsToProto(LocalOutputCacheStats* stats);
// For stats. These will be removed after merged to GomaStats.
size_t TotalCacheCount();
std::int64_t TotalCacheAmountInByte();
size_t TotalGCRemovedItems() const { return stats_gc_removed_items_.value(); }
std::int64_t TotalGCRemovedBytes() const {
return stats_gc_removed_bytes_.value();
}
private:
struct CacheEntry {
CacheEntry() : amount_byte(0) {}
CacheEntry(absl::Time mtime, std::int64_t amount_byte)
: mtime(mtime), amount_byte(amount_byte) {}
~CacheEntry() {}
absl::Time mtime;
std::int64_t amount_byte;
};
LocalOutputCache(std::string cache_dir,
std::int64_t max_cache_amount_byte,
std::int64_t threashold_cache_amount_byte,
size_t max_cache_items,
size_t threshold_cache_items);
~LocalOutputCache();
// load cache entries.
void StartLoadCacheEntries(WorkerThreadManager* wm);
void LoadCacheEntries();
void LoadCacheEntriesDone();
// Wait until all cache entries are loaded from the file.
void WaitUntilReady();
void AddCacheEntry(const SHA256HashValue& key,
std::int64_t cache_amount_in_byte);
// A cache entry is updated, so move it to last.
void UpdateCacheEntry(const SHA256HashValue& key);
void StartGarbageCollection(WorkerThreadManager* wm)
LOCKS_EXCLUDED(entries_mu_);
void StopGarbageCollection() LOCKS_EXCLUDED(entries_mu_);
void GarbageCollectionThread() LOCKS_EXCLUDED(entries_mu_);
bool ShouldInvokeGarbageCollection() const
LOCKS_EXCLUDED(entries_mu_);
bool ShouldInvokeGarbageCollectionUnlocked() const
SHARED_LOCKS_REQUIRED(entries_mu_);
bool ShouldContinueGarbageCollectionUnlocked() const
SHARED_LOCKS_REQUIRED(entries_mu_);
void RunGarbageCollection(GarbageCollectionStat* stat)
LOCKS_EXCLUDED(entries_mu_);
void WakeGCThread() LOCKS_EXCLUDED(entries_mu_);
void WaitUntilGarbageCollectionThreadDone() LOCKS_EXCLUDED(entries_mu_);
// Used only for test.
void SetReady(bool ready);
// Full path of cache directory + key prefix.
std::string CacheDirWithKeyPrefix(absl::string_view key) const;
// Full path of cache directory + key prefix + key.
std::string CacheFilePath(absl::string_view key) const;
static LocalOutputCache* instance_;
// LocalOutputCache configurations
const std::string cache_dir_;
const std::int64_t max_cache_amount_byte_;
const std::int64_t threshold_cache_amount_byte_;
const size_t max_cache_items_;
const size_t threshold_cache_items_;
// Using in initial load of cache entries.
// After loading all cache entries, |ready_| will become true.
mutable Lock ready_mu_;
ConditionVariable ready_cond_;
bool ready_ GUARDED_BY(ready_mu_);
// cache entries. Older cache is first.
using CacheEntryMap = LinkedUnorderedMap<SHA256HashValue, CacheEntry>;
mutable ReadWriteLock entries_mu_ ACQUIRED_AFTER(gc_mu_);
CacheEntryMap entries_ GUARDED_BY(entries_mu_);
// total cache amount in bytes.
std::int64_t entries_total_cache_amount_ GUARDED_BY(entries_mu_);
mutable Lock gc_mu_;
ConditionVariable gc_cond_;
bool gc_should_done_ GUARDED_BY(gc_mu_);
bool gc_working_ GUARDED_BY(gc_mu_);
StatsCounter stats_save_success_;
StatsCounter stats_save_success_time_ms_;
StatsCounter stats_save_failure_;
StatsCounter stats_lookup_success_;
StatsCounter stats_lookup_success_time_ms_;
StatsCounter stats_lookup_miss_;
StatsCounter stats_lookup_failure_;
StatsCounter stats_commit_success_;
StatsCounter stats_commit_success_time_ms_;
StatsCounter stats_commit_failure_;
StatsCounter stats_gc_count_;
StatsCounter stats_gc_total_time_ms_;
StatsCounter stats_gc_removed_items_;
StatsCounter stats_gc_removed_bytes_;
StatsCounter stats_gc_failed_items_;
friend class LocalOutputCacheTest;
};
} // namespace devtools_goma
#endif // DEVTOOLS_GOMA_CLIENT_LOCAL_OUTPUT_CACHE_H_
| 33.642487 | 80 | 0.740798 |
37c5d45edf47dfe8e4afee1229636eb35a6a8649 | 7,707 | c | C | xp_comm_proj/distmap/create_outf.c | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 3 | 2020-08-03T08:52:20.000Z | 2021-04-10T11:55:49.000Z | xp_comm_proj/distmap/create_outf.c | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | null | null | null | xp_comm_proj/distmap/create_outf.c | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 1 | 2021-06-08T18:16:45.000Z | 2021-06-08T18:16:45.000Z | #include "gen.h"
#include <math.h>
#define SEG_REPLACE 0
#define SEG_ADD 1
#define SEG_INTERSECT 2
#define SEG_SUBTRACT 3
//#define DEBUG
int create_outf(OMobj_id create_outf_id, OMevent_mask event_mask, int seq_num)
{
int init_mask;
int smooth;
int do_;
int t1;
int thr1;
OMobj_id in_id;
int in_ndim, *in_dims, in_nspace, in_npoints;
float *in_points;
int in_ncomp, in_comp_count, in_veclen;
int in_data_type, in_ndata;
unsigned char *in_data;
OMobj_id mask_id;
int mask_ndim, *mask_dims;
int mask_ncomp, mask_comp_count, mask_veclen;
int mask_data_type, mask_ndata;
int mask_num;
int mask_array_size = 0;
unsigned char *mask_array = NULL;
unsigned char *mask_data;
OMobj_id out_id;
int out_ndim, *out_dims, out_nspace, out_npoints;
float *out_points;
int out_ncomp, out_comp_count, out_veclen;
int out_data_type, out_ndata;
unsigned char *out_data;
int i,j,k,l,m,min,max;
int off[125];
float weight[125],w;
if (OMget_name_int_val(create_outf_id,
OMstr_to_name("smooth"), &smooth) != 1)
smooth = 0;
if (OMget_name_int_val(create_outf_id,
OMstr_to_name("do"), &do_) != 1)
do_ = 0;
if (OMget_name_int_val(create_outf_id,
OMstr_to_name("t1"), &t1) != 1)
t1 = 0;
if (OMget_name_int_val(create_outf_id,
OMstr_to_name("thr1"), &thr1) != 1)
thr1 = 127;
if (OMget_name_int_val(create_outf_id,
OMstr_to_name("init_mask"), &init_mask) != 1)
init_mask = 0;
if (OMget_name_int_val(create_outf_id,
OMstr_to_name("mask_num"), &mask_num) != 1)
mask_num = 0;
#ifdef DEBUG
fprintf(stderr,"doing out thr %5d smooth lev %d smooth thr %d\n",t1,smooth,thr1);fflush(stderr);
#endif
mask_array = (unsigned char *)OMret_name_array_ptr(
create_outf_id,
OMstr_to_name("mask_array"),
OM_GET_ARRAY_RW,
&mask_array_size, NULL);
if (init_mask==SEG_REPLACE)
for (i=0;i< mask_array_size; i++)
if (mask_array[i]==mask_num) mask_array[i]=0;
/* Get in uniform mesh */
in_id = OMfind_subobj(create_outf_id,
OMstr_to_name("in"), OM_OBJ_RD);
mask_id = OMfind_subobj(create_outf_id,
OMstr_to_name("mask_fld"), OM_OBJ_RD);
FLDget_dims (in_id, &in_dims, &in_ndim);
FLDget_dims (mask_id, &mask_dims, &mask_ndim);
if (in_dims==NULL || in_ndim!=3 || mask_dims==NULL || mask_ndim!=3)
{
if (in_dims)
ARRfree(in_dims);
if (mask_dims)
ARRfree(mask_dims);
#ifdef DEBUG
fprintf(stderr,"return in_dim %i mask_ndim %i\n",in_ndim, mask_ndim);fflush(stderr);
#endif
return 0;
}
w=0;
if (smooth==1)
{
for (i=-1,l=0;i<2;i++)
for (j=-1;j<2;j++)
for (k=-1;k<2;k++,l++)
{
off[l]=(i*in_dims[1]+j)*in_dims[0]+k;
w+=(weight[l]=exp(-i*i+j*j+k*k));
}
for (l=0;l<27;l++)
weight[l]/=w;
}
else if (smooth==2)
{
for (i=-2,l=0;i<3;i++)
for (j=-2;j<3;j++)
for (k=-2;k<3;k++,l++)
{
off[l]=(i*in_dims[1]+j)*in_dims[0]+k;
w+=(weight[l]=exp(-i*i+j*j+k*k));
}
for (l=0;l<125;l++)
weight[l]/=w;
}
FLDget_nspace (in_id, &in_nspace);
FLDget_points (in_id, &in_points, &in_npoints,
OM_GET_ARRAY_RD);
in_comp_count=mask_comp_count=0;
FLDget_node_data (in_id, in_comp_count, &in_data_type,
(char **)&in_data, &in_ndata, OM_GET_ARRAY_RD);
FLDget_node_data (mask_id, mask_comp_count, &mask_data_type,
(char **)&mask_data, &mask_ndata, OM_GET_ARRAY_RD);
out_id = OMfind_subobj(create_outf_id, OMstr_to_name("out"), OM_OBJ_RW);
out_ndim=3;
FLDset_ndim (out_id, out_ndim);
out_dims = (int *)ARRalloc(NULL, DTYPE_INT,
out_ndim, NULL);
for (i=0;i<out_ndim;i++)
out_dims[i] = in_dims[i];
FLDset_dims (out_id, out_dims);
if (out_dims)
ARRfree(out_dims);
out_nspace = 3;
FLDset_nspace (out_id, out_nspace);
out_npoints = 2*out_nspace;
out_points = (float *)ARRalloc(NULL, DTYPE_FLOAT,
out_npoints, NULL);
for (i=0;i<out_npoints;i++)
out_points[i] = in_points[i];
FLDset_points (out_id, out_points, out_npoints,
OM_SET_ARRAY_FREE);
out_ncomp = 1;
FLDset_node_data_ncomp (out_id, out_ncomp);
out_comp_count=0;
out_veclen = 1;
FLDset_node_data_veclen (out_id,out_comp_count,out_veclen);
out_data_type = DTYPE_BYTE;
out_ndata = in_ndata;
out_data = (unsigned char *)ARRalloc(NULL, out_data_type,
out_veclen*out_ndata, NULL);
for (l=0; l<out_ndata; l++)
if (mask_data[l]>t1) out_data[l]=255;
else out_data[l]=0;
switch (smooth)
{
case 0:
break;
case 1:
for (i=1;i<in_dims[2]-1;i++)
for (j=1;j<in_dims[1]-1;j++)
for (k=1,l=(i*in_dims[1]+j)*in_dims[0]+1;k<in_dims[0]-1;k++,l++)
{
w=0;
for (m=0;m<27;m++)
{
if((l+off[m]<0) || (l+off[m]>mask_comp_count))continue;
if (mask_data[l+off[m]]>t1)
w+=weight[m];
}
out_data[l]=255*w;
}
break;
case 2:
for (i=2;i<in_dims[2]-2;i++)
for (j=2;j<in_dims[1]-2;j++)
for (k=2,l=(i*in_dims[1]+j)*in_dims[0]+1;k<in_dims[0]-2;k++,l++)
{
w=0;
for (m=0;m<125;m++)
{
if((l+off[m]<0) || (l+off[m]>mask_comp_count))continue;
if (mask_data[l+off[m]]>t1)
w+=weight[m];
}
out_data[l]=255*w;
}
break;
}
switch(init_mask)
{
case SEG_REPLACE:
for (i=0;i<out_ndata;i++)
if (out_data[i]>thr1 && mask_array[i]==0)
mask_array[i]=mask_num;
break;
case SEG_ADD:
for (i=0;i<out_ndata;i++)
if (out_data[i]>thr1 && mask_array[i]==0)
mask_array[i]=mask_num;
break;
case SEG_INTERSECT:
for (i=0;i<out_ndata;i++)
{
if (out_data[i]<=thr1 && mask_array[i]==mask_num)
mask_array[i]=0;
}
break;
case SEG_SUBTRACT:
for (i=0;i<out_ndata;i++)
if (out_data[i]>thr1 && mask_array[i]==mask_num)
mask_array[i]=0;
break;
}
max=0; min=256;
for (i=0;i<in_ndata;i++)
if (mask_array[i]==mask_num)
{
if (in_data[i]>max) max=in_data[i];
if (in_data[i]<min) min=in_data[i];
}
if (min==max) max=min+1;
#ifdef DEBUG
fprintf(stderr,"%d %d\n",min,max);fflush(stderr);
#endif
for (i=0;i<out_ndata;i++)
if (mask_array[i]!=mask_num)
out_data[i]=(55*in_data[i])/255;
else
{
k = 200*(in_data[i]-min);
out_data[i]=55+k/(max-min);
}
FLDset_node_data (out_id, out_comp_count, (char *)out_data,
out_data_type,
out_ndata*out_veclen, OM_SET_ARRAY_FREE);
if (in_dims)
ARRfree(in_dims);
if (in_points)
ARRfree(in_points);
if (mask_dims)
ARRfree(mask_dims);
if (in_data)
ARRfree(in_data);
if (mask_data)
ARRfree(mask_data);
if (mask_array != NULL)
ARRfree(mask_array);
return(1);
}
| 28.973684 | 97 | 0.541067 |
5357dc98cd00ecac365a003b8a48cb1180b0be21 | 2,361 | h | C | include/nbl/core/decl/compile_config.h | deprilula28/Nabla | 6b5de216221718191713dcf6de8ed6407182ddf0 | [
"Apache-2.0"
] | null | null | null | include/nbl/core/decl/compile_config.h | deprilula28/Nabla | 6b5de216221718191713dcf6de8ed6407182ddf0 | [
"Apache-2.0"
] | null | null | null | include/nbl/core/decl/compile_config.h | deprilula28/Nabla | 6b5de216221718191713dcf6de8ed6407182ddf0 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O.
// This file is part of the "Nabla Engine".
// For conditions of distribution and use, see copyright notice in nabla.h
#ifndef __NBL_CORE_COMPILE_CONFIG_H_INCLUDED__
#define __NBL_CORE_COMPILE_CONFIG_H_INCLUDED__
//! Irrlicht SDK Version
#define NABLA_VERSION_MAJOR 0
#define NABLA_VERSION_MINOR 4
#define NABLA_VERSION_REVISION 0
#define NABLA_VERSION_INTEGER (NABLA_VERSION_MAJOR*100 + NABLA_VERSION_MINOR*10 + NABLA_VERSION_REVISION)
#define NABLA_SDK_VERSION "0.4.0-alpha1"
#include <stdio.h> // TODO: Although included elsewhere this is required at least for mingw
//#define _NBL_TEST_WAYLAND // TODO: need!?
// this actually includes file depending on build type (Debug/Release)
#include "BuildConfigOptions.h"
#if defined(_NBL_PLATFORM_LINUX_) || defined(_NBL_PLATFORM_ANDROID_)
# define _NBL_POSIX_API_ // Android is not 100% POSIX, but it's close enough
#elif defined(_NBL_PLATFORM_WINDOWS_)
# define _NBL_WINDOWS_API_
#endif
#ifdef _NBL_TARGET_ARCH_ARM_
# define __NBL_COMPILE_WITH_ARM_SIMD_ // NEON
#else // target arch x86
# define __NBL_COMPILE_WITH_SSE3
# define __NBL_COMPILE_WITH_X86_SIMD_ // SSE 4.2
# include <immintrin.h>
#endif
#ifdef _MSC_VER
# define _ENABLE_EXTENDED_ALIGNED_STORAGE
#endif
//! Uncomment the following line if you want to ignore the deprecated warnings
//#define IGNORE_DEPRECATED_WARNING
#ifdef _NBL_WINDOWS_API_
// To build Nabla as a static library, you must define _NBL_STATIC_LIB_ in both the
// Nabla build, *and* in the user application, before #including <nabla.h>
#ifndef _NBL_STATIC_LIB_
#ifdef NABLA_EXPORTS
#define NABLA_API __declspec(dllexport)
#else
#define NABLA_API __declspec(dllimport)
#endif // NABLA_EXPORT
#else
#define NABLA_API
#endif // _NBL_STATIC_LIB_
// Declare the calling convention.
#if defined(_STDCALL_SUPPORTED)
#define NBLCALLCONV __stdcall
#else
#define NBLCALLCONV __cdecl
#endif // STDCALL_SUPPORTED
#else // _NBL_WINDOWS_API_
// Force symbol export in shared libraries built with gcc.
#if (__GNUC__ >= 4) && !defined(_NBL_STATIC_LIB_) && defined(NABLA_EXPORTS)
#define NABLA_API __attribute__ ((visibility("default")))
#else
#define NABLA_API
#endif
#define NBLCALLCONV
#endif // _NBL_WINDOWS_API_
#ifndef _NBL_WINDOWS_API_
# undef _NBL_WCHAR_FILESYSTEM // TODO: need?
#endif
#endif
| 28.792683 | 105 | 0.790343 |
535cfae6ca18ca542ffac75e3c482926304c1936 | 44,946 | c | C | mi8/drivers/usb/gadget/function/f_qc_rndis.c | wqk317/mi8_kernel_source | e3482d1a7ea6021de2fc8f3178496b4b043bb727 | [
"MIT"
] | null | null | null | mi8/drivers/usb/gadget/function/f_qc_rndis.c | wqk317/mi8_kernel_source | e3482d1a7ea6021de2fc8f3178496b4b043bb727 | [
"MIT"
] | null | null | null | mi8/drivers/usb/gadget/function/f_qc_rndis.c | wqk317/mi8_kernel_source | e3482d1a7ea6021de2fc8f3178496b4b043bb727 | [
"MIT"
] | 1 | 2020-03-28T11:26:15.000Z | 2020-03-28T11:26:15.000Z | /*
* f_qc_rndis.c -- RNDIS link function driver
*
* Copyright (C) 2003-2005,2008 David Brownell
* Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
* Copyright (C) 2008 Nokia Corporation
* Copyright (C) 2009 Samsung Electronics
* Author: Michal Nazarewicz (mina86@mina86.com)
* Copyright (c) 2012-2019, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
*
* 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.
*/
/* #define VERBOSE_DEBUG */
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/etherdevice.h>
#include <linux/atomic.h>
#include "u_ether.h"
#include "rndis.h"
#include "u_data_ipa.h"
#include <linux/rndis_ipa.h>
#include "configfs.h"
unsigned int rndis_dl_max_xfer_size = 9216;
module_param(rndis_dl_max_xfer_size, uint, 0644);
MODULE_PARM_DESC(rndis_dl_max_xfer_size,
"Max size of bus transfer to host");
static struct class *rndis_class;
static dev_t rndis_dev;
static DEFINE_IDA(chardev_ida);
/*
* This function is an RNDIS Ethernet port -- a Microsoft protocol that's
* been promoted instead of the standard CDC Ethernet. The published RNDIS
* spec is ambiguous, incomplete, and needlessly complex. Variants such as
* ActiveSync have even worse status in terms of specification.
*
* In short: it's a protocol controlled by (and for) Microsoft, not for an
* Open ecosystem or markets. Linux supports it *only* because Microsoft
* doesn't support the CDC Ethernet standard.
*
* The RNDIS data transfer model is complex, with multiple Ethernet packets
* per USB message, and out of band data. The control model is built around
* what's essentially an "RNDIS RPC" protocol. It's all wrapped in a CDC ACM
* (modem, not Ethernet) veneer, with those ACM descriptors being entirely
* useless (they're ignored). RNDIS expects to be the only function in its
* configuration, so it's no real help if you need composite devices; and
* it expects to be the first configuration too.
*
* There is a single technical advantage of RNDIS over CDC Ethernet, if you
* discount the fluff that its RPC can be made to deliver: it doesn't need
* a NOP altsetting for the data interface. That lets it work on some of the
* "so smart it's stupid" hardware which takes over configuration changes
* from the software, and adds restrictions like "no altsettings".
*
* Unfortunately MSFT's RNDIS drivers are buggy. They hang or oops, and
* have all sorts of contrary-to-specification oddities that can prevent
* them from working sanely. Since bugfixes (or accurate specs, letting
* Linux work around those bugs) are unlikely to ever come from MSFT, you
* may want to avoid using RNDIS on purely operational grounds.
*
* Omissions from the RNDIS 1.0 specification include:
*
* - Power management ... references data that's scattered around lots
* of other documentation, which is incorrect/incomplete there too.
*
* - There are various undocumented protocol requirements, like the need
* to send garbage in some control-OUT messages.
*
* - MS-Windows drivers sometimes emit undocumented requests.
*
* This function is based on RNDIS link function driver and
* contains MSM specific implementation.
*/
struct f_rndis_qc {
struct usb_function func;
u8 ctrl_id, data_id;
u8 ethaddr[ETH_ALEN];
u32 vendorID;
u8 ul_max_pkt_per_xfer;
u8 pkt_alignment_factor;
u32 max_pkt_size;
const char *manufacturer;
struct rndis_params *params;
atomic_t ioctl_excl;
atomic_t open_excl;
struct usb_ep *notify;
struct usb_request *notify_req;
atomic_t notify_count;
struct data_port bam_port;
struct cdev cdev;
struct device *dev;
u8 port_num;
u16 cdc_filter;
bool net_ready_trigger;
};
static struct ipa_usb_init_params rndis_ipa_params;
static spinlock_t rndis_lock;
static bool rndis_ipa_supported;
static void rndis_qc_open(struct f_rndis_qc *rndis);
static inline struct f_rndis_qc *func_to_rndis_qc(struct usb_function *f)
{
return container_of(f, struct f_rndis_qc, func);
}
/* peak (theoretical) bulk transfer rate in bits-per-second */
static unsigned int rndis_qc_bitrate(struct usb_gadget *g)
{
if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
return 13 * 1024 * 8 * 1000 * 8;
else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
return 13 * 512 * 8 * 1000 * 8;
else
return 19 * 64 * 1 * 1000 * 8;
}
/*-------------------------------------------------------------------------*/
#define RNDIS_QC_LOG2_STATUS_INTERVAL_MSEC 5 /* 1 << 5 == 32 msec */
#define RNDIS_QC_STATUS_BYTECOUNT 8 /* 8 bytes data */
/* currently only one rndis instance is supported - port
* index 0.
*/
#define RNDIS_QC_NO_PORTS 1
#define RNDIS_QC_ACTIVE_PORT 0
/* default max packets per tarnsfer value */
#define DEFAULT_MAX_PKT_PER_XFER 15
/* default pkt alignment factor */
#define DEFAULT_PKT_ALIGNMENT_FACTOR 4
#define RNDIS_QC_IOCTL_MAGIC 'i'
#define RNDIS_QC_GET_MAX_PKT_PER_XFER _IOR(RNDIS_QC_IOCTL_MAGIC, 1, u8)
#define RNDIS_QC_GET_MAX_PKT_SIZE _IOR(RNDIS_QC_IOCTL_MAGIC, 2, u32)
/* interface descriptor: */
/* interface descriptor: Supports "Wireless" RNDIS; auto-detected by Windows*/
static struct usb_interface_descriptor rndis_qc_control_intf = {
.bLength = sizeof(rndis_qc_control_intf),
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
/* status endpoint is optional; this could be patched later */
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_WIRELESS_CONTROLLER,
.bInterfaceSubClass = 0x01,
.bInterfaceProtocol = 0x03,
/* .iInterface = DYNAMIC */
};
static struct usb_cdc_header_desc rndis_qc_header_desc = {
.bLength = sizeof(rndis_qc_header_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = cpu_to_le16(0x0110),
};
static struct usb_cdc_call_mgmt_descriptor rndis_qc_call_mgmt_descriptor = {
.bLength = sizeof(rndis_qc_call_mgmt_descriptor),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_CALL_MANAGEMENT_TYPE,
.bmCapabilities = 0x00,
.bDataInterface = 0x01,
};
static struct usb_cdc_acm_descriptor rndis_qc_acm_descriptor = {
.bLength = sizeof(rndis_qc_acm_descriptor),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_ACM_TYPE,
.bmCapabilities = 0x00,
};
static struct usb_cdc_union_desc rndis_qc_union_desc = {
.bLength = sizeof(rndis_qc_union_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC */
/* .bSlaveInterface0 = DYNAMIC */
};
/* the data interface has two bulk endpoints */
static struct usb_interface_descriptor rndis_qc_data_intf = {
.bLength = sizeof(rndis_qc_data_intf),
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
/* Supports "Wireless" RNDIS; auto-detected by Windows */
static struct usb_interface_assoc_descriptor
rndis_qc_iad_descriptor = {
.bLength = sizeof(rndis_qc_iad_descriptor),
.bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
.bFirstInterface = 0, /* XXX, hardcoded */
.bInterfaceCount = 2, /* control + data */
.bFunctionClass = USB_CLASS_WIRELESS_CONTROLLER,
.bFunctionSubClass = 0x01,
.bFunctionProtocol = 0x03,
/* .iFunction = DYNAMIC */
};
/* full speed support: */
static struct usb_endpoint_descriptor rndis_qc_fs_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(RNDIS_QC_STATUS_BYTECOUNT),
.bInterval = 1 << RNDIS_QC_LOG2_STATUS_INTERVAL_MSEC,
};
static struct usb_endpoint_descriptor rndis_qc_fs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor rndis_qc_fs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *eth_qc_fs_function[] = {
(struct usb_descriptor_header *) &rndis_qc_iad_descriptor,
/* control interface matches ACM, not Ethernet */
(struct usb_descriptor_header *) &rndis_qc_control_intf,
(struct usb_descriptor_header *) &rndis_qc_header_desc,
(struct usb_descriptor_header *) &rndis_qc_call_mgmt_descriptor,
(struct usb_descriptor_header *) &rndis_qc_acm_descriptor,
(struct usb_descriptor_header *) &rndis_qc_union_desc,
(struct usb_descriptor_header *) &rndis_qc_fs_notify_desc,
/* data interface has no altsetting */
(struct usb_descriptor_header *) &rndis_qc_data_intf,
(struct usb_descriptor_header *) &rndis_qc_fs_in_desc,
(struct usb_descriptor_header *) &rndis_qc_fs_out_desc,
NULL,
};
/* high speed support: */
static struct usb_endpoint_descriptor rndis_qc_hs_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(RNDIS_QC_STATUS_BYTECOUNT),
.bInterval = RNDIS_QC_LOG2_STATUS_INTERVAL_MSEC + 4,
};
static struct usb_endpoint_descriptor rndis_qc_hs_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_endpoint_descriptor rndis_qc_hs_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *eth_qc_hs_function[] = {
(struct usb_descriptor_header *) &rndis_qc_iad_descriptor,
/* control interface matches ACM, not Ethernet */
(struct usb_descriptor_header *) &rndis_qc_control_intf,
(struct usb_descriptor_header *) &rndis_qc_header_desc,
(struct usb_descriptor_header *) &rndis_qc_call_mgmt_descriptor,
(struct usb_descriptor_header *) &rndis_qc_acm_descriptor,
(struct usb_descriptor_header *) &rndis_qc_union_desc,
(struct usb_descriptor_header *) &rndis_qc_hs_notify_desc,
/* data interface has no altsetting */
(struct usb_descriptor_header *) &rndis_qc_data_intf,
(struct usb_descriptor_header *) &rndis_qc_hs_in_desc,
(struct usb_descriptor_header *) &rndis_qc_hs_out_desc,
NULL,
};
/* super speed support: */
static struct usb_endpoint_descriptor rndis_qc_ss_notify_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(RNDIS_QC_STATUS_BYTECOUNT),
.bInterval = RNDIS_QC_LOG2_STATUS_INTERVAL_MSEC + 4,
};
static struct usb_ss_ep_comp_descriptor rndis_qc_ss_intr_comp_desc = {
.bLength = sizeof(rndis_qc_ss_intr_comp_desc),
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
/* the following 3 values can be tweaked if necessary */
/* .bMaxBurst = 0, */
/* .bmAttributes = 0, */
.wBytesPerInterval = cpu_to_le16(RNDIS_QC_STATUS_BYTECOUNT),
};
static struct usb_endpoint_descriptor rndis_qc_ss_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_endpoint_descriptor rndis_qc_ss_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(1024),
};
static struct usb_ss_ep_comp_descriptor rndis_qc_ss_bulk_comp_desc = {
.bLength = sizeof(rndis_qc_ss_bulk_comp_desc),
.bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
/* the following 2 values can be tweaked if necessary */
/* .bMaxBurst = 0, */
/* .bmAttributes = 0, */
};
static struct usb_descriptor_header *eth_qc_ss_function[] = {
(struct usb_descriptor_header *) &rndis_qc_iad_descriptor,
/* control interface matches ACM, not Ethernet */
(struct usb_descriptor_header *) &rndis_qc_control_intf,
(struct usb_descriptor_header *) &rndis_qc_header_desc,
(struct usb_descriptor_header *) &rndis_qc_call_mgmt_descriptor,
(struct usb_descriptor_header *) &rndis_qc_acm_descriptor,
(struct usb_descriptor_header *) &rndis_qc_union_desc,
(struct usb_descriptor_header *) &rndis_qc_ss_notify_desc,
(struct usb_descriptor_header *) &rndis_qc_ss_intr_comp_desc,
/* data interface has no altsetting */
(struct usb_descriptor_header *) &rndis_qc_data_intf,
(struct usb_descriptor_header *) &rndis_qc_ss_in_desc,
(struct usb_descriptor_header *) &rndis_qc_ss_bulk_comp_desc,
(struct usb_descriptor_header *) &rndis_qc_ss_out_desc,
(struct usb_descriptor_header *) &rndis_qc_ss_bulk_comp_desc,
NULL,
};
/* string descriptors: */
static struct usb_string rndis_qc_string_defs[] = {
[0].s = "RNDIS Communications Control",
[1].s = "RNDIS Ethernet Data",
[2].s = "RNDIS",
{ } /* end of list */
};
static struct usb_gadget_strings rndis_qc_string_table = {
.language = 0x0409, /* en-us */
.strings = rndis_qc_string_defs,
};
static struct usb_gadget_strings *rndis_qc_strings[] = {
&rndis_qc_string_table,
NULL,
};
struct f_rndis_qc *_rndis_qc;
static inline int rndis_qc_lock(atomic_t *excl)
{
if (atomic_inc_return(excl) == 1)
return 0;
atomic_dec(excl);
return -EBUSY;
}
static inline void rndis_qc_unlock(atomic_t *excl)
{
atomic_dec(excl);
}
/*-------------------------------------------------------------------------*/
static void rndis_qc_response_available(void *_rndis)
{
struct f_rndis_qc *rndis = _rndis;
struct usb_request *req = rndis->notify_req;
__le32 *data = req->buf;
int status;
if (atomic_inc_return(&rndis->notify_count) != 1)
return;
if (!rndis->notify->driver_data)
return;
/* Send RNDIS RESPONSE_AVAILABLE notification; a
* USB_CDC_NOTIFY_RESPONSE_AVAILABLE "should" work too
*
* This is the only notification defined by RNDIS.
*/
data[0] = cpu_to_le32(1);
data[1] = cpu_to_le32(0);
status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
if (status) {
atomic_dec(&rndis->notify_count);
pr_info("notify/0 --> %d\n", status);
}
}
static void rndis_qc_response_complete(struct usb_ep *ep,
struct usb_request *req)
{
struct f_rndis_qc *rndis;
int status = req->status;
struct usb_composite_dev *cdev;
struct usb_ep *notify_ep;
spin_lock(&rndis_lock);
rndis = _rndis_qc;
if (!rndis || !rndis->notify || !rndis->notify->driver_data) {
spin_unlock(&rndis_lock);
return;
}
if (!rndis->func.config || !rndis->func.config->cdev) {
pr_err("%s(): cdev or config is NULL.\n", __func__);
spin_unlock(&rndis_lock);
return;
}
cdev = rndis->func.config->cdev;
/* after TX:
* - USB_CDC_GET_ENCAPSULATED_RESPONSE (ep0/control)
* - RNDIS_RESPONSE_AVAILABLE (status/irq)
*/
switch (status) {
case -ECONNRESET:
case -ESHUTDOWN:
/* connection gone */
atomic_set(&rndis->notify_count, 0);
goto out;
default:
pr_info("RNDIS %s response error %d, %d/%d\n",
ep->name, status,
req->actual, req->length);
/* FALLTHROUGH */
case 0:
if (ep != rndis->notify)
goto out;
/* handle multiple pending RNDIS_RESPONSE_AVAILABLE
* notifications by resending until we're done
*/
if (atomic_dec_and_test(&rndis->notify_count))
goto out;
notify_ep = rndis->notify;
spin_unlock(&rndis_lock);
status = usb_ep_queue(notify_ep, req, GFP_ATOMIC);
if (status) {
spin_lock(&rndis_lock);
if (!_rndis_qc)
goto out;
atomic_dec(&_rndis_qc->notify_count);
DBG(cdev, "notify/1 --> %d\n", status);
spin_unlock(&rndis_lock);
}
}
return;
out:
spin_unlock(&rndis_lock);
}
static void rndis_qc_command_complete(struct usb_ep *ep,
struct usb_request *req)
{
struct f_rndis_qc *rndis;
int status;
rndis_init_msg_type *buf;
u32 ul_max_xfer_size, dl_max_xfer_size;
if (req->status != 0) {
pr_err("%s: RNDIS command completion error %d\n",
__func__, req->status);
return;
}
spin_lock(&rndis_lock);
rndis = _rndis_qc;
if (!rndis || !rndis->notify || !rndis->notify->driver_data) {
spin_unlock(&rndis_lock);
return;
}
/* received RNDIS command from USB_CDC_SEND_ENCAPSULATED_COMMAND */
status = rndis_msg_parser(rndis->params, (u8 *) req->buf);
if (status < 0)
pr_err("RNDIS command error %d, %d/%d\n",
status, req->actual, req->length);
buf = (rndis_init_msg_type *)req->buf;
if (buf->MessageType == RNDIS_MSG_INIT) {
ul_max_xfer_size = rndis_get_ul_max_xfer_size(rndis->params);
ipa_data_set_ul_max_xfer_size(ul_max_xfer_size);
/*
* For consistent data throughput from IPA, it is required to
* fine tune aggregation byte limit as 7KB. RNDIS IPA driver
* use provided this value to calculate aggregation byte limit
* and program IPA hardware for aggregation.
* Host provides 8KB or 16KB as Max Transfer size, hence select
* minimum out of host provided value and optimum transfer size
* to get 7KB as aggregation byte limit.
*/
if (rndis_dl_max_xfer_size)
dl_max_xfer_size = min_t(u32, rndis_dl_max_xfer_size,
rndis_get_dl_max_xfer_size(rndis->params));
else
dl_max_xfer_size =
rndis_get_dl_max_xfer_size(rndis->params);
ipa_data_set_dl_max_xfer_size(dl_max_xfer_size);
}
spin_unlock(&rndis_lock);
}
static int
rndis_qc_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct f_rndis_qc *rndis = func_to_rndis_qc(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
/* composite driver infrastructure handles everything except
* CDC class messages; interface activation uses set_alt().
*/
pr_debug("%s: Enter\n", __func__);
switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
/* RNDIS uses the CDC command encapsulation mechanism to implement
* an RPC scheme, with much getting/setting of attributes by OID.
*/
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_SEND_ENCAPSULATED_COMMAND:
if (w_value || w_index != rndis->ctrl_id)
goto invalid;
/* read the request; process it later */
value = w_length;
req->complete = rndis_qc_command_complete;
/* later, rndis_response_available() sends a notification */
break;
case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_GET_ENCAPSULATED_RESPONSE:
if (w_value || w_index != rndis->ctrl_id)
goto invalid;
else {
u8 *buf;
u32 n;
/* return the result */
buf = rndis_get_next_response(rndis->params, &n);
if (buf) {
memcpy(req->buf, buf, n);
req->complete = rndis_qc_response_complete;
rndis_free_response(rndis->params, buf);
value = n;
}
/* else stalls ... spec says to avoid that */
}
break;
default:
invalid:
VDBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
}
/* respond with data transfer or status phase? */
if (value >= 0) {
DBG(cdev, "rndis req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->context = rndis;
req->zero = (value < w_length);
req->length = value;
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
pr_err("rndis response on err %d\n", value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
struct net_device *rndis_qc_get_net(const char *netname)
{
struct net_device *net_dev;
net_dev = dev_get_by_name(&init_net, netname);
if (!net_dev)
return ERR_PTR(-EINVAL);
/*
* Decrement net_dev refcount as it was incremented in
* dev_get_by_name().
*/
dev_put(net_dev);
return net_dev;
}
static int rndis_qc_set_alt(struct usb_function *f, unsigned int intf,
unsigned int alt)
{
struct f_rndis_qc *rndis = func_to_rndis_qc(f);
struct f_rndis_qc_opts *opts;
struct usb_composite_dev *cdev = f->config->cdev;
u8 src_connection_idx;
u8 dst_connection_idx;
enum usb_ctrl usb_bam_type;
int ret;
/* we know alt == 0 */
opts = container_of(f->fi, struct f_rndis_qc_opts, func_inst);
if (intf == rndis->ctrl_id) {
if (rndis->notify->driver_data) {
VDBG(cdev, "reset rndis control %d\n", intf);
usb_ep_disable(rndis->notify);
}
if (!rndis->notify->desc) {
VDBG(cdev, "init rndis ctrl %d\n", intf);
if (config_ep_by_speed(cdev->gadget, f, rndis->notify))
goto fail;
}
usb_ep_enable(rndis->notify);
rndis->notify->driver_data = rndis;
} else if (intf == rndis->data_id) {
struct net_device *net;
rndis->net_ready_trigger = false;
if (rndis->bam_port.in->driver_data) {
DBG(cdev, "reset rndis\n");
/* bam_port is needed for disconnecting the BAM data
* path. Only after the BAM data path is disconnected,
* we can disconnect the port from the network layer.
*/
ipa_data_disconnect(&rndis->bam_port,
USB_IPA_FUNC_RNDIS);
}
if (!rndis->bam_port.in->desc || !rndis->bam_port.out->desc) {
DBG(cdev, "init rndis\n");
if (config_ep_by_speed(cdev->gadget, f,
rndis->bam_port.in) ||
config_ep_by_speed(cdev->gadget, f,
rndis->bam_port.out)) {
rndis->bam_port.in->desc = NULL;
rndis->bam_port.out->desc = NULL;
goto fail;
}
}
/* RNDIS should be in the "RNDIS uninitialized" state,
* either never activated or after rndis_uninit().
*
* We don't want data to flow here until a nonzero packet
* filter is set, at which point it enters "RNDIS data
* initialized" state ... but we do want the endpoints
* to be activated. It's a strange little state.
*
* REVISIT the RNDIS gadget code has done this wrong for a
* very long time. We need another call to the link layer
* code -- gether_updown(...bool) maybe -- to do it right.
*/
rndis->cdc_filter = 0;
rndis->bam_port.cdev = cdev;
rndis->bam_port.func = &rndis->func;
ipa_data_port_select(USB_IPA_FUNC_RNDIS);
usb_bam_type = usb_bam_get_bam_type(cdev->gadget->name);
src_connection_idx = usb_bam_get_connection_idx(usb_bam_type,
IPA_P_BAM, USB_TO_PEER_PERIPHERAL, USB_BAM_DEVICE,
rndis->port_num);
dst_connection_idx = usb_bam_get_connection_idx(usb_bam_type,
IPA_P_BAM, PEER_PERIPHERAL_TO_USB, USB_BAM_DEVICE,
rndis->port_num);
if (src_connection_idx < 0 || dst_connection_idx < 0) {
pr_err("%s: usb_bam_get_connection_idx failed\n",
__func__);
return ret;
}
if (ipa_data_connect(&rndis->bam_port, USB_IPA_FUNC_RNDIS,
src_connection_idx, dst_connection_idx))
goto fail;
DBG(cdev, "RNDIS RX/TX early activation ...\n");
rndis_qc_open(rndis);
net = rndis_qc_get_net("rndis0");
if (IS_ERR(net))
return PTR_ERR(net);
opts->net = net;
rndis_set_param_dev(rndis->params, net,
&rndis->cdc_filter);
} else
goto fail;
return 0;
fail:
return -EINVAL;
}
static void rndis_qc_disable(struct usb_function *f)
{
struct f_rndis_qc *rndis = func_to_rndis_qc(f);
struct usb_composite_dev *cdev = f->config->cdev;
unsigned long flags;
if (!rndis->notify->driver_data)
return;
DBG(cdev, "rndis deactivated\n");
spin_lock_irqsave(&rndis_lock, flags);
rndis_uninit(rndis->params);
spin_unlock_irqrestore(&rndis_lock, flags);
ipa_data_disconnect(&rndis->bam_port, USB_IPA_FUNC_RNDIS);
msm_ep_unconfig(rndis->bam_port.out);
msm_ep_unconfig(rndis->bam_port.in);
usb_ep_disable(rndis->notify);
rndis->notify->driver_data = NULL;
}
static void rndis_qc_suspend(struct usb_function *f)
{
struct f_rndis_qc *rndis = func_to_rndis_qc(f);
bool remote_wakeup_allowed;
if (f->config->cdev->gadget->speed == USB_SPEED_SUPER)
remote_wakeup_allowed = f->func_wakeup_allowed;
else
remote_wakeup_allowed = f->config->cdev->gadget->remote_wakeup;
pr_info("%s(): start rndis suspend: remote_wakeup_allowed:%d\n:",
__func__, remote_wakeup_allowed);
if (!remote_wakeup_allowed) {
/* This is required as Linux host side RNDIS driver doesn't
* send RNDIS_MESSAGE_PACKET_FILTER before suspending USB bus.
* Hence we perform same operations explicitly here for Linux
* host case. In case of windows, this RNDIS state machine is
* already updated due to receiving of PACKET_FILTER.
*/
rndis_flow_control(rndis->params, true);
pr_debug("%s(): Disconnecting\n", __func__);
}
ipa_data_suspend(&rndis->bam_port, USB_IPA_FUNC_RNDIS,
remote_wakeup_allowed);
pr_debug("rndis suspended\n");
}
static void rndis_qc_resume(struct usb_function *f)
{
struct f_rndis_qc *rndis = func_to_rndis_qc(f);
bool remote_wakeup_allowed;
pr_debug("%s: rndis resumed\n", __func__);
/* Nothing to do if DATA interface wasn't initialized */
if (!rndis->bam_port.cdev) {
pr_debug("data interface was not up\n");
return;
}
if (f->config->cdev->gadget->speed == USB_SPEED_SUPER)
remote_wakeup_allowed = f->func_wakeup_allowed;
else
remote_wakeup_allowed = f->config->cdev->gadget->remote_wakeup;
ipa_data_resume(&rndis->bam_port, USB_IPA_FUNC_RNDIS,
remote_wakeup_allowed);
if (!remote_wakeup_allowed) {
rndis_qc_open(rndis);
/*
* Linux Host doesn't sends RNDIS_MSG_INIT or non-zero value
* set with RNDIS_MESSAGE_PACKET_FILTER after performing bus
* resume. Hence trigger USB IPA transfer functionality
* explicitly here. For Windows host case is also being
* handle with RNDIS state machine.
*/
rndis_flow_control(rndis->params, false);
}
pr_debug("%s: RNDIS resume completed\n", __func__);
}
/*-------------------------------------------------------------------------*/
/*
* This isn't quite the same mechanism as CDC Ethernet, since the
* notification scheme passes less data, but the same set of link
* states must be tested. A key difference is that altsettings are
* not used to tell whether the link should send packets or not.
*/
static void rndis_qc_open(struct f_rndis_qc *rndis)
{
struct usb_composite_dev *cdev = rndis->func.config->cdev;
DBG(cdev, "%s\n", __func__);
rndis_set_param_medium(rndis->params, RNDIS_MEDIUM_802_3,
rndis_qc_bitrate(cdev->gadget) / 100);
rndis_signal_connect(rndis->params);
}
void ipa_data_flow_control_enable(bool enable, struct rndis_params *param)
{
if (enable)
ipa_data_stop_rndis_ipa(USB_IPA_FUNC_RNDIS);
else
ipa_data_start_rndis_ipa(USB_IPA_FUNC_RNDIS);
}
/*-------------------------------------------------------------------------*/
/* ethernet function driver setup/binding */
static int
rndis_qc_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_rndis_qc *rndis = func_to_rndis_qc(f);
struct rndis_params *params;
int status;
struct usb_ep *ep;
status = rndis_ipa_init(&rndis_ipa_params);
if (status) {
pr_err("%s: failed to init rndis_ipa\n", __func__);
return status;
}
rndis_ipa_supported = true;
/* maybe allocate device-global string IDs */
if (rndis_qc_string_defs[0].id == 0) {
/* control interface label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
rndis_qc_string_defs[0].id = status;
rndis_qc_control_intf.iInterface = status;
/* data interface label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
rndis_qc_string_defs[1].id = status;
rndis_qc_data_intf.iInterface = status;
/* IAD iFunction label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
rndis_qc_string_defs[2].id = status;
rndis_qc_iad_descriptor.iFunction = status;
}
/* allocate instance-specific interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
rndis->ctrl_id = status;
rndis_qc_iad_descriptor.bFirstInterface = status;
rndis_qc_control_intf.bInterfaceNumber = status;
rndis_qc_union_desc.bMasterInterface0 = status;
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
rndis->data_id = status;
rndis_qc_data_intf.bInterfaceNumber = status;
rndis_qc_union_desc.bSlaveInterface0 = status;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, &rndis_qc_fs_in_desc);
if (!ep)
goto fail;
rndis->bam_port.in = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &rndis_qc_fs_out_desc);
if (!ep)
goto fail;
rndis->bam_port.out = ep;
ep->driver_data = cdev; /* claim */
/* NOTE: a status/notification endpoint is, strictly speaking,
* optional. We don't treat it that way though! It's simpler,
* and some newer profiles don't treat it as optional.
*/
ep = usb_ep_autoconfig(cdev->gadget, &rndis_qc_fs_notify_desc);
if (!ep)
goto fail;
rndis->notify = ep;
ep->driver_data = cdev; /* claim */
status = -ENOMEM;
/* allocate notification request and buffer */
rndis->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (!rndis->notify_req)
goto fail;
rndis->notify_req->buf = kmalloc(RNDIS_QC_STATUS_BYTECOUNT, GFP_KERNEL);
if (!rndis->notify_req->buf)
goto fail;
rndis->notify_req->length = RNDIS_QC_STATUS_BYTECOUNT;
rndis->notify_req->context = rndis;
rndis->notify_req->complete = rndis_qc_response_complete;
/* copy descriptors, and track endpoint copies */
f->fs_descriptors = usb_copy_descriptors(eth_qc_fs_function);
if (!f->fs_descriptors)
goto fail;
/* support all relevant hardware speeds... we expect that when
* hardware is dual speed, all bulk-capable endpoints work at
* both speeds
*/
if (gadget_is_dualspeed(c->cdev->gadget)) {
rndis_qc_hs_in_desc.bEndpointAddress =
rndis_qc_fs_in_desc.bEndpointAddress;
rndis_qc_hs_out_desc.bEndpointAddress =
rndis_qc_fs_out_desc.bEndpointAddress;
rndis_qc_hs_notify_desc.bEndpointAddress =
rndis_qc_fs_notify_desc.bEndpointAddress;
/* copy descriptors, and track endpoint copies */
f->hs_descriptors = usb_copy_descriptors(eth_qc_hs_function);
if (!f->hs_descriptors)
goto fail;
}
if (gadget_is_superspeed(c->cdev->gadget)) {
rndis_qc_ss_in_desc.bEndpointAddress =
rndis_qc_fs_in_desc.bEndpointAddress;
rndis_qc_ss_out_desc.bEndpointAddress =
rndis_qc_fs_out_desc.bEndpointAddress;
rndis_qc_ss_notify_desc.bEndpointAddress =
rndis_qc_fs_notify_desc.bEndpointAddress;
/* copy descriptors, and track endpoint copies */
f->ss_descriptors = usb_copy_descriptors(eth_qc_ss_function);
if (!f->ss_descriptors)
goto fail;
}
params = rndis_register(rndis_qc_response_available, rndis,
ipa_data_flow_control_enable);
if (params < 0)
goto fail;
rndis->params = params;
rndis_set_param_medium(rndis->params, RNDIS_MEDIUM_802_3, 0);
rndis_set_host_mac(rndis->params, rndis->ethaddr);
if (rndis->manufacturer && rndis->vendorID &&
rndis_set_param_vendor(rndis->params, rndis->vendorID,
rndis->manufacturer))
goto fail;
pr_debug("%s(): max_pkt_per_xfer:%d\n", __func__,
rndis->ul_max_pkt_per_xfer);
rndis_set_max_pkt_xfer(rndis->params, rndis->ul_max_pkt_per_xfer);
/* In case of aggregated packets QC device will request
* aliment to 4 (2^2).
*/
pr_debug("%s(): pkt_alignment_factor:%d\n", __func__,
rndis->pkt_alignment_factor);
rndis_set_pkt_alignment_factor(rndis->params,
rndis->pkt_alignment_factor);
/* NOTE: all that is done without knowing or caring about
* the network link ... which is unavailable to this code
* until we're activated via set_alt().
*/
c->cdev->gadget->bam2bam_func_enabled = true;
DBG(cdev, "RNDIS: %s speed IN/%s OUT/%s NOTIFY/%s\n",
gadget_is_superspeed(c->cdev->gadget) ? "super" :
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
rndis->bam_port.in->name, rndis->bam_port.out->name,
rndis->notify->name);
return 0;
fail:
if (gadget_is_superspeed(c->cdev->gadget) && f->ss_descriptors)
usb_free_descriptors(f->ss_descriptors);
if (gadget_is_dualspeed(c->cdev->gadget) && f->hs_descriptors)
usb_free_descriptors(f->hs_descriptors);
if (f->fs_descriptors)
usb_free_descriptors(f->fs_descriptors);
if (rndis->notify_req) {
kfree(rndis->notify_req->buf);
usb_ep_free_request(rndis->notify, rndis->notify_req);
}
/* we might as well release our claims on endpoints */
if (rndis->notify)
rndis->notify->driver_data = NULL;
if (rndis->bam_port.out->desc)
rndis->bam_port.out->driver_data = NULL;
if (rndis->bam_port.in->desc)
rndis->bam_port.in->driver_data = NULL;
pr_err("%s: can't bind, err %d\n", f->name, status);
return status;
}
static void rndis_qc_free(struct usb_function *f)
{
struct f_rndis_qc_opts *opts;
opts = container_of(f->fi, struct f_rndis_qc_opts, func_inst);
opts->refcnt--;
}
static void
rndis_qc_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_rndis_qc *rndis = func_to_rndis_qc(f);
pr_debug("rndis_qc_unbind: free\n");
rndis_deregister(rndis->params);
if (gadget_is_dualspeed(c->cdev->gadget))
usb_free_descriptors(f->hs_descriptors);
usb_free_descriptors(f->fs_descriptors);
c->cdev->gadget->bam2bam_func_enabled = false;
kfree(rndis->notify_req->buf);
usb_ep_free_request(rndis->notify, rndis->notify_req);
/*
* call flush_workqueue to make sure that any pending
* disconnect_work() from u_bam_data.c file is being
* flushed before calling this rndis_ipa_cleanup API
* as rndis ipa disconnect API is required to be
* called before this.
*/
ipa_data_flush_workqueue();
rndis_ipa_cleanup(rndis_ipa_params.private);
rndis_ipa_supported = false;
}
void rndis_ipa_reset_trigger(void)
{
struct f_rndis_qc *rndis;
rndis = _rndis_qc;
if (!rndis) {
pr_err("%s: No RNDIS instance", __func__);
return;
}
rndis->net_ready_trigger = false;
}
/*
* Callback let RNDIS_IPA trigger us when network interface is up
* and userspace is ready to answer DHCP requests
*/
void rndis_net_ready_notify(void)
{
struct f_rndis_qc *rndis;
unsigned long flags;
spin_lock_irqsave(&rndis_lock, flags);
rndis = _rndis_qc;
if (!rndis) {
pr_err("%s: No RNDIS instance", __func__);
spin_unlock_irqrestore(&rndis_lock, flags);
return;
}
if (rndis->net_ready_trigger) {
pr_err("%s: Already triggered", __func__);
spin_unlock_irqrestore(&rndis_lock, flags);
return;
}
pr_debug("%s: Set net_ready_trigger", __func__);
rndis->net_ready_trigger = true;
spin_unlock_irqrestore(&rndis_lock, flags);
ipa_data_start_rx_tx(USB_IPA_FUNC_RNDIS);
}
/**
* rndis_qc_bind_config - add RNDIS network link to a configuration
* @c: the configuration to support the network link
* @ethaddr: a buffer in which the ethernet address of the host side
* side of the link was recorded
* Context: single threaded during gadget setup
*
* Returns zero on success, else negative errno.
*
* Caller must have called @gether_setup(). Caller is also responsible
* for calling @gether_cleanup() before module unload.
*/
static struct
usb_function *rndis_qc_bind_config_vendor(struct usb_function_instance *fi,
u32 vendorID, const char *manufacturer,
u8 max_pkt_per_xfer, u8 pkt_alignment_factor)
{
struct f_rndis_qc_opts *opts = container_of(fi,
struct f_rndis_qc_opts, func_inst);
struct f_rndis_qc *rndis;
/* allocate and initialize one new instance */
opts = container_of(fi, struct f_rndis_qc_opts, func_inst);
opts->refcnt++;
rndis = opts->rndis;
rndis->vendorID = opts->vendor_id;
rndis->manufacturer = opts->manufacturer;
/* export host's Ethernet address in CDC format */
random_ether_addr(rndis_ipa_params.host_ethaddr);
random_ether_addr(rndis_ipa_params.device_ethaddr);
pr_debug("setting host_ethaddr=%pM, device_ethaddr=%pM\n",
rndis_ipa_params.host_ethaddr,
rndis_ipa_params.device_ethaddr);
ether_addr_copy(rndis->ethaddr, rndis_ipa_params.host_ethaddr);
rndis_ipa_params.device_ready_notify = rndis_net_ready_notify;
/* if max_pkt_per_xfer was not configured set to default value */
rndis->ul_max_pkt_per_xfer =
max_pkt_per_xfer ? max_pkt_per_xfer :
DEFAULT_MAX_PKT_PER_XFER;
ipa_data_set_ul_max_pkt_num(rndis->ul_max_pkt_per_xfer);
/*
* Check no RNDIS aggregation, and alignment if not mentioned,
* use alignment factor as zero. If aggregated RNDIS data transfer,
* max packet per transfer would be default if it is not set
* explicitly, and same way use alignment factor as 2 by default.
* This would eliminate need of writing to sysfs if default RNDIS
* aggregation setting required. Writing to both sysfs entries,
* those values will always override default values.
*/
if ((rndis->pkt_alignment_factor == 0) &&
(rndis->ul_max_pkt_per_xfer == 1))
rndis->pkt_alignment_factor = 0;
else
rndis->pkt_alignment_factor = pkt_alignment_factor ?
pkt_alignment_factor :
DEFAULT_PKT_ALIGNMENT_FACTOR;
/* RNDIS activates when the host changes this filter */
rndis->cdc_filter = 0;
rndis->func.name = "rndis";
rndis->func.strings = rndis_qc_strings;
/* descriptors are per-instance copies */
rndis->func.bind = rndis_qc_bind;
rndis->func.unbind = rndis_qc_unbind;
rndis->func.set_alt = rndis_qc_set_alt;
rndis->func.setup = rndis_qc_setup;
rndis->func.disable = rndis_qc_disable;
rndis->func.suspend = rndis_qc_suspend;
rndis->func.resume = rndis_qc_resume;
rndis->func.free_func = rndis_qc_free;
_rndis_qc = rndis;
return &rndis->func;
}
static struct usb_function *qcrndis_alloc(struct usb_function_instance *fi)
{
return rndis_qc_bind_config_vendor(fi, 0, NULL, 0, 0);
}
static int rndis_qc_open_dev(struct inode *ip, struct file *fp)
{
int ret = 0;
unsigned long flags;
pr_info("Open rndis QC driver\n");
spin_lock_irqsave(&rndis_lock, flags);
if (!_rndis_qc) {
pr_err("rndis_qc_dev not created yet\n");
ret = -ENODEV;
goto fail;
}
if (rndis_qc_lock(&_rndis_qc->open_excl)) {
pr_err("Already opened\n");
ret = -EBUSY;
goto fail;
}
fp->private_data = _rndis_qc;
fail:
spin_unlock_irqrestore(&rndis_lock, flags);
if (!ret)
pr_info("rndis QC file opened\n");
return ret;
}
static int rndis_qc_release_dev(struct inode *ip, struct file *fp)
{
unsigned long flags;
pr_info("Close rndis QC file\n");
spin_lock_irqsave(&rndis_lock, flags);
if (!_rndis_qc) {
pr_err("rndis_qc_dev not present\n");
spin_unlock_irqrestore(&rndis_lock, flags);
return -ENODEV;
}
rndis_qc_unlock(&_rndis_qc->open_excl);
spin_unlock_irqrestore(&rndis_lock, flags);
return 0;
}
static long rndis_qc_ioctl(struct file *fp, unsigned int cmd, unsigned long arg)
{
u8 qc_max_pkt_per_xfer = 0;
u32 qc_max_pkt_size = 0;
int ret = 0;
unsigned long flags;
spin_lock_irqsave(&rndis_lock, flags);
if (!_rndis_qc) {
pr_err("rndis_qc_dev not present\n");
ret = -ENODEV;
goto fail;
}
qc_max_pkt_per_xfer = _rndis_qc->ul_max_pkt_per_xfer;
qc_max_pkt_size = _rndis_qc->max_pkt_size;
if (rndis_qc_lock(&_rndis_qc->ioctl_excl)) {
ret = -EBUSY;
goto fail;
}
spin_unlock_irqrestore(&rndis_lock, flags);
pr_info("Received command %d\n", cmd);
switch (cmd) {
case RNDIS_QC_GET_MAX_PKT_PER_XFER:
ret = copy_to_user((void __user *)arg,
&qc_max_pkt_per_xfer,
sizeof(qc_max_pkt_per_xfer));
if (ret) {
pr_err("copying to user space failed\n");
ret = -EFAULT;
}
pr_info("Sent UL max packets per xfer %d\n",
qc_max_pkt_per_xfer);
break;
case RNDIS_QC_GET_MAX_PKT_SIZE:
ret = copy_to_user((void __user *)arg,
&qc_max_pkt_size,
sizeof(qc_max_pkt_size));
if (ret) {
pr_err("copying to user space failed\n");
ret = -EFAULT;
}
pr_debug("Sent max packet size %d\n",
qc_max_pkt_size);
break;
default:
pr_err("Unsupported IOCTL\n");
ret = -EINVAL;
}
spin_lock_irqsave(&rndis_lock, flags);
if (!_rndis_qc) {
pr_err("rndis_qc_dev not present\n");
ret = -ENODEV;
goto fail;
}
rndis_qc_unlock(&_rndis_qc->ioctl_excl);
fail:
spin_unlock_irqrestore(&rndis_lock, flags);
return ret;
}
static const struct file_operations rndis_qc_fops = {
.owner = THIS_MODULE,
.open = rndis_qc_open_dev,
.release = rndis_qc_release_dev,
.unlocked_ioctl = rndis_qc_ioctl,
};
static void qcrndis_free_inst(struct usb_function_instance *f)
{
struct f_rndis_qc_opts *opts = container_of(f,
struct f_rndis_qc_opts, func_inst);
int minor = MINOR(opts->rndis->cdev.dev);
unsigned long flags;
device_destroy(rndis_class, MKDEV(MAJOR(rndis_dev), minor));
class_destroy(rndis_class);
cdev_del(&opts->rndis->cdev);
ida_simple_remove(&chardev_ida, minor);
unregister_chrdev_region(rndis_dev, 1);
ipa_data_free(USB_IPA_FUNC_RNDIS);
spin_lock_irqsave(&rndis_lock, flags);
kfree(opts->rndis);
_rndis_qc = NULL;
kfree(opts);
spin_unlock_irqrestore(&rndis_lock, flags);
}
static int qcrndis_set_inst_name(struct usb_function_instance *fi,
const char *name)
{
struct f_rndis_qc_opts *opts = container_of(fi,
struct f_rndis_qc_opts, func_inst);
struct f_rndis_qc *rndis;
int name_len;
int ret, minor;
name_len = strlen(name) + 1;
if (name_len > MAX_INST_NAME_LEN)
return -ENAMETOOLONG;
pr_debug("initialize rndis QC instance\n");
rndis = kzalloc(sizeof(*rndis), GFP_KERNEL);
if (!rndis) {
pr_err("%s: fail allocate and initialize new instance\n",
__func__);
return -ENOMEM;
}
spin_lock_init(&rndis_lock);
opts->rndis = rndis;
rndis_class = class_create(THIS_MODULE, "usbrndis");
ret = alloc_chrdev_region(&rndis_dev, 0, 1, "usb_rndis");
if (ret < 0) {
pr_err("Fail to allocate usb rndis char dev region\n");
return ret;
}
/* get a minor number */
minor = ida_simple_get(&chardev_ida, 0, 0, GFP_KERNEL);
if (minor < 0) {
pr_err("%s: No more minor numbers left! rc:%d\n", __func__,
minor);
ret = -ENODEV;
goto fail_out_of_minors;
}
rndis->dev = device_create(rndis_class, NULL,
MKDEV(MAJOR(rndis_dev), minor),
rndis, "android_rndis_qc");
if (IS_ERR(rndis->dev)) {
ret = PTR_ERR(rndis->dev);
pr_err("%s: device_create failed for (%d)", __func__, ret);
goto fail_return_minor;
}
cdev_init(&rndis->cdev, &rndis_qc_fops);
ret = cdev_add(&rndis->cdev, MKDEV(MAJOR(rndis_dev), minor), 1);
if (ret < 0) {
pr_err("%s: cdev_add failed for %s (%d)", __func__,
name, ret);
goto fail_cdev_add;
}
if (ret)
pr_err("rndis QC driver failed to register\n");
ret = ipa_data_setup(USB_IPA_FUNC_RNDIS);
if (ret) {
pr_err("bam_data_setup failed err: %d\n", ret);
goto fail_data_setup;
}
return 0;
fail_data_setup:
cdev_del(&rndis->cdev);
fail_cdev_add:
device_destroy(rndis_class, MKDEV(MAJOR(rndis_dev), minor));
fail_return_minor:
ida_simple_remove(&chardev_ida, minor);
fail_out_of_minors:
unregister_chrdev_region(rndis_dev, 1);
class_destroy(rndis_class);
kfree(rndis);
return ret;
}
static inline
struct f_rndis_qc_opts *to_f_qc_rndis_opts(struct config_item *item)
{
return container_of(to_config_group(item), struct f_rndis_qc_opts,
func_inst.group);
}
static void qcrndis_attr_release(struct config_item *item)
{
struct f_rndis_qc_opts *opts = to_f_qc_rndis_opts(item);
usb_put_function_instance(&opts->func_inst);
}
static struct configfs_item_operations qcrndis_item_ops = {
.release = qcrndis_attr_release,
};
static struct config_item_type qcrndis_func_type = {
.ct_item_ops = &qcrndis_item_ops,
.ct_owner = THIS_MODULE,
};
static struct usb_function_instance *qcrndis_alloc_inst(void)
{
struct f_rndis_qc_opts *opts;
opts = kzalloc(sizeof(*opts), GFP_KERNEL);
if (!opts)
return ERR_PTR(-ENOMEM);
opts->func_inst.set_inst_name = qcrndis_set_inst_name;
opts->func_inst.free_func_inst = qcrndis_free_inst;
config_group_init_type_name(&opts->func_inst.group, "",
&qcrndis_func_type);
return &opts->func_inst;
}
void *rndis_qc_get_ipa_rx_cb(void)
{
return rndis_ipa_params.ipa_rx_notify;
}
void *rndis_qc_get_ipa_tx_cb(void)
{
return rndis_ipa_params.ipa_tx_notify;
}
void *rndis_qc_get_ipa_priv(void)
{
return rndis_ipa_params.private;
}
bool rndis_qc_get_skip_ep_config(void)
{
return rndis_ipa_params.skip_ep_cfg;
}
DECLARE_USB_FUNCTION_INIT(rndis_bam, qcrndis_alloc_inst, qcrndis_alloc);
static int __init usb_qcrndis_init(void)
{
int ret;
ret = usb_function_register(&rndis_bamusb_func);
if (ret) {
pr_err("%s: failed to register diag %d\n", __func__, ret);
return ret;
}
return ret;
}
static void __exit usb_qcrndis_exit(void)
{
usb_function_unregister(&rndis_bamusb_func);
}
module_init(usb_qcrndis_init);
module_exit(usb_qcrndis_exit);
MODULE_DESCRIPTION("USB RMNET Function Driver");
| 28.867052 | 80 | 0.734259 |
bb253b84f32d1dd5f08cccca03bbb6a2a41dc5bf | 615 | h | C | tools/makeproject/pmake/headers/application/mycontexth.h | lihw/paper3d | a06d056b2ad894a8065b7a996eb7f6ceefec1511 | [
"MIT"
] | 34 | 2015-01-29T12:27:25.000Z | 2022-03-09T08:07:11.000Z | tools/makeproject/pmake/headers/wallpaper/mycontexth.h | lihw/paper3d | a06d056b2ad894a8065b7a996eb7f6ceefec1511 | [
"MIT"
] | 1 | 2015-02-04T07:26:50.000Z | 2015-02-04T07:36:55.000Z | tools/makeproject/pmake/headers/wallpaper/mycontexth.h | lihw/paper3d | a06d056b2ad894a8065b7a996eb7f6ceefec1511 | [
"MIT"
] | 12 | 2015-03-24T22:16:53.000Z | 2018-07-22T02:09:49.000Z | const char MYCONTEXTH_STR[] =
"// mycontext.h\n"
"%s\n"
"//\n"
"\n"
"#ifndef MYCONTEXT_H\n"
"#define MYCONTEXT_H\n"
"\n"
"#include <PFoundation/pcontext.h>\n"
"#include <PFoundation/pcontextproperties.h>\n"
"\n"
"class MyScene;\n"
"\n"
"class MyContext : public PContext\n"
"{\n"
"public:\n"
" MyContext(const PContextProperties &properties);\n"
" ~MyContext();\n"
" \n"
" virtual pbool onInitialized();\n"
" virtual pbool onUpdate();\n"
" virtual void onDestroy();\n"
" \n"
" virtual pbool onKeyboard(PEvent *event);\n"
"\n"
"private:\n"
" MyScene *m_scene;\n"
"};\n"
"\n"
"#endif\n"
;
| 19.21875 | 56 | 0.621138 |
9dfbc02ecd3cacd1983b7ec352dd65d557dedfa8 | 1,106 | h | C | src/student/euler_particle.h | Tagglink/archimedes-principle | 93a2ce101bc8f3ac2653da667887c8d36a6e86a7 | [
"MIT"
] | null | null | null | src/student/euler_particle.h | Tagglink/archimedes-principle | 93a2ce101bc8f3ac2653da667887c8d36a6e86a7 | [
"MIT"
] | null | null | null | src/student/euler_particle.h | Tagglink/archimedes-principle | 93a2ce101bc8f3ac2653da667887c8d36a6e86a7 | [
"MIT"
] | null | null | null | #ifndef STUDENT_BODY_H
#define STUDENT_BODY_H
#include "entity.h"
namespace student {
class EulerParticle : public Entity {
Point position_;
Vector velocity_;
Vector force_;
float mass_;
float inverse_mass_;
public:
EulerParticle();
EulerParticle(Point position);
EulerParticle(Point position, float mass);
virtual void Update(float delta_time) = 0;
virtual void Draw(DemoHandler* engine) const = 0;
void UpdatePosition(float delta_time);
void AddForce(const Vector& force);
Point GetPosition() const { return position_; }
void SetPosition(Point position) noexcept { position_ = position; }
Vector GetVelocity() const { return velocity_; }
void SetVelocity(Vector velocity) noexcept { velocity_ = velocity; }
float GetMass() const noexcept { return mass_; }
void SetMass(float mass) noexcept { mass_ = mass; inverse_mass_ = 1.0f / mass_; }
Vector GetForce() const { return force_; }
void SetForce(Vector force) noexcept { force_ = force; }
float GetInverseMass() const noexcept { return inverse_mass_; }
};
} // namespace student
#endif // !STUDENT_BODY_H
| 28.358974 | 83 | 0.735986 |
a02b966ae7a464f85b157f16769b0333464ce63e | 31,397 | c | C | ports/nrf/modules/machine/lcd.c | Afantor/micropython | bfb4a79a0479791f44a8f01d18554f2823d384e2 | [
"MIT"
] | 2 | 2019-05-05T10:07:27.000Z | 2019-08-06T02:04:32.000Z | ports/nrf/modules/machine/lcd.c | Afantor/micropython | bfb4a79a0479791f44a8f01d18554f2823d384e2 | [
"MIT"
] | null | null | null | ports/nrf/modules/machine/lcd.c | Afantor/micropython | bfb4a79a0479791f44a8f01d18554f2823d384e2 | [
"MIT"
] | null | null | null | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Afantor.lan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/mphal.h"
#include "mphalport.h"
#include "lcd.h"
#include "lcdfont.h"
#include "bmp.h"
#include "mpconfigboard.h"
#if MICROPY_PY_MACHINE_LCD
uint16_t BACK_COLOR; //背景色
uint8_t USE_HORIZONTAL = 3;
uint8_t LCD_W = 240;
uint8_t LCD_H = 135;
typedef struct _machine_lcd_obj_t {
mp_obj_base_t base;
} machine_lcd_obj_t;
/******************************************************************************
函数说明:LCD串行数据写入函数
入口数据:dat 要写入的串行数据
返回值: 无
******************************************************************************/
void LCD_Writ_Bus(uint8_t dat)
{
uint8_t i;
for(i=0;i<8;i++)
{
LCD_SCLK_Clr();
if(dat&0x80)
LCD_SDIN_Set();
else
LCD_SDIN_Clr();
LCD_SCLK_Set();
dat<<=1;
}
}
/******************************************************************************
函数说明:LCD写入数据
入口数据:dat 写入的数据
返回值: 无
******************************************************************************/
void LCD_WR_DATA8(uint8_t dat)
{
LCD_DC_Set();//写数据
LCD_Writ_Bus(dat);
}
/******************************************************************************
函数说明:LCD写入数据
入口数据:dat 写入的数据
返回值: 无
******************************************************************************/
void LCD_WR_DATA(uint16_t dat)
{
LCD_DC_Set();//写数据
LCD_Writ_Bus(dat>>8);
LCD_Writ_Bus(dat);
}
/******************************************************************************
函数说明:LCD写入命令
入口数据:dat 写入的命令
返回值: 无
******************************************************************************/
void LCD_WR_REG(uint8_t dat)
{
LCD_DC_Clr();//写命令
LCD_Writ_Bus(dat);
}
/******************************************************************************
函数说明:设置起始和结束地址
入口数据:x1,x2 设置列的起始和结束地址
y1,y2 设置行的起始和结束地址
返回值: 无
******************************************************************************/
void LCD_Address_Set(uint16_t x1,uint16_t y1,uint16_t x2,uint16_t y2)
{
if(USE_HORIZONTAL==0)
{
LCD_WR_REG(0x2a);//列地址设置
LCD_WR_DATA(x1+52);
LCD_WR_DATA(x2+52);
LCD_WR_REG(0x2b);//行地址设置
LCD_WR_DATA(y1+40);
LCD_WR_DATA(y2+40);
LCD_WR_REG(0x2c);//储存器写
}
else if(USE_HORIZONTAL==1)
{
LCD_WR_REG(0x2a);//列地址设置
LCD_WR_DATA(x1+53);
LCD_WR_DATA(x2+53);
LCD_WR_REG(0x2b);//行地址设置
LCD_WR_DATA(y1+40);
LCD_WR_DATA(y2+40);
LCD_WR_REG(0x2c);//储存器写
}
else if(USE_HORIZONTAL==2)
{
LCD_WR_REG(0x2a);//列地址设置
LCD_WR_DATA(x1+40);
LCD_WR_DATA(x2+40);
LCD_WR_REG(0x2b);//行地址设置
LCD_WR_DATA(y1+53);
LCD_WR_DATA(y2+53);
LCD_WR_REG(0x2c);//储存器写
}
else if(USE_HORIZONTAL==3)
{
LCD_WR_REG(0x2a);//列地址设置
LCD_WR_DATA(x1+40);
LCD_WR_DATA(x2+40);
LCD_WR_REG(0x2b);//行地址设置
LCD_WR_DATA(y1+52);
LCD_WR_DATA(y2+52);
LCD_WR_REG(0x2c);//储存器写
}
}
void lcd_init(uint8_t dir) {
// uint8_t log[]= "MicroPython";
nrf_gpio_cfg_output(LCD_SDA_PIN); //配置管脚为输出
nrf_gpio_cfg_output(LCD_SCL_PIN);
nrf_gpio_cfg_output(LCD_RES_PIN);
nrf_gpio_cfg_output(LCD_DC_PIN);
nrf_gpio_cfg_output(LCD_CS_PIN);
nrf_gpio_pin_set(LCD_SDA_PIN);
nrf_gpio_pin_set(LCD_SCL_PIN);
nrf_gpio_pin_set(LCD_RES_PIN);
nrf_gpio_pin_set(LCD_DC_PIN);
nrf_gpio_pin_clear(LCD_CS_PIN);
mp_hal_delay_ms(10);
LCD_RST_Clr();
mp_hal_delay_ms(50);
LCD_RST_Set();
mp_hal_delay_ms(20);
//************* Start Initial Sequence **********//
LCD_WR_REG(0x36);
USE_HORIZONTAL = dir;
if(USE_HORIZONTAL==0)LCD_WR_DATA8(0x00);
else if(USE_HORIZONTAL==1)LCD_WR_DATA8(0xC0);
else if(USE_HORIZONTAL==2)LCD_WR_DATA8(0x70);
else if(USE_HORIZONTAL==3)LCD_WR_DATA8(0xA0);
if (USE_HORIZONTAL==0 || USE_HORIZONTAL==1)
{
LCD_W = 135;
LCD_H = 240;
}
else if (USE_HORIZONTAL==2 || USE_HORIZONTAL==3)
{
LCD_W = 240;
LCD_H = 135;
}
LCD_WR_REG(0x3A);
LCD_WR_DATA8(0x05);
LCD_WR_REG(0xB2);
LCD_WR_DATA8(0x0C);
LCD_WR_DATA8(0x0C);
LCD_WR_DATA8(0x00);
LCD_WR_DATA8(0x33);
LCD_WR_DATA8(0x33);
LCD_WR_REG(0xB7);
LCD_WR_DATA8(0x35);
LCD_WR_REG(0xBB);
LCD_WR_DATA8(0x19);
LCD_WR_REG(0xC0);
LCD_WR_DATA8(0x2C);
LCD_WR_REG(0xC2);
LCD_WR_DATA8(0x01);
LCD_WR_REG(0xC3);
LCD_WR_DATA8(0x12);
LCD_WR_REG(0xC4);
LCD_WR_DATA8(0x20);
LCD_WR_REG(0xC6);
LCD_WR_DATA8(0x0F);
LCD_WR_REG(0xD0);
LCD_WR_DATA8(0xA4);
LCD_WR_DATA8(0xA1);
LCD_WR_REG(0xE0);
LCD_WR_DATA8(0xD0);
LCD_WR_DATA8(0x04);
LCD_WR_DATA8(0x0D);
LCD_WR_DATA8(0x11);
LCD_WR_DATA8(0x13);
LCD_WR_DATA8(0x2B);
LCD_WR_DATA8(0x3F);
LCD_WR_DATA8(0x54);
LCD_WR_DATA8(0x4C);
LCD_WR_DATA8(0x18);
LCD_WR_DATA8(0x0D);
LCD_WR_DATA8(0x0B);
LCD_WR_DATA8(0x1F);
LCD_WR_DATA8(0x23);
LCD_WR_REG(0xE1);
LCD_WR_DATA8(0xD0);
LCD_WR_DATA8(0x04);
LCD_WR_DATA8(0x0C);
LCD_WR_DATA8(0x11);
LCD_WR_DATA8(0x13);
LCD_WR_DATA8(0x2C);
LCD_WR_DATA8(0x3F);
LCD_WR_DATA8(0x44);
LCD_WR_DATA8(0x51);
LCD_WR_DATA8(0x2F);
LCD_WR_DATA8(0x1F);
LCD_WR_DATA8(0x1F);
LCD_WR_DATA8(0x20);
LCD_WR_DATA8(0x23);
LCD_WR_REG(0x21);
LCD_WR_REG(0x11);
//Delay (120);
LCD_WR_REG(0x29);
mp_hal_delay_ms(20);
LCD_Clear(LCD_WHITE);
BACK_COLOR = LCD_WHITE;
LCD_ShowLogo();
// LCD_ShowPicture(99,37,138,76);
// LCD_ShowString(76,85,log,LCD_RED);
}
/******************************************************************************
函数说明:LCD清屏函数
入口数据:无
返回值: 无
******************************************************************************/
void LCD_Clear(uint16_t Color)
{
uint16_t i,j;
LCD_Address_Set(0,0,LCD_W-1,LCD_H-1);
for(i=0;i<LCD_W;i++)
{
for (j=0;j<LCD_H;j++)
{
LCD_WR_DATA(Color);
}
}
}
void LCD_ShowDisable(void)
{
nrf_gpio_pin_set(LCD_CS_PIN);
}
void LCD_ShowEnable(void)
{
nrf_gpio_pin_clear(LCD_CS_PIN);
}
/******************************************************************************
函数说明:LCD显示汉字
入口数据:x,y 起始坐标
index 汉字的序号
size 字号
返回值: 无
******************************************************************************/
void LCD_ShowChinese(uint16_t x,uint16_t y,uint8_t index,uint8_t size,uint16_t color)
{
uint8_t i,j;
uint8_t *temp,size1;
if(size==16){temp=Hzk16;}//选择字号
if(size==32){temp=Hzk32;}
LCD_Address_Set(x,y,x+size-1,y+size-1); //设置一个汉字的区域
size1=size*size/8;//一个汉字所占的字节
temp+=index*size1;//写入的起始位置
for(j=0;j<size1;j++)
{
for(i=0;i<8;i++)
{
if((*temp&(1<<i))!=0)//从数据的低位开始读
{
LCD_WR_DATA(color);//点亮
}
else
{
LCD_WR_DATA(BACK_COLOR);//不点亮
}
}
temp++;
}
}
/******************************************************************************
函数说明:LCD显示汉字
入口数据:x,y 起始坐标
返回值: 无
******************************************************************************/
void LCD_DrawPoint(uint16_t x,uint16_t y,uint16_t color)
{
LCD_Address_Set(x,y,x,y);//设置光标位置
LCD_WR_DATA(color);
}
/******************************************************************************
函数说明:LCD画一个大的点
入口数据:x,y 起始坐标
返回值: 无
******************************************************************************/
void LCD_DrawBigPoint(uint16_t x,uint16_t y,uint16_t color)
{
LCD_Fill(x-1,y-1,x+1,y+1,color);
}
/******************************************************************************
函数说明:在指定区域填充颜色
入口数据:xsta,ysta 起始坐标
xend,yend 终止坐标
返回值: 无
******************************************************************************/
void LCD_Fill(uint16_t xsta,uint16_t ysta,uint16_t xend,uint16_t yend,uint16_t color)
{
uint16_t i,j;
LCD_Address_Set(xsta,ysta,xend,yend); //设置光标位置
for(i=ysta;i<=yend;i++)
{
for(j=xsta;j<=xend;j++)LCD_WR_DATA(color);//设置光标位置
}
}
/******************************************************************************
函数说明:画线
入口数据:x1,y1 起始坐标
x2,y2 终止坐标
返回值: 无
******************************************************************************/
void LCD_DrawLine(uint16_t x1,uint16_t y1,uint16_t x2,uint16_t y2,uint16_t color)
{
uint16_t t;
int xerr=0,yerr=0,delta_x,delta_y,distance;
int incx,incy,uRow,uCol;
delta_x=x2-x1; //计算坐标增量
delta_y=y2-y1;
uRow=x1;//画线起点坐标
uCol=y1;
if(delta_x>0)incx=1; //设置单步方向
else if (delta_x==0)incx=0;//垂直线
else {incx=-1;delta_x=-delta_x;}
if(delta_y>0)incy=1;
else if (delta_y==0)incy=0;//水平线
else {incy=-1;delta_y=-delta_x;}
if(delta_x>delta_y)distance=delta_x; //选取基本增量坐标轴
else distance=delta_y;
for(t=0;t<distance+1;t++)
{
LCD_DrawPoint(uRow,uCol,color);//画点
xerr+=delta_x;
yerr+=delta_y;
if(xerr>distance)
{
xerr-=distance;
uRow+=incx;
}
if(yerr>distance)
{
yerr-=distance;
uCol+=incy;
}
}
}
/******************************************************************************
函数说明:画矩形
入口数据:x1,y1 起始坐标
x2,y2 终止坐标
返回值: 无
******************************************************************************/
void LCD_DrawRectangle(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2,uint16_t color)
{
LCD_DrawLine(x1,y1,x2,y1,color);
LCD_DrawLine(x1,y1,x1,y2,color);
LCD_DrawLine(x1,y2,x2,y2,color);
LCD_DrawLine(x2,y1,x2,y2,color);
}
/******************************************************************************
函数说明:画圆
入口数据:x0,y0 圆心坐标
r 半径
返回值: 无
******************************************************************************/
void LCD_DrawCircle(uint16_t x0,uint16_t y0,uint8_t r,uint16_t color)
{
int a,b;
a=0;b=r;
while(a<=b)
{
LCD_DrawPoint(x0-b,y0-a,color); //3
LCD_DrawPoint(x0+b,y0-a,color); //0
LCD_DrawPoint(x0-a,y0+b,color); //1
LCD_DrawPoint(x0-a,y0-b,color); //2
LCD_DrawPoint(x0+b,y0+a,color); //4
LCD_DrawPoint(x0+a,y0-b,color); //5
LCD_DrawPoint(x0+a,y0+b,color); //6
LCD_DrawPoint(x0-b,y0+a,color); //7
a++;
if((a*a+b*b)>(r*r))//判断要画的点是否过远
{
b--;
}
}
}
/******************************************************************************
函数说明:显示字符
入口数据:x,y 起点坐标
num 要显示的字符
mode 1叠加方式 0非叠加方式
返回值: 无
******************************************************************************/
void LCD_ShowChar(uint16_t x,uint16_t y,uint8_t num,uint8_t mode,uint16_t color)
{
uint8_t temp;
uint8_t pos,t;
uint16_t x0=x;
if(x>LCD_W-16||y>LCD_H-16)return; //设置窗口
num=num-' ';//得到偏移后的值
LCD_Address_Set(x,y,x+8-1,y+16-1); //设置光标位置
if(!mode) //非叠加方式
{
for(pos=0;pos<16;pos++)
{
temp=asc2_1608[(uint16_t)num*16+pos]; //调用1608字体
for(t=0;t<8;t++)
{
if(temp&0x01)LCD_WR_DATA(color);
else LCD_WR_DATA(BACK_COLOR);
temp>>=1;
x++;
}
x=x0;
y++;
}
}
else//叠加方式
{
for(pos=0;pos<16;pos++)
{
temp=asc2_1608[(uint16_t)num*16+pos]; //调用1608字体
for(t=0;t<8;t++)
{
if(temp&0x01)LCD_DrawPoint(x+t,y+pos,color);//画一个点
temp>>=1;
}
}
}
}
/******************************************************************************
函数说明:显示字符串
入口数据:x,y 起点坐标
*p 字符串起始地址
返回值: 无
******************************************************************************/
void LCD_ShowString(uint16_t x,uint16_t y,const uint8_t *p,uint16_t color)
{
while(*p!='\0')
{
if(x>LCD_W-16){x=0;y+=16;}
if(y>LCD_H-16){y=x=0;LCD_Clear(LCD_RED);}
LCD_ShowChar(x,y,*p,1,color);
x+=8;
p++;
}
}
/******************************************************************************
函数说明:显示数字
入口数据:m底数,n指数
返回值: 无
******************************************************************************/
uint32_t mypow(uint8_t m,uint8_t n)
{
uint32_t result=1;
while(n--)result*=m;
return result;
}
/******************************************************************************
函数说明:显示数字
入口数据:x,y 起点坐标
num 要显示的数字
len 要显示的数字个数
返回值: 无
******************************************************************************/
void LCD_ShowNum(uint16_t x,uint16_t y,uint16_t num,uint8_t len,uint16_t color)
{
uint8_t t,temp;
uint8_t enshow=0;
for(t=0;t<len;t++)
{
temp=(num/mypow(10,len-t-1))%10;
if(enshow==0&&t<(len-1))
{
if(temp==0)
{
LCD_ShowChar(x+8*t,y,' ',1,color);
continue;
}else enshow=1;
}
LCD_ShowChar(x+8*t,y,temp+48,1,color);
}
}
/******************************************************************************
函数说明:显示小数
入口数据:x,y 起点坐标
num 要显示的小数
len 要显示的数字个数
返回值: 无
******************************************************************************/
void LCD_ShowFloat(uint16_t x,uint16_t y,float num,uint8_t len,uint16_t color)
{
uint8_t t,temp;
uint16_t num1;
num1=num*100;
for(t=0;t<len;t++)
{
temp=(num1/mypow(10,len-t-1))%10;
if(t==(len-2))
{
LCD_ShowChar(x+8*(len-2),y,'.',1,color);
t++;
len+=1;
}
LCD_ShowChar(x+8*t,y,temp+48,1,color);
}
}
/******************************************************************************
函数说明:显示40x40图片
入口数据:x,y 起点坐标
返回值: 无
******************************************************************************/
void LCD_ShowPicture(uint16_t x1,uint16_t y1,uint16_t x2,uint16_t y2)
{
int i;
LCD_Address_Set(x1,y1,x2,y2);
for(i=0;i<1600;i++)
{
LCD_WR_DATA8(image[i*2+1]);
LCD_WR_DATA8(image[i*2]);
}
}
/******************************************************************************
函数说明:显示240x135图片
入口数据:x,y 起点坐标
返回值: 无
******************************************************************************/
void LCD_ShowLogo(void)
{
int i;
LCD_Address_Set(0,0,239,134);
for(i=0;i<32400;i++)
{
LCD_WR_DATA8(gImage_logo[i*2+1]);
LCD_WR_DATA8(gImage_logo[i*2]);
}
}
/******************************************************************************
函数说明:显示40x40图片
入口数据:x,y 起点坐标
返回值: 无
******************************************************************************/
void LCD_ShowBLE(uint16_t x1,uint16_t y1,uint16_t x2,uint16_t y2)
{
int i;
LCD_Address_Set(x1,y1,x2,y2);
for(i=0;i<1600;i++)
{
LCD_WR_DATA8(gImage_ble[i*2+1]);
LCD_WR_DATA8(gImage_ble[i*2]);
}
}
/// \method __str__()
/// Return a string describing the lcd object.
STATIC void machine_lcd_print(const mp_print_t *print, mp_obj_t o, mp_print_kind_t kind) {
machine_lcd_obj_t *self = o;
(void)self;
mp_printf(print, "LCD Display");
}
/******************************************************************************/
/* MicroPython bindings for machine API */
STATIC mp_obj_t machine_lcd_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
static const mp_arg_t allowed_args[] = {
{ },
};
// parse args
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
machine_lcd_obj_t *self = m_new_obj(machine_lcd_obj_t);
self->base.type = &machine_lcd_type;
return MP_OBJ_FROM_PTR(self);
}
/// \method init()
/// init lcd display.
STATIC mp_obj_t machine_lcd_init(mp_obj_t self_in, mp_obj_t dir_in) {
machine_lcd_obj_t *self = self_in;
uint8_t dir = mp_obj_get_int(dir_in);
(void)self;
lcd_init(dir);
mp_hal_delay_ms(20);
LCD_Clear(LCD_WHITE);
BACK_COLOR = LCD_WHITE;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_machine_lcd_init_obj, machine_lcd_init);
/// \method setRotation()
/// set lcd display Rotation.
STATIC mp_obj_t machine_lcd_setRotation(mp_obj_t self_in, mp_obj_t dir_in) {
machine_lcd_obj_t *self = self_in;
uint8_t dir = mp_obj_get_int(dir_in);
(void)self;
USE_HORIZONTAL = dir;
if (USE_HORIZONTAL==0 || USE_HORIZONTAL==1)
{
LCD_W = 135;
LCD_H = 240;
}
else if (USE_HORIZONTAL==2 || USE_HORIZONTAL==3)
{
LCD_W = 240;
LCD_H = 135;
}
if(USE_HORIZONTAL==0)LCD_WR_DATA8(0x00);
else if(USE_HORIZONTAL==1)LCD_WR_DATA8(0xC0);
else if(USE_HORIZONTAL==2)LCD_WR_DATA8(0x70);
else if(USE_HORIZONTAL==3)LCD_WR_DATA8(0xA0);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_machine_lcd_setRotation_obj, machine_lcd_setRotation);
/// \method fillScreen()
/// fill screen lcd display.
STATIC mp_obj_t machine_lcd_fillScreen(mp_obj_t self_in, mp_obj_t color_in) {
machine_lcd_obj_t *self = self_in;
// get the character to write (might be 9 bits)
uint16_t color = mp_obj_get_int(color_in);
(void)self;
LCD_Clear(color);
BACK_COLOR = color;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_machine_lcd_fillScreen_obj, machine_lcd_fillScreen);
/// \method clear()
/// clear lcd screen display by color.
STATIC mp_obj_t machine_lcd_clear(mp_obj_t self_in, mp_obj_t color_in) {
machine_lcd_obj_t *self = self_in;
// get the character to write (might be 9 bits)
uint16_t color = mp_obj_get_int(color_in);
(void)self;
LCD_Clear(color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_machine_lcd_clear_obj, machine_lcd_clear);
/// \method showChinese()
/// show chinese word, in parameters: x,y,index,size,color.
STATIC mp_obj_t machine_lcd_showChinese(size_t n_args, const mp_obj_t *args) {
mp_int_t x = mp_obj_get_int(args[1]);
mp_int_t y = mp_obj_get_int(args[2]);
mp_int_t index = mp_obj_get_int(args[3]);
mp_int_t size = mp_obj_get_int(args[4]);
mp_int_t color = mp_obj_get_int(args[5]);
LCD_ShowChinese(x,y,index,size,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_showChinese_obj, 6, 6, machine_lcd_showChinese);
/// \method drawPoint()
/// draw point, in parameters x,y,color.
STATIC mp_obj_t machine_lcd_drawPoint(size_t n_args, const mp_obj_t *args) {
mp_int_t x = mp_obj_get_int(args[1]);
mp_int_t y = mp_obj_get_int(args[2]);
mp_int_t color = mp_obj_get_int(args[3]);
LCD_DrawPoint(x,y,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_drawPoint_obj, 4, 4, machine_lcd_drawPoint);
/// \method drawBigPoint()
/// draw big point, in parameters x,y,color.
STATIC mp_obj_t machine_lcd_drawBigPoint(size_t n_args, const mp_obj_t *args) {
mp_int_t x = mp_obj_get_int(args[1]);
mp_int_t y = mp_obj_get_int(args[2]);
mp_int_t color = mp_obj_get_int(args[3]);
LCD_DrawBigPoint(x,y,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_drawBigPoint_obj, 4, 4, machine_lcd_drawBigPoint);
/// \method fill()
/// draw fill area, in parameters x1,y1,x2,y2,color.
STATIC mp_obj_t machine_lcd_fill(size_t n_args, const mp_obj_t *args) {
mp_int_t x1 = mp_obj_get_int(args[1]);
mp_int_t y1 = mp_obj_get_int(args[2]);
mp_int_t x2 = mp_obj_get_int(args[3]);
mp_int_t y2 = mp_obj_get_int(args[4]);
mp_int_t color = mp_obj_get_int(args[5]);
LCD_Fill(x1,y1,x2,y2,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_fill_obj, 6, 6, machine_lcd_fill);
/// \method drawLine()
/// draw a line, in parameters x1,y1,x2,y2,color.
STATIC mp_obj_t machine_lcd_drawLine(size_t n_args, const mp_obj_t *args) {
mp_int_t x1 = mp_obj_get_int(args[1]);
mp_int_t y1 = mp_obj_get_int(args[2]);
mp_int_t x2 = mp_obj_get_int(args[3]);
mp_int_t y2 = mp_obj_get_int(args[4]);
mp_int_t color = mp_obj_get_int(args[5]);
LCD_DrawLine(x1,y1,x2,y2,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_drawLine_obj, 6, 6, machine_lcd_drawLine);
/// \method drawRectangle()
/// draw a rectangle, in parameters x1,y1,x2,y2,color.
STATIC mp_obj_t machine_lcd_drawRectangle(size_t n_args, const mp_obj_t *args) {
mp_int_t x1 = mp_obj_get_int(args[1]);
mp_int_t y1 = mp_obj_get_int(args[2]);
mp_int_t x2 = mp_obj_get_int(args[3]);
mp_int_t y2 = mp_obj_get_int(args[4]);
mp_int_t color = mp_obj_get_int(args[5]);
LCD_DrawRectangle(x1,y1,x2,y2,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_drawRectangle_obj, 6, 6,machine_lcd_drawRectangle);
/// \method drawCircle()
/// draw a Circle, in parameters x,y,rad,color.
STATIC mp_obj_t machine_lcd_drawCircle(size_t n_args, const mp_obj_t *args) {
mp_int_t x = mp_obj_get_int(args[1]);
mp_int_t y = mp_obj_get_int(args[2]);
mp_int_t r = mp_obj_get_int(args[3]);
mp_int_t color = mp_obj_get_int(args[4]);
LCD_DrawCircle(x,y,r,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_drawCircle_obj, 5, 5,machine_lcd_drawCircle);
/// \method showChar()
/// show a Char, in parameters x,y,char,mode,color.
STATIC mp_obj_t machine_lcd_showChar(size_t n_args, const mp_obj_t *args) {
mp_int_t x = mp_obj_get_int(args[1]);
mp_int_t y = mp_obj_get_int(args[2]);
mp_int_t c = mp_obj_get_int(args[3]);
mp_int_t m = mp_obj_get_int(args[4]);
mp_int_t color = mp_obj_get_int(args[5]);
LCD_ShowChar(x,y,c,m,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_showChar_obj, 6, 6, machine_lcd_showChar);
/// \method showString()
/// show String, in parameters x,y,string,color.
STATIC mp_obj_t machine_lcd_showString(size_t n_args, const mp_obj_t *args) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
mp_int_t x = mp_obj_get_int(args[1]);
mp_int_t y = mp_obj_get_int(args[2]);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ);
mp_int_t color = mp_obj_get_int(args[4]);
(void)self;
LCD_ShowString(x,y,bufinfo.buf,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_showString_obj, 5, 5, machine_lcd_showString);
/// \method showNum()
/// show Num, in parameters x,y,Num,len,color.
STATIC mp_obj_t machine_lcd_showNum(size_t n_args, const mp_obj_t *args) {
mp_int_t x = mp_obj_get_int(args[1]);
mp_int_t y = mp_obj_get_int(args[2]);
mp_int_t n = mp_obj_get_int(args[3]);
mp_int_t l = mp_obj_get_int(args[4]);
mp_int_t color = mp_obj_get_int(args[5]);
LCD_ShowNum(x,y,n,l,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_showNum_obj, 6, 6, machine_lcd_showNum);
/// \method showFloat()
/// show Float, in parameters x,y,Float,len,color.
STATIC mp_obj_t machine_lcd_showFloat(size_t n_args, const mp_obj_t *args) {
mp_int_t x = mp_obj_get_int(args[1]);
mp_int_t y = mp_obj_get_int(args[2]);
mp_float_t f = mp_obj_get_float(args[3]);
mp_int_t l = mp_obj_get_int(args[4]);
mp_int_t color = mp_obj_get_int(args[5]);
LCD_ShowFloat(x,y,f,l,color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_showFloat_obj, 6, 6, machine_lcd_showFloat);
/// \method showPicture()
/// show Picture, in parameters x1,y1
STATIC mp_obj_t machine_lcd_showPicture(size_t n_args, const mp_obj_t *args) {
mp_int_t x1 = mp_obj_get_int(args[1]);
mp_int_t y1 = mp_obj_get_int(args[2]);
mp_int_t x2 = x1 + 39;
mp_int_t y2 = y1 + 39;
LCD_ShowPicture(x1,y1,x2,y2);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_showPicture_obj, 3, 3, machine_lcd_showPicture);
/// \method showLogo()
/// show Logo.
STATIC mp_obj_t machine_lcd_showLogo(mp_obj_t self_in) {
machine_lcd_obj_t *self = self_in;
(void)self;
LCD_ShowLogo();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_machine_lcd_showLogo_obj, machine_lcd_showLogo);
/// \method showBLE()
/// show BLE LOGO, in parameters x1,y1
STATIC mp_obj_t machine_lcd_showBLE(size_t n_args, const mp_obj_t *args) {
mp_int_t x1 = mp_obj_get_int(args[1]);
mp_int_t y1 = mp_obj_get_int(args[2]);
mp_int_t x2 = x1 + 39;
mp_int_t y2 = y1 + 39;
LCD_ShowBLE(x1,y1,x2,y2);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_lcd_showBLE_obj, 3, 3, machine_lcd_showBLE);
/// \method showEnable()
/// show enable.
STATIC mp_obj_t machine_lcd_showEnable(mp_obj_t self_in) {
machine_lcd_obj_t *self = self_in;
(void)self;
LCD_ShowEnable();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_machine_lcd_showEnable_obj, machine_lcd_showEnable);
/// \method showDisable()
/// show disable.
STATIC mp_obj_t machine_lcd_showDisable(mp_obj_t self_in) {
machine_lcd_obj_t *self = self_in;
(void)self;
LCD_ShowDisable();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_machine_lcd_showDisable_obj, machine_lcd_showDisable);
STATIC const mp_rom_map_elem_t machine_lcd_locals_dict_table[] = {
// instance methods
// class methods
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&mp_machine_lcd_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&mp_machine_lcd_clear_obj) },
{ MP_ROM_QSTR(MP_QSTR_setRotation), MP_ROM_PTR(&mp_machine_lcd_setRotation_obj) },
{ MP_ROM_QSTR(MP_QSTR_fillScreen), MP_ROM_PTR(&mp_machine_lcd_fillScreen_obj) },
{ MP_ROM_QSTR(MP_QSTR_showChinese), MP_ROM_PTR(&mp_machine_lcd_showChinese_obj) },
{ MP_ROM_QSTR(MP_QSTR_drawPoint), MP_ROM_PTR(&mp_machine_lcd_drawPoint_obj) },
{ MP_ROM_QSTR(MP_QSTR_drawBigPoint), MP_ROM_PTR(&mp_machine_lcd_drawBigPoint_obj) },
{ MP_ROM_QSTR(MP_QSTR_fill), MP_ROM_PTR(&mp_machine_lcd_fill_obj) },
{ MP_ROM_QSTR(MP_QSTR_drawLine), MP_ROM_PTR(&mp_machine_lcd_drawLine_obj) },
{ MP_ROM_QSTR(MP_QSTR_drawRectangle), MP_ROM_PTR(&mp_machine_lcd_drawRectangle_obj) },
{ MP_ROM_QSTR(MP_QSTR_drawCircle), MP_ROM_PTR(&mp_machine_lcd_drawCircle_obj) },
{ MP_ROM_QSTR(MP_QSTR_showChar), MP_ROM_PTR(&mp_machine_lcd_showChar_obj) },
{ MP_ROM_QSTR(MP_QSTR_showString), MP_ROM_PTR(&mp_machine_lcd_showString_obj) },
{ MP_ROM_QSTR(MP_QSTR_showNum), MP_ROM_PTR(&mp_machine_lcd_showNum_obj) },
{ MP_ROM_QSTR(MP_QSTR_showFloat), MP_ROM_PTR(&mp_machine_lcd_showFloat_obj) },
{ MP_ROM_QSTR(MP_QSTR_showPicture), MP_ROM_PTR(&mp_machine_lcd_showPicture_obj) },
{ MP_ROM_QSTR(MP_QSTR_showLogo), MP_ROM_PTR(&mp_machine_lcd_showLogo_obj) },
{ MP_ROM_QSTR(MP_QSTR_showBLE), MP_ROM_PTR(&mp_machine_lcd_showBLE_obj) },
{ MP_ROM_QSTR(MP_QSTR_showEnable), MP_ROM_PTR(&mp_machine_lcd_showEnable_obj) },
{ MP_ROM_QSTR(MP_QSTR_showDisable), MP_ROM_PTR(&mp_machine_lcd_showDisable_obj) },
{ MP_ROM_QSTR(MP_QSTR_WHITE), MP_ROM_INT(LCD_WHITE) },
{ MP_ROM_QSTR(MP_QSTR_BLACK), MP_ROM_INT(LCD_BLACK) },
{ MP_ROM_QSTR(MP_QSTR_BLUE), MP_ROM_INT(LCD_BLUE) },
{ MP_ROM_QSTR(MP_QSTR_BRED), MP_ROM_INT(LCD_BRED) },
{ MP_ROM_QSTR(MP_QSTR_GRED), MP_ROM_INT(LCD_GRED) },
{ MP_ROM_QSTR(MP_QSTR_GBLUE), MP_ROM_INT(LCD_GBLUE) },
{ MP_ROM_QSTR(MP_QSTR_RED), MP_ROM_INT(LCD_RED) },
{ MP_ROM_QSTR(MP_QSTR_MAGENTA), MP_ROM_INT(LCD_MAGENTA) },
{ MP_ROM_QSTR(MP_QSTR_GREEN), MP_ROM_INT(LCD_GREEN) },
{ MP_ROM_QSTR(MP_QSTR_CYAN), MP_ROM_INT(LCD_CYAN) },
{ MP_ROM_QSTR(MP_QSTR_YELLOW), MP_ROM_INT(LCD_YELLOW) },
{ MP_ROM_QSTR(MP_QSTR_BROWN), MP_ROM_INT(LCD_BROWN) },
{ MP_ROM_QSTR(MP_QSTR_BRRED), MP_ROM_INT(LCD_BRRED) },
{ MP_ROM_QSTR(MP_QSTR_GRAY), MP_ROM_INT(LCD_GRAY) },
{ MP_ROM_QSTR(MP_QSTR_DARKBLUE), MP_ROM_INT(LCD_DARKBLUE) },
{ MP_ROM_QSTR(MP_QSTR_LIGHTBLUE), MP_ROM_INT(LCD_LIGHTBLUE) },
{ MP_ROM_QSTR(MP_QSTR_GRAYBLUE), MP_ROM_INT(LCD_GRAYBLUE) },
{ MP_ROM_QSTR(MP_QSTR_IGHTGREEN), MP_ROM_INT(LCD_IGHTGREEN) },
{ MP_ROM_QSTR(MP_QSTR_LGRAY), MP_ROM_INT(LCD_LGRAY) },
{ MP_ROM_QSTR(MP_QSTR_LGRAYBLUE), MP_ROM_INT(LCD_LGRAYBLUE) },
{ MP_ROM_QSTR(MP_QSTR_LBBLUE), MP_ROM_INT(LCD_LBBLUE) },
};
STATIC MP_DEFINE_CONST_DICT(machine_lcd_locals_dict, machine_lcd_locals_dict_table);
const mp_obj_type_t machine_lcd_type = {
{ &mp_type_type },
.name = MP_QSTR_LCD,
.make_new = machine_lcd_make_new,
.locals_dict = (mp_obj_dict_t*)&machine_lcd_locals_dict,
.print = machine_lcd_print,
};
#endif // MICROPY_PY_MACHINE_LCD
| 30.933005 | 119 | 0.573558 |
53ada91bdd5bc17178f520f6cb9fb82444b85b99 | 712 | c | C | Programs/rotate an araay.c | Sanketkadam143/Hacktoberfest2021 | 3862433f8af941c48c915446fa23b5aa28d38af3 | [
"MIT"
] | 21 | 2021-10-02T07:10:18.000Z | 2022-01-28T08:38:27.000Z | Programs/rotate an araay.c | mrcoder991/Hacktoberfest2021--gkulk007 | f19a5b121f08419d4e42407d9bc0738a17b4c192 | [
"MIT"
] | 19 | 2021-10-01T17:03:46.000Z | 2021-10-20T07:31:36.000Z | Programs/rotate an araay.c | mrcoder991/Hacktoberfest2021--gkulk007 | f19a5b121f08419d4e42407d9bc0738a17b4c192 | [
"MIT"
] | 115 | 2021-10-01T22:03:58.000Z | 2022-01-28T08:38:31.000Z | #include<stdio.h>
int display(int arr[],int n)
{
int i;
printf("The array is: ");
for(i=0;i<n;i++)
{
printf("%d, ",arr[i]);
}
printf("\n");
}
int rotate(int arr[], int d, int n)
{
int i;
for (i=0;i<d;i++)
{
int temp=arr[0],i;
for (i=0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n-1] = temp;
}
}
int main()
{
int n,d,i;
printf("Enter the number of elements: ");
scanf("%d",&n);
int arr[n];
for(i=0;i<n;i++)
{
printf("Enter element %d in the array: " , i+1);
scanf("%d",&arr[i]);
}
display(arr,n);
printf("Enter the number of elements by which you want to rotate: ");
scanf("%d",&d);
rotate(arr,d,n);
display(arr,n);
} | 16.952381 | 71 | 0.492978 |
3ef26f867afe005ec4555f6065b4ffb248295a94 | 5,195 | h | C | src/poller.h | mmig/zeromq.js | e2821f002eebec2428e83614d8b5309388c79342 | [
"MIT"
] | 1,180 | 2016-10-30T15:46:20.000Z | 2022-03-27T21:12:21.000Z | src/poller.h | mmig/zeromq.js | e2821f002eebec2428e83614d8b5309388c79342 | [
"MIT"
] | 358 | 2016-10-29T17:12:17.000Z | 2022-03-25T15:18:30.000Z | src/poller.h | mmig/zeromq.js | e2821f002eebec2428e83614d8b5309388c79342 | [
"MIT"
] | 205 | 2016-10-30T07:44:13.000Z | 2022-03-08T17:39:15.000Z | /* Copyright (c) 2017-2019 Rolf Timmermans */
#pragma once
#include "util/uvhandle.h"
#include "util/uvloop.h"
namespace zmq {
/* Starts a UV poller with an attached timeout. The poller can be started
and stopped multiple times. */
template <typename T>
class Poller {
UvHandle<uv_poll_t> poll;
UvHandle<uv_timer_t> readable_timer;
UvHandle<uv_timer_t> writable_timer;
int32_t events{0};
std::function<void()> finalize = nullptr;
public:
/* Initialize the poller with the given file descriptor. FD should be
ZMQ style edge-triggered, with READABLE state indicating that ANY
event may be present on the corresponding ZMQ socket. */
inline int32_t Initialize(
Napi::Env env, uv_os_sock_t& fd, std::function<void()> finalizer = nullptr) {
auto loop = UvLoop(env);
poll->data = this;
if (auto err = uv_poll_init_socket(loop, poll, fd); err != 0) {
return err;
}
readable_timer->data = this;
if (auto err = uv_timer_init(loop, readable_timer); err != 0) {
return err;
}
writable_timer->data = this;
if (auto err = uv_timer_init(loop, writable_timer); err != 0) {
return err;
}
finalize = finalizer;
return 0;
}
/* Safely close and release all handles. This can be called before
destruction to release resources early. */
inline void Close() {
/* Trigger watched events manually, which causes any pending operation
to succeed or fail immediately. */
Trigger(events);
/* Pollers and timers are stopped automatically by uv_close() which is
wrapped in UvHandle. */
/* Release references to all UV handles. */
poll.reset();
readable_timer.reset();
writable_timer.reset();
if (finalize) finalize();
}
/* Start polling for readable state, with the given timeout. */
inline void PollReadable(int64_t timeout) {
assert((events & UV_READABLE) == 0);
if (timeout > 0) {
auto err = uv_timer_start(readable_timer,
[](uv_timer_t* timer) {
auto& poller = *reinterpret_cast<Poller*>(timer->data);
poller.Trigger(UV_READABLE);
},
timeout, 0);
assert(err == 0);
}
if (!events) {
/* Only start polling if we were not polling already. */
auto err = uv_poll_start(poll, UV_READABLE, Callback);
assert(err == 0);
}
events |= UV_READABLE;
}
inline void PollWritable(int64_t timeout) {
assert((events & UV_WRITABLE) == 0);
if (timeout > 0) {
auto err = uv_timer_start(writable_timer,
[](uv_timer_t* timer) {
auto& poller = *reinterpret_cast<Poller*>(timer->data);
poller.Trigger(UV_WRITABLE);
},
timeout, 0);
assert(err == 0);
}
/* Note: We poll for READS only! "ZMQ shall signal ANY pending
events on the socket in an edge-triggered fashion by making the
file descriptor become ready for READING." */
if (!events) {
auto err = uv_poll_start(poll, UV_READABLE, Callback);
assert(err == 0);
}
events |= UV_WRITABLE;
}
/* Trigger any events that are ready. Use validation callbacks to see
which events are actually available. */
inline void TriggerReadable() {
if (events & UV_READABLE) {
if (static_cast<T*>(this)->ValidateReadable()) {
Trigger(UV_READABLE);
}
}
}
inline void TriggerWritable() {
if (events & UV_WRITABLE) {
if (static_cast<T*>(this)->ValidateWritable()) {
Trigger(UV_WRITABLE);
}
}
}
private:
/* Trigger one or more specific events manually. No validation is
performed, which means these will cause EAGAIN errors if no events
were actually available. */
inline void Trigger(int32_t triggered) {
events &= ~triggered;
if (!events) {
auto err = uv_poll_stop(poll);
assert(err == 0);
}
if (triggered & UV_READABLE) {
auto err = uv_timer_stop(readable_timer);
assert(err == 0);
static_cast<T*>(this)->ReadableCallback();
}
if (triggered & UV_WRITABLE) {
auto err = uv_timer_stop(writable_timer);
assert(err == 0);
static_cast<T*>(this)->WritableCallback();
}
}
/* Callback is called when FD is set to a readable state. This is an
edge trigger that should allow us to check for read AND write events.
There is no guarantee that any events are available. */
static void Callback(uv_poll_t* poll, int32_t status, int32_t events) {
if (status == 0) {
auto& poller = *reinterpret_cast<Poller*>(poll->data);
poller.TriggerReadable();
poller.TriggerWritable();
}
}
};
}
| 30.922619 | 85 | 0.571126 |
99200a6199205d7d97f802e3ea893b33abf91de2 | 4,545 | h | C | platform/windows/Corona.Native.Library.Win32/Interop/Storage/MStoredPreferences.h | agramonte/corona | 3a6892f14eea92fdab5fa6d41920aa1e97bc22b1 | [
"MIT"
] | 1,968 | 2018-12-30T21:14:22.000Z | 2022-03-31T23:48:16.000Z | platform/windows/Corona.Native.Library.Win32/Interop/Storage/MStoredPreferences.h | agramonte/corona | 3a6892f14eea92fdab5fa6d41920aa1e97bc22b1 | [
"MIT"
] | 303 | 2019-01-02T19:36:43.000Z | 2022-03-31T23:52:45.000Z | platform/windows/Corona.Native.Library.Win32/Interop/Storage/MStoredPreferences.h | agramonte/corona | 3a6892f14eea92fdab5fa6d41920aa1e97bc22b1 | [
"MIT"
] | 254 | 2019-01-02T19:05:52.000Z | 2022-03-30T06:32:28.000Z | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Rtt_Preference.h"
#include "Rtt_OperationResult.h"
namespace Rtt
{
class PreferenceCollection;
}
namespace Interop { namespace Storage {
/// <summary>
/// <para>Interface to an object used to read, write, and delete an application's preferences to storage.</para>
/// <para>Preferences are key-value pairs used to easily store simple data/settings.</para>
/// </summary>
/// <remarks>
/// This is an abstract class. A derived class is expected to implement how preferences are stored,
/// such as to a SQLite database or to the Windows registys. This allows us to easily swap out the storage
/// implementation that the Corona "RuntimeEnvironment" class will use.
/// </remarks>
class MStoredPreferences
{
public:
/// <summary>Destroys this object.</summary>
virtual ~MStoredPreferences() {}
/// <summary>Fetches a preference's value by its unique key name.</summary>
/// <param name="keyName">The unique name of the preference in UTF-8 form.</param>
/// <returns>
/// <para>
/// Returns a success result if the preference was found.
/// The result object's GetValue() method will return the fetched preference's value.
/// </para>
/// <para>
/// Returns a failure result if the preference key was not found or if there was a problem accessing storage.
/// The result object's GetUtf8Message() method will return a string detailing why it failed.
/// </para>
/// </returns>
virtual Rtt::Preference::ReadValueResult Fetch(const char* keyName) = 0;
/// <summary>Writes the given preference key-value pair to storage.</summary>
/// <param name="preference">The preference key name and value.</param>
/// <returns>
/// <para>Returns a success result if the given preference was written to storage.</para>
/// <para>
/// Returns a failure result if failed to write the given preference to storage.
/// The result object's GetUtf8Message() method will return a string detailing why it failed.
/// </para>
/// </returns>
virtual Rtt::OperationResult UpdateWith(const Rtt::Preference& preference) = 0;
/// <summary>Writes the given collection of preference key-value pairs to storage.</summary>
/// <param name="preferences">Collection of preferences to write to storage. Can be empty.</param>
/// <returns>
/// <para>Returns a success result if all of the given preferences were written to storage.</para>
/// <para>
/// Returns a failure result if at least 1 preference has failed to write to storage.
/// The result object's GetUtf8Message() method will return a string detailing why it failed.
/// </para>
/// </returns>
virtual Rtt::OperationResult UpdateWith(const Rtt::PreferenceCollection& preferences) = 0;
/// <summary>Delete a preference from storage by its unique string key.</summary>
/// <param name="keyName">The unique name of the preference to delete in UTF-8 form.</param>
/// <returns>
/// <para>Returns a success result if the preference was deleted from storage.</para>
/// <para>
/// Returns a failure result if failed to access storage or unable to delete the preference.
/// The result object's GetUtf8Message() method will return a string detailing why it failed.
/// </para>
/// </returns>
virtual Rtt::OperationResult Delete(const char* keyName) = 0;
/// <summary>Delete multiple preferences from storage by their unique string keys.</summary>
/// <param name="keyNameArray">Array of unique preference names (in UTF-8 form) to delete from storage.</param>
/// <param name="count">The number of keys/elements in the "keyNameArray" argument.</param>
/// <returns>
/// <para>Returns a success result if all of the given preferences have been deleted from storage.</para>
/// <para>
/// Returns a failure result if failed to access storage, if unable to delete at least 1 preference,
/// or if "keyNameArray" is null.
/// The result object's GetUtf8Message() method will return a string detailing why it failed.
/// </para>
/// </returns>
virtual Rtt::OperationResult Delete(const char* keyNameArray[], int count) = 0;
};
} } // namespace Interop::Storage
| 45 | 113 | 0.681408 |
994eea59b2e68bfa5986598591260a2922c26a7c | 2,559 | h | C | WaspmoteEd25519/Curve25519.h | khssnv/waspmote_ed25519 | c669547e96a71e9689cc17a426e6be1fc13f54d3 | [
"BSD-3-Clause"
] | 1 | 2022-02-15T02:58:46.000Z | 2022-02-15T02:58:46.000Z | WaspmoteEd25519/Curve25519.h | khssnv/waspmote_ed25519 | c669547e96a71e9689cc17a426e6be1fc13f54d3 | [
"BSD-3-Clause"
] | null | null | null | WaspmoteEd25519/Curve25519.h | khssnv/waspmote_ed25519 | c669547e96a71e9689cc17a426e6be1fc13f54d3 | [
"BSD-3-Clause"
] | 1 | 2018-07-31T12:58:51.000Z | 2018-07-31T12:58:51.000Z | /*
* Copyright (C) 2015 Southern Storm Software, Pty Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef CRYPTO_CURVE25519_h
#define CRYPTO_CURVE25519_h
#include "BigNumberUtil.h"
class Ed25519;
class Curve25519
{
public:
static bool eval(uint8_t result[32], const uint8_t s[32], const uint8_t x[32]);
#if defined(TEST_CURVE25519_FIELD_OPS)
public:
#else
private:
#endif
static uint8_t isWeakPoint(const uint8_t k[32]);
static void reduce(limb_t *result, limb_t *x, uint8_t size);
static limb_t reduceQuick(limb_t *x);
static void mulNoReduce(limb_t *result, const limb_t *x, const limb_t *y);
static void mul(limb_t *result, const limb_t *x, const limb_t *y);
static void square(limb_t *result, const limb_t *x)
{
mul(result, x, x);
}
static void mulA24(limb_t *result, const limb_t *x);
static void mul_P(limb_t *result, const limb_t *x, const limb_t *y);
static void add(limb_t *result, const limb_t *x, const limb_t *y);
static void sub(limb_t *result, const limb_t *x, const limb_t *y);
static void cswap(limb_t select, limb_t *x, limb_t *y);
static void cmove(limb_t select, limb_t *x, const limb_t *y);
static void pow250(limb_t *result, const limb_t *x);
static void recip(limb_t *result, const limb_t *x);
static bool sqrt(limb_t *result, const limb_t *x);
// Constructor and destructor are private - cannot instantiate this class.
Curve25519() {}
~Curve25519() {}
friend class Ed25519;
};
#endif
| 34.12 | 83 | 0.724502 |
3e3854e87af434fed1f74d85cc9743a9be70fae9 | 601 | c | C | tests/tests_libmy/tests_my_str/tests_my_strncmp.c | BourgeoisBenjamin/EPITECH_PSU_42sh_2018 | b1163ad4369f5512eb2d049bec5350ce31af4175 | [
"MIT"
] | null | null | null | tests/tests_libmy/tests_my_str/tests_my_strncmp.c | BourgeoisBenjamin/EPITECH_PSU_42sh_2018 | b1163ad4369f5512eb2d049bec5350ce31af4175 | [
"MIT"
] | null | null | null | tests/tests_libmy/tests_my_str/tests_my_strncmp.c | BourgeoisBenjamin/EPITECH_PSU_42sh_2018 | b1163ad4369f5512eb2d049bec5350ce31af4175 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2018
** PROJECT - UNIT TEST
** File description:
** Unit Tests for my_strncmp function
*/
#include "my.h"
#include "unittest.h"
Test(my_strncmp, test_00)
{
cr_expect_eq(my_strncmp("abcd", "bacd", 2), -1);
}
Test(my_strncmp, test_01)
{
cr_expect_eq(my_strncmp("Hello World\t\n", "Hello World\t\n", 5), 0);
}
Test(my_strncmp, test_02)
{
cr_expect_eq(my_strncmp(" ", " ", 7), 0);
}
Test(my_strncmp, test_03)
{
cr_expect_eq(my_strncmp("bacd", "abcd", 4), 1);
}
Test(my_strncmp, test_04)
{
cr_expect_eq(my_strncmp("djizad123", "djizad123", 6), 0);
}
| 17.171429 | 73 | 0.643927 |
c43963f286ed2788abe9581130ae86cacda286a6 | 7,272 | h | C | xdk-asf-3.51.0/thirdparty/wireless/ble_sdk/services/serial/uart/sam/module_config/samg55/conf_serialdrv.h | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | xdk-asf-3.51.0/thirdparty/wireless/ble_sdk/services/serial/uart/sam/module_config/samg55/conf_serialdrv.h | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | xdk-asf-3.51.0/thirdparty/wireless/ble_sdk/services/serial/uart/sam/module_config/samg55/conf_serialdrv.h | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | /**
* \file
*
* \brief SAM G55 serial driver configuration.
*
* Copyright (c) 2017-2018 Microchip Technology Inc. and its subsidiaries.
*
* \asf_license_start
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip
* software and any derivatives exclusively with Microchip products.
* It is your responsibility to comply with third party license terms applicable
* to your use of third party software (including open source software) that
* may accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES,
* WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE,
* INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY,
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE
* LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL
* LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE
* SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE
* POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT
* ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY
* RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*
* \asf_license_stop
*
*/
#ifndef CONF_SERIALDRV_H_INCLUDED
#define CONF_SERIALDRV_H_INCLUDED
#if ((UART_FLOWCONTROL_4WIRE_MODE == true) || (UART_FLOWCONTROL_6WIRE_MODE == true))
#if (BLE_MODULE == BTLC1000_MR)
/* BTLC1000 Wakeup Pin */
#define BTLC1000_WAKEUP_PIN (EXT1_PIN_4)
/* BTLC1000 Chip Enable Pin */
#define BTLC1000_CHIP_ENABLE_PIN (EXT1_PIN_10)
#if SAMG55
#warning "EXT1 PIN6 is configured as BTLC1000 Wakeup Pin. \
Inorder to Use USART0 Hardware Flowcontrol, BTLC1000 Wakeup \
Pin moved to EXT1 PIN 4 and BTLC1000 Chip Enable Pin moved to ETX1 PIN10"
#endif
# elif (BLE_MODULE == BTLC1000_ZR)
/* BTLC1000 Wakeup Pin */
#define BTLC1000_WAKEUP_PIN (EXT1_PIN_3)
/* BTLC1000 Chip Enable Pin */
#define BTLC1000_CHIP_ENABLE_PIN (EXT1_PIN_7)
#endif // BLE_MODULE
#else
/* BTLC1000 Wakeup Pin */
#define BTLC1000_WAKEUP_PIN (EXT1_PIN_6)
/* BTLC1000 Chip Enable Pin */
#define BTLC1000_CHIP_ENABLE_PIN (EXT1_PIN_4)
#endif
/* BTLC1000 50ms Reset Duration */
#define BTLC1000_RESET_MS (50)
/* set port pin high */
#define IOPORT_PIN_LEVEL_HIGH (true)
/* Set port pin low */
#define IOPORT_PIN_LEVEL_LOW (false)
/** UART Interface */
#define BLE_UART EXT1_UART_MODULE
#define BLE_UART_ID ID_FLEXCOM0
#define BLE_USART_FLEXCOM FLEXCOM0
#define BLE_UART_IRQn FLEXCOM0_IRQn
/* Configuration for console uart IRQ handler */
#define BLE_UART_Handler FLEXCOM0_Handler
/** UART Flow Control Interface */
#define BLE_PATCH_UART USART5
#define BLE_PATCH_UART_ID ID_FLEXCOM5
#define BLE_PATCH_USART_FLEXCOM FLEXCOM5
#define BLE_PATCH_UART_IRQn FLEXCOM5_IRQn
/* Configuration for console uart IRQ handler */
#define BLE_PATCH_UART_Handler FLEXCOM5_Handler
/* This value used to get Rx Timeout at end of Rx frame @115200 3.5Character Timeout used */
#define RX_TIMEOUT_VALUE 35
/** Baudrate setting */
#define CONF_UART_BAUDRATE (115200UL)
/** Character length setting */
#define CONF_UART_CHAR_LENGTH US_MR_CHRL_8_BIT
/** Parity setting */
#define CONF_UART_PARITY US_MR_PAR_NO
/** Stop bits setting */
#define CONF_UART_STOP_BITS US_MR_NBSTOP_1_BIT
#define SERIAL_DRV_RX_CB plaform_ble_rx_callback
#define SERIAL_DRV_RX_CB_ENABLE true
#ifdef BLE_OBSERVER_APP
#define BLE_MAX_RX_PAYLOAD_SIZE 512
#else
#define BLE_MAX_RX_PAYLOAD_SIZE 1024
#endif
#define BLE_MAX_TX_PAYLOAD_SIZE 1024
/**
* BTLC1000 Host Wakeup Control
* @{
*/
/* BTLC1000 Host Wakeup Pin */
#define BTLC1000_HOST_WAKEUP_PIN (EXT1_PIN_9)
#define BLE_HOST_UART_RTS_PIN (EXT1_PIN_5)
#define PIN_BTLC1000_HOST_WAKEUP_PIO PIOA
#define PIN_BTLC1000_HOST_WAKEUP_MASK PIO_PA24
#define PIN_BTLC1000_HOST_WAKEUP_ID ID_PIOA
#define PIN_BTLC1000_HOST_WAKEUP_ATTR PIO_DEFAULT
#define BTLC1000_HOST_WAKEUP_WAIT_INPUT_ID (1u << 11)
#define BTLC1000_HOST_WAKEUP_BACKUP_INPUT_ID (1u << 11)
void platform_host_wake_interrupt_handler(void);
static inline void btlc1000_host_wakeup_config(void);
static inline void btlc1000_host_wakeup_handler(uint32_t ul_id, uint32_t ul_mask);
/* BTLC1000 Host Wakeup Initialization */
static inline void btlc1000_host_wakeup_config(void)
{
/* Adjust PIO de-bounce filter parameters, Wakeup Immediately */
pio_set_debounce_filter(PIN_BTLC1000_HOST_WAKEUP_PIO,
PIN_BTLC1000_HOST_WAKEUP_MASK, 0);
/* Initialize PIO interrupt handlers, see PIO definition in board.h. */
pio_handler_set(PIN_BTLC1000_HOST_WAKEUP_PIO, PIN_BTLC1000_HOST_WAKEUP_ID,
PIN_BTLC1000_HOST_WAKEUP_MASK, PIN_BTLC1000_HOST_WAKEUP_ATTR,
btlc1000_host_wakeup_handler);
/* Enable PIO controller IRQs. */
NVIC_EnableIRQ((IRQn_Type)PIN_BTLC1000_HOST_WAKEUP_ID);
/* Enable PIO line interrupts. */
pio_enable_interrupt(PIN_BTLC1000_HOST_WAKEUP_PIO,
PIN_BTLC1000_HOST_WAKEUP_MASK);
/* System Controller Wake-up input for Wakeup Pin-11 and Falling Edge */
supc_set_wakeup_inputs(SUPC, SUPC_WUIR_WKUPEN11, SUPC_WUIR_WKUPT11_LOW);
/* set pmc to wakeup from wait mode sleep */
pmc_set_fast_startup_input(PMC_FSMR_FSTT11);
}
/**
* \brief Handler for button interrupt.
*
* \note This interrupt is for waking up from sleep mode or exiting from active
* mode.
*/
static inline void btlc1000_host_wakeup_handler(uint32_t ul_id, uint32_t ul_mask)
{
if (PIN_BTLC1000_HOST_WAKEUP_ID == ul_id &&
PIN_BTLC1000_HOST_WAKEUP_MASK == ul_mask) {
platform_host_wake_interrupt_handler();
}
}
static inline bool host_event_data_ready_pin_level(void)
{
return (ioport_get_pin_level(BTLC1000_HOST_WAKEUP_PIN));
}
static inline bool ble_host_rts_pin_level(void)
{
return (ioport_get_pin_level(BLE_HOST_UART_RTS_PIN));
}
/* Set BLE Wakeup pin to be low */
static inline bool ble_wakeup_pin_level(void)
{
return (ioport_get_pin_level(BTLC1000_WAKEUP_PIN));
}
/* Set BLE Wakeup pin to be low */
static inline void ble_wakeup_pin_set_low(void)
{
ioport_set_pin_level(BTLC1000_WAKEUP_PIN,
IOPORT_PIN_LEVEL_LOW);
}
/* Set wakeup pin to high */
static inline void ble_wakeup_pin_set_high(void)
{
ioport_set_pin_level(BTLC1000_WAKEUP_PIN,
IOPORT_PIN_LEVEL_HIGH);
}
/* Set enable pin to Low */
static inline void ble_enable_pin_set_low(void)
{
ioport_set_pin_level(BTLC1000_CHIP_ENABLE_PIN,
IOPORT_PIN_LEVEL_LOW);
}
/* Set enable pin to high */
static inline void ble_enable_pin_set_high(void)
{
ioport_set_pin_level(BTLC1000_CHIP_ENABLE_PIN,
IOPORT_PIN_LEVEL_HIGH);
}
/* Configure the BTLC1000 control(chip_enable, wakeup) pins */
static inline void ble_configure_control_pin(void)
{
/* initialize the delay before use */
delay_init();
/* Configure control pins as output */
ioport_init();
ioport_reset_pin_mode(BTLC1000_WAKEUP_PIN);
ioport_enable_pin(BTLC1000_WAKEUP_PIN);
ioport_set_pin_dir(BTLC1000_WAKEUP_PIN, IOPORT_DIR_OUTPUT);
ioport_reset_pin_mode(BTLC1000_CHIP_ENABLE_PIN);
ioport_enable_pin(BTLC1000_CHIP_ENABLE_PIN);
ioport_set_pin_dir(BTLC1000_CHIP_ENABLE_PIN, IOPORT_DIR_OUTPUT);
}
#endif /* CONF_SERIALDRV_H_INCLUDED */
| 30.683544 | 92 | 0.781491 |
3f23cba2fef93ecb603642fc2faf52d6584f76bd | 10,917 | c | C | src/mame/machine/6532riot.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | src/mame/machine/6532riot.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | src/mame/machine/6532riot.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | /***************************************************************************
RIOT 6532 emulation
The timer seems to follow these rules:
- When the timer flag changes from 0 to 1 the timer continues to count
down at a 1 cycle rate.
- When the timer is being read or written the timer flag is reset.
- When the timer flag is set and the timer contents are 0, the counting
stops.
***************************************************************************/
#include "driver.h"
#include "machine/6532riot.h"
struct riot6532
{
const struct riot6532_interface *intf;
UINT8 in_a;
UINT8 out_a;
UINT8 in_b;
UINT8 out_b;
UINT8 ddr_a;
UINT8 ddr_b;
int shift;
int pa7_enable;
int pa7_direction; /* 0x80 = high-to-low, 0x00 = low-to-high */
int pa7_flag;
UINT8 pa7;
int timer_irq_enable;
int timer_irq;
mame_timer *counter_timer;
int clock;
};
static struct riot6532 r6532[MAX_R6532];
INLINE void r6532_set_timer(int which, UINT8 count)
{
mame_timer_adjust( r6532[which].counter_timer, scale_up_mame_time(MAME_TIME_IN_HZ(r6532[which].clock), (count << r6532[which].shift) + 1), which, time_zero );
}
static TIMER_CALLBACK( r6532_irq_timer_callback )
{
int which = param;
if ( r6532[which].timer_irq_enable )
{
r6532[which].timer_irq = 1;
if (r6532[which].intf->irq_func)
(*r6532[which].intf->irq_func)(ASSERT_LINE);
else
logerror("6532RIOT chip #%d: Interrupt is asserted but there is no callback function. PC: %08X\n", which, safe_activecpu_get_pc());
}
}
static void r6532_pa7_check(int which){
UINT8 data = ( ( r6532[which].ddr_a & r6532[which].out_a ) | ( ~r6532[which].ddr_a & r6532[which].in_a ) ) & 0x80;
if ((r6532[which].pa7 ^ data) && (r6532[which].pa7_direction ^ data))
{
r6532[which].pa7_flag = 1;
if (r6532[which].pa7_enable)
{
if (r6532[which].intf->irq_func)
(*r6532[which].intf->irq_func)(ASSERT_LINE);
else
logerror("6532RIOT chip #%d: Interrupt is asserted but there is no callback function. PC: %08X\n", which, safe_activecpu_get_pc());
}
}
r6532[which].pa7 = data;
}
void r6532_write(int which, offs_t offset, UINT8 data)
{
if (offset & 4)
{
if (offset & 0x10)
{
switch (offset & 3)
{
case 0:
r6532[which].shift = 0;
break;
case 1:
r6532[which].shift = 3;
break;
case 2:
r6532[which].shift = 6;
break;
case 3:
r6532[which].shift = 10;
break;
}
r6532[which].timer_irq_enable = (offset & 8);
r6532_set_timer( which, data );
}
else
{
r6532[which].pa7_enable = (offset & 2) >> 1;
r6532[which].pa7_direction = ( offset & 1 ) << 7;
}
}
else
{
offset &= 3;
switch (offset)
{
case 0:
r6532[which].out_a = data;
if (r6532[which].ddr_a)
{
UINT8 write_data = ( r6532[which].ddr_a & r6532[which].out_a ) | ( ~r6532[which].ddr_a & 0xFF );
if (r6532[which].intf->out_a_func)
r6532[which].intf->out_a_func(0, write_data);
else
logerror("6532RIOT chip #%d: Port A is being written to but has no handler. PC: %08X - %02X\n", which, safe_activecpu_get_pc(), write_data);
/* Check for PA7 change */
r6532_pa7_check(which);
}
break;
case 1:
r6532[which].ddr_a = data;
r6532_pa7_check(which);
break;
case 2:
r6532[which].out_b = data;
if (r6532[which].ddr_b)
{
UINT8 write_data = ( r6532[which].ddr_b & r6532[which].out_b ) | ( ~r6532[which].ddr_b & 0xFF );
if (r6532[which].intf->out_b_func)
r6532[which].intf->out_b_func(0, write_data);
else
logerror("6532RIOT chip #%d: Port B is being written to but has no handler. PC: %08X - %02X\n", which, safe_activecpu_get_pc(), write_data);
}
break;
case 3:
r6532[which].ddr_b = data;
break;
}
}
}
INLINE UINT8 r6532_read_timer(int which)
{
int timer_cycles_left = ( mame_time_to_double(mame_timer_timeleft( r6532[which].counter_timer )) * r6532[which].clock ) - 1;
if ( timer_cycles_left >= 0)
{
timer_cycles_left = timer_cycles_left >> r6532[which].shift;
}
else
{
if (timer_cycles_left != -1)
{
if (r6532[which].intf->irq_func && r6532[which].timer_irq)
(*r6532[which].intf->irq_func)(CLEAR_LINE);
else
logerror("6532RIOT chip #%d: Interrupt is cleared but there is no callback function. PC: %08X\n", which, safe_activecpu_get_pc());
/* Timer flag is cleared, so adjust the target */
timer_cycles_left = ( timer_cycles_left > -256 ) ? timer_cycles_left & 0xFF : 0;
r6532_set_timer( which, timer_cycles_left );
}
}
return timer_cycles_left;
}
void r6532_set_input_a(int which, UINT8 data)
{
r6532[which].in_a = data;
/* Check for PA7 change */
r6532_pa7_check(which);
}
void r6532_set_input_b(int which, UINT8 data)
{
r6532[which].in_b = data;
}
INLINE UINT8 r6532_read_irq_flags(int which)
{
int timer_cycles_left = ( mame_time_to_double(mame_timer_timeleft( r6532[which].counter_timer )) * r6532[which].clock ) - 1;
int res = 0;
if ( timer_cycles_left < 0 )
{
res |= 0x80;
if ( timer_cycles_left < -1 )
{
if ( r6532[which].intf->irq_func)
(*r6532[which].intf->irq_func)(CLEAR_LINE);
else
logerror("6532RIOT chip #%d: Interrupt is cleared but there is no callback function. PC: %08X\n", which, safe_activecpu_get_pc());
/* Timer flag is cleared, so adjust the target */
r6532_set_timer( which, timer_cycles_left > -256 ? timer_cycles_left & 0xFF : 0 );
}
}
if (r6532[which].pa7_flag)
{
res |= 0x40;
r6532[which].pa7_flag = 0;
if (r6532[which].intf->irq_func && timer_cycles_left != -1)
(*r6532[which].intf->irq_func)(CLEAR_LINE);
else
logerror("6532RIOT chip #%d: Interrupt is cleared but there is no callback function. PC: %08X\n", which, safe_activecpu_get_pc());
}
return res;
}
UINT8 r6532_read(int which, offs_t offset)
{
UINT8 val = 0;
switch (offset & 7)
{
case 0:
if (r6532[which].intf->in_a_func)
r6532[which].in_a = r6532[which].intf->in_a_func(0);
else
logerror("6532RIOT chip #%d: Port A is being read but has no handler. PC: %08X\n", which, safe_activecpu_get_pc());
val = ( r6532[which].ddr_a & r6532[which].out_a ) | ( ~r6532[which].ddr_a & r6532[which].in_a );
/* Check for PA7 change */
r6532_pa7_check(which);
break;
case 1:
val = r6532[which].ddr_a;
break;
case 2:
if (r6532[which].intf->in_b_func)
r6532[which].in_b = r6532[which].intf->in_b_func(0);
else
logerror("6532RIOT chip #%d: Port B is being read but has no handler. PC: %08X\n", which, safe_activecpu_get_pc());
val = ( r6532[which].ddr_b & r6532[which].out_b ) | ( ~r6532[which].ddr_b & r6532[which].in_b );
break;
case 3:
val = r6532[which].ddr_b;
break;
case 4:
case 6:
r6532[which].timer_irq_enable = offset & 8;
val = r6532_read_timer(which);
break;
case 5:
case 7:
val = r6532_read_irq_flags(which);
break;
}
return val;
}
void r6532_set_clock(int which, int clock)
{
r6532[which].clock = clock;
}
void r6532_reset(int which)
{
r6532[which].out_a = 0;
r6532[which].out_b = 0;
r6532[which].ddr_a = 0;
r6532[which].ddr_b = 0;
r6532[which].shift = 10;
r6532[which].counter_timer = mame_timer_alloc(r6532_irq_timer_callback);
r6532_set_timer( which, 0xFF );
r6532[which].pa7_enable = 0;
r6532[which].pa7_direction = 0x80;
r6532[which].pa7_flag = 0;
r6532[which].pa7 = 0;
r6532[which].timer_irq_enable = 0;
r6532[which].timer_irq = 0;
if (r6532[which].intf->irq_func)
(*r6532[which].intf->irq_func)(CLEAR_LINE);
else
logerror("6532RIOT chip #%d: Interrupt is cleared but there is no callback function. PC: %08X\n", which, safe_activecpu_get_pc());
}
void r6532_config(int which, const struct riot6532_interface* intf)
{
assert_always(mame_get_phase(Machine) == MAME_PHASE_INIT, "Can only call r6532_init at init time!");
assert_always( which < MAX_R6532, "which exceeds maximum number of configured r6532s!" );
r6532[which].intf = intf;
/* Default clock is CPU #0 clock */
r6532_set_clock( which, Machine->drv->cpu[0].cpu_clock );
}
WRITE8_HANDLER( r6532_0_w ) { r6532_write(0, offset, data); }
WRITE8_HANDLER( r6532_1_w ) { r6532_write(1, offset, data); }
WRITE8_HANDLER( r6532_2_w ) { r6532_write(2, offset, data); }
WRITE8_HANDLER( r6532_3_w ) { r6532_write(3, offset, data); }
WRITE8_HANDLER( r6532_4_w ) { r6532_write(4, offset, data); }
WRITE8_HANDLER( r6532_5_w ) { r6532_write(5, offset, data); }
WRITE8_HANDLER( r6532_6_w ) { r6532_write(6, offset, data); }
WRITE8_HANDLER( r6532_7_w ) { r6532_write(7, offset, data); }
READ8_HANDLER( r6532_0_r ) { return r6532_read(0, offset); }
READ8_HANDLER( r6532_1_r ) { return r6532_read(1, offset); }
READ8_HANDLER( r6532_2_r ) { return r6532_read(2, offset); }
READ8_HANDLER( r6532_3_r ) { return r6532_read(3, offset); }
READ8_HANDLER( r6532_4_r ) { return r6532_read(4, offset); }
READ8_HANDLER( r6532_5_r ) { return r6532_read(5, offset); }
READ8_HANDLER( r6532_6_r ) { return r6532_read(6, offset); }
READ8_HANDLER( r6532_7_r ) { return r6532_read(7, offset); }
WRITE8_HANDLER( r6532_0_porta_w) { r6532_set_input_a(0, data); }
WRITE8_HANDLER( r6532_1_porta_w) { r6532_set_input_a(1, data); }
WRITE8_HANDLER( r6532_2_porta_w) { r6532_set_input_a(2, data); }
WRITE8_HANDLER( r6532_3_porta_w) { r6532_set_input_a(3, data); }
WRITE8_HANDLER( r6532_4_porta_w) { r6532_set_input_a(4, data); }
WRITE8_HANDLER( r6532_5_porta_w) { r6532_set_input_a(5, data); }
WRITE8_HANDLER( r6532_6_porta_w) { r6532_set_input_a(6, data); }
WRITE8_HANDLER( r6532_7_porta_w) { r6532_set_input_a(7, data); }
WRITE8_HANDLER( r6532_0_portb_w) { r6532_set_input_b(0, data); }
WRITE8_HANDLER( r6532_1_portb_w) { r6532_set_input_b(1, data); }
WRITE8_HANDLER( r6532_2_portb_w) { r6532_set_input_b(2, data); }
WRITE8_HANDLER( r6532_3_portb_w) { r6532_set_input_b(3, data); }
WRITE8_HANDLER( r6532_4_portb_w) { r6532_set_input_b(4, data); }
WRITE8_HANDLER( r6532_5_portb_w) { r6532_set_input_b(5, data); }
WRITE8_HANDLER( r6532_6_portb_w) { r6532_set_input_b(6, data); }
WRITE8_HANDLER( r6532_7_portb_w) { r6532_set_input_b(7, data); }
READ8_HANDLER( r6532_0_porta_r) { return r6532[0].in_a; }
READ8_HANDLER( r6532_1_porta_r) { return r6532[1].in_a; }
READ8_HANDLER( r6532_2_porta_r) { return r6532[2].in_a; }
READ8_HANDLER( r6532_3_porta_r) { return r6532[3].in_a; }
READ8_HANDLER( r6532_4_porta_r) { return r6532[4].in_a; }
READ8_HANDLER( r6532_5_porta_r) { return r6532[5].in_a; }
READ8_HANDLER( r6532_6_porta_r) { return r6532[6].in_a; }
READ8_HANDLER( r6532_7_porta_r) { return r6532[7].in_a; }
READ8_HANDLER( r6532_0_portb_r) { return r6532[0].in_b; }
READ8_HANDLER( r6532_1_portb_r) { return r6532[1].in_b; }
READ8_HANDLER( r6532_2_portb_r) { return r6532[2].in_b; }
READ8_HANDLER( r6532_3_portb_r) { return r6532[3].in_b; }
READ8_HANDLER( r6532_4_portb_r) { return r6532[4].in_b; }
READ8_HANDLER( r6532_5_portb_r) { return r6532[5].in_b; }
READ8_HANDLER( r6532_6_portb_r) { return r6532[6].in_b; }
READ8_HANDLER( r6532_7_portb_r) { return r6532[7].in_b; }
| 29.18984 | 159 | 0.688468 |
ac3f0e28ab362a220a02e1ce1cff187c643c89b4 | 1,017 | h | C | Pokemon_client/bag.h | 960813/pokemon | b78781ecb98fa89b533ad967ee1ef5c92d507ba4 | [
"MIT"
] | 5 | 2020-07-01T17:47:11.000Z | 2021-03-16T00:01:05.000Z | Pokemon_client/bag.h | 960813/pokemon | b78781ecb98fa89b533ad967ee1ef5c92d507ba4 | [
"MIT"
] | null | null | null | Pokemon_client/bag.h | 960813/pokemon | b78781ecb98fa89b533ad967ee1ef5c92d507ba4 | [
"MIT"
] | null | null | null | #pragma once
#ifndef _POKEMON_BAG_HEADER_
#define _POKEMON_BAG_HEADER_
#include "book.h"
#include "nginx_common.h"
/*
가방 상태를 저장하는 구조체
bool bagUIOpen;
bool bagUIConv;
int currentMenu;
int currentIndex;
*/
typedef struct BAGUI_STATUS {
bool bagUIOpen;
bool bagUIConv;
int currentMenu;
int currentIndex;
int lastIndex;
} bagUIStatus;
/*
인벤토리 아이템을 저장하는 구조체
int itemType;
int itemStock;
int itemPrice;
char* itemName;
char* itemDesc[3];
*/
typedef struct INVENTORY_ITEM {
int itemType;
int itemStock;
int itemPrice;
char* itemName;
char* itemDesc[3];
} inventoryItem;
// 가방 UI 비트맵을 저장하는 변수
ALLEGRO_BITMAP* bagUIBitmap;
/// <summary>
/// 인벤토리 상호작용에 대한 함수
/// </summary>
void interactInventory();
/// <summary>
/// 아이템 상호작용에 대한 함수
/// </summary>
/// <param name="itemNo"></param>
/// <param name="target"></param>
void interactItem(int itemNo, pokemon* target);
/// <summary>
/// 가방 UI를 그리는 함수
/// </summary>
void drawBagUI();
/// <summary>
/// 가방 메뉴를 닫는 함수
/// </summary>
void closeBagMenu();
#endif | 17.237288 | 47 | 0.699115 |
b169103d29b1e22c48e0c88709dfa84778edc49d | 15,245 | h | C | himan-lib/include/numerical_functions_impl.h | fox91/himan | 4bb0ba4b034675edb21a1b468c0104f00f78784b | [
"MIT"
] | 18 | 2017-04-20T18:51:41.000Z | 2022-03-23T21:12:49.000Z | himan-lib/include/numerical_functions_impl.h | fox91/himan | 4bb0ba4b034675edb21a1b468c0104f00f78784b | [
"MIT"
] | 5 | 2018-07-05T02:15:56.000Z | 2021-06-01T09:36:51.000Z | himan-lib/include/numerical_functions_impl.h | fox91/himan | 4bb0ba4b034675edb21a1b468c0104f00f78784b | [
"MIT"
] | 2 | 2020-02-18T06:32:53.000Z | 2021-03-29T15:17:09.000Z | namespace himan
{
namespace numerical_functions
{
template <typename T, class F, class G>
himan::matrix<T> Reduce2D(const himan::matrix<T>& A, const himan::matrix<T>& B, F&& f, G&& g, T init1, T init2)
{
// find center position of kernel (half of kernel size)
himan::matrix<T> ret(A.SizeX(), A.SizeY(), 1, A.MissingValue());
T convolution_value; // accumulated value of the convolution at a given grid point in A
T kernel_weight_sum; // accumulated value of the kernel weights in B that are used to compute the convolution
// at given point A
int ASizeX = int(A.SizeX());
int ASizeY = int(A.SizeY());
int BSizeX = int(B.SizeX());
int BSizeY = int(B.SizeY());
int kCenterX = BSizeX / 2;
int kCenterY = BSizeY / 2;
for (int j = kCenterY; j < ASizeY - kCenterY; ++j) // columns
{
for (int i = kCenterX; i < ASizeX - kCenterX; ++i) // rows
{
convolution_value = init1;
kernel_weight_sum = init2;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
f(convolution_value, kernel_weight_sum, a, b);
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = g(convolution_value, kernel_weight_sum);
}
}
// treat boundaries separately
// weights get adjusted so that the sum of weights for the active part of the kernel remains 1
// calculate for upper boundary
for (int j = 0; j < kCenterY; ++j) // columns
{
for (int i = 0; i < ASizeX; ++i) // rows
{
convolution_value = init1;
kernel_weight_sum = init2;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
// ignore input samples which are out of bound
if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY)
{
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
f(convolution_value, kernel_weight_sum, a, b);
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = g(convolution_value, kernel_weight_sum); // convolution_value / kernel_weight_sum;
}
}
// calculate for lower boundary
for (int j = ASizeY - kCenterY; j < ASizeY; ++j) // columns
{
for (int i = 0; i < ASizeX; ++i) // rows
{
convolution_value = init1;
kernel_weight_sum = init2;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
// ignore input samples which are out of bound
if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY)
{
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
f(convolution_value, kernel_weight_sum, a, b);
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = g(convolution_value, kernel_weight_sum); // convolution_value / kernel_weight_sum;
}
}
// calculate for left boundary
for (int j = 0; j < ASizeY; ++j) // columns
{
for (int i = 0; i < kCenterX; ++i) // rows
{
convolution_value = init1;
kernel_weight_sum = init2;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
// ignore input samples which are out of bound
if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY)
{
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
f(convolution_value, kernel_weight_sum, a, b);
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = g(convolution_value, kernel_weight_sum); // convolution_value / kernel_weight_sum;
}
}
// calculate for right boundary
for (int j = 0; j < ASizeY; ++j) // columns
{
for (int i = ASizeX - kCenterX; i < ASizeX; ++i) // rows
{
convolution_value = init1;
kernel_weight_sum = init2;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
// ignore input samples which are out of bound
if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY)
{
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
f(convolution_value, kernel_weight_sum, a, b);
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = g(convolution_value, kernel_weight_sum); // convolution_value / kernel_weight_sum;
}
}
return ret;
}
template <typename T, class F>
himan::matrix<T> Prob2D(const himan::matrix<T>& A, const himan::matrix<T>& B, F&& f)
{
return Reduce2D(A, B,
[=](T& val1, T& val2, const T& a, const T& b) {
if (IsValid(a * b))
{
val1 += f(a) ? b : T(0);
val2 += b;
}
},
[=](const T& val1, const T& val2) { return val2 == T(0) ? MissingValue<T>() : val1 / val2; }, T(0),
T(0));
}
template <typename T, class F>
himan::matrix<size_t> FindIndex2D(const himan::matrix<T>& A, const himan::matrix<T>& B, F&& f, T init1)
{
// find center position of kernel (half of kernel size)
himan::matrix<size_t> ret(A.SizeX(), A.SizeY(), 1, kHPMissingInt);
T current_value; //
size_t current_index; //
int ASizeX = int(A.SizeX());
int ASizeY = int(A.SizeY());
int BSizeX = int(B.SizeX());
int BSizeY = int(B.SizeY());
int kCenterX = BSizeX / 2;
int kCenterY = BSizeY / 2;
for (int j = kCenterY; j < ASizeY - kCenterY; ++j) // columns
{
for (int i = kCenterX; i < ASizeX - kCenterX; ++i) // rows
{
current_value = init1;
current_index = 0;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
if (f(current_value, a, b))
{
current_index = A.Index(ii, jj, 0);
current_value = a;
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = current_index;
}
}
// treat boundaries separately
// weights get adjusted so that the sum of weights for the active part of the kernel remains 1
// calculate for upper boundary
for (int j = 0; j < kCenterY; ++j) // columns
{
for (int i = 0; i < ASizeX; ++i) // rows
{
current_value = init1;
current_index = 0;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
// ignore input samples which are out of bound
if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY)
{
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
if (f(current_value, a, b))
{
current_index = A.Index(ii, jj, 0);
current_value = a;
}
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = current_index;
}
}
// calculate for lower boundary
for (int j = ASizeY - kCenterY; j < ASizeY; ++j) // columns
{
for (int i = 0; i < ASizeX; ++i) // rows
{
current_value = init1;
current_index = 0;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
// ignore input samples which are out of bound
if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY)
{
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
if (f(current_value, a, b))
{
current_index = A.Index(ii, jj, 0);
current_value = a;
}
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = current_index;
}
}
// calculate for left boundary
for (int j = 0; j < ASizeY; ++j) // columns
{
for (int i = 0; i < kCenterX; ++i) // rows
{
current_value = init1;
current_index = 0;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
// ignore input samples which are out of bound
if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY)
{
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
if (f(current_value, a, b))
{
current_index = A.Index(ii, jj, 0);
current_value = a;
}
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = current_index;
}
}
// calculate for right boundary
for (int j = 0; j < ASizeY; ++j) // columns
{
for (int i = ASizeX - kCenterX; i < ASizeX; ++i) // rows
{
current_value = init1;
current_index = 0;
for (int n = 0; n < BSizeY; ++n) // kernel columns
{
int nn = BSizeY - 1 - n; // column index of flipped kernel
for (int m = 0; m < BSizeX; ++m) // kernel rows
{
int mm = BSizeX - 1 - m; // row index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterX);
int jj = j + (n - kCenterY);
// ignore input samples which are out of bound
if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY)
{
const T a = A.At(ii, jj, 0);
const T b = B.At(mm, nn, 0);
if (f(current_value, a, b))
{
current_index = A.Index(ii, jj, 0);
current_value = a;
}
}
}
}
const size_t index = ret.Index(i, j, 0);
ret[index] = current_index;
}
}
return ret;
}
#ifdef __CUDACC__
/**
* @brief himan::matrix indexing for identical behaviour with the CPU Filter2D
* @param W width of the matrix
* @param H height of the matrix
*/
CUDA_DEVICE CUDA_INLINE size_t CudaMatrixIndex(size_t x, size_t y, size_t z, size_t W, size_t H)
{
return z * W * H + y * W + x;
}
template <typename T, class F, class G>
CUDA_KERNEL void Reduce2DGPUKernel(const T* __restrict__ A, const T* __restrict__ B, T* __restrict__ C, F f, G g,
T init1, T init2, filter_opts opts)
{
const int kCenterX = opts.bDimX / 2;
const int kCenterY = opts.bDimY / 2;
const int M = opts.aDimX;
const int N = opts.aDimY;
const int i = blockIdx.x * blockDim.x + threadIdx.x;
const int j = blockIdx.y * blockDim.y + threadIdx.y;
if (i < M && j < N)
{
T convolutionValue = init1;
T kernelWeightSum = init2;
// kernel columns
for (int n = 0; n < opts.bDimY; n++)
{
const int nn = opts.bDimY - 1 - n;
// kernel rows
for (int m = 0; m < opts.bDimX; m++)
{
const int mm = opts.bDimX - 1 - m;
const int ii = i + (m - kCenterX);
const int jj = j + (n - kCenterY);
if (ii >= 0 && ii < M && jj >= 0 && jj < N)
{
const int aIdx = CudaMatrixIndex(ii, jj, 0, M, N);
const int bIdx = CudaMatrixIndex(mm, nn, 0, opts.bDimX, opts.bDimY);
const T aVal = A[aIdx];
const T bVal = B[bIdx];
f(convolutionValue, kernelWeightSum, aVal, bVal);
}
}
}
C[CudaMatrixIndex(i, j, 0, M, N)] = g(convolutionValue, kernelWeightSum);
}
}
template <typename T, class F, class G>
himan::matrix<T> Reduce2DGPU(const himan::matrix<T>& A, const himan::matrix<T>& B, F&& f, G&& g, T init1, T init2)
{
himan::matrix<T> C(A.SizeX(), A.SizeY(), 1, himan::MissingValue<T>());
T* d_A = 0;
T* d_B = 0;
T* d_C = 0;
CUDA_CHECK(cudaMalloc(&d_A, A.Size() * sizeof(T)));
CUDA_CHECK(cudaMalloc(&d_B, B.Size() * sizeof(T)));
CUDA_CHECK(cudaMalloc(&d_C, C.Size() * sizeof(T)));
cudaStream_t stream;
CUDA_CHECK(cudaStreamCreate(&stream));
CUDA_CHECK(cudaMemcpyAsync(d_A, A.ValuesAsPOD(), A.Size() * sizeof(T), cudaMemcpyHostToDevice, stream));
CUDA_CHECK(cudaMemcpyAsync(d_B, B.ValuesAsPOD(), B.Size() * sizeof(T), cudaMemcpyHostToDevice, stream));
numerical_functions::filter_opts opts = {static_cast<int>(A.SizeX()), static_cast<int>(A.SizeY()),
static_cast<int>(B.SizeX()), static_cast<int>(B.SizeY())};
const int blockSizeX = 32;
const int blockSizeY = 32;
const auto gridSizeX = static_cast<int>(opts.aDimX / blockSizeX + (opts.aDimX % blockSizeX == 0 ? 0 : 1));
const auto gridSizeY = opts.aDimY / blockSizeY + (opts.aDimY % blockSizeY == 0 ? 0 : 1);
const dim3 gridSize(gridSizeX, gridSizeY);
const dim3 blockSize(blockSizeX, blockSizeY);
Reduce2DGPUKernel<<<gridSize, blockSize, 0, stream>>>(d_A, d_B, d_C, f, g, init1, init2, opts);
CUDA_CHECK(cudaMemcpyAsync(C.ValuesAsPOD(), d_C, C.Size() * sizeof(T), cudaMemcpyDeviceToHost, stream));
CUDA_CHECK(cudaStreamSynchronize(stream));
CUDA_CHECK(cudaFree(d_A));
CUDA_CHECK(cudaFree(d_B));
CUDA_CHECK(cudaFree(d_C));
CUDA_CHECK(cudaStreamDestroy(stream));
return C;
}
template <typename T, class F>
himan::matrix<T> Prob2DGPU(const himan::matrix<T>& A, const himan::matrix<T>& B, F&& f)
{
return Reduce2DGPU(
A, B,
[=] __device__(T & val1, T & val2, const T& a, const T& b) {
if (IsValid(a * b))
{
val1 += f(a) ? b : T(0);
val2 += b;
}
},
[=] __device__(const T& val1, const T& val2) { return val2 == T(0) ? MissingValue<T>() : val1 / val2; }, T(0),
T(0));
}
#endif
} // namespace numerical_functions
} // namespace himan
| 29.14914 | 116 | 0.569695 |
16af63a7d0ea6561e628539932b33e8cd25eab40 | 4,583 | h | C | ios/WowzaGoCoderSDK.framework/Headers/WOWZCameraPreview.h | VNAPNIC/flutter-wowza | 25f8d844a38a786cf95907823f1a72221bec190f | [
"BSD-2-Clause"
] | 11 | 2020-03-13T08:19:11.000Z | 2021-08-19T10:32:47.000Z | ios/WowzaGoCoderSDK.framework/Headers/WOWZCameraPreview.h | VNAPNIC/flutter-wowza | 25f8d844a38a786cf95907823f1a72221bec190f | [
"BSD-2-Clause"
] | 7 | 2020-03-23T09:08:54.000Z | 2020-06-08T11:43:13.000Z | ios/WowzaGoCoderSDK.framework/Headers/WOWZCameraPreview.h | VNAPNIC/flutter-wowza | 25f8d844a38a786cf95907823f1a72221bec190f | [
"BSD-2-Clause"
] | 1 | 2021-07-14T02:19:57.000Z | 2021-07-14T02:19:57.000Z | //
// WOWZCameraPreview
// WowzaGoCoderSDK
//
// © 2007 – 2019 Wowza Media Systems, LLC. All rights reserved.
//
// 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 <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import "WOWZCamera.h"
#import "WowzaConfig.h"
#pragma mark WOWZCameraPreview Class
#pragma mark -
/*!
@class WOWZCameraPreview
@discussion The WOWZCameraPreview class allows you to preview video captured from a camera device.
*/
@interface WOWZCameraPreview : NSObject
/*!
* @typedef WOWZCameraPreviewGravity
* @constant WOWZCameraPreviewGravityResizeAspect Preserve aspect ratio; fit within layer bounds.
* @constant WOWZCameraPreviewGravityResizeAspectFill Preserve aspect ratio; fill layer bounds.
* @constant WOWZCameraPreviewGravityResize Stretch to fill layer bounds.
* @discussion Describes how the video should fill the preview frame.
*/
typedef NS_ENUM(NSUInteger, WOWZCameraPreviewGravity) {
WOWZCameraPreviewGravityResizeAspect = 0,
WOWZCameraPreviewGravityResizeAspectFill,
WOWZCameraPreviewGravityResize
};
#pragma mark -
#pragma mark Public Class Methods
#pragma mark -
/*!
* Gets the number of cameras available on the device.
*
* @return The number of cameras available.
*/
+ (NSInteger) numberOfDeviceCameras;
/*!
* Gets an array of the WOWZCamera objects available on the device.
*
* @return The array of WOWZCamera objects.
*/
+ (nonnull NSArray<WOWZCamera *> *) deviceCameras;
#pragma mark -
#pragma mark Public Properties
#pragma mark -
/*!
* The active camera.
*/
@property (nonatomic, nullable) WOWZCamera* camera;
/*!
* The active config for the camera.
*/
@property (nonatomic, nonnull) WowzaConfig *config;
/*!
* The AV Foundation preview layer. Null until startPreview is called.
*/
@property (nonatomic, readonly, nullable) AVCaptureVideoPreviewLayer *previewLayer;
/*!
* The preview gravity to use to display the video preview.
* Preview gravity describes how the video should fill the available screen area.
*/
@property (nonatomic, assign) WOWZCameraPreviewGravity previewGravity;
/*!
* The array of WOWZCamera objects available on the device.
*/
@property (nonatomic, readonly, nullable) NSArray<WOWZCamera *> *cameras;
/*!
* Indicates whether a video is actively previewing.
*/
@property (nonatomic, readonly, getter=isPreviewActive) BOOL previewActive;
#pragma mark -
#pragma mark Constructors
#pragma mark -
- (nonnull instancetype) init __attribute__((unavailable("init is unavailable")));
/*!
* Initializes a WOWZCameraPreview object.
*
* @param containingView The view to which the preview layer will be added.
* @param aConfig The configuration settings for the camera and the preview.
*
* @return An initialized WOWZCameraPreview object.
*/
- (nonnull instancetype) initWithViewAndConfig:(nonnull UIView *)containingView config:(nonnull WowzaConfig *)aConfig;
#pragma mark -
#pragma mark Public Instance Methods
#pragma mark -
/*!
* Starts previewing the video stream.
*/
- (void) startPreview;
/*!
* Stops previewing the video stream.
*/
- (void) stopPreview;
#pragma mark -
/*!
* Indicates whether another camera is available on the device and whether
* that camera supports the specified WOWZMediaConfig.
*
* @param config The WOWZMediaConfig to test for support by the other camera.
*
* @return Yes if the device has another camera that supports the specified WOWZMediaConfig, no otherwise.
*/
- (BOOL) isSwitchCameraAvailableForConfig:(nonnull WOWZMediaConfig *)config;
/*!
* Switches to the device's other camera.
*
* @return The device's other camera, if it exists and supports the current config; otherwise, the same camera.
*/
- (nonnull WOWZCamera *) switchCamera;
/*!
* Gets a reference to the camera not currently in use, if the device has more than one camera.
*
* @return The reference to the camera not in use, or nil if there's only one camera.
*/
- (nullable WOWZCamera *) otherCamera;
@end
| 28.290123 | 118 | 0.747327 |
0dcf2d9dd86e500e9f48bba35ad80647537cee0a | 9,750 | h | C | printscan/ui/wiaacmgr/camsel.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/ui/wiaacmgr/camsel.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/ui/wiaacmgr/camsel.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*******************************************************************************
*
* (C) COPYRIGHT MICROSOFT CORPORATION, 1998
*
* TITLE: CAMSEL.H
*
* VERSION: 1.0
*
* AUTHOR: ShaunIv
*
* DATE: 9/28/1999
*
* DESCRIPTION: Camera selection page. Displays thumbnails, and lets the user select which
* ones to download.
*
*******************************************************************************/
#ifndef __CAMSEL_H_INCLUDED
#define __CAMSEL_H_INCLUDED
#include <windows.h>
#include "acqmgrcw.h"
#include "simarray.h"
#include "gphelper.h"
#include "itranhlp.h"
#include "createtb.h"
#include "wiavideo.h"
class CCameraSelectionPage
{
private:
//
// Used for icon grouping
//
class CListviewGroupInfo
{
private:
CSimpleStringWide m_strGroupName;
int m_nGroupId;
public:
CListviewGroupInfo(void)
: m_strGroupName(TEXT("")),
m_nGroupId(-1)
{
}
CListviewGroupInfo( const CListviewGroupInfo &other )
: m_strGroupName(other.GroupName()),
m_nGroupId(other.GroupId())
{
}
CListviewGroupInfo( const CSimpleStringWide &strGroupName, int nGroupId=-1 )
: m_strGroupName(strGroupName),
m_nGroupId(nGroupId)
{
}
~CListviewGroupInfo(void)
{
}
CListviewGroupInfo &operator=( const CListviewGroupInfo &other )
{
if (this != &other)
{
m_strGroupName = other.GroupName();
m_nGroupId = other.GroupId();
}
return *this;
}
bool operator==( const CListviewGroupInfo &other )
{
return (other.GroupName() == m_strGroupName);
}
bool operator==( const CSimpleStringWide &strGroupName )
{
return (strGroupName == m_strGroupName);
}
CSimpleStringWide GroupName(void) const
{
return m_strGroupName;
}
int GroupId(void) const
{
return m_nGroupId;
}
};
class CIconGroupList : public CSimpleDynamicArray<CListviewGroupInfo>
{
private:
CIconGroupList( const CIconGroupList & );
CIconGroupList& operator=( const CIconGroupList & );
public:
CIconGroupList(void)
{
}
~CIconGroupList(void)
{
}
int Add( HWND hwndList, const CSimpleStringWide &strwGroupName )
{
int nResult = -1;
CSimpleString strGroupName = CSimpleStringConvert::NaturalString(strwGroupName);
if (strGroupName.Length())
{
LVGROUP LvGroup = {0};
LvGroup.cbSize = sizeof(LvGroup);
LvGroup.pszHeader = const_cast<LPTSTR>(strGroupName.String());
LvGroup.mask = LVGF_HEADER | LVGF_ALIGN | LVGF_GROUPID | LVGF_STATE;
LvGroup.uAlign = LVGA_HEADER_LEFT;
LvGroup.iGroupId = Size();
LvGroup.state = LVGS_NORMAL;
nResult = static_cast<int>(ListView_InsertGroup( hwndList, Size(), &LvGroup ));
WIA_TRACE((TEXT("ListView_InsertGroup on %s returned %d"), strGroupName.String(), nResult ));
if (nResult >= 0)
{
Append( CListviewGroupInfo( strwGroupName, nResult ) );
}
}
return nResult;
}
int GetGroupId( CWiaItem *pWiaItem, HWND hwndList )
{
WIA_PUSH_FUNCTION((TEXT("GetGroupId(%ws)"),pWiaItem->ItemName().String()));
int nResult = -1;
if (Size())
{
nResult = (*this)[0].GroupId();
if (pWiaItem)
{
CWiaItem *pWiaItemParent = pWiaItem->Parent();
if (pWiaItemParent)
{
CSimpleStringWide strwFolderName = pWiaItemParent->ItemName();
if (strwFolderName.Length())
{
int nIndex = Find(strwFolderName);
if (nIndex < 0)
{
CSimpleString strFolderName = CSimpleStringConvert::NaturalString(strwFolderName);
if (strFolderName.Length())
{
LVGROUP LvGroup = {0};
LvGroup.cbSize = sizeof(LvGroup);
LvGroup.pszHeader = const_cast<LPTSTR>(strFolderName.String());
LvGroup.mask = LVGF_HEADER | LVGF_ALIGN | LVGF_GROUPID | LVGF_STATE;
LvGroup.uAlign = LVGA_HEADER_LEFT;
LvGroup.iGroupId = Size();
LvGroup.state = LVGS_NORMAL;
nResult = static_cast<int>(ListView_InsertGroup( hwndList, Size(), &LvGroup ));
WIA_TRACE((TEXT("ListView_InsertGroup on %s returned %d"), strFolderName.String(), nResult ));
if (nResult >= 0)
{
Append( CListviewGroupInfo( strwFolderName, nResult ) );
}
}
}
else
{
nResult = (*this)[nIndex].GroupId();
}
}
}
}
}
return nResult;
}
};
CIconGroupList m_GroupInfoList;
// Private data
HWND m_hWnd;
CAcquisitionManagerControllerWindow *m_pControllerWindow;
int m_nDefaultThumbnailImageListIndex;
int m_nProgrammaticSetting;
CGdiPlusHelper m_GdiPlusHelper;
UINT m_nThreadNotificationMessage;
UINT m_nWiaEventMessage;
bool m_bThumbnailsRequested;
HICON m_hIconAudioAnnotation;
HICON m_hIconMiscellaneousAnnotation;
CComPtr<IWiaAnnotationHelpers> m_pWiaAnnotationHelpers;
CComPtr<IWiaVideo> m_pWiaVideo;
ToolbarHelper::CToolbarBitmapInfo m_CameraSelectionButtonBarBitmapInfo;
ToolbarHelper::CToolbarBitmapInfo m_CameraTakePictureButtonBarBitmapInfo;
ToolbarHelper::CToolbarBitmapInfo m_CameraActionButtonBarBitmapInfo;
HACCEL m_hAccelerators;
private:
// No implementation
CCameraSelectionPage(void);
CCameraSelectionPage( const CCameraSelectionPage & );
CCameraSelectionPage &operator=( const CCameraSelectionPage & );
private:
// Constructor and destructor
explicit CCameraSelectionPage( HWND hWnd );
~CCameraSelectionPage(void);
private:
int AddItem( HWND hwndList, CWiaItem *pWiaItem, bool bEnsureVisible=false );
void AddEnumeratedItems( HWND hwndList, CWiaItem *pFirstItem );
void PopulateListView(void);
CWiaItem *GetItemFromListByIndex( HWND hwndList, int nItem );
int FindItemListIndex( HWND hwndList, CWiaItem *pWiaItem );
int AddThumbnailToListViewImageList( HWND hwndList, CWiaItem *pWiaItem, int nIndex );
int GetSelectionIndices( CSimpleDynamicArray<int> &aIndices );
void UpdateControls(void);
void InitializeVideoCamera(void);
void DrawAnnotationIcons( HDC hDC, CWiaItem *pWiaItem, HBITMAP hBitmap );
void MyEnableToolbarButton( int nButtonId, bool bEnable );
void RepaintAllThumbnails();
private:
// WM_COMMAND handlers
void OnSelectAll( WPARAM, LPARAM );
void OnClearAll( WPARAM, LPARAM );
void OnProperties( WPARAM, LPARAM );
void OnRotate( WPARAM, LPARAM );
void OnTakePicture( WPARAM, LPARAM );
void OnDelete( WPARAM, LPARAM );
// WM_NOTIFY handlers
LRESULT OnWizNext( WPARAM, LPARAM );
LRESULT OnWizBack( WPARAM, LPARAM );
LRESULT OnSetActive( WPARAM, LPARAM );
LRESULT OnTranslateAccelerator( WPARAM, LPARAM );
LRESULT OnGetToolTipDispInfo( WPARAM, LPARAM );
// Message handlers
LRESULT OnInitDialog( WPARAM, LPARAM );
LRESULT OnDestroy( WPARAM, LPARAM );
LRESULT OnCommand( WPARAM, LPARAM );
LRESULT OnNotify( WPARAM, LPARAM );
LRESULT OnThreadNotification( WPARAM, LPARAM );
LRESULT OnEventNotification( WPARAM, LPARAM );
LRESULT OnThumbnailListSelChange( WPARAM, LPARAM );
LRESULT OnThumbnailListKeyDown( WPARAM, LPARAM );
LRESULT OnShowWindow( WPARAM, LPARAM );
LRESULT OnTimer( WPARAM wParam, LPARAM );
LRESULT OnSysColorChange( WPARAM, LPARAM );
LRESULT OnThemeChanged( WPARAM, LPARAM );
LRESULT OnSettingChange( WPARAM, LPARAM );
// Thread notification message handlers
void OnNotifyDownloadThumbnail( UINT, CThreadNotificationMessage * );
void OnNotifyDownloadImage( UINT, CThreadNotificationMessage * );
public:
static INT_PTR CALLBACK DialogProc( HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam );
};
#endif __CAMSEL_H_INCLUDED
| 38.385827 | 131 | 0.531795 |
d4dadf614069b9c465388e2c3290bb8ba513372d | 87 | c | C | cil/test/small1/combineinline2_2.c | petr-muller/abductor | 4c9199378e847e22660daab5e5843805d4035d0a | [
"Intel",
"Unlicense"
] | 266 | 2015-01-23T16:06:52.000Z | 2022-03-17T19:49:34.000Z | cil/test/small1/combineinline2_2.c | petr-muller/abductor | 4c9199378e847e22660daab5e5843805d4035d0a | [
"Intel",
"Unlicense"
] | 93 | 2015-07-31T21:38:04.000Z | 2022-03-24T03:21:34.000Z | cil/test/small1/combineinline2_2.c | petr-muller/abductor | 4c9199378e847e22660daab5e5843805d4035d0a | [
"Intel",
"Unlicense"
] | 73 | 2015-01-11T17:06:17.000Z | 2022-02-21T06:20:37.000Z | static int g;
inline int foo(int x) { return g; }
int getfoo2() { return (int)foo; }
| 14.5 | 35 | 0.632184 |
1ded23520fd746ac16a8124e78f19893cd7257a4 | 1,733 | h | C | src/hive.h | Brenocq/Honeybee-Simulation | ff2af91ef3c313e72e56542702f28fb7fd285168 | [
"MIT"
] | null | null | null | src/hive.h | Brenocq/Honeybee-Simulation | ff2af91ef3c313e72e56542702f28fb7fd285168 | [
"MIT"
] | null | null | null | src/hive.h | Brenocq/Honeybee-Simulation | ff2af91ef3c313e72e56542702f28fb7fd285168 | [
"MIT"
] | 1 | 2020-04-23T22:13:40.000Z | 2020-04-23T22:13:40.000Z | #ifndef HIVE_H
#define HIVE_H
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sstream>
#include <chrono>
#include <math.h>
#include "defines.h"
#include "parameters.h"
#include "scoutBee.h"
#include "utils.h"
#include "nestBox.h"
// Cuda
#include <curand.h>
#include <curand_kernel.h>
class Hive
{
public:
Hive(float x, float y, double* gene, float r, float g, float b, int qtyBees);
~Hive();
void reset(float x, float y, double* gene);
void setGene(double* gene) { _gene = gene; }
void setNestBoxes(NestBox* nestBoxes, int qtyNestBoxes);
void updateConsensus();
int getQtyScoutBees() const { return _qtyScoutBees; }
int* getConsensus() const { return _consensus; }
float getFitness();
double* getGene() const { return _gene; }
float getColor(int color);
std::string toString();
void draw();
void run(int steps);
private:
// Gene
double* _gene;
// 0 -> _randomChance;// Chance search new nestBox
// 1 -> _followChance;// Chance follow other bee
// 2 -> _linearDecay; // Linear supporting decay (0-1)
// 3 -> _danceForceExponent; // dance force = (nestbox goodness)^danceForceExponent (0-1) mapped to (0-10)
// Hive info
float _x;
float _y;
float _size;
float _r,_g,_b;
// Scout bees
const int _qtyScoutBees;
ScoutBee* _scoutBees;
ScoutBee* _scoutBeesCuda;
enum State { REST, SEARCH_NEW_NESTBOX, FIND_NESTBOX, BACK_TO_HOME, DANCE };
// Nest boxes
int _qtyNestBoxes;
NestBox* _nestBoxes;
NestBox* _nestBoxesCuda;
// Consensus
float _fitness;
int* _consensus;
// Choice probability (used by bees to select who to follow)
float* _choiceProb;
float* _choiceProbCuda;
// Cuda
curandState* _cuState;
};
#endif// HIVE_H
| 23.106667 | 108 | 0.689556 |
07db7a542718d63f07ec591bf2f8d308d50eeaf7 | 1,102 | h | C | Frameworks/Intents.framework/_INPBConflictingParameter.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | Frameworks/Intents.framework/_INPBConflictingParameter.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | Frameworks/Intents.framework/_INPBConflictingParameter.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/Intents.framework/Intents
*/
@interface _INPBConflictingParameter : PBCodable <NSCopying> {
NSMutableArray * _alternateItems;
NSString * _keyPath;
PBUnknownFields * _unknownFields;
}
@property (nonatomic, retain) NSMutableArray *alternateItems;
@property (nonatomic, readonly) bool hasKeyPath;
@property (nonatomic, retain) NSString *keyPath;
@property (nonatomic, readonly) PBUnknownFields *unknownFields;
+ (Class)alternateItemsType;
+ (id)options;
- (void).cxx_destruct;
- (void)addAlternateItems:(id)arg1;
- (id)alternateItems;
- (id)alternateItemsAtIndex:(unsigned long long)arg1;
- (unsigned long long)alternateItemsCount;
- (void)clearAlternateItems;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (id)description;
- (id)dictionaryRepresentation;
- (bool)hasKeyPath;
- (unsigned long long)hash;
- (bool)isEqual:(id)arg1;
- (id)keyPath;
- (void)mergeFrom:(id)arg1;
- (bool)readFrom:(id)arg1;
- (void)setAlternateItems:(id)arg1;
- (void)setKeyPath:(id)arg1;
- (id)unknownFields;
- (void)writeTo:(id)arg1;
@end
| 27.55 | 63 | 0.747731 |
e0214a88a7a76a3854262d8828f760ef0e81bf8c | 17,656 | c | C | extsrc/mesa/src/mesa/main/uniforms.c | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 28 | 2015-07-11T17:11:12.000Z | 2022-03-26T04:14:16.000Z | extsrc/mesa/src/mesa/main/uniforms.c | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 2 | 2019-05-26T19:02:24.000Z | 2021-05-27T14:15:04.000Z | extsrc/mesa/src/mesa/main/uniforms.c | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 9 | 2019-07-04T12:54:29.000Z | 2022-02-09T13:04:38.000Z | /*
* Mesa 3-D graphics library
*
* Copyright (C) 2004-2008 Brian Paul All Rights Reserved.
* Copyright (C) 2009-2010 VMware, Inc. All Rights Reserved.
* Copyright © 2010 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
* BRIAN PAUL 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 uniforms.c
* Functions related to GLSL uniform variables.
* \author Brian Paul
*/
/**
* XXX things to do:
* 1. Check that the right error code is generated for all _mesa_error() calls.
* 2. Insert FLUSH_VERTICES calls in various places
*/
#include "main/glheader.h"
#include "main/context.h"
#include "main/dispatch.h"
#include "main/shaderapi.h"
#include "main/shaderobj.h"
#include "main/uniforms.h"
#include "ir_uniform.h"
#include "glsl_types.h"
/**
* Update the vertex/fragment program's TexturesUsed array.
*
* This needs to be called after glUniform(set sampler var) is called.
* A call to glUniform(samplerVar, value) causes a sampler to point to a
* particular texture unit. We know the sampler's texture target
* (1D/2D/3D/etc) from compile time but the sampler's texture unit is
* set by glUniform() calls.
*
* So, scan the program->SamplerUnits[] and program->SamplerTargets[]
* information to update the prog->TexturesUsed[] values.
* Each value of TexturesUsed[unit] is one of zero, TEXTURE_1D_INDEX,
* TEXTURE_2D_INDEX, TEXTURE_3D_INDEX, etc.
* We'll use that info for state validation before rendering.
*/
void
_mesa_update_shader_textures_used(struct gl_shader_program *shProg,
struct gl_program *prog)
{
GLuint s;
memset(prog->TexturesUsed, 0, sizeof(prog->TexturesUsed));
for (s = 0; s < MAX_SAMPLERS; s++) {
if (prog->SamplersUsed & (1 << s)) {
GLuint unit = shProg->SamplerUnits[s];
GLuint tgt = shProg->SamplerTargets[s];
assert(unit < Elements(prog->TexturesUsed));
assert(tgt < NUM_TEXTURE_TARGETS);
prog->TexturesUsed[unit] |= (1 << tgt);
}
}
}
/**
* Connect a piece of driver storage with a part of a uniform
*
* \param uni The uniform with which the storage will be associated
* \param element_stride Byte-stride between array elements.
* \sa gl_uniform_driver_storage::element_stride.
* \param vector_stride Byte-stride between vectors (in a matrix).
* \sa gl_uniform_driver_storage::vector_stride.
* \param format Conversion from native format to driver format
* required by the driver.
* \param data Location to dump the data.
*/
void
_mesa_uniform_attach_driver_storage(struct gl_uniform_storage *uni,
unsigned element_stride,
unsigned vector_stride,
enum gl_uniform_driver_format format,
void *data)
{
uni->driver_storage = (struct gl_uniform_driver_storage*)
realloc(uni->driver_storage,
sizeof(struct gl_uniform_driver_storage)
* (uni->num_driver_storage + 1));
uni->driver_storage[uni->num_driver_storage].element_stride = element_stride;
uni->driver_storage[uni->num_driver_storage].vector_stride = vector_stride;
uni->driver_storage[uni->num_driver_storage].format = (uint8_t) format;
uni->driver_storage[uni->num_driver_storage].data = data;
uni->num_driver_storage++;
}
/**
* Sever all connections with all pieces of driver storage for all uniforms
*
* \warning
* This function does \b not release any of the \c data pointers
* previously passed in to \c _mesa_uniform_attach_driver_stoarge.
*/
void
_mesa_uniform_detach_all_driver_storage(struct gl_uniform_storage *uni)
{
free(uni->driver_storage);
uni->driver_storage = NULL;
uni->num_driver_storage = 0;
}
void GLAPIENTRY
_mesa_Uniform1fARB(GLint location, GLfloat v0)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, &v0, GL_FLOAT);
}
void GLAPIENTRY
_mesa_Uniform2fARB(GLint location, GLfloat v0, GLfloat v1)
{
GET_CURRENT_CONTEXT(ctx);
GLfloat v[2];
v[0] = v0;
v[1] = v1;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_FLOAT_VEC2);
}
void GLAPIENTRY
_mesa_Uniform3fARB(GLint location, GLfloat v0, GLfloat v1, GLfloat v2)
{
GET_CURRENT_CONTEXT(ctx);
GLfloat v[3];
v[0] = v0;
v[1] = v1;
v[2] = v2;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_FLOAT_VEC3);
}
void GLAPIENTRY
_mesa_Uniform4fARB(GLint location, GLfloat v0, GLfloat v1, GLfloat v2,
GLfloat v3)
{
GET_CURRENT_CONTEXT(ctx);
GLfloat v[4];
v[0] = v0;
v[1] = v1;
v[2] = v2;
v[3] = v3;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_FLOAT_VEC4);
}
void GLAPIENTRY
_mesa_Uniform1iARB(GLint location, GLint v0)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, &v0, GL_INT);
}
void GLAPIENTRY
_mesa_Uniform2iARB(GLint location, GLint v0, GLint v1)
{
GET_CURRENT_CONTEXT(ctx);
GLint v[2];
v[0] = v0;
v[1] = v1;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_INT_VEC2);
}
void GLAPIENTRY
_mesa_Uniform3iARB(GLint location, GLint v0, GLint v1, GLint v2)
{
GET_CURRENT_CONTEXT(ctx);
GLint v[3];
v[0] = v0;
v[1] = v1;
v[2] = v2;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_INT_VEC3);
}
void GLAPIENTRY
_mesa_Uniform4iARB(GLint location, GLint v0, GLint v1, GLint v2, GLint v3)
{
GET_CURRENT_CONTEXT(ctx);
GLint v[4];
v[0] = v0;
v[1] = v1;
v[2] = v2;
v[3] = v3;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_INT_VEC4);
}
void GLAPIENTRY
_mesa_Uniform1fvARB(GLint location, GLsizei count, const GLfloat * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_FLOAT);
}
void GLAPIENTRY
_mesa_Uniform2fvARB(GLint location, GLsizei count, const GLfloat * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_FLOAT_VEC2);
}
void GLAPIENTRY
_mesa_Uniform3fvARB(GLint location, GLsizei count, const GLfloat * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_FLOAT_VEC3);
}
void GLAPIENTRY
_mesa_Uniform4fvARB(GLint location, GLsizei count, const GLfloat * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_FLOAT_VEC4);
}
void GLAPIENTRY
_mesa_Uniform1ivARB(GLint location, GLsizei count, const GLint * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_INT);
}
void GLAPIENTRY
_mesa_Uniform2ivARB(GLint location, GLsizei count, const GLint * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_INT_VEC2);
}
void GLAPIENTRY
_mesa_Uniform3ivARB(GLint location, GLsizei count, const GLint * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_INT_VEC3);
}
void GLAPIENTRY
_mesa_Uniform4ivARB(GLint location, GLsizei count, const GLint * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_INT_VEC4);
}
/** OpenGL 3.0 GLuint-valued functions **/
void GLAPIENTRY
_mesa_Uniform1ui(GLint location, GLuint v0)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, &v0, GL_UNSIGNED_INT);
}
void GLAPIENTRY
_mesa_Uniform2ui(GLint location, GLuint v0, GLuint v1)
{
GET_CURRENT_CONTEXT(ctx);
GLuint v[2];
v[0] = v0;
v[1] = v1;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_UNSIGNED_INT_VEC2);
}
void GLAPIENTRY
_mesa_Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2)
{
GET_CURRENT_CONTEXT(ctx);
GLuint v[3];
v[0] = v0;
v[1] = v1;
v[2] = v2;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_UNSIGNED_INT_VEC3);
}
void GLAPIENTRY
_mesa_Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
{
GET_CURRENT_CONTEXT(ctx);
GLuint v[4];
v[0] = v0;
v[1] = v1;
v[2] = v2;
v[3] = v3;
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, 1, v, GL_UNSIGNED_INT_VEC4);
}
void GLAPIENTRY
_mesa_Uniform1uiv(GLint location, GLsizei count, const GLuint *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_UNSIGNED_INT);
}
void GLAPIENTRY
_mesa_Uniform2uiv(GLint location, GLsizei count, const GLuint *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_UNSIGNED_INT_VEC2);
}
void GLAPIENTRY
_mesa_Uniform3uiv(GLint location, GLsizei count, const GLuint *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_UNSIGNED_INT_VEC3);
}
void GLAPIENTRY
_mesa_Uniform4uiv(GLint location, GLsizei count, const GLuint *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform(ctx, ctx->Shader.ActiveProgram, location, count, value, GL_UNSIGNED_INT_VEC4);
}
void GLAPIENTRY
_mesa_UniformMatrix2fvARB(GLint location, GLsizei count, GLboolean transpose,
const GLfloat * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
2, 2, location, count, transpose, value);
}
void GLAPIENTRY
_mesa_UniformMatrix3fvARB(GLint location, GLsizei count, GLboolean transpose,
const GLfloat * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
3, 3, location, count, transpose, value);
}
void GLAPIENTRY
_mesa_UniformMatrix4fvARB(GLint location, GLsizei count, GLboolean transpose,
const GLfloat * value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
4, 4, location, count, transpose, value);
}
/**
* Non-square UniformMatrix are OpenGL 2.1
*/
void GLAPIENTRY
_mesa_UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
2, 3, location, count, transpose, value);
}
void GLAPIENTRY
_mesa_UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
3, 2, location, count, transpose, value);
}
void GLAPIENTRY
_mesa_UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
2, 4, location, count, transpose, value);
}
void GLAPIENTRY
_mesa_UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
4, 2, location, count, transpose, value);
}
void GLAPIENTRY
_mesa_UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
3, 4, location, count, transpose, value);
}
void GLAPIENTRY
_mesa_UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_uniform_matrix(ctx, ctx->Shader.ActiveProgram,
4, 3, location, count, transpose, value);
}
void GLAPIENTRY
_mesa_GetnUniformfvARB(GLhandleARB program, GLint location,
GLsizei bufSize, GLfloat *params)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_get_uniform(ctx, program, location, bufSize, GLSL_TYPE_FLOAT, params);
}
void GLAPIENTRY
_mesa_GetUniformfvARB(GLhandleARB program, GLint location, GLfloat *params)
{
_mesa_GetnUniformfvARB(program, location, INT_MAX, params);
}
void GLAPIENTRY
_mesa_GetnUniformivARB(GLhandleARB program, GLint location,
GLsizei bufSize, GLint *params)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_get_uniform(ctx, program, location, bufSize, GLSL_TYPE_INT, params);
}
void GLAPIENTRY
_mesa_GetUniformivARB(GLhandleARB program, GLint location, GLint *params)
{
_mesa_GetnUniformivARB(program, location, INT_MAX, params);
}
/* GL3 */
void GLAPIENTRY
_mesa_GetnUniformuivARB(GLhandleARB program, GLint location,
GLsizei bufSize, GLuint *params)
{
GET_CURRENT_CONTEXT(ctx);
_mesa_get_uniform(ctx, program, location, bufSize, GLSL_TYPE_UINT, params);
}
void GLAPIENTRY
_mesa_GetUniformuiv(GLhandleARB program, GLint location, GLuint *params)
{
_mesa_GetnUniformuivARB(program, location, INT_MAX, params);
}
/* GL4 */
void GLAPIENTRY
_mesa_GetnUniformdvARB(GLhandleARB program, GLint location,
GLsizei bufSize, GLdouble *params)
{
GET_CURRENT_CONTEXT(ctx);
(void) program;
(void) location;
(void) bufSize;
(void) params;
/*
_mesa_get_uniform(ctx, program, location, bufSize, GL_DOUBLE, params);
*/
_mesa_error(ctx, GL_INVALID_OPERATION, "glGetUniformdvARB"
"(GL_ARB_gpu_shader_fp64 not implemented)");
}
void GLAPIENTRY
_mesa_GetUniformdv(GLhandleARB program, GLint location, GLdouble *params)
{
_mesa_GetnUniformdvARB(program, location, INT_MAX, params);
}
GLint GLAPIENTRY
_mesa_GetUniformLocationARB(GLhandleARB programObj, const GLcharARB *name)
{
struct gl_shader_program *shProg;
GET_CURRENT_CONTEXT(ctx);
shProg = _mesa_lookup_shader_program_err(ctx, programObj,
"glGetUniformLocation");
if (!shProg)
return -1;
/* Page 80 (page 94 of the PDF) of the OpenGL 2.1 spec says:
*
* "If program has not been successfully linked, the error
* INVALID_OPERATION is generated."
*/
if (shProg->LinkStatus == GL_FALSE) {
_mesa_error(ctx, GL_INVALID_OPERATION,
"glGetUniformLocation(program not linked)");
return -1;
}
return _mesa_get_uniform_location(ctx, shProg, name);
}
/**
* Plug in shader uniform-related functions into API dispatch table.
*/
void
_mesa_init_shader_uniform_dispatch(struct _glapi_table *exec)
{
#if FEATURE_GL
SET_Uniform1fARB(exec, _mesa_Uniform1fARB);
SET_Uniform2fARB(exec, _mesa_Uniform2fARB);
SET_Uniform3fARB(exec, _mesa_Uniform3fARB);
SET_Uniform4fARB(exec, _mesa_Uniform4fARB);
SET_Uniform1iARB(exec, _mesa_Uniform1iARB);
SET_Uniform2iARB(exec, _mesa_Uniform2iARB);
SET_Uniform3iARB(exec, _mesa_Uniform3iARB);
SET_Uniform4iARB(exec, _mesa_Uniform4iARB);
SET_Uniform1fvARB(exec, _mesa_Uniform1fvARB);
SET_Uniform2fvARB(exec, _mesa_Uniform2fvARB);
SET_Uniform3fvARB(exec, _mesa_Uniform3fvARB);
SET_Uniform4fvARB(exec, _mesa_Uniform4fvARB);
SET_Uniform1ivARB(exec, _mesa_Uniform1ivARB);
SET_Uniform2ivARB(exec, _mesa_Uniform2ivARB);
SET_Uniform3ivARB(exec, _mesa_Uniform3ivARB);
SET_Uniform4ivARB(exec, _mesa_Uniform4ivARB);
SET_UniformMatrix2fvARB(exec, _mesa_UniformMatrix2fvARB);
SET_UniformMatrix3fvARB(exec, _mesa_UniformMatrix3fvARB);
SET_UniformMatrix4fvARB(exec, _mesa_UniformMatrix4fvARB);
SET_GetActiveUniformARB(exec, _mesa_GetActiveUniformARB);
SET_GetUniformLocationARB(exec, _mesa_GetUniformLocationARB);
SET_GetUniformfvARB(exec, _mesa_GetUniformfvARB);
SET_GetUniformivARB(exec, _mesa_GetUniformivARB);
/* OpenGL 2.1 */
SET_UniformMatrix2x3fv(exec, _mesa_UniformMatrix2x3fv);
SET_UniformMatrix3x2fv(exec, _mesa_UniformMatrix3x2fv);
SET_UniformMatrix2x4fv(exec, _mesa_UniformMatrix2x4fv);
SET_UniformMatrix4x2fv(exec, _mesa_UniformMatrix4x2fv);
SET_UniformMatrix3x4fv(exec, _mesa_UniformMatrix3x4fv);
SET_UniformMatrix4x3fv(exec, _mesa_UniformMatrix4x3fv);
/* OpenGL 3.0 */
SET_Uniform1uiEXT(exec, _mesa_Uniform1ui);
SET_Uniform2uiEXT(exec, _mesa_Uniform2ui);
SET_Uniform3uiEXT(exec, _mesa_Uniform3ui);
SET_Uniform4uiEXT(exec, _mesa_Uniform4ui);
SET_Uniform1uivEXT(exec, _mesa_Uniform1uiv);
SET_Uniform2uivEXT(exec, _mesa_Uniform2uiv);
SET_Uniform3uivEXT(exec, _mesa_Uniform3uiv);
SET_Uniform4uivEXT(exec, _mesa_Uniform4uiv);
SET_GetUniformuivEXT(exec, _mesa_GetUniformuiv);
/* GL_ARB_robustness */
SET_GetnUniformfvARB(exec, _mesa_GetnUniformfvARB);
SET_GetnUniformivARB(exec, _mesa_GetnUniformivARB);
SET_GetnUniformuivARB(exec, _mesa_GetnUniformuivARB);
SET_GetnUniformdvARB(exec, _mesa_GetnUniformdvARB); /* GL 4.0 */
#endif /* FEATURE_GL */
}
| 30.388985 | 95 | 0.730743 |
a30bd51c92dcacf8658dbc46ac462acaed0fc2fd | 1,549 | h | C | TOOLS/bmfontutil/distancefield.h | kulseran/FISHY | d01d05c03404a0c95d864a8cde899d355873592b | [
"MIT"
] | 3 | 2016-12-30T23:19:15.000Z | 2018-07-04T15:17:26.000Z | TOOLS/bmfontutil/distancefield.h | kulseran/FISHY | d01d05c03404a0c95d864a8cde899d355873592b | [
"MIT"
] | 7 | 2015-11-27T16:34:42.000Z | 2016-05-07T18:29:24.000Z | TOOLS/bmfontutil/distancefield.h | kulseran/FISHY | d01d05c03404a0c95d864a8cde899d355873592b | [
"MIT"
] | 1 | 2016-12-31T03:59:46.000Z | 2016-12-31T03:59:46.000Z | /**
* Utility for converting a binary on/off image to
* a signed distance field image.
*/
#ifndef FISHY_DISTANCE_FIELD_H
#define FISHY_DISTANCE_FIELD_H
#include <CORE/types.h>
#include <vector>
/**
* Conversion utility for computing the signed distance field
* representation of an input black and white image.
*/
class DistanceGrid {
public:
/**
* Initialize a grid converter for a fixed image size and
* distance scaling factor.
*
* @param sx horizontal width
* @param sy vertical height
* @param scale distance scaling factor
*/
DistanceGrid(const u32 sx, const u32 sy, const f32 scale);
/**
* Perform a conversion
*
* @param pImageDataIn the input black-and-white image
* @param pImageDataOut teh output greyscale image with 128 as the midpoint
* color.
*/
void convertToSdf(const u8 *pImageDataIn, u8 *pImageDataOut);
private:
struct DistancePoint {
f32 m_dx;
f32 m_dy;
DistancePoint() : m_dx(0.0f), m_dy(0.0f) {}
DistancePoint(f32 dx, f32 dy) : m_dx(dx), m_dy(dy) {}
f32 dist() const { return m_dx * m_dx + m_dy * m_dy; }
};
s32 m_szx;
s32 m_szy;
f32 m_scale;
std::vector< DistancePoint > m_gridInside;
std::vector< DistancePoint > m_gridOutside;
void fromRgba(const u8 *pImageData);
void toRgba(u8 *pImageData);
void computeSdf(std::vector< DistancePoint > &);
int index(int x, int y) const;
DistancePoint compare(
const std::vector< DistancePoint > &,
const DistancePoint &p,
int x,
int y) const;
};
#endif
| 23.830769 | 77 | 0.677857 |
b871561f59844b55ba22bfa0d44e91df74faeec1 | 999 | h | C | src/prod/test/TracePoints/TracePointsWinFabric/TracePointPayload.h | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/test/TracePoints/TracePointsWinFabric/TracePointPayload.h | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/test/TracePoints/TracePointsWinFabric/TracePointPayload.h | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
#include "stdafx.h"
namespace TracePoints
{
class TracePointPayload
{
public:
TracePointPayload();
void Parse(std::wstring const & message);
USHORT GetMessageId() const;
std::wstring GetFullyQualifiedPipeName() const;
std::wstring GetNodeId() const;
bool HasAction() const;
std::wstring GetAction() const;
private:
std::wstring message_;
USHORT messageId_;
std::wstring fullyQualifiedPipeName_;
std::wstring nodeId_;
bool hasAction_;
std::wstring action_;
std::vector<std::wstring> split(const std::wstring &s, std::wstring const& delimiters);
};
}
| 22.2 | 98 | 0.55956 |
b888b95c5d8f2b25b220ec73aba06dc1fb7c2ea0 | 1,652 | h | C | Class_01/nitoClassEnvironmentSetup/nitoClassEnvironmentSetup/Classes/HelperClass.h | lechium/nitoClass | 9e2884803e61097dc3f26d375b90ebf796f91c59 | [
"MIT"
] | 4 | 2020-03-27T21:43:53.000Z | 2021-04-05T10:54:08.000Z | Class_01/nitoClassEnvironmentSetup/nitoClassEnvironmentSetup/Classes/HelperClass.h | lechium/nitoClass | 9e2884803e61097dc3f26d375b90ebf796f91c59 | [
"MIT"
] | null | null | null | Class_01/nitoClassEnvironmentSetup/nitoClassEnvironmentSetup/Classes/HelperClass.h | lechium/nitoClass | 9e2884803e61097dc3f26d375b90ebf796f91c59 | [
"MIT"
] | 1 | 2020-04-05T21:25:43.000Z | 2020-04-05T21:25:43.000Z | #import "XcodeDownloads.h"
@interface HelperClass: NSObject
@property XcodeDownloads *xcDownloadInfo;
@property BOOL hasAppleId;
@property BOOL hasDeveloperAccount;
@property NSString *theosPath;
@property NSString *dpkgPath;
@property NSString *username;
@property (strong, atomic) void (^BasicProgressBlock)(NSString *progressDetails, BOOL indeterminate, double percentComplete);
@property (strong, atomic) void (^HelperProgressBlock)(NSString *progressDetails, double percentComplete, double writtenBytes, double expectedBytes);
+ (NSString *)theosPath;
+ (NSString *)aliasPath;
+ (NSString *)defaultShell;
+ (NCSystemVersionType)currentVersion;
+ (float)freeSpaceAvailable;
+ (NSString *)freeSpaceString;
- (void)checkoutTheosIfNecessary:(void(^)(BOOL success))block;
- (NSString *)processDownload:(NSString *)download;
+ (NSURL *)moreDownloadsURL;
+ (NSURL *)appleIDPage;
+ (NSURL *)developerAccountSite;
+ (BOOL)xcodeInstalled;
+ (BOOL)brewInstalled;
+ (BOOL)commandLineToolsInstalled;
- (void)installHomebrewIfNecessary;
+ (void)openIDSignupPage;
+ (void)openDeveloperAccountSite;
+ (BOOL)queryUserWithString:(NSString *)query;
+ (NSInteger)runTask:(NSString *)fullCommand inFolder:(NSString *)targetFolder;
+ (NSArray *)returnForProcess:(NSString *)call;
+ (NSString *)singleLineReturnForProcess:(NSString *)call;
+ (NSArray *)arrayReturnForTask:(NSString *)taskBinary withArguments:(NSArray *)taskArguments;
+ (NSString *)mountImage:(NSString *)irString;
+ (NSArray *)scanForDrives;
+ (NSString *)cacheFolder ;
+ (NSString *)sessionCache;
+ (long long)sessionCacheSize;
+ (long long) folderSizeAtPath: (const char*)folderPath;
@end
| 32.392157 | 149 | 0.775424 |
ef9bb84e702dca46921e92129eda9635770cd1e0 | 5,576 | h | C | src/proc/synthetic-stream.h | GameHuiTea/librealsense | 6c4fd2dbb082e7765c5a9f7c9f5b14275fda565c | [
"Apache-2.0"
] | 1 | 2020-04-14T12:25:42.000Z | 2020-04-14T12:25:42.000Z | src/proc/synthetic-stream.h | GameHuiTea/librealsense | 6c4fd2dbb082e7765c5a9f7c9f5b14275fda565c | [
"Apache-2.0"
] | 2 | 2021-01-21T14:23:05.000Z | 2022-01-15T02:35:49.000Z | src/proc/synthetic-stream.h | GameHuiTea/librealsense | 6c4fd2dbb082e7765c5a9f7c9f5b14275fda565c | [
"Apache-2.0"
] | 2 | 2016-11-29T07:22:57.000Z | 2016-12-05T16:04:59.000Z | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2017 Intel Corporation. All Rights Reserved.
#pragma once
#include "core/processing.h"
#include "image.h"
#include "source.h"
#include "../include/librealsense2/hpp/rs_frame.hpp"
#include "../include/librealsense2/hpp/rs_processing.hpp"
namespace librealsense
{
class synthetic_source : public synthetic_source_interface
{
public:
synthetic_source(frame_source& actual)
: _actual_source(actual), _c_wrapper(new rs2_source{ this })
{
}
frame_interface* allocate_video_frame(std::shared_ptr<stream_profile_interface> stream,
frame_interface* original,
int new_bpp = 0,
int new_width = 0,
int new_height = 0,
int new_stride = 0,
rs2_extension frame_type = RS2_EXTENSION_VIDEO_FRAME) override;
frame_interface* allocate_composite_frame(std::vector<frame_holder> frames) override;
frame_interface* allocate_points(std::shared_ptr<stream_profile_interface> stream,
frame_interface* original, rs2_extension frame_type = RS2_EXTENSION_POINTS) override;
void frame_ready(frame_holder result) override;
rs2_source* get_c_wrapper() override { return _c_wrapper.get(); }
private:
frame_source & _actual_source;
std::shared_ptr<rs2_source> _c_wrapper;
};
class LRS_EXTENSION_API processing_block : public processing_block_interface, public options_container, public info_container
{
public:
processing_block(std::string name);
void set_processing_callback(frame_processor_callback_ptr callback) override;
void set_output_callback(frame_callback_ptr callback) override;
void invoke(frame_holder frames) override;
synthetic_source_interface& get_source() override { return _source_wrapper; }
virtual ~processing_block() { _source.flush(); }
protected:
frame_source _source;
std::mutex _mutex;
frame_processor_callback_ptr _callback;
synthetic_source _source_wrapper;
};
class generic_processing_block : public processing_block
{
public:
generic_processing_block(std::string name);
virtual ~generic_processing_block() { _source.flush(); }
protected:
virtual rs2::frame prepare_output(const rs2::frame_source& source, rs2::frame input, std::vector<rs2::frame> results);
virtual bool should_process(const rs2::frame& frame) = 0;
virtual rs2::frame process_frame(const rs2::frame_source& source, const rs2::frame& f) = 0;
};
struct stream_filter
{
rs2_stream stream;
rs2_format format;
int index;
stream_filter() : stream(RS2_STREAM_ANY), format(RS2_FORMAT_ANY), index(-1) {}
stream_filter(rs2_stream s, rs2_format f, int i) : stream(s), format(f), index(i) {}
bool match(const rs2::frame& frame)
{
stream_filter filter(frame.get_profile().stream_type(), frame.get_profile().format(), frame.get_profile().stream_index());
return match(filter);
}
bool match(const stream_filter& other)
{
if (stream != RS2_STREAM_ANY && stream != other.stream)
return false;
if (format != RS2_FORMAT_ANY && format != other.format)
return false;
if (index != -1 && index != other.index)
return false;
return true;
}
bool operator==(const stream_filter& other)
{
if (stream != other.stream)
return false;
if (format != other.format)
return false;
if (index != other.index)
return false;
return true;
}
bool operator!=(const stream_filter& other)
{
return !(*this == other);
}
void operator=(const stream_filter& other)
{
stream = other.stream;
format = other.format;
index = other.index;
}
};
class LRS_EXTENSION_API stream_filter_processing_block : public generic_processing_block
{
public:
stream_filter_processing_block(std::string name);
virtual ~stream_filter_processing_block() { _source.flush(); }
protected:
stream_filter _stream_filter;
bool should_process(const rs2::frame& frame) override;
};
class depth_processing_block : public stream_filter_processing_block
{
public:
depth_processing_block(std::string name) :stream_filter_processing_block(name)
{}
virtual ~depth_processing_block() { _source.flush(); }
protected:
bool should_process(const rs2::frame& frame) override;
};
}
// API structures
struct rs2_options
{
rs2_options(librealsense::options_interface* options) : options(options) { }
librealsense::options_interface* options;
virtual ~rs2_options() = default;
};
struct rs2_options_list
{
std::vector<rs2_option> list;
};
struct rs2_processing_block : public rs2_options
{
rs2_processing_block(std::shared_ptr<librealsense::processing_block_interface> block)
: rs2_options((librealsense::options_interface*)block.get()),
block(block) { }
std::shared_ptr<librealsense::processing_block_interface> block;
rs2_processing_block& operator=(const rs2_processing_block&) = delete;
rs2_processing_block(const rs2_processing_block&) = delete;
};
| 31.862857 | 134 | 0.654591 |
d4844c3248a1fd63bcdc251eb5a18404a26d0052 | 1,269 | h | C | Frameworks/NetworkExtension.framework/NEPacketTunnelFlow.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | Frameworks/NetworkExtension.framework/NEPacketTunnelFlow.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | Frameworks/NetworkExtension.framework/NEPacketTunnelFlow.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/NetworkExtension.framework/NetworkExtension
*/
@interface NEPacketTunnelFlow : NSObject {
bool _handlerSetup;
struct NEVirtualInterface_s { } * _interface;
long long _interfaceType;
id /* block */ _packetHandler;
NSObject<OS_dispatch_queue> * _queue;
NSFileHandle * _socket;
}
@property bool handlerSetup;
@property (readonly) struct NEVirtualInterface_s { }*interface;
@property (readonly) long long interfaceType;
@property (copy) id /* block */ packetHandler;
@property (retain) NSObject<OS_dispatch_queue> *queue;
@property (retain) NSFileHandle *socket;
- (void).cxx_destruct;
- (void)closeVirtualInterface;
- (void)dealloc;
- (bool)handlerSetup;
- (id)initWithVirtualInterfaceType:(long long)arg1;
- (struct NEVirtualInterface_s { }*)interface;
- (long long)interfaceType;
- (id /* block */)packetHandler;
- (id)queue;
- (void)readPacketsWithCompletionHandler:(id /* block */)arg1;
- (void)resetReadHandler;
- (void)setHandlerSetup:(bool)arg1;
- (void)setPacketHandler:(id /* block */)arg1;
- (void)setQueue:(id)arg1;
- (void)setSocket:(id)arg1;
- (bool)setVirtualInterfaceSocket:(id)arg1;
- (id)socket;
- (bool)writePackets:(id)arg1 withProtocols:(id)arg2;
@end
| 30.95122 | 80 | 0.738377 |
c2d3819dd101c89be4e0f0944c8e4baeffed09ab | 189 | h | C | UnrealPlugin/DazToUnreal/Source/DazToUnreal/Public/DazToUnrealUtils.h | daz3d/DazToUnreal | 5f44437f58c69777ea43b73a8d02856ea1f16ba7 | [
"Apache-2.0"
] | 33 | 2020-07-23T03:00:03.000Z | 2021-12-16T03:02:22.000Z | UnrealPlugin/DazToUnreal/Source/DazToUnreal/Public/DazToUnrealUtils.h | Dracoonica/DazToUnreal | 5f44437f58c69777ea43b73a8d02856ea1f16ba7 | [
"Apache-2.0"
] | 5 | 2020-08-11T06:04:20.000Z | 2021-03-21T04:01:09.000Z | UnrealPlugin/DazToUnreal/Source/DazToUnreal/Public/DazToUnrealUtils.h | Dracoonica/DazToUnreal | 5f44437f58c69777ea43b73a8d02856ea1f16ba7 | [
"Apache-2.0"
] | 8 | 2020-07-27T17:03:26.000Z | 2021-12-11T11:02:33.000Z | // Copyright 2018-2020 David Vodhanel. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
class FDazToUnrealUtils
{
public:
static FString SanitizeName(FString OriginalName);
}; | 17.181818 | 59 | 0.783069 |
720ab80fa8b9329cf71e33deb5d061b017414efa | 2,867 | h | C | src/assetdb.h | RustKnight/Dwarf-Vision | 60753142b8b5f550d8c3a6f53c6240bd6faadcd5 | [
"MIT"
] | 6 | 2020-12-13T23:45:07.000Z | 2022-01-26T22:11:15.000Z | src/assetdb.h | RustKnight/Dwarf-Vision | 60753142b8b5f550d8c3a6f53c6240bd6faadcd5 | [
"MIT"
] | null | null | null | src/assetdb.h | RustKnight/Dwarf-Vision | 60753142b8b5f550d8c3a6f53c6240bd6faadcd5 | [
"MIT"
] | null | null | null | #ifndef ASSETDB_H
#define ASSETDB_H
#include <QList>
#include <QPixmap>
#include <QDir>
#include <QFile>
#include <QRegularExpression>
#include "Ticket.h"
#include "sheet.h"
struct NamedPixmap{
NamedPixmap(QPixmap pix, QString name) : pixmap {pix}, name {name}
{
if (pixmap.size() != g_assetSize){
// Check size of asset. Warn. Option to stop.
QString var = QString::number(pixmap.size().width()) + "x" + QString::number(pixmap.size().height());
QString varExpected = QString::number(g_assetSize.width()) + "x" + QString::number(g_assetSize.height());
QMessageBox messageBox;
messageBox.warning(0,"Warning", "Asset is " + var + "\nExpected size is " + varExpected + "!\nFile name: " + name);
messageBox.setFixedSize(500,200);
QMessageBox::StandardButton reply;
reply = messageBox.question(nullptr, "", "Ignore and continue?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::No)
exit(0);
}
}
bool passedFilters (QList<QStringList>& filterLists) const{
// split bodyParts name
QStringList splitList = name.split("_");
bool filterFoundStatus;
// check splitList against filters
for (QStringList& filterList: filterLists){
filterFoundStatus = false;
for (QString& filter : filterList){
for (QString& split: splitList){
if (split.compare(filter, Qt::CaseInsensitive) == 0){
filterFoundStatus = true;
goto nextFilterList;
}
// finised all splits
}
// finised all filters from list (for this loop)
}
// if false, we failed to match the current filter in the filters for-loop; return false
if (filterFoundStatus == false)
return filterFoundStatus;
nextFilterList:;
}
// if here, all filters found, return true
return true;
}
QPixmap pixmap;
QString name;
};
class AssetDB
{
public:
AssetDB();
void loadResources();
void checkAssetsNameCorrectness(QStringList allFilters);
Sheet getSheet (Ticket ticket, QList<QStringList>& filters);
QList<Sheet> getAllSheets (Ticket ticket);
void readTotalRaces(QFileInfoList allPNGs);
int getRaceIndex (QString pngName);
const QStringList& getRacesList();
void shortenBodyPart(QString& pngName);
private:
QList < QList < QList < QList <NamedPixmap> > > > assetDB;
QStringList culturesList;
};
#endif // ASSETDB_H
| 25.828829 | 128 | 0.561911 |
818b7b99de93ff9ea42732730d23c80a6e96f698 | 1,405 | h | C | core/NonFungibleToken.h | mm-s/symbol-sdk-cpp | 2151503ff69d582de47acde1dffae02ed21e78ab | [
"MIT"
] | null | null | null | core/NonFungibleToken.h | mm-s/symbol-sdk-cpp | 2151503ff69d582de47acde1dffae02ed21e78ab | [
"MIT"
] | null | null | null | core/NonFungibleToken.h | mm-s/symbol-sdk-cpp | 2151503ff69d582de47acde1dffae02ed21e78ab | [
"MIT"
] | null | null | null | /**
*** Copyright (c) 2016-2019, Jaguar0625, gimre, BloodyRookie, Tech Bureau, Corp.
*** Copyright (c) 2020-present, Jaguar0625, gimre, BloodyRookie.
*** All rights reserved.
***
*** This file is part of Catapult.
***
*** Catapult is free software: you can redistribute it and/or modify
*** it under the terms of the GNU Lesser General Public License as published by
*** the Free Software Foundation, either version 3 of the License, or
*** (at your option) any later version.
***
*** Catapult 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 Catapult. If not, see <http://www.gnu.org/licenses/>.
**/
#pragma once
#include "base.h"
#include "Network.h"
#include <string>
#include <vector>
namespace symbol { namespace core {
using std::string;
using std::vector;
using std::pair;
class NonFungibleToken {
public:
NonFungibleToken();
static ptr<NonFungibleToken> load(const string& fileOrDir);
string save(const string& fileOrDir) const;
// Commit to blockchain
vector<ptr<Network::Account>> commit(const Network::Account& owner);
private:
ptr<Network::Account> m_owner;
};
}} // Namespaces
| 28.1 | 80 | 0.720996 |
f10aa426bd8c72d396838a70873bf8d0619ea657 | 1,004 | h | C | Example/Draw1.1/DrawAndEditTest/DrawAndEditTest/qgraphicspolylineitem.h | pprp/QPainter | 98e6df3c74027b690ba379aab3f4f34676a31d27 | [
"Apache-2.0"
] | 17 | 2018-07-01T13:23:23.000Z | 2022-02-05T02:10:56.000Z | Example/Draw1.1/DrawAndEditTest/DrawAndEditTest/qgraphicspolylineitem.h | pprp/QPainter | 98e6df3c74027b690ba379aab3f4f34676a31d27 | [
"Apache-2.0"
] | 1 | 2018-07-01T13:59:30.000Z | 2018-07-01T13:59:30.000Z | Example/Draw1.1/DrawAndEditTest/DrawAndEditTest/qgraphicspolylineitem.h | pprp/QPainter | 98e6df3c74027b690ba379aab3f4f34676a31d27 | [
"Apache-2.0"
] | 9 | 2018-07-01T13:20:32.000Z | 2021-09-08T05:28:14.000Z | #ifndef QGRAPHICSPOLYLINEITEM_H
#define QGRAPHICSPOLYLINEITEM_H
#include <QRect>
#include <QPainterPath>
#include <QStyleOptionGraphicsItem>
#include <QVector>
#include<QGraphicsLineItem>
#include <QtGui>
class QGraphicsPolylineItem : public QGraphicsPathItem
{
public:
QGraphicsPolylineItem();
QGraphicsPolylineItem(QVector<QPointF> ps);
QVector<QPointF> points;
~QGraphicsPolylineItem();
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
private:
// QRectF m_rect;
bool cScale;
QCursor* m_cursor;
QPointF start;
QPointF end;
int direction;
bool isReadyToEdit;
int nearByPointI(QPointF point);
};
#endif // QGRAPHICSPOLYLINEITEM_H
| 23.348837 | 60 | 0.767928 |
da48a26da49494d6c594194c748cb940d6db2d20 | 236 | c | C | ports/japanese/cdrom2/dragonfly/patch-cdgaiji.c | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 31 | 2015-02-06T17:06:37.000Z | 2022-03-08T19:53:28.000Z | ports/japanese/cdrom2/dragonfly/patch-cdgaiji.c | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 236 | 2015-06-29T19:51:17.000Z | 2021-12-16T22:46:38.000Z | ports/japanese/cdrom2/dragonfly/patch-cdgaiji.c | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 52 | 2015-02-06T17:05:36.000Z | 2021-10-21T12:13:06.000Z | --- cdgaiji.c.orig 1996-06-29 16:25:22 UTC
+++ cdgaiji.c
@@ -9,6 +9,8 @@
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
+#include <unistd.h>
+#include <stdlib.h>
#ifdef MSC
#include <sys/types.h>
#define size_t off_t
| 19.666667 | 42 | 0.635593 |
0a0f4ada2d93be5b2f87c3acde2962f6fe635a7f | 2,631 | h | C | include/cetty/channel/CompleteChannelFuture.h | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 26 | 2015-11-08T10:58:21.000Z | 2021-02-25T08:27:26.000Z | include/cetty/channel/CompleteChannelFuture.h | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2019-02-18T08:46:17.000Z | 2019-02-18T08:46:17.000Z | include/cetty/channel/CompleteChannelFuture.h | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 8 | 2016-02-27T02:37:10.000Z | 2021-09-29T05:25:00.000Z | #if !defined(CETTY_CHANNEL_COMPLETECHANNELFUTURE_H)
#define CETTY_CHANNEL_COMPLETECHANNELFUTURE_H
/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat 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.
*/
/*
* Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
* Distributed under under the Apache License, version 2.0 (the "License").
*/
#include <cetty/channel/ChannelFuture.h>
namespace cetty {
namespace channel {
/**
* A skeletal {@link ChannelFuture} implementation which represents a
* {@link ChannelFuture} which has been completed already.
*
*
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
*
* @author <a href="mailto:frankee.zhou@gmail.com">Frankee Zhou</a>
*/
class CompleteChannelFuture : public ChannelFuture {
public:
virtual ~CompleteChannelFuture() {}
virtual ChannelFuturePtr addListener(const CompletedCallback& listener, int priority = 0);
virtual ChannelFuturePtr addProgressListener(const ProgressedCallback& listener);
virtual ChannelFuturePtr removeListener(const CompletedCallback& listener);
virtual ChannelFuturePtr removeProgressListener(const ProgressedCallback& listener);
virtual ChannelFuturePtr await();
virtual bool await(int64_t timeoutMillis);
virtual ChannelFuturePtr awaitUninterruptibly();
virtual bool awaitUninterruptibly(int64_t timeoutMillis);
virtual ChannelPtr channel() const;
//virtual ChannelPtr sharedChannel() const;
virtual bool isDone() const;
virtual bool setProgress(int amount, int current, int total);
virtual bool setFailure(const Exception& cause);
virtual bool setSuccess();
virtual bool cancel();
virtual bool isCancelled() const;
protected:
/**
* Creates a new instance.
*
* @param channel the {@link Channel} associated with this future
*/
CompleteChannelFuture(const ChannelPtr& channel);
CompleteChannelFuture(const ChannelWeakPtr& channel);
private:
ChannelWeakPtr channel_;
};
}
}
#endif //#if !defined(CETTY_CHANNEL_COMPLETECHANNELFUTURE_H)
// Local Variables:
// mode: c++
// End:
| 29.233333 | 94 | 0.739263 |
97583ab8fc85f927a162675ade48fb7a36b3ba03 | 405 | h | C | Ascension/AscApplication.h | osakahq/OsakaEngine | 47dd0ec5b67a176c552441a25168ecb48b52e14b | [
"Zlib",
"MIT"
] | 2 | 2016-04-04T06:00:28.000Z | 2016-04-18T15:39:38.000Z | Ascension/AscApplication.h | osakahq/OsakaEngine | 47dd0ec5b67a176c552441a25168ecb48b52e14b | [
"Zlib",
"MIT"
] | null | null | null | Ascension/AscApplication.h | osakahq/OsakaEngine | 47dd0ec5b67a176c552441a25168ecb48b52e14b | [
"Zlib",
"MIT"
] | null | null | null | #include "stdafx.h"
#ifndef ASC_ASCAPPLICATION_H
#define ASC_ASCAPPLICATION_H
#include <RPGApplication.h>
namespace Osaka{
namespace Asc{
class AscApplication : public RPGLib::RPGApplication{
public:
AscApplication(Debug::DebugPTR& d, Engine::SDLLibPTR& sdl, Engine::IFileLoaderPTR& fileloader);
~AscApplication();
void _delete();
void Update();
};
}
}
#endif | 19.285714 | 99 | 0.693827 |
ee81b97a5ea6ab062f56051ca3f65dde3c0d4980 | 2,005 | h | C | Source/ARTPushActivationEvent.h | ably/ably-cocoa | 51de8ebd5b4f40427405f69f9d9cc9e81228decc | [
"Apache-2.0"
] | 18 | 2019-12-29T16:34:59.000Z | 2022-01-17T20:42:07.000Z | Source/ARTPushActivationEvent.h | ably/ably-ios | 0fe3c59658ce7d0b7181571cdad1f068d4085088 | [
"Apache-2.0"
] | 698 | 2015-01-19T18:24:24.000Z | 2019-02-06T17:04:57.000Z | Source/ARTPushActivationEvent.h | ably/ably-ios | 0fe3c59658ce7d0b7181571cdad1f068d4085088 | [
"Apache-2.0"
] | 13 | 2015-01-19T10:04:50.000Z | 2017-12-05T16:36:01.000Z | #import <Foundation/Foundation.h>
@class ARTErrorInfo;
@class ARTPushActivationState;
@class ARTDeviceIdentityTokenDetails;
NS_ASSUME_NONNULL_BEGIN
@interface ARTPushActivationEvent : NSObject <NSSecureCoding>
- (NSData *)archive;
+ (nullable ARTPushActivationState *)unarchive:(NSData *)data;
@end
/// Event with Error info
@interface ARTPushActivationErrorEvent : ARTPushActivationEvent
@property (nonatomic, readonly) ARTErrorInfo *error;
- (instancetype)initWithError:(ARTErrorInfo *)error;
+ (instancetype)newWithError:(ARTErrorInfo *)error;
@end
/// Event with Device Identity Token details
@interface ARTPushActivationDeviceIdentityEvent : ARTPushActivationEvent
@property (nonatomic, readonly, nullable) ARTDeviceIdentityTokenDetails *identityTokenDetails;
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new;
- (instancetype)initWithIdentityTokenDetails:(nullable ARTDeviceIdentityTokenDetails *)identityTokenDetails;
+ (instancetype)newWithIdentityTokenDetails:(ARTDeviceIdentityTokenDetails *)identityTokenDetails;
@end
#pragma mark - Events
@interface ARTPushActivationEventCalledActivate : ARTPushActivationEvent
@end
@interface ARTPushActivationEventCalledDeactivate : ARTPushActivationEvent
@end
@interface ARTPushActivationEventGotPushDeviceDetails : ARTPushActivationEvent
@end
@interface ARTPushActivationEventGettingPushDeviceDetailsFailed : ARTPushActivationErrorEvent
@end
@interface ARTPushActivationEventGotDeviceRegistration : ARTPushActivationDeviceIdentityEvent
@end
@interface ARTPushActivationEventGettingDeviceRegistrationFailed : ARTPushActivationErrorEvent
@end
@interface ARTPushActivationEventRegistrationSynced : ARTPushActivationDeviceIdentityEvent
@end
@interface ARTPushActivationEventSyncRegistrationFailed : ARTPushActivationErrorEvent
@end
@interface ARTPushActivationEventDeregistered : ARTPushActivationEvent
@end
@interface ARTPushActivationEventDeregistrationFailed : ARTPushActivationErrorEvent
@end
NS_ASSUME_NONNULL_END
| 27.847222 | 108 | 0.859352 |
205b2fc989ad2af268160972df91d1307d0c8203 | 6,344 | h | C | constrained_ik/include/constrained_ik/constraints/avoid_joint_limits.h | tfoote/industrial_moveit | 2365f555e2909351510236875f0dc69ffb316d49 | [
"Apache-2.0"
] | 97 | 2015-09-02T03:32:44.000Z | 2022-02-20T16:42:03.000Z | constrained_ik/include/constrained_ik/constraints/avoid_joint_limits.h | tfoote/industrial_moveit | 2365f555e2909351510236875f0dc69ffb316d49 | [
"Apache-2.0"
] | 77 | 2015-08-26T15:58:13.000Z | 2021-09-29T12:38:30.000Z | constrained_ik/include/constrained_ik/constraints/avoid_joint_limits.h | tfoote/industrial_moveit | 2365f555e2909351510236875f0dc69ffb316d49 | [
"Apache-2.0"
] | 62 | 2015-04-24T16:17:21.000Z | 2021-11-22T13:54:11.000Z | /**
* @file avoid_joint_limits.h
* @brief Constraint to avoid joint position limits.
*
* Using cubic velocity ramp, it pushes each joint away from its limits,
* with a maximimum velocity of 2*threshold*(joint range).
* Only affects joints that are within theshold of joint limit.
*
* @author dsolomon
* @date Sep 23, 2013
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2013, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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 AVOID_JOINT_LIMITS_H_
#define AVOID_JOINT_LIMITS_H_
#include "constrained_ik/constraint.h"
#include <vector>
namespace constrained_ik
{
namespace constraints
{
/**
* @class constrained_ik::constraints::AvoidJointLimits
* @brief Constraint to avoid joint position limits
*
* Using cubic velocity ramp, it pushes each joint away from its limits,
* with a maximimum velocity of 2*threshold*(joint range).
* Only affects joints that are within theshold of joint limit.
*
* @par Examples:
* All examples are located here @ref avoid_joint_limits_example
*/
class AvoidJointLimits: public Constraint
{
protected:
/**
* @brief Stores joint limit constraint data for a single joint.
*/
struct LimitsT
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
double min_pos; /**< @brief minimum joint position */
double max_pos; /**< @brief maximum joint position */
double lower_thresh; /**< @brief lower threshold at which limiting begins */
double upper_thresh; /**< @brief upper threshold at which limiting begins */
double e; /**< @brief threshold as a distance from limit */
double k3; /**< @brief factor used in cubic velocity ramp */
/**
* @brief Constructor for LimitsT
* @param minPos Minimum allowed joint position
* @param maxPos Maximum allowed joint position
* @param threshold Limiting threshold given as a percentage of joint range
*/
LimitsT(double minPos, double maxPos, double threshold);
/**
* @brief Calculates velocity for joint position avoidance
* Uses cubic function v = y-y0 = k(x-x0)^3 where k=max_vel/(joint_range/2)^3
* @param angle Angle to calculate velocity for
* @param limit Angle limit
* @return joint velocity to avoid joint limits
*/
double cubicVelRamp(double angle, double limit) const;
};
std::vector<LimitsT> limits_; /**< @brief vector holding joint limit data */
double weight_; /**< @brief weights used to scale the jocabian and error */
double threshold_; /**< @brief threshold (% of range) at which to engage limit avoidance */
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/** @brief This structure stores constraint data */
struct AvoidJointLimitsData: public ConstraintData
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
std::vector<int> limited_joints_; /**< @brief list of joints that will be constrained */
const constraints::AvoidJointLimits* parent_; /**< @brief pointer to parent class object */
/** @brief See base class for documentation */
AvoidJointLimitsData(const constrained_ik::SolverState &state, const constraints::AvoidJointLimits* parent);
/**
* @brief Check if a given joint is near its lower limit
* @param idx Index of joint
* @return True if joint position is within threshold of lower limit
*/
bool nearLowerLimit(size_t idx) const;
/**
* @brief Check if a given joint is near its upper limit
* @param idx Index of joint
* @return True if joint position is within threshold of upper limit
*/
bool nearUpperLimit(size_t idx) const;
};
AvoidJointLimits();
/**
* @brief Initialize constraint (overrides Constraint::init)
* Initializes internal limit variables
* Should be called before using class.
* @param ik Pointer to Constrained_IK used for base-class init
*/
void init(const Constrained_IK* ik) override;
/** @brief see base class for documentation*/
constrained_ik::ConstraintResults evalConstraint(const SolverState &state) const override;
/** @brief see base class for documentation */
void loadParameters(const XmlRpc::XmlRpcValue &constraint_xml) override;
/**
* @brief Creates jacobian rows corresponding to joint velocity limit avoidance
* Each limited joint gets a 0 row with a 1 in that joint's column
* @param cdata The constraint specific data
* @return Pseudo-Identity scaled by weight_
*/
virtual Eigen::MatrixXd calcJacobian(const AvoidJointLimitsData &cdata) const;
/**
* @brief Creates vector representing velocity error term
* corresponding to calcJacobian()
* @param cdata The constraint specific data.
* @return VectorXd of joint velocities for joint limit avoidance
*/
virtual Eigen::VectorXd calcError(const AvoidJointLimitsData &cdata) const;
/**
* @brief Checks termination criteria
* There are no termination criteria for this constraint
* @param cdata The constraint specific data.
* @return True
*/
virtual bool checkStatus(const AvoidJointLimitsData &cdata) const {return true;}
/**
* @brief getter for weight_
* @return weight_
*/
virtual double getWeight() const {return weight_;}
/**
* @brief setter for weight_
* @param weight Value to set weight_ to
*/
virtual void setWeight(const double &weight) {weight_ = weight;}
/**
* @brief getter for threshold_
* @return threshold_
*/
virtual double getThreshold() const {return threshold_;}
/**
* @brief setter for threshold_
* @param threshold Value to set threshold_ to
*/
virtual void setThreshold(const double &threshold) {threshold_ = threshold;}
};
} /* namespace constraints */
} /* namespace constrained_ik */
#endif /* AVOID_JOINT_LIMITS_H_ */
| 34.291892 | 112 | 0.711696 |
e3db92be8f24c4293a144efdad6bdd1de9acdc53 | 305 | h | C | DrStep/DSProfileCell.h | davidjeong/dr-step | 53ee76dbed207f7effdc827466034d961966d6d7 | [
"MIT"
] | null | null | null | DrStep/DSProfileCell.h | davidjeong/dr-step | 53ee76dbed207f7effdc827466034d961966d6d7 | [
"MIT"
] | null | null | null | DrStep/DSProfileCell.h | davidjeong/dr-step | 53ee76dbed207f7effdc827466034d961966d6d7 | [
"MIT"
] | null | null | null | //
// DSProfileCell.h
// DrStep
//
// Created by Juhwan Jeong on 3/18/16.
//
//
#import <UIKit/UIKit.h>
@interface DSProfileCell : UITableViewCell
@property (nonatomic, strong) UIImage *profileImage;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *email;
@end
| 16.944444 | 52 | 0.711475 |
eea81dde2b4c1ddf12f60c0ba6cab279c7b2c4f7 | 1,299 | h | C | src/OSTempsReel/Timer.h | gabrielriqu3ti/OSTempsReel | 4bc35d13e27b512d32f415af191cbaee4ee3c4db | [
"MIT"
] | null | null | null | src/OSTempsReel/Timer.h | gabrielriqu3ti/OSTempsReel | 4bc35d13e27b512d32f415af191cbaee4ee3c4db | [
"MIT"
] | null | null | null | src/OSTempsReel/Timer.h | gabrielriqu3ti/OSTempsReel | 4bc35d13e27b512d32f415af191cbaee4ee3c4db | [
"MIT"
] | null | null | null | /*///////////////////////////////////////////////////////////////////////
|
| Fichier : Timer.h
|| Auteur : RIQUETI Gabriel Henrique
| Date : 18/10/2019
| Commentaires : ENSTA ParisTech ROB305 TD-3b
Historique de R�vision :
|
*////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef OSTempsReel_Timer_h_INCLUDED
#define OSTempsReel_Timer_h_INCLUDED
#include <time.h>
#include <signal.h>
namespace OSTempsReel
{
/***********************************************************************
* Classe : Timer
* Auteur : RIQUETI
* Date : 22/11/2019
*
* But : Implémenter les fonctionnalités d'un timer
* Posix
***********************************************************************/
class Timer
{
// Données
protected:
timer_t tid;
// Méthodes
public:
Timer();
~Timer();
void start(double duration_ms);
void stop();
protected:
virtual void callback()=0;
private:
static void call_callback(int sig, siginfo_t* si, void*);
};
}
#endif // !OSTempsReel_Timer_h_INCLUDED
| 25.98 | 73 | 0.400308 |
0ca940fcf87e71eb1863e408afa1b30fb7a781c7 | 3,894 | c | C | src/interpreter/statement.c | h010dev/smallsh | fa46b1ee2dfd82c830e75f9fe9c6e987fd8de17e | [
"MIT"
] | null | null | null | src/interpreter/statement.c | h010dev/smallsh | fa46b1ee2dfd82c830e75f9fe9c6e987fd8de17e | [
"MIT"
] | null | null | null | src/interpreter/statement.c | h010dev/smallsh | fa46b1ee2dfd82c830e75f9fe9c6e987fd8de17e | [
"MIT"
] | null | null | null | /**
* @file statement.c
* @author Mohamed Al-Hussein
* @date 02 Feb 2022
* @brief For creating command statements to later be executed.
*/
#include <stdlib.h>
#include <stdio.h>
#include "interpreter/statement.h"
/* *****************************************************************************
* PUBLIC DEFINITIONS
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
******************************************************************************/
/* *****************************************************************************
* CONSTRUCTORS + DESTRUCTORS
*
*
*
*
*
*
*
******************************************************************************/
SH_Statement *SH_CreateStatement(void)
{
SH_Statement *stmt = malloc(sizeof(SH_Statement));
// statement command init
stmt->cmd = malloc(sizeof(StmtCmd));
stmt->cmd->count = 0;
stmt->cmd->args = malloc(sizeof(char *));
stmt->cmd->args[0] = NULL;
// statement io redirection: stdin init
stmt->infile = malloc(sizeof(StmtStdin));
stmt->infile->n = 0;
stmt->infile->streams = malloc(sizeof(char *));
stmt->infile->streams[0] = NULL;
// statement io redirection: stdout init
stmt->outfile = malloc(sizeof(StmtStdout));
stmt->outfile->n = 0;
stmt->outfile->streams = malloc(sizeof(char *));
stmt->outfile->streams[0] = NULL;
// statement flags init
stmt->flags = 0;
return stmt;
}
void SH_DestroyStatement(SH_Statement **stmt)
{
// statement command delete
for (size_t i = 0; i < (*stmt)->cmd->count; i++) {
free((*stmt)->cmd->args[i]);
(*stmt)->cmd->args[i] = NULL;
}
free((*stmt)->cmd->args);
(*stmt)->cmd->count = 0;
(*stmt)->cmd->args = NULL;
free((*stmt)->cmd);
(*stmt)->cmd = NULL;
// statement io redirection: stdin delete
for (size_t i = 0; i < (*stmt)->infile->n; i++) {
free((*stmt)->infile->streams[i]);
(*stmt)->infile->streams[i] = NULL;
}
free((*stmt)->infile->streams);
(*stmt)->infile->n = 0;
(*stmt)->infile->streams = NULL;
free((*stmt)->infile);
(*stmt)->infile = NULL;
// statement io redirection: stdout delete
for (size_t i = 0; i < (*stmt)->outfile->n; i++) {
free((*stmt)->outfile->streams[i]);
(*stmt)->outfile->streams[i] = NULL;
}
free((*stmt)->outfile->streams);
(*stmt)->outfile->n = 0;
(*stmt)->outfile->streams = NULL;
free((*stmt)->outfile);
(*stmt)->outfile = NULL;
// statement flags delete
(*stmt)->flags = FLAGS_NONE;
// statement delete
free(*stmt);
*stmt = NULL;
}
/* *****************************************************************************
* FUNCTIONS
*
*
*
*
*
*
*
******************************************************************************/
void SH_PrintStatement(SH_Statement const *stmt)
{
printf("STATEMENT(\n");
printf("\tFLAGS(\n");
if (stmt->flags == FLAGS_BGCTRL) {
printf("\t\tBG_CTRL,\n");
}
printf("\t)\n");
printf("\tCMD(\n");
for (size_t i = 0; i < stmt->cmd->count; i++) {
printf("\t\tARG [%zu] = %s,\n", i, stmt->cmd->args[i]);
}
printf("\t)\n");
printf("\tSTDIN(\n");
for (size_t i = 0; i < stmt->infile->n; i++) {
printf("\t\t[%zu] = %s,\n", i, stmt->infile->streams[i]);
}
printf("\t)\n");
printf("\tSTDOUT(\n");
for (size_t i = 0; i < stmt->outfile->n; i++) {
printf("\t\t[%zu] = %s,\n", i, stmt->outfile->streams[i]);
}
printf("\t)\n");
printf(")\n");
}
| 26.134228 | 80 | 0.426554 |
6b12e4f2d7c5df68e14a3c972ed911c67bcbd30e | 820 | c | C | tester_serial.c | hcho3/skiplist_cuda | 3a1f64c4ca8de0bf02995a206c139f4084eb47f0 | [
"BSD-2-Clause"
] | 12 | 2015-05-26T08:35:23.000Z | 2022-03-02T12:39:36.000Z | tester_serial.c | tpn/skiplist_cuda | 3a1f64c4ca8de0bf02995a206c139f4084eb47f0 | [
"BSD-2-Clause"
] | null | null | null | tester_serial.c | tpn/skiplist_cuda | 3a1f64c4ca8de0bf02995a206c139f4084eb47f0 | [
"BSD-2-Clause"
] | 5 | 2015-04-30T23:22:26.000Z | 2021-03-27T05:32:25.000Z | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "skip_serial.h"
int main(void)
{
int N = 100;
int i;
Skiplist *sl;
Node *cur;
int *result;
int result_dim;
srand(time(NULL));
sl = skiplist_create();
for (i = 0; i < N; i++)
skiplist_insert(sl, rand() % 100);
printf("size = %d\n", skiplist_size(sl));
result = skiplist_gather(sl, &result_dim);
printf("result_dim = %d\n", result_dim);
for (i = 0; i < N; i++)
printf("%d ", result[i]);
printf("\n");
free(result);
skiplist_remove(sl, 30);
printf("size = %d\n", skiplist_size(sl));
result = skiplist_gather(sl, &result_dim);
printf("result_dim = %d\n", result_dim);
for (i = 0; i < result_dim; i++)
printf("%d ", result[i]);
printf("\n");
skiplist_destroy(sl);
free(result);
return 0;
}
| 19.069767 | 44 | 0.595122 |
0b178a700e3c5ca6658bdd586a696b64011f384a | 1,548 | c | C | learn-c/Chapter-02-Conditional-and-Branching/ch02-08.c | hailehong95/Practice-Coding | 729acdd596f15657b717975bfa54da1e39114f8a | [
"MIT"
] | null | null | null | learn-c/Chapter-02-Conditional-and-Branching/ch02-08.c | hailehong95/Practice-Coding | 729acdd596f15657b717975bfa54da1e39114f8a | [
"MIT"
] | null | null | null | learn-c/Chapter-02-Conditional-and-Branching/ch02-08.c | hailehong95/Practice-Coding | 729acdd596f15657b717975bfa54da1e39114f8a | [
"MIT"
] | null | null | null | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
// a.x^4 + b.x^2 + c = 0
int main()
{
/*
** Phương pháp đặt ẩn phụ: t = x^2 (t >= 0)
** => at^2 + bt + c = 0
** Khi tính ra được một nghiệm t => Có 2 nghiệm x là: +sqrt(t) và -sqrt(t)
*/
float a, b, c;
printf("Giai phuong trinh ax^4 + bx^2 + c = 0\n");
printf("Nhap cac he so a, b, c = ");
scanf("%f %f %f", &a, &b, &c);
if (a == 0) {
// PT bậc nhất b.x + c = 0
if (b == 0) {
if (c == 0) printf("Phuong trinh co vo so nghiem\n");
else printf("Phuong trinh vo nghiem\n");
}
else {
float t = -c / b;
if (t < 0) printf("Phuong trinh vo nghiem\n");
else
{
float x1 = sqrt(t);
float x2 = -sqrt(t);
printf("X1 = %f\n", x1);
printf("X2 = %f\n", x2);
}
}
}
else {
float delta = b * b - 4 * a * c;
if (delta > 0) {
float t1 = (-b - sqrt(delta)) / (2 * a);
float t2 = (-b + sqrt(delta)) / (2 * a);
if (t1 >= 0) {
float x1 = sqrt(t1);
float x2 = -sqrt(t1);
printf("X1 = %f\n", x1);
printf("X2 = %f\n", x2);
}
if (t2 >= 0) {
float x3 = sqrt(t2);
float x4 = -sqrt(t2);
printf("X3 = %f\n", x3);
printf("X4 = %f\n", x4);
}
if (t1 < 0 && t2 < 0) {
printf("Phuong trinh vo nghiem\n");
}
}
else if (delta == 0) {
float t = -b / (2 * a);
if (t < 0) printf("Phuong trinh vo nghiem\n");
else {
float x1 = sqrt(t);
float x2 = -sqrt(t);
printf("X1 = %f\n", x1);
printf("X2 = %f\n", x2);
}
}
else {
printf("Phuong trinh vo nghiem\n");
}
}
return 0;
} | 20.918919 | 75 | 0.472222 |
ad84ef41dff7105b0b89c87175132e287ef20f77 | 2,150 | c | C | lumber/lumber_game.c | suicvne/ps2-lumberjack | aaf09c4ff10155f34b715616ab3ca039f87679c1 | [
"MIT"
] | null | null | null | lumber/lumber_game.c | suicvne/ps2-lumberjack | aaf09c4ff10155f34b715616ab3ca039f87679c1 | [
"MIT"
] | null | null | null | lumber/lumber_game.c | suicvne/ps2-lumberjack | aaf09c4ff10155f34b715616ab3ca039f87679c1 | [
"MIT"
] | null | null | null | #include "lumber_game.h"
#include "../input.h"
#include "log.h"
#include "branch.h"
/**
Globals
*/
sprite_t* branch_left;
sprite_t* branch_right;
sprite_t* log;
#define LOG_COUNT 2
log_t p1_log[LOG_COUNT];
#define MAX_BRANCHES 6
branch_t p1_branches[MAX_BRANCHES];
float p1_log_y = 0;
/**
End Globals
*/
/**
Private Functions
*/
void lumber_draw_p1(); //draw p1 and his/her tree
void lumber_draw_p2(); //draw p2 and his/her tree
void init_branches();
/**
End Private Functions
*/
lumber_game_t lumber_game_create()
{
lumber_game_t game;
game.p1_score = 0;
game.p2_score = 0;
if(branch_left == NULL)
{
branch_left = sprite_create("branch_left.png");
}
if(branch_right == NULL)
{
branch_right = sprite_create("branch_right.png");
}
if(log == NULL)
{
log = sprite_create("log.png");
}
//init input
//input_player_mode = INPUT_TWO_PLAYER;
input_player_mode = INPUT_SINGLE_PLAYER;
input_initialize();
//end init input
//set log positions
p1_log[0].y = (0 - log->texture.Height);
p1_log[1].y = 0;
//p1_log[2].y = 0 + log->texture.Height;
p1_log[0].x = (120 - log->texture.Width);
p1_log[1].x = (120 - log->texture.Width);
//p1_log[2].x = (120 - log->texture.Width);
//end set log positions
init_branches();
return game;
}
void init_branches()
{
int i;
for(i = 0; i < MAX_BRANCHES; i++)
{
//TODO: set various positions
p1_branches[i].side = RIGHT;
p1_branches[i].player = P1;
}
}
void lumber_draw_p1()
{
int i = 0;
for(i = 0; i < LOG_COUNT; i++)
{
sprite_draw(log, p1_log[i].x, p1_log[i].y);
}
for(i = 0; i < MAX_BRANCHES; i++)
{
sprite_t* sprite = (p1_branches[i].side == LEFT) ? branch_left : branch_right;
branch_draw(&p1_branches[i], sprite);
}
}
void lumber_draw(lumber_game_t* game)
{
gsKit_clear(gsGlobal, GS_SETREG_RGBAQ(0x87,0xCE,0xEB,0x00,0x00)); //sky blue
lumber_draw_p1();
flip_screen();
}
void lumber_update(lumber_game_t* game)
{
input_update(0); //player one
input_update(1); //player two
int i = 0;
for(i = 0; i < LOG_COUNT; i++)
{
log_update(&(p1_log[i]));
}
for(i = 0; i < MAX_BRANCHES; i++)
{
branch_update(&(p1_branches[i]));
}
} | 15.925926 | 80 | 0.66186 |
adc0ff9e3d6876628d2d28bd7834c5859215be6c | 191 | h | C | include/NTL/vec_GF2XVec.h | EUye9IM/Block_cipher | 6527330ceb6d92ca3f9a7069a449bca850de329d | [
"MIT"
] | null | null | null | include/NTL/vec_GF2XVec.h | EUye9IM/Block_cipher | 6527330ceb6d92ca3f9a7069a449bca850de329d | [
"MIT"
] | null | null | null | include/NTL/vec_GF2XVec.h | EUye9IM/Block_cipher | 6527330ceb6d92ca3f9a7069a449bca850de329d | [
"MIT"
] | null | null | null |
#ifndef NTL_vec_GF2XVec__H
#define NTL_vec_GF2XVec__H
#include <NTL/vector.h>
#include <NTL/GF2XVec.h>
NTL_OPEN_NNS
typedef Vec<GF2XVec> vec_GF2XVec;
NTL_CLOSE_NNS
#endif
| 12.733333 | 34 | 0.73822 |
953e18bea61f027833eb0820770bc319b2a0ce2f | 925 | h | C | src/QuestTracker.h | MartGon/ArcherDuel | 4d68d1fe4b9457772d095f39728422269fa0d856 | [
"MIT"
] | null | null | null | src/QuestTracker.h | MartGon/ArcherDuel | 4d68d1fe4b9457772d095f39728422269fa0d856 | [
"MIT"
] | null | null | null | src/QuestTracker.h | MartGon/ArcherDuel | 4d68d1fe4b9457772d095f39728422269fa0d856 | [
"MIT"
] | null | null | null | #include "GameObject.h"
#include "TextLabel.h"
#include <functional>
class QuestTracker : public GameObject
{
public:
enum QuestTrackerType
{
QUEST_TRACKER_UNIQUE_OBJECTIVE,
QUEST_TRACKER_MULTI_OBJECTIVE
};
QuestTrackerType type = QUEST_TRACKER_UNIQUE_OBJECTIVE;
// Constructor
QuestTracker(std::string quest_text, QuestTrackerType type, Uint32 max_amount = 1);
// Attributes
bool isComplete = false;
Uint32 progress_amount = 0;
Uint32 max_amount = 5;
// Members
TextLabel* quest_text = nullptr;
TextLabel* progress_text = nullptr;
// Member methods
void setQuestText(std::string quest_text);
void setTrackingText(bool completed);
void setTrackingText(std::string completed_text);
void setType(QuestTrackerType type, Uint32 max_amount = 1);
void setProgressText(Uint32 amount);
void updateProgress(Uint32 amount);
void reset();
// Callback methods
std::function<void()> onComplete;
}; | 20.108696 | 84 | 0.766486 |
794533b0d18dd8e373411f242ca2b7d6392ccb1f | 527 | h | C | include/owl/pch.h | pierrebestwork/owl-next | 94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e | [
"Zlib"
] | null | null | null | include/owl/pch.h | pierrebestwork/owl-next | 94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e | [
"Zlib"
] | null | null | null | include/owl/pch.h | pierrebestwork/owl-next | 94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e | [
"Zlib"
] | null | null | null | //----------------------------------------------------------------------------
// ObjectWindows
// Copyright (c) 1992, 1996 by Borland International, All Rights Reserved
//
// Include for ObjectWindows, gets owlcore.h or owlall.h when precompiled
// headers are enabled.
//----------------------------------------------------------------------------
#if defined(_OWLVCLPCH)
#include <owl/owlvcl.h>
#endif
#if defined(_OWLALLPCH)
#include <owl/owlall.h>
#elif defined(_OWLPCH)
#include <owl/owlcore.h>
#endif
| 29.277778 | 79 | 0.500949 |
398f2d0cc1837ff53a37856b3be4250b4fff8ba4 | 947 | h | C | caffe2/operators/glu_op.h | tpys/face-recognition-caffe2 | 5fcd5abd22f542356102b3ec248ebc1b35b87a96 | [
"Apache-2.0"
] | 42 | 2017-10-26T21:34:44.000Z | 2021-01-22T14:35:42.000Z | caffe2/operators/glu_op.h | prigoyal/caffe2 | cacdca73861e5828bf933883ac4786a763db1803 | [
"Apache-2.0"
] | 3 | 2018-03-21T08:01:18.000Z | 2019-02-15T22:24:44.000Z | caffe2/operators/glu_op.h | prigoyal/caffe2 | cacdca73861e5828bf933883ac4786a763db1803 | [
"Apache-2.0"
] | 13 | 2017-11-04T04:48:33.000Z | 2021-04-23T17:03:57.000Z | #ifndef CAFFE2_OPERATOR_GLU_OP_H_
#define CAFFE2_OPERATOR_GLU_OP_H_
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
namespace caffe2 {
template <typename T, class Context>
class GluOp final : public Operator<Context> {
public:
GluOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<Context>(operator_def, ws) {}
USE_OPERATOR_CONTEXT_FUNCTIONS;
bool RunOnDevice() {
auto& X = Input(0);
auto* Y = Output(0);
const int M = X.size_to_dim(X.ndim() - 1);
const int N = X.dim32(X.ndim() - 1);
vector<TIndex> Yshape;
Yshape.insert(Yshape.end(), X.dims().begin(), X.dims().end());
Yshape[Yshape.size() - 1] = N / 2;
Y->Resize(Yshape);
ComputeGlu(M, N / 2, X.template data<T>(), Y->template mutable_data<T>());
return true;
}
protected:
void ComputeGlu(const int M, const int N, const T* X, T* output);
};
} // namespace caffe2
#endif // CAFFE2_OPERATOR_GLU_OP_H_
| 27.057143 | 78 | 0.671595 |
f91a8cc73e2d995b1ece597b37991140c5aa9daf | 1,324 | h | C | samples/trackingtest/datagenerator.h | kulikovv/ProcessingSDK | 5e1046c9a361b0e321d3df2094d596709be39325 | [
"Apache-2.0"
] | null | null | null | samples/trackingtest/datagenerator.h | kulikovv/ProcessingSDK | 5e1046c9a361b0e321d3df2094d596709be39325 | [
"Apache-2.0"
] | null | null | null | samples/trackingtest/datagenerator.h | kulikovv/ProcessingSDK | 5e1046c9a361b0e321d3df2094d596709be39325 | [
"Apache-2.0"
] | null | null | null | #ifndef DATAGENERATOR_H
#define DATAGENERATOR_H
#include <QObject>
#include <io/sourcenode.h>
#include <types/data.h>
using namespace io;
using namespace types;
class DataGenerator : public SourceNode
{
Q_OBJECT
Q_PROPERTY(int countArguments READ getCountArguments WRITE setCountArguments)
Q_PROPERTY(int countObjects READ getCountObjects WRITE setCountObjects)
Q_PROPERTY(bool typeData READ getTypeData WRITE setTypeData)
public:
explicit DataGenerator(QObject *parent = 0);
virtual esp get(const base::timestamp frame);
int getCountArguments() {
return countArguments;
}
int getCountObjects() {
return countObjects;
}
bool getTypeData() {
return typeData;
}
//virtual void onConnected();
signals:
public slots:
void setCountArguments(int value) {
if (value > 0) {
countArguments = value;
}
}
void setCountObjects(int value) {
if (value > 0) {
countObjects = value;
}
}
void setTypeData(bool value) {
typeData = value;
}
private:
int countArguments;
int countObjects;
bool typeData;
Data genData(base::timestamp frame, int objectId);
};
#endif // DATAGENERATOR_H
| 21.704918 | 82 | 0.630665 |
66f4865c4891c0338a397339ad17472c9b7dbe5f | 8,055 | h | C | aws-cpp-sdk-codeguruprofiler/include/aws/codeguruprofiler/model/RemovePermissionRequest.h | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-codeguruprofiler/include/aws/codeguruprofiler/model/RemovePermissionRequest.h | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-codeguruprofiler/include/aws/codeguruprofiler/model/RemovePermissionRequest.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/codeguruprofiler/CodeGuruProfiler_EXPORTS.h>
#include <aws/codeguruprofiler/CodeGuruProfilerRequest.h>
#include <aws/codeguruprofiler/model/ActionGroup.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Http
{
class URI;
} //namespace Http
namespace CodeGuruProfiler
{
namespace Model
{
/**
* <p> <pre><code> The structure representing the
* <code>removePermissionRequest</code>.</p>
* </code></pre><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/RemovePermissionRequest">AWS
* API Reference</a></p>
*/
class AWS_CODEGURUPROFILER_API RemovePermissionRequest : public CodeGuruProfilerRequest
{
public:
RemovePermissionRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "RemovePermission"; }
Aws::String SerializePayload() const override;
void AddQueryStringParameters(Aws::Http::URI& uri) const override;
/**
* <p> Specifies an action group that contains the permissions to remove from a
* profiling group's resource-based policy. One action group is supported,
* <code>agentPermissions</code>, which grants <code>ConfigureAgent</code> and
* <code>PostAgentProfile</code> permissions. </p>
*/
inline const ActionGroup& GetActionGroup() const{ return m_actionGroup; }
/**
* <p> Specifies an action group that contains the permissions to remove from a
* profiling group's resource-based policy. One action group is supported,
* <code>agentPermissions</code>, which grants <code>ConfigureAgent</code> and
* <code>PostAgentProfile</code> permissions. </p>
*/
inline bool ActionGroupHasBeenSet() const { return m_actionGroupHasBeenSet; }
/**
* <p> Specifies an action group that contains the permissions to remove from a
* profiling group's resource-based policy. One action group is supported,
* <code>agentPermissions</code>, which grants <code>ConfigureAgent</code> and
* <code>PostAgentProfile</code> permissions. </p>
*/
inline void SetActionGroup(const ActionGroup& value) { m_actionGroupHasBeenSet = true; m_actionGroup = value; }
/**
* <p> Specifies an action group that contains the permissions to remove from a
* profiling group's resource-based policy. One action group is supported,
* <code>agentPermissions</code>, which grants <code>ConfigureAgent</code> and
* <code>PostAgentProfile</code> permissions. </p>
*/
inline void SetActionGroup(ActionGroup&& value) { m_actionGroupHasBeenSet = true; m_actionGroup = std::move(value); }
/**
* <p> Specifies an action group that contains the permissions to remove from a
* profiling group's resource-based policy. One action group is supported,
* <code>agentPermissions</code>, which grants <code>ConfigureAgent</code> and
* <code>PostAgentProfile</code> permissions. </p>
*/
inline RemovePermissionRequest& WithActionGroup(const ActionGroup& value) { SetActionGroup(value); return *this;}
/**
* <p> Specifies an action group that contains the permissions to remove from a
* profiling group's resource-based policy. One action group is supported,
* <code>agentPermissions</code>, which grants <code>ConfigureAgent</code> and
* <code>PostAgentProfile</code> permissions. </p>
*/
inline RemovePermissionRequest& WithActionGroup(ActionGroup&& value) { SetActionGroup(std::move(value)); return *this;}
/**
* <p>The name of the profiling group.</p>
*/
inline const Aws::String& GetProfilingGroupName() const{ return m_profilingGroupName; }
/**
* <p>The name of the profiling group.</p>
*/
inline bool ProfilingGroupNameHasBeenSet() const { return m_profilingGroupNameHasBeenSet; }
/**
* <p>The name of the profiling group.</p>
*/
inline void SetProfilingGroupName(const Aws::String& value) { m_profilingGroupNameHasBeenSet = true; m_profilingGroupName = value; }
/**
* <p>The name of the profiling group.</p>
*/
inline void SetProfilingGroupName(Aws::String&& value) { m_profilingGroupNameHasBeenSet = true; m_profilingGroupName = std::move(value); }
/**
* <p>The name of the profiling group.</p>
*/
inline void SetProfilingGroupName(const char* value) { m_profilingGroupNameHasBeenSet = true; m_profilingGroupName.assign(value); }
/**
* <p>The name of the profiling group.</p>
*/
inline RemovePermissionRequest& WithProfilingGroupName(const Aws::String& value) { SetProfilingGroupName(value); return *this;}
/**
* <p>The name of the profiling group.</p>
*/
inline RemovePermissionRequest& WithProfilingGroupName(Aws::String&& value) { SetProfilingGroupName(std::move(value)); return *this;}
/**
* <p>The name of the profiling group.</p>
*/
inline RemovePermissionRequest& WithProfilingGroupName(const char* value) { SetProfilingGroupName(value); return *this;}
/**
* <p> A universally unique identifier (UUID) for the revision of the
* resource-based policy from which you want to remove permissions. </p>
*/
inline const Aws::String& GetRevisionId() const{ return m_revisionId; }
/**
* <p> A universally unique identifier (UUID) for the revision of the
* resource-based policy from which you want to remove permissions. </p>
*/
inline bool RevisionIdHasBeenSet() const { return m_revisionIdHasBeenSet; }
/**
* <p> A universally unique identifier (UUID) for the revision of the
* resource-based policy from which you want to remove permissions. </p>
*/
inline void SetRevisionId(const Aws::String& value) { m_revisionIdHasBeenSet = true; m_revisionId = value; }
/**
* <p> A universally unique identifier (UUID) for the revision of the
* resource-based policy from which you want to remove permissions. </p>
*/
inline void SetRevisionId(Aws::String&& value) { m_revisionIdHasBeenSet = true; m_revisionId = std::move(value); }
/**
* <p> A universally unique identifier (UUID) for the revision of the
* resource-based policy from which you want to remove permissions. </p>
*/
inline void SetRevisionId(const char* value) { m_revisionIdHasBeenSet = true; m_revisionId.assign(value); }
/**
* <p> A universally unique identifier (UUID) for the revision of the
* resource-based policy from which you want to remove permissions. </p>
*/
inline RemovePermissionRequest& WithRevisionId(const Aws::String& value) { SetRevisionId(value); return *this;}
/**
* <p> A universally unique identifier (UUID) for the revision of the
* resource-based policy from which you want to remove permissions. </p>
*/
inline RemovePermissionRequest& WithRevisionId(Aws::String&& value) { SetRevisionId(std::move(value)); return *this;}
/**
* <p> A universally unique identifier (UUID) for the revision of the
* resource-based policy from which you want to remove permissions. </p>
*/
inline RemovePermissionRequest& WithRevisionId(const char* value) { SetRevisionId(value); return *this;}
private:
ActionGroup m_actionGroup;
bool m_actionGroupHasBeenSet;
Aws::String m_profilingGroupName;
bool m_profilingGroupNameHasBeenSet;
Aws::String m_revisionId;
bool m_revisionIdHasBeenSet;
};
} // namespace Model
} // namespace CodeGuruProfiler
} // namespace Aws
| 40.275 | 142 | 0.700683 |
c983eba80563b7058cadd19711378a9e07ddbec3 | 536 | h | C | PDLocoFramework/PDLocoFramework/PDLocoFramework.h | PankajDwivedi15/PDLokoFramework | baa66aad84983a9a7c9800fb5e94248a31064019 | [
"MIT"
] | null | null | null | PDLocoFramework/PDLocoFramework/PDLocoFramework.h | PankajDwivedi15/PDLokoFramework | baa66aad84983a9a7c9800fb5e94248a31064019 | [
"MIT"
] | null | null | null | PDLocoFramework/PDLocoFramework/PDLocoFramework.h | PankajDwivedi15/PDLokoFramework | baa66aad84983a9a7c9800fb5e94248a31064019 | [
"MIT"
] | null | null | null | //
// PDLocoFramework.h
// PDLocoFramework
//
// Created by Apple on 05/05/21.
// Copyright © 2021 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for PDLocoFramework.
FOUNDATION_EXPORT double PDLocoFrameworkVersionNumber;
//! Project version string for PDLocoFramework.
FOUNDATION_EXPORT const unsigned char PDLocoFrameworkVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <PDLocoFramework/PublicHeader.h>
| 26.8 | 140 | 0.779851 |
bf91920633ee116eea88ba61d9ace4e11d8bf625 | 1,869 | h | C | minerva/common/concurrent_blocking_queue.h | jjzhang166/minerva | 7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f | [
"Apache-2.0"
] | 561 | 2015-04-05T02:50:00.000Z | 2022-03-04T09:05:16.000Z | minerva/common/concurrent_blocking_queue.h | jjzhang166/minerva | 7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f | [
"Apache-2.0"
] | 35 | 2015-04-05T12:46:45.000Z | 2016-06-14T00:58:17.000Z | minerva/common/concurrent_blocking_queue.h | jjzhang166/minerva | 7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f | [
"Apache-2.0"
] | 161 | 2015-04-15T05:47:34.000Z | 2022-01-25T16:01:20.000Z | #pragma once
#include <list>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <thread>
#include <cstdio>
#include "bool_flag.h"
#include "common.h"
template<typename T> class ConcurrentBlockingQueue {
const static int BUSY_LOOP = 1000;
public:
ConcurrentBlockingQueue() : has_elmt_(false), exit_now_(false) {
}
void Push(const T& e) {
std::lock_guard<std::mutex> lock(mutex_);
has_elmt_ = true;
queue_.push_back(e);
if (queue_.size() == 1) {
cv_.notify_all();
}
}
bool Pop(T& rv) {
for (int i = 0; i < BUSY_LOOP; i++) {
if (has_elmt_) {
std::lock_guard<std::mutex> lock(mutex_);
if (!has_elmt_) {
assert(queue_.empty());
continue;
}
rv = queue_.front();
queue_.pop_front();
if (queue_.empty())
has_elmt_ = false;
return false;
}
}
{
std::unique_lock<std::mutex> lock(mutex_);
while (queue_.empty() && !exit_now_.Read()) {
cv_.wait(lock);
}
if (!exit_now_.Read()) {
rv = queue_.front();
queue_.pop_front();
if (queue_.empty())
has_elmt_ = false;
return false;
} else {
return true;
}
}
}
std::list<T> PopAll() {
std::lock_guard<std::mutex> lock(mutex_);
std::list<T> rv;
rv.swap(queue_);
return rv;
}
// Call `SignalForKill` before destruction
void SignalForKill() {
std::unique_lock<std::mutex> lock(mutex_);
exit_now_.Write(true);
cv_.notify_all();
}
size_t QueueSize() {
std::unique_lock<std::mutex> lock(mutex_);
return queue_.size();
}
private:
std::atomic<bool> has_elmt_;
std::list<T> queue_;
std::mutex mutex_;
std::condition_variable cv_;
BoolFlag exit_now_;
DISALLOW_COPY_AND_ASSIGN(ConcurrentBlockingQueue);
};
| 23.074074 | 66 | 0.585875 |
b50b6c259eeccf2455cb46b4f9e0f083b030862b | 14 | c | C | tests/preprocessor/errorGeneration/output/error_noMessage.c | eternalSeeker/pcc | c2b64c2b9e3f9374063854fff953c19efcdad514 | [
"MIT"
] | 1 | 2019-10-09T14:24:01.000Z | 2019-10-09T14:24:01.000Z | tests/preprocessor/errorGeneration/output/error_noMessage.c | eternalSeeker/pcc | c2b64c2b9e3f9374063854fff953c19efcdad514 | [
"MIT"
] | null | null | null | tests/preprocessor/errorGeneration/output/error_noMessage.c | eternalSeeker/pcc | c2b64c2b9e3f9374063854fff953c19efcdad514 | [
"MIT"
] | null | null | null | 2 | error
| 7 | 13 | 0.428571 |
c9c4ed5c8882ff31b7f01f98fbe699061cfbbeb3 | 2,034 | h | C | source/Renderer/Dx11Texture.h | Sherin192/NoctisEngine | ac0eccf1822f9e05203f53028e4c77b71da9bf9b | [
"MIT"
] | null | null | null | source/Renderer/Dx11Texture.h | Sherin192/NoctisEngine | ac0eccf1822f9e05203f53028e4c77b71da9bf9b | [
"MIT"
] | null | null | null | source/Renderer/Dx11Texture.h | Sherin192/NoctisEngine | ac0eccf1822f9e05203f53028e4c77b71da9bf9b | [
"MIT"
] | null | null | null | #ifndef _DX11_TEXTURE_H
#define _DX11_TEXTURE_H
#include "Core_pch.h"
#include "NoctisRenderDevice.h"
#include <wrl.h>
namespace noctis::rdr
{
//------------------------------------------------------------------------------------
// Dx11Texture: Dx11 base class for textures.
//------------------------------------------------------------------------------------
class Dx11Texture
{
protected:
//C.35: A base class destructor should be either public and virtual, or protected and nonvirtual
~Dx11Texture() = default;
public:
Dx11Texture() = default;
Dx11Texture(std::shared_ptr<RenderDevice>& renderDevice, void* data, unsigned int width, unsigned int height, unsigned int nrChannels, TextureUsage type, Format format = Format::kRGBA8UN);
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> GetSRV() const noexcept;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> GetRTV() const noexcept;
Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> GetUAV() const noexcept;
void Bind(std::shared_ptr<RenderDevice>& renderDevice, AccessType type, int8_t slot) const noexcept;
void Unbind(std::shared_ptr<RenderDevice>& renderDevice, AccessType type, int8_t slot) const noexcept;
void BindCompute(std::shared_ptr<RenderDevice>& renderDevice, AccessType type, int8_t slot) const noexcept;
void UnbindCompute(std::shared_ptr<RenderDevice>& renderDevice, AccessType type, int8_t slot) const noexcept;
std::shared_ptr<Sampler>& GetSampler();
private:
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_pTextureRTV;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_pTextureSRV;
Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> m_pTextureUAV;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_pTexture;
//TODO: Make a cache of common samplers which will be bound to the pipeline at each draw
std::shared_ptr<Sampler> m_pSampler;
};
//====================================================================================
}
#endif //_DX11_TEXTURE_H | 48.428571 | 190 | 0.656342 |
68d0d319e3c0bb48a02ae73291124f450ac447f0 | 582 | h | C | storage libs/sjon/include/simple_json_error.h | donovan-westwater/2dGameProject | c7c834a831b8bf0dfcb41ae319cb580d6a9b596a | [
"MIT"
] | 1 | 2017-06-24T01:10:42.000Z | 2017-06-24T01:10:42.000Z | storage libs/sjon/include/simple_json_error.h | donovan-westwater/2dGameProject | c7c834a831b8bf0dfcb41ae319cb580d6a9b596a | [
"MIT"
] | null | null | null | storage libs/sjon/include/simple_json_error.h | donovan-westwater/2dGameProject | c7c834a831b8bf0dfcb41ae319cb580d6a9b596a | [
"MIT"
] | null | null | null | #ifndef __SIMPLE_JSON_ERROR_H__
#define __SIMPLE_JSON_ERROR_H__
#ifndef MIN
#define MIN(a,b) (a<=b?a:b)
#endif
#ifndef MAX
#define MAX(a,b) (a>=b?a:b)
#endif
#ifndef false
#define false 0
#endif
#ifndef true
#define true 1
#endif
/**
* @brief get the last reported error for simple json
* @return a character array with the error message
*/
char *sj_get_error();
/**
* @brief used internally to se the error message
* @param error the error message to set
* @param <vargs> variable arguments for the string
*/
void sj_set_error(char *error,...);
#endif
| 18.1875 | 53 | 0.694158 |
3b8cb3dacbb73369329fa346da98405d84005b53 | 340 | h | C | Mage/Recording.h | bosborn/mage-ios | dcca4f16be47a344d9568229529375a85832ca9f | [
"Apache-2.0"
] | 40 | 2015-09-11T22:31:02.000Z | 2022-03-10T04:59:25.000Z | Mage/Recording.h | bosborn/mage-ios | dcca4f16be47a344d9568229529375a85832ca9f | [
"Apache-2.0"
] | 49 | 2015-09-30T14:16:56.000Z | 2018-08-09T17:05:50.000Z | Mage/Recording.h | bosborn/mage-ios | dcca4f16be47a344d9568229529375a85832ca9f | [
"Apache-2.0"
] | 17 | 2015-10-01T22:09:47.000Z | 2021-12-07T05:55:09.000Z |
#import <Foundation/Foundation.h>
@interface Recording : NSObject
@property (nonatomic, strong) NSString *mediaType;
@property (nonatomic, strong) NSString *fileName;
@property (nonatomic, strong) NSString *filePath;
@property (nonatomic, strong) NSString *mediaTempFolder;
@property (nonatomic, strong) NSNumber *recordingLength;
@end
| 26.153846 | 56 | 0.782353 |
b3df4c01773eccabb250f240cd86a1f5668ca134 | 1,770 | h | C | inc/IAMMediaStream.h | AutoGavy/cnc-ddraw | b813d262ad27f8a07c2da828e049541a865f81f6 | [
"MIT"
] | 672 | 2018-01-02T12:29:31.000Z | 2022-03-31T07:35:31.000Z | inc/IAMMediaStream.h | AutoGavy/cnc-ddraw | b813d262ad27f8a07c2da828e049541a865f81f6 | [
"MIT"
] | 147 | 2018-06-10T03:39:07.000Z | 2022-03-29T12:12:12.000Z | inc/IAMMediaStream.h | AutoGavy/cnc-ddraw | b813d262ad27f8a07c2da828e049541a865f81f6 | [
"MIT"
] | 60 | 2018-08-21T16:43:36.000Z | 2022-03-21T02:01:43.000Z | #ifndef IAMMEDIASTREAM_H
#define IAMMEDIASTREAM_H
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
DEFINE_GUID(IID_IMediaStream, 0xb502d1bd, 0x9a57, 0x11d0, 0x8f, 0xde, 0x00, 0xc0, 0x4f, 0xd9, 0x18, 0x9d);
DEFINE_GUID(IID_IAMMediaStream, 0xbebe595d, 0x9a6f, 0x11d0, 0x8f, 0xde, 0x00, 0xc0, 0x4f, 0xd9, 0x18, 0x9d);
extern struct IAMMediaStreamImplVtbl g_ms_vtbl;
struct IAMMediaStreamImpl;
struct IAMMediaStreamImplVtbl;
typedef struct IAMMediaStreamImpl
{
struct IAMMediaStreamImplVtbl* lpVtbl;
ULONG ref;
} IAMMediaStreamImpl;
typedef struct IAMMediaStreamImplVtbl IAMMediaStreamImplVtbl;
struct IAMMediaStreamImplVtbl
{
HRESULT(__stdcall* QueryInterface) (IAMMediaStreamImpl*, const IID* const riid, LPVOID* ppvObj);
ULONG(__stdcall* AddRef) (IAMMediaStreamImpl*);
ULONG(__stdcall* Release) (IAMMediaStreamImpl*);
/* IMediaStream */
HRESULT(__stdcall* GetMultiMediaStream)(IAMMediaStreamImpl* This, int a);
HRESULT(__stdcall* GetInformation)(IAMMediaStreamImpl* This, int a, int b);
HRESULT(__stdcall* SetSameFormat)(IAMMediaStreamImpl* This, int a, int b);
HRESULT(__stdcall* AllocateSample)(IAMMediaStreamImpl* This, int a, int b);
HRESULT(__stdcall* CreateSharedSample)(IAMMediaStreamImpl* This, int a, int b, int c);
HRESULT(__stdcall* SendEndOfStream)(IAMMediaStreamImpl* This, int a);
/* IAMMediaStream */
HRESULT(__stdcall* Initialize)(IAMMediaStreamImpl* This, int a, int b, int c, int d);
HRESULT(__stdcall* SetState)(IAMMediaStreamImpl* This, int a);
HRESULT(__stdcall* JoinAMMultiMediaStream)(IAMMediaStreamImpl* This, int a);
HRESULT(__stdcall* JoinFilter)(IAMMediaStreamImpl* This, int a);
HRESULT(__stdcall* JoinFilterGraph)(IAMMediaStreamImpl* This, int a);
};
#endif
| 37.659574 | 108 | 0.766102 |
01c7f50327c0a8987dbe95691f47cb44940b02fb | 540 | h | C | srcs/src/simulator/Obstacle.h | snumrl/CrowdSimulation_jaedong | d317e9fca08617f8dddf27d8e5a80f337417482f | [
"Apache-2.0"
] | 2 | 2018-06-06T11:47:30.000Z | 2022-01-14T12:57:18.000Z | srcs/src/simulator/Obstacle.h | snumrl/CrowdSimulation_jaedong | d317e9fca08617f8dddf27d8e5a80f337417482f | [
"Apache-2.0"
] | null | null | null | srcs/src/simulator/Obstacle.h | snumrl/CrowdSimulation_jaedong | d317e9fca08617f8dddf27d8e5a80f337417482f | [
"Apache-2.0"
] | 4 | 2020-03-26T02:23:50.000Z | 2022-01-14T12:57:22.000Z | #ifndef OBSTACLE_H
#define OBSTACLE_H
class Obstacle{
protected:
double _p[2];
double _r[2];
double _front = 0.0;
int _id;
public:
Obstacle();
Obstacle(double* r, double* p);
~Obstacle();
void setP(double x, double y) {_p[0] = x; _p[1] = y;};
void setR(double rx, double ry) {_r[0] = rx; _r[1] = ry;};
void setFront();
void setId (int id) {_id = id;}
double* getP() {return _p;};
double* getR() {return _r;};
double getFront();
int getId () const {return _id;}
void getData(double* _data);
};
#endif
| 18 | 60 | 0.611111 |
2be8e2de3f8eef4c7fb22863b9719d77741209cb | 291 | h | C | OgvKit-master/OgvDemo/OgvDemo/OGVCommonsMediaList.h | theclashingfritz/sonic-3-remastered | 36210fa69d468b4d90cf26a67c6be0410b53c595 | [
"Apache-2.0",
"MIT"
] | 3 | 2018-07-26T02:12:08.000Z | 2022-02-27T20:57:05.000Z | OgvKit-master/OgvDemo/OgvDemo/OGVCommonsMediaList.h | theclashingfritz/sonic-3-remastered | 36210fa69d468b4d90cf26a67c6be0410b53c595 | [
"Apache-2.0",
"MIT"
] | null | null | null | OgvKit-master/OgvDemo/OgvDemo/OGVCommonsMediaList.h | theclashingfritz/sonic-3-remastered | 36210fa69d468b4d90cf26a67c6be0410b53c595 | [
"Apache-2.0",
"MIT"
] | null | null | null | //
// OGVCommonsMediaList.h
// OgvDemo
//
// Created by Brion on 11/11/13.
// Copyright (c) 2013 Brion Vibber. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface OGVCommonsMediaList : NSObject
+ (NSArray *)list;
+ (NSArray *)listWithFilter:(NSString *)filter;
@end
| 17.117647 | 57 | 0.697595 |
cd2493085a947b10892a25f8cbe4547f67fdea7e | 2,059 | h | C | src/config-def.h | hayounglee/LaTTe | b4a74510d8cbe112e1897db2de75c0ff5ab97a9b | [
"BSD-3-Clause"
] | 4 | 2016-11-02T09:56:14.000Z | 2020-10-13T04:30:02.000Z | src/config-def.h | hayounglee/LaTTe | b4a74510d8cbe112e1897db2de75c0ff5ab97a9b | [
"BSD-3-Clause"
] | 1 | 2015-07-23T02:34:11.000Z | 2015-07-23T02:34:11.000Z | src/config-def.h | hayounglee/LaTTe | b4a74510d8cbe112e1897db2de75c0ff5ab97a9b | [
"BSD-3-Clause"
] | 3 | 2015-07-23T02:30:48.000Z | 2019-10-06T07:31:22.000Z | /* config-def.h
Set definitions according to configuration.
Written by: Yoo C. Chung <chungyc@altair.snu.ac.kr>
Copyright (C) 1999 MASS Lab., Seoul, Korea.
See the file LICENSE for usage and redistribution terms and a
disclaimer of all warranties. */
#define OPTIM_LOOKUPSWITCH 1
#define OPTIM_INVOKESTATIC 1
#define JP_OPTIM_INVOKE 1
#define OPTIM_INVOKE 1
/* Work done by scdoner. */
#define NO_REDUNDANT_EDGE 1 /* unique edge for jump tables */
#define NEW_TRANSLATOR_LOCK 1
#define PRECISE_MONITOREXIT 1
#define OUTLINING 1
/* Work done by hacker. */
#define NEW_INTERFACETABLE 1 /* interface table implementation */
#define NEW_CODE_ALLOC 1
#define NEW_VAR_OFFSET 1
#define EXCEPTION_EDGE_CONNECT 1 /* connects exception edge if possible */
#define USE_CODE_ALLOCATOR 1
#define SPLIT_TEXT_DATA 1
#undef RETRAN_CALLER
#undef HANDLER_INLINE
#undef UPDATED_RETRAN
#undef NEW_COUNT_RISC
#undef USE_KAFFE_TRANSLATOR
/* Work done by walker. */
#define LOCK_OPT 1 /* only lock_info is included to each object */
#define NEW_NULL_CHECK 1
#define W_MERGE 1
#define DELAY_PROLOGUE_CODE_GENERATION 1
#define USE_TRAP_FOR_ARRAY_BOUND_CHECK 1
#define VARIABLE_RET_COUNT 1
#define GIVEUP_INHERIT 1
#define INLINE_INVOKEINTERFACE 1
#define UPDATE_INCLUSION_TEST 1
#define UPDATE_CONSTANT_PROPAGATION 1
#define DFS_CODE_PLACEMENT 1
#if defined(INTERPRETER) && !defined(TRANSLATOR)
#undef DYNAMIC_CHA
#else /* not defined(INTERPRETER) && !defined(TRANSLATOR) */
#define DYNAMIC_CHA 1
#endif /* not defined(INTERPRETER) && !defined(TRANSLATOR) */
#undef CUSTOMIZATION_DBG
#undef EXPAND_INLINE_CACHE
/* Work done by chungyc. */
#if defined(INTERPRETER) && !defined(TRANSLATOR)
#undef METHOD_COUNT /* maintain method count */
#else /* not defined(INTERPRETER) && !defined(TRANSLATOR) */
#define METHOD_COUNT 1 /* maintain method count */
#endif /* not defined(INTERPRETER) && !defined(TRANSLATOR) */
/* Other flags. */
#define NEW_LOCK_HANDLING 1
#define EFFICIENT_SUBCLASS_INFERRING 1
#define USE_INLINE 1
#define CHECK_NULL_POINTER 1
| 29.84058 | 74 | 0.775619 |
fab6f834ab878d07023ad23d5a0790d66981e938 | 437 | h | C | application/InstanceProxyModel.h | KosmX/MultiMC5 | dc3a4cebce489b5d61081a315311ffa3d34992ef | [
"Apache-2.0"
] | 73 | 2020-10-23T11:33:36.000Z | 2022-03-23T17:24:47.000Z | application/InstanceProxyModel.h | Tominous/MultiMC5 | bc07351142b76e51ff0288e354402ba6a66a961e | [
"Apache-2.0"
] | 20 | 2020-03-25T20:39:32.000Z | 2021-10-02T13:51:20.000Z | application/InstanceProxyModel.h | Tominous/MultiMC5 | bc07351142b76e51ff0288e354402ba6a66a961e | [
"Apache-2.0"
] | 23 | 2020-10-14T21:08:19.000Z | 2022-03-20T16:24:08.000Z | #pragma once
#include "groupview/GroupedProxyModel.h"
/**
* A proxy model that is responsible for sorting instances into groups
*/
class InstanceProxyModel : public GroupedProxyModel
{
public:
explicit InstanceProxyModel(QObject *parent = 0);
QVariant data(const QModelIndex & index, int role) const override;
protected:
virtual bool subSortLessThan(const QModelIndex &left, const QModelIndex &right) const override;
};
| 25.705882 | 99 | 0.76659 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.