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
bf38efc367d82b3fed49376d18f5c6fcf6a2435a
332
c
C
tests/CompileTests/ElsaTestCases/ctests/k0006.c
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
tests/CompileTests/ElsaTestCases/ctests/k0006.c
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
tests/CompileTests/ElsaTestCases/ctests/k0006.c
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
// static inline function implicitly returning int // originally found in package framerd_2.4.1-1.1 // a.i:4:1: Parse error (state 954) at { // ERR-MATCH: Parse error.*at { static inline foo() { return 0; } inline static bar() { return 0; } const inline static f1() { return 0; } int main() { return foo(); }
11.857143
50
0.629518
d743f17e233f2829db4f5bf2315845a1e318faad
1,793
h
C
sources/plugins/scg/scgcontentimage.h
ostis-ai/kbe
7105798d4edad0993a80f8275cec974badf74d55
[ "MIT" ]
5
2016-12-25T15:43:50.000Z
2021-04-02T13:54:14.000Z
sources/plugins/scg/scgcontentimage.h
ostis-ai/kbe
7105798d4edad0993a80f8275cec974badf74d55
[ "MIT" ]
11
2016-12-13T21:00:35.000Z
2021-03-11T09:11:05.000Z
sources/plugins/scg/scgcontentimage.h
ostis-ai/kbe
7105798d4edad0993a80f8275cec974badf74d55
[ "MIT" ]
12
2016-12-13T20:49:03.000Z
2021-12-14T15:42:37.000Z
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #pragma once #include "scgcontentdialog.h" #include "scgcontentfactory.h" #include "scgcontentviewer.h" class SCgNode; class QToolButton; class QLabel; class SCgContentImageViewer : public SCgContentViewer { Q_OBJECT public: explicit SCgContentImageViewer(QGraphicsItem *parent = 0); virtual ~SCgContentImageViewer(); protected: void setData(const QVariant &data); //! Widget to show image QLabel *mImageLabel; }; // --------------------------------------------------- class SCgContentImageDialog : public SCgContentDialog { Q_OBJECT public: explicit SCgContentImageDialog(SCgNode *node, QWidget *parent = 0); virtual ~SCgContentImageDialog(){} private slots: void chooseSource(); protected: void apply(); //! @see SCgContentDialog::contentInfo() void contentInfo(SCgContent::ContInfo &info); private: void chooseImage(const QString &title, QImage *image, QToolButton *button); void loadImage(const QString &fileName, QImage *image, QToolButton *button); QPoint imagePos(const QImage &image) const; QImage sourceImage; //! Choose image area QToolButton *mChooseButton; }; // --------------------------------------------------- class SCgContentImageFactory : public SCgContentFactory { public: virtual ~SCgContentImageFactory(){} SCgContentViewer* createViewerInstance(); SCgContentDialog* createDialogInstance(SCgNode *node); QMap<QString, MimeAndSCgTypes> supportedExtentions(); };
22.696203
91
0.65923
0ff6cf7c04a5aeaf7bebf4cfb7137c3bce85fc26
3,829
c
C
daq/Sat1/fftw-3.0.1/rdft/codelets/hc2r/hc2r_10.c
abrahamneben/orbcomm_beam_mapping
71b3e7d6e4214db0a6f4e68ebeeb7d7f846f5004
[ "MIT" ]
1
2019-04-10T02:50:19.000Z
2019-04-10T02:50:19.000Z
power_data_to_sat_passes/Sat1/fftw-3.0.1/rdft/codelets/hc2r/hc2r_10.c
abrahamneben/orbcomm_beam_mapping
71b3e7d6e4214db0a6f4e68ebeeb7d7f846f5004
[ "MIT" ]
null
null
null
power_data_to_sat_passes/Sat1/fftw-3.0.1/rdft/codelets/hc2r/hc2r_10.c
abrahamneben/orbcomm_beam_mapping
71b3e7d6e4214db0a6f4e68ebeeb7d7f846f5004
[ "MIT" ]
null
null
null
/* * Copyright (c) 2003 Matteo Frigo * Copyright (c) 2003 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Sat Jul 5 22:11:11 EDT 2003 */ #include "codelet-rdft.h" /* Generated by: /homee/stevenj/cvs/fftw3.0.1/genfft/gen_hc2r -compact -variables 4 -sign 1 -n 10 -name hc2r_10 -include hc2r.h */ /* * This function contains 34 FP additions, 14 FP multiplications, * (or, 26 additions, 6 multiplications, 8 fused multiply/add), * 26 stack variables, and 20 memory accesses */ /* * Generator Id's : * $Id: algsimp.ml,v 1.7 2003/03/15 20:29:42 stevenj Exp $ * $Id: fft.ml,v 1.2 2003/03/15 20:29:42 stevenj Exp $ * $Id: gen_hc2r.ml,v 1.14 2003/04/17 19:25:50 athena Exp $ */ #include "hc2r.h" static void hc2r_10(const R *ri, const R *ii, R *O, stride ris, stride iis, stride os, int v, int ivs, int ovs) { DK(KP500000000, +0.500000000000000000000000000000000000000000000); DK(KP1_902113032, +1.902113032590307144232878666758764286811397268); DK(KP1_175570504, +1.175570504584946258337411909278145537195304875); DK(KP2_000000000, +2.000000000000000000000000000000000000000000000); DK(KP1_118033988, +1.118033988749894848204586834365638117720309180); int i; for (i = v; i > 0; i = i - 1, ri = ri + ivs, ii = ii + ivs, O = O + ovs) { E T3, Tb, Tn, Tv, Tk, Tu, Ta, Ts, Te, Tg, Ti, Tj; { E T1, T2, Tl, Tm; T1 = ri[0]; T2 = ri[WS(ris, 5)]; T3 = T1 - T2; Tb = T1 + T2; Tl = ii[WS(iis, 4)]; Tm = ii[WS(iis, 1)]; Tn = Tl - Tm; Tv = Tl + Tm; } Ti = ii[WS(iis, 2)]; Tj = ii[WS(iis, 3)]; Tk = Ti - Tj; Tu = Ti + Tj; { E T6, Tc, T9, Td; { E T4, T5, T7, T8; T4 = ri[WS(ris, 2)]; T5 = ri[WS(ris, 3)]; T6 = T4 - T5; Tc = T4 + T5; T7 = ri[WS(ris, 4)]; T8 = ri[WS(ris, 1)]; T9 = T7 - T8; Td = T7 + T8; } Ta = T6 + T9; Ts = KP1_118033988 * (T6 - T9); Te = Tc + Td; Tg = KP1_118033988 * (Tc - Td); } O[WS(os, 5)] = FMA(KP2_000000000, Ta, T3); O[0] = FMA(KP2_000000000, Te, Tb); { E To, Tq, Th, Tp, Tf; To = FNMS(KP1_902113032, Tn, KP1_175570504 * Tk); Tq = FMA(KP1_902113032, Tk, KP1_175570504 * Tn); Tf = FNMS(KP500000000, Te, Tb); Th = Tf - Tg; Tp = Tg + Tf; O[WS(os, 2)] = Th - To; O[WS(os, 4)] = Tp + Tq; O[WS(os, 8)] = Th + To; O[WS(os, 6)] = Tp - Tq; } { E Tw, Ty, Tt, Tx, Tr; Tw = FNMS(KP1_902113032, Tv, KP1_175570504 * Tu); Ty = FMA(KP1_902113032, Tu, KP1_175570504 * Tv); Tr = FNMS(KP500000000, Ta, T3); Tt = Tr - Ts; Tx = Ts + Tr; O[WS(os, 7)] = Tt - Tw; O[WS(os, 9)] = Tx + Ty; O[WS(os, 3)] = Tt + Tw; O[WS(os, 1)] = Tx - Ty; } } } static const khc2r_desc desc = { 10, "hc2r_10", {26, 6, 8, 0}, &GENUS, 0, 0, 0, 0, 0 }; void X(codelet_hc2r_10) (planner *p) { X(khc2r_register) (p, hc2r_10, &desc); }
32.176471
130
0.57404
67adeaf3a37440efab156578732c76debd99e333
324
h
C
Data mining/Apriori/source/UserExpensesAnalyzer.h
Maxikq/Algorithms
cd76ca2f02ccd1d4e5b014373f6da5deb054ee93
[ "MIT" ]
2
2015-02-21T13:31:05.000Z
2016-04-05T07:54:04.000Z
Data mining/Apriori/source/UserExpensesAnalyzer.h
wojciech-kulik/Algorithms
cd76ca2f02ccd1d4e5b014373f6da5deb054ee93
[ "MIT" ]
null
null
null
Data mining/Apriori/source/UserExpensesAnalyzer.h
wojciech-kulik/Algorithms
cd76ca2f02ccd1d4e5b014373f6da5deb054ee93
[ "MIT" ]
1
2018-05-19T12:33:37.000Z
2018-05-19T12:33:37.000Z
#ifndef _USER_EXPENSES_ANALYZER_H_ #define _USER_EXPENSES_ANALYZER_H_ #include <stdio.h> #include <vector> #include "Common.h" #include "Database.h" using namespace std; class UserExpensesAnalyzer { protected: Database & db; public: UserExpensesAnalyzer(Database & db); void updateUsersExpenses(); }; #endif
13.5
40
0.756173
9c7a232aa569d35f00086f8cd1322480810c0572
598
h
C
code/Game/SpriteRenderer.h
warzes/SmallIsland2D
bd539c086ef5c6f6d04f0290d7b15313dec264a4
[ "MIT" ]
null
null
null
code/Game/SpriteRenderer.h
warzes/SmallIsland2D
bd539c086ef5c6f6d04f0290d7b15313dec264a4
[ "MIT" ]
null
null
null
code/Game/SpriteRenderer.h
warzes/SmallIsland2D
bd539c086ef5c6f6d04f0290d7b15313dec264a4
[ "MIT" ]
null
null
null
#pragma once #if EXAMPLE_BREAKOUT #include "Texture2D.h" #include "Shader.h" namespace Breakout { class SpriteRenderer { public: SpriteRenderer(const Shader& shader); ~SpriteRenderer(); // Renders a defined quad textured with given sprite void DrawSprite(const Texture2D& texture, glm::vec2 position, glm::vec2 size = glm::vec2(10.0f, 10.0f), float rotate = 0.0f, glm::vec3 color = glm::vec3(1.0f)); private: // Render state Shader m_shader; unsigned int m_quadVAO; // Initializes and configures the quad's buffer and vertex attributes void initRenderData(); }; } #endif
22.148148
162
0.722408
41dad7a412d79783debc01f641ba8c292f39bf26
700
h
C
src/models/FeedItem.h
dak180/vienna
06b9535a795a5ac249eddb3e406c6cc5f1e713ea
[ "Apache-2.0" ]
null
null
null
src/models/FeedItem.h
dak180/vienna
06b9535a795a5ac249eddb3e406c6cc5f1e713ea
[ "Apache-2.0" ]
null
null
null
src/models/FeedItem.h
dak180/vienna
06b9535a795a5ac249eddb3e406c6cc5f1e713ea
[ "Apache-2.0" ]
null
null
null
// // FeedItem.h // Vienna // // Created by Joshua Pore on 7/08/2015. // Copyright (c) 2015 uk.co.opencommunity. All rights reserved. // #import <Foundation/Foundation.h> @interface FeedItem : NSObject { NSString * title; NSString * author; NSString * link; NSString * guid; NSDate * date; NSString * description; NSString * enclosure; } @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *description; @property (nonatomic, copy) NSString *author; @property (nonatomic, copy) NSString *guid; @property (nonatomic, copy) NSDate *date; @property (nonatomic, copy) NSString *link; @property (nonatomic, copy) NSString *enclosure; @end
23.333333
64
0.695714
41fa35a4c30143c943f214c0d754dc35ae1d60af
13,023
c
C
libav-12.3/libavcodec/x86/vp9dsp_init.c
aldarons-tech/aci
0fc09bea7274737a2aa7a3422d65e2630af64b58
[ "MIT" ]
null
null
null
libav-12.3/libavcodec/x86/vp9dsp_init.c
aldarons-tech/aci
0fc09bea7274737a2aa7a3422d65e2630af64b58
[ "MIT" ]
3
2020-07-02T01:33:51.000Z
2020-08-11T14:40:29.000Z
libav-12.3/libavcodec/x86/vp9dsp_init.c
aldarons-tech/aci
0fc09bea7274737a2aa7a3422d65e2630af64b58
[ "MIT" ]
null
null
null
/* * VP9 SIMD optimizations * * Copyright (c) 2013 Ronald S. Bultje <rsbultje@gmail.com> * * This file is part of Libav. * * Libav 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. * * Libav 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/attributes.h" #include "libavutil/cpu.h" #include "libavutil/internal.h" #include "libavutil/mem.h" #include "libavutil/x86/cpu.h" #include "libavcodec/vp9.h" #if HAVE_YASM #define fpel_func(avg, sz, opt) \ void ff_vp9_ ## avg ## sz ## _ ## opt(uint8_t *dst, const uint8_t *src, \ ptrdiff_t dst_stride, \ ptrdiff_t src_stride, \ int h, int mx, int my) fpel_func(put, 4, mmx); fpel_func(put, 8, mmx); fpel_func(put, 16, sse); fpel_func(put, 32, sse); fpel_func(put, 64, sse); fpel_func(avg, 4, mmxext); fpel_func(avg, 8, mmxext); fpel_func(avg, 16, sse2); fpel_func(avg, 32, sse2); fpel_func(avg, 64, sse2); fpel_func(put, 32, avx); fpel_func(put, 64, avx); fpel_func(avg, 32, avx2); fpel_func(avg, 64, avx2); #undef fpel_func #define mc_func(avg, sz, dir, opt, type, f_sz) \ void \ ff_vp9_ ## avg ## _8tap_1d_ ## dir ## _ ## sz ## _ ## opt(uint8_t *dst, \ const uint8_t *src, \ ptrdiff_t dst_stride, \ ptrdiff_t src_stride, \ int h, \ const type (*filter)[f_sz]) #define mc_funcs(sz, opt, type, f_sz) \ mc_func(put, sz, h, opt, type, f_sz); \ mc_func(avg, sz, h, opt, type, f_sz); \ mc_func(put, sz, v, opt, type, f_sz); \ mc_func(avg, sz, v, opt, type, f_sz) mc_funcs(4, mmxext, int16_t, 8); mc_funcs(8, sse2, int16_t, 8); mc_funcs(4, ssse3, int8_t, 32); mc_funcs(8, ssse3, int8_t, 32); #if ARCH_X86_64 mc_funcs(16, ssse3, int8_t, 32); mc_funcs(32, avx2, int8_t, 32); #endif #undef mc_funcs #undef mc_func #define mc_rep_func(avg, sz, hsz, dir, opt, type, f_sz) \ static av_always_inline void \ ff_vp9_ ## avg ## _8tap_1d_ ## dir ## _ ## sz ## _ ## opt(uint8_t *dst, \ const uint8_t *src, \ ptrdiff_t dst_stride, \ ptrdiff_t src_stride, \ int h, \ const type (*filter)[f_sz]) \ { \ ff_vp9_ ## avg ## _8tap_1d_ ## dir ## _ ## hsz ## _ ## opt(dst, src, \ dst_stride, \ src_stride, \ h, \ filter); \ ff_vp9_ ## avg ## _8tap_1d_ ## dir ## _ ## hsz ## _ ## opt(dst + hsz, \ src + hsz, \ dst_stride, \ src_stride, \ h, filter); \ } #define mc_rep_funcs(sz, hsz, opt, type, f_sz) \ mc_rep_func(put, sz, hsz, h, opt, type, f_sz); \ mc_rep_func(avg, sz, hsz, h, opt, type, f_sz); \ mc_rep_func(put, sz, hsz, v, opt, type, f_sz); \ mc_rep_func(avg, sz, hsz, v, opt, type, f_sz) mc_rep_funcs(16, 8, sse2, int16_t, 8); #if ARCH_X86_32 mc_rep_funcs(16, 8, ssse3, int8_t, 32); #endif mc_rep_funcs(32, 16, sse2, int16_t, 8); mc_rep_funcs(32, 16, ssse3, int8_t, 32); mc_rep_funcs(64, 32, sse2, int16_t, 8); mc_rep_funcs(64, 32, ssse3, int8_t, 32); #if ARCH_X86_64 && HAVE_AVX2_EXTERNAL mc_rep_funcs(64, 32, avx2, int8_t, 32); #endif #undef mc_rep_funcs #undef mc_rep_func extern const int8_t ff_filters_ssse3[3][15][4][32]; extern const int16_t ff_filters_sse2[3][15][8][8]; #define filter_8tap_2d_fn(op, sz, f, f_opt, fname, align, opt) \ static void \ op ## _8tap_ ## fname ## _ ## sz ## hv_ ## opt(uint8_t *dst, \ const uint8_t *src, \ ptrdiff_t dst_stride, \ ptrdiff_t src_stride, \ int h, int mx, int my) \ { \ LOCAL_ALIGNED_ ## align(uint8_t, temp, [71 * 64]); \ ff_vp9_put_8tap_1d_h_ ## sz ## _ ## opt(temp, src - 3 * src_stride, \ 64, src_stride, \ h + 7, \ ff_filters_ ## f_opt[f][mx - 1]); \ ff_vp9_ ## op ## _8tap_1d_v_ ## sz ## _ ## opt(dst, temp + 3 * 64, \ dst_stride, 64, \ h, \ ff_filters_ ## f_opt[f][my - 1]); \ } #define filters_8tap_2d_fn(op, sz, align, opt, f_opt) \ filter_8tap_2d_fn(op, sz, FILTER_8TAP_REGULAR, f_opt, regular, align, opt) \ filter_8tap_2d_fn(op, sz, FILTER_8TAP_SHARP, f_opt, sharp, align, opt) \ filter_8tap_2d_fn(op, sz, FILTER_8TAP_SMOOTH, f_opt, smooth, align, opt) #define filters_8tap_2d_fn2(op, align, opt4, opt8, f_opt) \ filters_8tap_2d_fn(op, 64, align, opt8, f_opt) \ filters_8tap_2d_fn(op, 32, align, opt8, f_opt) \ filters_8tap_2d_fn(op, 16, align, opt8, f_opt) \ filters_8tap_2d_fn(op, 8, align, opt8, f_opt) \ filters_8tap_2d_fn(op, 4, align, opt4, f_opt) filters_8tap_2d_fn2(put, 16, mmxext, sse2, sse2) filters_8tap_2d_fn2(avg, 16, mmxext, sse2, sse2) filters_8tap_2d_fn2(put, 16, ssse3, ssse3, ssse3) filters_8tap_2d_fn2(avg, 16, ssse3, ssse3, ssse3) #if ARCH_X86_64 && HAVE_AVX2_EXTERNAL filters_8tap_2d_fn(put, 64, 32, avx2, ssse3) filters_8tap_2d_fn(put, 32, 32, avx2, ssse3) filters_8tap_2d_fn(avg, 64, 32, avx2, ssse3) filters_8tap_2d_fn(avg, 32, 32, avx2, ssse3) #endif #undef filters_8tap_2d_fn2 #undef filters_8tap_2d_fn #undef filter_8tap_2d_fn #define filter_8tap_1d_fn(op, sz, f, f_opt, fname, dir, dvar, opt) \ static void \ op ## _8tap_ ## fname ## _ ## sz ## dir ## _ ## opt(uint8_t *dst, \ const uint8_t *src, \ ptrdiff_t dst_stride, \ ptrdiff_t src_stride, \ int h, int mx, \ int my) \ { \ ff_vp9_ ## op ## _8tap_1d_ ## dir ## _ ## sz ## _ ## opt(dst, src, \ dst_stride, \ src_stride, h,\ ff_filters_ ## f_opt[f][dvar - 1]); \ } #define filters_8tap_1d_fn(op, sz, dir, dvar, opt, f_opt) \ filter_8tap_1d_fn(op, sz, FILTER_8TAP_REGULAR, f_opt, regular, dir, dvar, opt) \ filter_8tap_1d_fn(op, sz, FILTER_8TAP_SHARP, f_opt, sharp, dir, dvar, opt) \ filter_8tap_1d_fn(op, sz, FILTER_8TAP_SMOOTH, f_opt, smooth, dir, dvar, opt) #define filters_8tap_1d_fn2(op, sz, opt, f_opt) \ filters_8tap_1d_fn(op, sz, h, mx, opt, f_opt) \ filters_8tap_1d_fn(op, sz, v, my, opt, f_opt) #define filters_8tap_1d_fn3(op, opt4, opt8, f_opt) \ filters_8tap_1d_fn2(op, 64, opt8, f_opt) \ filters_8tap_1d_fn2(op, 32, opt8, f_opt) \ filters_8tap_1d_fn2(op, 16, opt8, f_opt) \ filters_8tap_1d_fn2(op, 8, opt8, f_opt) \ filters_8tap_1d_fn2(op, 4, opt4, f_opt) filters_8tap_1d_fn3(put, mmxext, sse2, sse2) filters_8tap_1d_fn3(avg, mmxext, sse2, sse2) filters_8tap_1d_fn3(put, ssse3, ssse3, ssse3) filters_8tap_1d_fn3(avg, ssse3, ssse3, ssse3) #if ARCH_X86_64 && HAVE_AVX2_EXTERNAL filters_8tap_1d_fn2(put, 64, avx2, ssse3) filters_8tap_1d_fn2(put, 32, avx2, ssse3) filters_8tap_1d_fn2(avg, 64, avx2, ssse3) filters_8tap_1d_fn2(avg, 32, avx2, ssse3) #endif #undef filters_8tap_1d_fn #undef filters_8tap_1d_fn2 #undef filters_8tap_1d_fn3 #undef filter_8tap_1d_fn #endif /* HAVE_YASM */ av_cold void ff_vp9dsp_init_x86(VP9DSPContext *dsp) { #if HAVE_YASM int cpu_flags = av_get_cpu_flags(); #define init_fpel(idx1, idx2, sz, type, opt) \ dsp->mc[idx1][FILTER_8TAP_SMOOTH ][idx2][0][0] = \ dsp->mc[idx1][FILTER_8TAP_REGULAR][idx2][0][0] = \ dsp->mc[idx1][FILTER_8TAP_SHARP ][idx2][0][0] = \ dsp->mc[idx1][FILTER_BILINEAR ][idx2][0][0] = ff_vp9_ ## type ## sz ## _ ## opt #define init_subpel1(idx1, idx2, idxh, idxv, sz, dir, type, opt) \ dsp->mc[idx1][FILTER_8TAP_SMOOTH][idx2][idxh][idxv] = type ## _8tap_smooth_ ## sz ## dir ## _ ## opt; \ dsp->mc[idx1][FILTER_8TAP_REGULAR][idx2][idxh][idxv] = type ## _8tap_regular_ ## sz ## dir ## _ ## opt; \ dsp->mc[idx1][FILTER_8TAP_SHARP][idx2][idxh][idxv] = type ## _8tap_sharp_ ## sz ## dir ## _ ## opt #define init_subpel2(idx1, idx2, sz, type, opt) \ init_subpel1(idx1, idx2, 1, 1, sz, hv, type, opt); \ init_subpel1(idx1, idx2, 0, 1, sz, v, type, opt); \ init_subpel1(idx1, idx2, 1, 0, sz, h, type, opt) #define init_subpel3_32_64(idx, type, opt) \ init_subpel2(0, idx, 64, type, opt); \ init_subpel2(1, idx, 32, type, opt) #define init_subpel3_8to64(idx, type, opt) \ init_subpel3_32_64(idx, type, opt); \ init_subpel2(2, idx, 16, type, opt); \ init_subpel2(3, idx, 8, type, opt) #define init_subpel3(idx, type, opt) \ init_subpel3_8to64(idx, type, opt); \ init_subpel2(4, idx, 4, type, opt) if (EXTERNAL_MMX(cpu_flags)) { init_fpel(4, 0, 4, put, mmx); init_fpel(3, 0, 8, put, mmx); } if (EXTERNAL_MMXEXT(cpu_flags)) { init_subpel2(4, 0, 4, put, mmxext); init_subpel2(4, 1, 4, avg, mmxext); init_fpel(4, 1, 4, avg, mmxext); init_fpel(3, 1, 8, avg, mmxext); } if (EXTERNAL_SSE(cpu_flags)) { init_fpel(2, 0, 16, put, sse); init_fpel(1, 0, 32, put, sse); init_fpel(0, 0, 64, put, sse); } if (EXTERNAL_SSE2(cpu_flags)) { init_subpel3_8to64(0, put, sse2); init_subpel3_8to64(1, avg, sse2); init_fpel(2, 1, 16, avg, sse2); init_fpel(1, 1, 32, avg, sse2); init_fpel(0, 1, 64, avg, sse2); } if (EXTERNAL_SSSE3(cpu_flags)) { init_subpel3(0, put, ssse3); init_subpel3(1, avg, ssse3); } if (EXTERNAL_AVX(cpu_flags)) { init_fpel(1, 0, 32, put, avx); init_fpel(0, 0, 64, put, avx); } if (EXTERNAL_AVX2(cpu_flags)) { init_fpel(1, 1, 32, avg, avx2); init_fpel(0, 1, 64, avg, avx2); #if ARCH_X86_64 && HAVE_AVX2_EXTERNAL init_subpel3_32_64(0, put, avx2); init_subpel3_32_64(1, avg, avx2); #endif /* ARCH_X86_64 && HAVE_AVX2_EXTERNAL */ } #undef init_fpel #undef init_subpel1 #undef init_subpel2 #undef init_subpel3 #endif /* HAVE_YASM */ }
42.009677
109
0.49712
3b67167ed06a7098190e65153bb2d46a57c16942
36,121
h
C
Translator_file/deal.II/numerics/time_dependent.h
jiaqiwang969/deal.ii-course-practice
0da5ad1537d8152549d8a0e4de5872efe7619c8a
[ "MIT" ]
null
null
null
Translator_file/deal.II/numerics/time_dependent.h
jiaqiwang969/deal.ii-course-practice
0da5ad1537d8152549d8a0e4de5872efe7619c8a
[ "MIT" ]
null
null
null
Translator_file/deal.II/numerics/time_dependent.h
jiaqiwang969/deal.ii-course-practice
0da5ad1537d8152549d8a0e4de5872efe7619c8a
[ "MIT" ]
null
null
null
//include/deal.II-translator/numerics/time_dependent_0.txt // --------------------------------------------------------------------- // // Copyright (C) 1999 - 2020 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE.md at // the top level directory of deal.II. // // --------------------------------------------------------------------- #ifndef dealii_time_dependent_h # define dealii_time_dependent_h /*---------------------------- time-dependent.h ---------------------------*/ # include <deal.II/base/config.h> # include <deal.II/base/exceptions.h> # include <deal.II/base/smartpointer.h> # include <deal.II/base/subscriptor.h> # include <utility> # include <vector> DEAL_II_NAMESPACE_OPEN // forward declarations # ifndef DOXYGEN class TimeStepBase; template <typename number> class Vector; template <int dim, int spacedim> class Triangulation; # endif /** * 这个类为时间相关问题提供了一个抽象接口,它解决了这一类问题中最令人讨厌的一些方面:数据管理。这些问题经常需要大量的计算机资源,最明显的是计算时间、主内存和磁盘空间。减少主内存往往是最迫切的需求,不过实现它的方法几乎总是相当混乱,很快就会导致代码在散落在程序各处的地方存储和重新加载数据,而且有时变得无法维护。本类试图提供一个更加结构化的接口,尽管很简单,这是在我搞了几个月的波浪方程模拟之后在我的脑海中出现的。 * 这个类的设计主要是为解决与时间有关的偏微分方程而定制的,在这些方程中,每两个时间段的计算网格可能不同,而且与这个类的开销相比,每个时间段的计算需要相当长的时间。由于本类中没有提到问题的类别,因此它并不局限于PDEs,尽管如此,大型普通矩阵微分方程的求解器似乎有可能成功地使用相同的设置,因此本类。 * * <h3>Overview</h3> * 使用时间步进方案的时间相关问题求解器的一般结构大约如下:我们有一个时间步进对象的集合,我们随后在其上求解我们的问题。为了做到这一点,我们需要知道之前的零个或几个时间步长的数据(当使用单步或多步方法时,即),也许还需要一些时间步长的数据(例如,这些时间步长的计算网格)。根据有关问题,可以在所有时间步上进行第二次循环,解决一个对偶问题,循环可以向前运行(每个时间步的一个对偶问题)或向后运行(使用一个全局对偶问题)。在这些循环中的一个或使用一个单独的循环,可以计算误差估计值并完善网格。这些循环中的每一个都是由一个为下一个循环准备每个时间步对象的调用开始的,然后才实际开始循环本身。 * 我们将用术语 "扫频 * "来表示所有这些循环的完整集合。由于这个库主要是关于自适应方法的,所以在一个扫频中的最后一个循环可能会产生精炼的网格,我们将对这些精炼的网格进行另一次扫频。因此,一个总的运行往往是几个扫频的序列。因此,全局设置看起来像这样。 * * @verbatim * for sweep=0 to n_sweeps-1 * { * for i=0 to n_timesteps-1 * initialize timestep i for this sweep, e.g. for setting up * data structures, creating temporary files, etc. * * for i=0 to n_timesteps-1 * prepare timestep i for loop 0 * for i=0 to n_timesteps-1 * perform loop 0 on timestep i (e.g. solve primal problem) * * for i=0 to n_timesteps-1 * prepare timestep i for loop 1 * for i=0 to n_timesteps-1 * perform loop 1 on timestep i (e.g. solve dual problem) * * for i=0 to n_timesteps-1 * prepare timestep i for loop 2 * for i=0 to n_timesteps-1 * perform loop 2 on timestep i (e.g. compute error information) * * ... * * for i=0 to n_timesteps-1 * notify timestep i of the end of the sweep, e.g. for cleanups, * deletion of temporary files, etc. * } * @endverbatim * 用户可以指定一个循环应向前或向后运行(例如,后者是解决全局对偶问题所需要的)。 * 从全局的角度来看,我们注意到,当一个循环访问一个时间段时(例如,解决原始或对偶问题,或计算误差信息),我们需要关于这个时间段、之前的一个或多个时间段以及未来的零个或多个时间段的信息。然而,往往不需要知道这些时间步骤的所有信息,而且在不再需要数据的时候,在第一个可能的时间删除数据往往是一种计算要求。同样,数据也应该在可能的最晚时间被重新加载。 * 为了促进这些原则,开发了唤醒和让一个时间步长对象睡眠的概念。假设我们有一个时间步长方案,需要向前看一个时间步长,并且需要最后两个时间步长的数据,下面的伪代码描述了当我们从时间步长 * @p n-1移到时间步长 @p n: * 时,这个类的中心循环函数将做什么 * * @verbatim * wake up timestep n+1 with signal 1 * wake up timestep n with signal 0 * do computation on timestep n * let timestep n sleep with signal 0 * let timestep n-1 sleep with signal 1 * let timestep n-2 sleep with signal 2 * * move from n to n+1 * @endverbatim * 这里的信号号表示被发送信号的时间段到进行计算的时间段的距离。对 * @p wake_up和 @p sleep * 函数的信号0的调用原则上可以被吸收到进行计算的函数中;然而,我们使用这些多余的信号是为了将计算和数据管理相互分离,允许将所有围绕网格管理、数据重载和存储的东西放到一组函数中,而将计算放到另一组中。 * 在上面的例子中,可能的动作是:时间步数<tt>n+1</tt>重建计算网格(有一个专门的类可以为你做这个);时间步数 * @p n * 建立矩阵并将解决方案向量设置为合适的大小,也许使用一个初始猜测;然后它进行计算;然后它删除矩阵,因为它们不被后续时间步数需要;时间步数 * @p n-1 * ]删除那些只被前面一个时间步骤所需要的数据向量;时间步骤 * @p n-2 * 删除剩余的向量并删除计算网格,在某处存储如何最终重建它的信息。 * 从上面给定的草图中可以看出,每个时间步骤对象都看到以下的事件序列。 * * @verbatim * wake up with signal 1 * wake up with signal 0 * do computation * sleep with signal 0 * sleep with signal 1 * sleep with signal 2 * @endverbatim * 这个模式对每个扫频中的每个循环都是重复的。 * 对于每个扫频中的不同循环,可以分别选择向前看(即对 * @p wake_up 函数的最大信号数)和向后看(即对 @p sleep * 函数的最大信号数)的时间步数。例如,在计算误差估计时,通常只需要往后看一个时间步长(在某些情况下,甚至可以完全不往前看或往后看,在这种情况下,将只发送零号信号),而对于时间步长法,则需要至少往后看一个。 * 最后,关于前看和后看的方向的说明:前看总是指循环运行的方向,即对于向前运行的循环, * @p wake_up * 是为时间值大于先前计算的时间段对象而调用的,而 @p * sleep * 是为时间值较低的时间段调用的。如果循环运行的方向相反,例如在解决一个全局对偶问题时,这个顺序是相反的。 * * <h3>Implementation</h3> * 使用这个类的程序的主循环通常会像下面这样,从一个没有作为库的一部分分发的应用程序中修改而来。 * * @code * template <int dim> * void TimeDependent_Wave<dim>::run_sweep (const unsigned int sweep_no) * { * start_sweep (sweep_no); * * solve_primal_problem (); * * if (compute_dual_problem) * solve_dual_problem (); * * postprocess (); * * if (sweep_no != number_of_sweeps-1) * refine_grids (); * * write_statistics (); * * end_sweep (); * } * * * * * * template <int dim> * void WaveProblem<dim>::run () * { * for (unsigned int sweep=0; sweep<number_of_sweeps; ++sweep) * timestep_manager.run_sweep (sweep); * } * @endcode * 这里, @p timestep_manager * 是一个类型为TimeDependent_Wave<dim>的对象,它是一个从TimeDependent派生的类。 * @p start_sweep, @p solve_primal_problem, @p solve_dual_problem, @p * postprocess 和 @p end_sweep * 是继承自这个类的函数。它们都在这个对象中的所有时间段上做循环,并在每个对象上调用各自的函数。例如,这里有两个函数是由库实现的。 * * @code * void TimeDependent::start_sweep (const unsigned int s) * { * sweep_no = s; * * // reset the number each time step has, since some time steps might have * // been added since the last time we visited them. * // also set the sweep we will process in the sequel * for (unsigned int step=0; step<timesteps.size(); ++step) * { * timesteps[step]->set_timestep_no (step); * timesteps[step]->set_sweep_no (sweep_no); * } * * for (unsigned int step=0; step<timesteps.size(); ++step) * timesteps[step]->start_sweep (); * } * * * * * void * TimeDependent::solve_primal_problem () * { * do_loop([](TimeStepBaseconst time_step) * { time_step->init_for_primal_problem(); }, * [](TimeStepBaseconst time_step) * { time_step->solve_primal_problem(); }, * timestepping_data_primal, * forward); * } * @endcode * 后一个函数相当清楚地显示了大多数循环的调用方式( * @p solve_primal_problem, @p solve_dual_problem, @p postprocess, @p * refine_grids和 @p write_statistics * 都有这种形式,其中后两个函数给出了派生时间段类的函数,而不是来自基类)。函数 * TimeStepBase::init_for_primal_problem * 和该类定义的其他操作的相应函数仅用于存储目前执行的循环将进行的操作类型。 * 可以看出,大部分工作是由该类的 @p do_loop * 函数完成的,它接收两个函数的地址,这两个函数用于初始化循环的所有时间步长对象和实际执行一些动作。下一个参数给出了一些关于前视和后视的信息,最后一个参数表示了循环运行的方向。 * 使用lambda函数可以做一些巧妙的技巧,就像下面这种情况下的函数 * @p refine_grids: 。 * * @code * ... * compute the thresholds for refinement * ... * * do_loop([](TimeStepBase_Tria<dim>const time_step) * { time_step->init_for_refinement(); }, * [=](TimeStepBase_Wave<dim>const time_step) * { * time_step->solve_primal_problem( * TimeStepBase_Tria<dim>::RefinementData ( * top_threshold, bottom_threshold))); * }, * TimeDependent::TimeSteppingData (0,1), * TimeDependent::forward); * @endcode * TimeStepBase_Wave<dim>::refine_grid * 是一个带参数的函数,与上面在循环中使用的所有其他函数不同。然而,在这种特殊情况下,参数对所有时间段都是一样的,而且在循环开始之前就已经知道了,所以我们把它固定下来,做成一个对外界来说不需要参数的函数对象。 * 因为它是这个类的中心函数,所以我们最后展示了一个精简版的 * @p do_loop * 方法,展示它的目的是为了让大家更好地了解这个类的内部结构。为了简洁起见,我们省略了处理向后运行循环的部分,以及检查唤醒和睡眠操作是否在<tt>0...n_timesteps-1</tt>以外的时间步长上进行。 * * @code * template <typename InitFunctionObject, typename LoopFunctionObject> * void TimeDependent::do_loop (InitFunctionObject init_function, * LoopFunctionObject loop_function, * const TimeSteppingData &timestepping_data, * const Direction direction) * { * // initialize the time steps for a round of this loop * for (unsigned int step=0; step<n_timesteps; ++step) * init_function (static_cast<typename InitFunctionObject::argument_type> * (timesteps[step])); * * // wake up the first few time levels * for (int step=-timestepping_data.look_ahead; step<0; ++step) * for (int look_ahead=0; * look_ahead<=timestepping_data.look_ahead; * ++look_ahead) * timesteps[step+look_ahead]->wake_up(look_ahead); * * * * * for (unsigned int step=0; step<n_timesteps; ++step) * { * // first thing: wake up the timesteps ahead as necessary * for (unsigned int look_ahead=0; * look_ahead<=timestepping_data.look_ahead; * ++look_ahead) * timesteps[step+look_ahead]->wake_up(look_ahead); * * * * * // actually do the work * loop_function( * static_cast<typename LoopFunctionObject::argument_type> ( * timesteps[step])); * * // let the timesteps behind sleep * for (unsigned int look_back=0; * look_back<=timestepping_data.look_back; * ++look_back) * timesteps[step-look_back]->sleep(look_back); * } * * // make the last few timesteps sleep * for (int step=n_timesteps; * step<=n_timesteps+timestepping_data.look_back; * ++step) * for (int look_back=0; * look_back<=timestepping_data.look_back; * ++look_back) * timesteps[step-look_back]->sleep(look_back); * } * @endcode * * */ class TimeDependent { public: /** * 持有两个基本实体的结构,它们控制着所有时间步数的循环:我们应在当前步数的前面多少个时间步数开始唤醒时间步数对象,以及在后面多少个时间步数调用它们的 * @p sleep 方法。 * */ struct TimeSteppingData { /** * 构造函数;参见不同的字段,以了解参数的含义。 * */ TimeSteppingData(const unsigned int look_ahead, const unsigned int look_back); /** * 这表示分时算法需要向前看的时间步数。通常情况下,这个数字将是0,因为提前看的算法不能作为时隙方案,因为它们不能只从过去的知识中计算它们的数据,因此在时间上是全局的。 * 然而,在其他情况下,当不想访问下一个时间步骤的数据时,可能有必要向前看,但例如要知道下一个网格,下一个时间层次上的二元问题的解决方案,等等。 * 请注意,对于一个向后走的二元问题,"向前看 * "意味着向更小的时间值看。 * 这个数字的值决定了,时间步长管理器开始在每个时间步长中调用 * @p wake_up 函数。 * */ const unsigned int look_ahead; /** * 这是一个与上述变量相反的变量。它表示在目前的时间步数之后的时间步数,我们需要保留所有的数据,以便在目前的时间水平上进行计算。 * 对于单步方案(例如欧拉方案或克拉克-尼科尔森方案),这个值是1。 * 这个数字的值决定了在一个时间层上做完计算后,时间步长管理器将在每个时间步长上调用 * @p 睡眠函数。 * */ const unsigned int look_back; }; /** * 枚举提供了由 @p * do_loop执行的循环可能运行的不同方向。 * */ enum Direction { /** * 往前走。 * */ forward, /** * 在后退方向上走。 * */ backward }; /** * 构造函数。 * */ TimeDependent(const TimeSteppingData &data_primal, const TimeSteppingData &data_dual, const TimeSteppingData &data_postprocess); /** * 销毁器。这将删除给<tt>insert_*</tt>和 @p add_timestep * 函数的指针所指向的对象,也就是说,它将删除在每个时间步长进行计算的对象。 * */ virtual ~TimeDependent(); /** * 在任何位置添加一个时间步长。该位置是一个指向现有时间步长对象的指针,或者一个表示时间步长序列结束的空指针。如果 * @p position * 为非空,新的时间步长将被插入到相应的元素之前。 * 请注意,通过将一个对象交给这个函数,TimeDependent对象承担了该对象的所有权;因此它也将负责删除其管理的对象。 * 还有一个函数, @p add_timestep, * ,在列表的末尾插入一个时间步骤。 * 注意,这个函数不会改变存储在其他时间步长对象中的时间步长,也不会设置这个新时间步长的时间步长。这只有在调用 * @p start_sweep * 函数时才会完成。在不改变时间步数的情况下,对时空三角的操作更简单,因为可以一直使用上一次扫频中使用的时间步数。 * */ void insert_timestep(const TimeStepBase *position, TimeStepBase *new_timestep); /** * 就像 @p insert_timestep, 一样,但在最后插入。 * 这种机制通常会导致像这样的设置循环 * @code * for (int i=0; i<N; ++i) * manager.add_timestep(new MyTimeStep()); * @endcode * * */ void add_timestep(TimeStepBase *new_timestep); /** * 删除一个时间段。只有当你想在两次扫描之间删除它时,才有必要调用这个功能;在这个对象的生命周期结束时,会自动注意删除时间步长对象。解构器对对象的删除也是通过这个函数完成的。 * 注意,这个函数不会改变存储在其他时间步数对象中的时间步数。这只有在调用 * @p * start_sweep函数时才会完成。在不改变时间步数的情况下,对时空三角的操作更加简单,因为可以一直使用上一次扫频中使用的时间步数。 * */ void delete_timestep(const unsigned int position); /** * 解决原始问题;通过TimeStepBase类的 @p init_for_primal_problem * 和 @p solve_primal_problem do_loop函数使用该类的函数。 * 向前看和向后看是由给构造函数的 @p * timestepping_data_primal对象决定的。 * */ void solve_primal_problem(); /** * 解决对偶问题;通过TimeStepBase类的 @p do_loop * 函数使用该类的 @p init_for_dual_problem 和 @p solve_dual_problem * 函数。 向前看和向后看是由给构造函数的 @p * timestepping_data_dual 对象决定的。 * */ void solve_dual_problem(); /** * 做一轮后处理;通过本类的 @p do_loop * 函数使用TimeStepBase类的 @p init_for_postprocessing 和 @p * postprocess 函数。 向前看和向后看是由给构造函数的 @p * timestepping_data_postprocess对象决定的。 * */ void postprocess(); /** * 在所有时间步长上做一个循环,在开始时调用 @p * init_function ,在每个时间步长的 @p loop_function 上调用。 * @p timestepping_data * 决定在当前时间段前后有多少个时间段调用 @p wake_up和 * @p sleep 函数。 * 为了了解这个函数的工作原理,请注意,函数 @p * solve_primal_problem只包括以下调用。 * @code * do_loop([](TimeStepBaseconst time_step) * { time_step->init_for_primal_problem(); }, * [](TimeStepBaseconst time_step) * { time_step->solve_primal_problem(); }, * timestepping_data_primal, * forward); * @endcode * 还请注意,这两个函数所来自的给定类不一定是TimeStepBase,但也可以是一个派生类,即 * @p static_castable * 来自一个TimeStepBase。该函数可以是该类的一个虚函数(甚至是一个纯函数),如果实现该函数的实际类是一个通过虚基类派生的类,从而无法通过 * @p static_cast 从TimeStepBase类到达,这应该会有帮助。 * 不使用上述形式,你同样可以使用<tt>[args...](Xconst * x){x->unary_function(args...);}</tt>,让 @p do_loop * 函数用指定参数调用给定的函数。 * */ template <typename InitFunctionObject, typename LoopFunctionObject> void do_loop(InitFunctionObject init_function, LoopFunctionObject loop_function, const TimeSteppingData &timestepping_data, const Direction direction); /** * 为下一次扫描初始化对象。这个函数具体做了以下工作:给每个时间层分配它目前在数组中的编号(如果时间层被插入或删除,这个编号可能会改变),并将本次扫描的编号传送给这些对象。 * 在上述数字设定后,它还调用每个时间层对象的 @p * start_sweep 函数。 * 这个函数是虚拟的,所以你可以重载它。然而,你不应该忘记在你的重载版本中也调用这个函数,最好是在你的函数的开头,因为这是某种 * "类似构造器 "的函数,应该自下而上地调用。 * 这个函数的默认实现在所有时间步长对象上调用 @p * start_sweep 。 * */ virtual void start_sweep(const unsigned int sweep_no); /** * 与上述函数类似,调用每个时间步长对象的 @p end_sweep * 。这个函数的 @p virtualness 与前一个函数的 @p virtualness * 同样适用。 * @note 这个函数并不保证 @p end_sweep * 对连续的时间步长连续调用,相反,调用该函数的时间步长对象的顺序是任意的。因此,你不应该认为该函数已经为以前的时间步数调用过了。如果在多线程模式下,几个时间步骤的 * @p end_sweep * 函数可能会被同时调用,所以如果你的程序需要,你应该使用同步机制。 * */ virtual void end_sweep(); /** * 确定这个对象的内存消耗(以字节为单位)的估计值。 * */ std::size_t memory_consumption() const; /** * 异常情况。 * */ DeclExceptionMsg(ExcInvalidPosition, "You cannot insert a time step at the specified position."); protected: /** * 持有指向时间级别对象的指针的向量。这是此对象操作的主要数据。请注意,这个对象占有这个集合中的指针所指向的对象。 * */ std::vector<SmartPointer<TimeStepBase, TimeDependent>> timesteps; /** * 当前扫频的编号。这将由每次扫描开始时调用的 @p * start_sweep 函数重置。 * */ unsigned int sweep_no; /** * 一些告诉 @p solve_primal_problem * 函数要做什么的标志。更多信息请参见该结构的文档。 * */ const TimeSteppingData timestepping_data_primal; /** * 一些告诉 @p solve_dual_problem * 函数要做什么的标志。更多信息请参见此结构的文档。 * */ const TimeSteppingData timestepping_data_dual; /** * 一些告诉 @p postprocess * 函数要做什么的标志。更多信息请参见此结构的文档。 * */ const TimeSteppingData timestepping_data_postprocess; private: /** * 只对某些时间段做<tt>end_sweep()/tt>的工作。这在多线程模式下是很有用的。 * */ void end_sweep(const unsigned int begin_timestep, const unsigned int end_timestep); }; /** * 在时间相关问题中,一个时间步长的基类。这个类只提供了基本的框架,定义了必要的虚拟函数(即 * @p sleep 和 @p wake_up), * 前一个和后一个网格的接口,以及一些在所有时间步长的新循环开始前要调用的函数。 * * */ class TimeStepBase : public Subscriptor { public: /** * 表示接下来要解决的问题类型的枚举。 * */ enum SolutionState { /** * 接下来解决原始问题。 * */ primal_problem = 0x0, /** * 接下来解决对偶问题。 * */ dual_problem = 0x1, /** * 接下来进行后处理。 * */ postprocess = 0x2 }; /** * 构造函数。除了设置时间外,这里不做任何事情。 * */ TimeStepBase(const double time); /** * 解构器。目前,它什么都不做。 * */ virtual ~TimeStepBase() override = default; /** * 删除了拷贝构造函数,以避免浅层拷贝的意外行为。 * */ TimeStepBase(const TimeStepBase &) = delete; /** * 删除了复制赋值操作符,以避免浅层拷贝的意外行为。 * */ TimeStepBase & operator=(const TimeStepBase &) = delete; /** * 重建这个时间级别工作所需的所有数据。这个函数的作用是在所有的变量和数据结构被送入睡眠状态后,或者在我们第一次访问这个时间层时,让它们重新开始工作。特别是,它被用来重建三角形、自由度处理程序,在数据向量被存储到磁盘的情况下重新加载它们,等等。 * 这个函数的实际实现没有任何作用。 * 由于这是一个重要的任务,如果你选择在自己的类中重载这个函数(很可能是这样),你应该从自己的函数中调用这个函数,最好是在开始的时候,这样你的函数就可以对已经存在的三角测量产生影响。 * */ virtual void wake_up(const unsigned int); /** * 这是一个与 @p wake_up. * 相反的函数,它用于删除数据或在当前扫描不再需要它们时将其保存到磁盘。 * 典型的数据种类是数据向量、自由度处理程序、三角测量对象等,它们占据了大量的内存,因此可能被外部化。 * 默认情况下,这个函数不做任何事情。 * */ virtual void sleep(const unsigned int); /** * 每次在开始新的扫频之前都会调用这个函数。你可能想在计算过程中设置一些需要的字段,等等。然而,你应该很小心,不要安装大的对象,这应该推迟到 * @p wake_up 函数被调用。 * 这个函数的一个典型动作是整理解题过程中需要的临时文件的名称,等等。 * 在这个函数被调用时, @p timestep_no, @p * sweep_no的值以及指向上一个和下一个时间步长对象的指针已经具有正确的值。 * 这个函数的默认实现不做任何事情。 * */ virtual void start_sweep(); /** * 这个函数类似于上面的函数,但它是在扫频结束时调用的。你通常想在这个函数中进行清理,比如删除临时文件之类的。 * */ virtual void end_sweep(); /** * 在每个时间层的原始问题被解决之前,这个函数被调用(也就是在第一个时间层的解决发生之前)。默认情况下,该函数设置该类的 * @p next_action 变量。 * 你可以重载这个函数,但你应该在你自己的函数中调用这个函数。 * */ virtual void init_for_primal_problem(); /** * 和上面一样,但在一轮对偶问题解决之前调用。 * */ virtual void init_for_dual_problem(); /** * 同上,但在一轮后处理步骤之前调用。 * */ virtual void init_for_postprocessing(); /** * 当需要解决这个时间层次上的原始问题时,这个函数被管理器对象调用。它在 * @p wake_up 函数被调用之后,在 @p sleep * 函数将被调用之前被调用。 * 由于明显的原因,没有默认的实现,所以你必须重载这个函数。 * */ virtual void solve_primal_problem() = 0; /** * 当需要解决这个时间层次上的二元问题时,这个函数会被管理器对象调用。它在 * @p wake_up 函数被调用后,在 @p sleep * 函数将被调用前被调用。 * 有一个默认的实现是什么都不做,因为有些问题可能不需要解决对偶问题。然而,当被调用时,它将中止程序,因为那时你真的应该重载该函数。 * */ virtual void solve_dual_problem(); /** * 当需要对这个时间级别进行后处理时,这个函数被管理器对象调用。它在 * @p wake_up 函数被调用后,在 @p sleep * 函数将被调用前被调用。有一个默认的实现是什么都不做,因为有些问题可能不需要做后处理步骤,例如,如果在解决原始问题时已经完成了一切。然而,当被调用时,它将中止程序,因为那时你真的应该重载这个函数。 * */ virtual void postprocess_timestep(); /** * 返回这个时间步骤的时间值。 * */ double get_time() const; /** * 返回这个时间步长的数字。注意,如果增加或删除时间步长,这个数字在不同的扫频之间可能会有所不同。 * */ unsigned int get_timestep_no() const; /** * 计算与上一个时间步长的时间差。如果这个时间步长是第一个时间步长,这个函数将导致一个异常。虽然这种行为看起来有点激烈,但在大多数情况下是合适的,因为如果没有上一个时间步长,无论如何你都需要特殊处理,这样就不会返回无效的值,这可能导致错误的但未被注意的计算结果。(在这种情况下,唯一合理的返回值不会是零,因为有效的计算可以用它来完成,而是一个变性的值,如 * @p NaN. * 。然而,发现计算结果都是变性的值或得到一个异常并没有太大的区别;在后一种情况下,你至少可以得到你问题所在的确切位置。) * */ double get_backward_timestep() const; /** * 返回到下一个时间步骤的时间差。关于没有下一个时间步骤的情况,和上面的函数同样适用。 * */ double get_forward_timestep() const; /** * 确定这个对象的内存消耗(以字节为单位)的估计值。 * 你要在派生类中重载这个函数来计算派生类所使用的内存量,并把这个函数的结果加到你的结果中。 * */ virtual std::size_t memory_consumption() const; protected: /** * 指向列表中前一个时间步骤对象的指针。 * */ const TimeStepBase *previous_timestep; /** * 指向列表中下一个时间步长对象的指针。 * */ const TimeStepBase *next_timestep; /** * 我们目前所处的扫频的编号。这个数字在扫频开始前由时间级别管理器重置。 * */ unsigned int sweep_no; /** * 时间步骤的编号,从零开始计算。这个数字在每次扫频开始时由时间级别管理器重置,因为一些时间步长可能在上一次扫频后被插入或删除。 * */ unsigned int timestep_no; /** * 本级操作的离散时间。 * */ const double time; /** * 存储原始问题或对偶问题的解决是否实际的变量,或任何其他指定的行动。这个变量是由<tt>init_for_*</tt>函数设置的。 * */ unsigned int next_action; private: /** * 重置指向上一个时间步长的指针;只应由时间层管理器对象调用。 * 该函数在管理器对象的设置以及每当插入或删除一个时间步长时被调用。 * */ void set_previous_timestep(const TimeStepBase *previous); /** * 重置指向下一个时间步长的指针;只应由时间级管理器对象调用。 * 该函数在管理器对象的设置以及每当插入或删除一个时间步长时被调用。 * */ void set_next_timestep(const TimeStepBase *next); /** * 设置该时间步长在时间步长列表中的编号。这个函数在每次扫描开始时由时间步长管理对象调用,以更新由于增加或删除时间层而可能改变的信息。 * */ void set_timestep_no(const unsigned int step_no); /** * 设置我们目前所处的扫频的编号。这个函数是由时间层管理对象在每次扫频的启动时调用的。 * */ void set_sweep_no(const unsigned int sweep_no); // make the manager object a friend friend class TimeDependent; }; /** * 名称空间,其中声明了一些类,这些类封装了TimeStepBase_Tria()类的标志。这些曾经是该类的本地数据类型,但是一些编译器在某些方面扼杀了它们,所以我们把它们放到了一个自己的命名空间。 * * */ namespace TimeStepBase_Tria_Flags { /** * 这个结构是用来告诉TimeStepBase_Tria()类应该如何处理网格。它有一些标志,定义了网格应被重新制作以及何时可以删除的时刻。此外,还有一个变量规定了网格是否应该保留在内存中,或者应该在两次使用之间删除以节省内存。 * */ template <int dim> struct Flags { /** * 默认的构造函数;产生一个异常,所以不能真正使用。 * */ Flags(); /** * 构造函数;请看不同字段对参数含义的描述。 * */ Flags(const bool delete_and_rebuild_tria, const unsigned int wakeup_level_to_build_grid, const unsigned int sleep_level_to_delete_grid); /** * 这个标志决定了 @p sleep 和 @p wake_up * 函数是否要删除和重建三角结构。 * 虽然对于小问题来说,这不是必要的,但对于大问题来说,这对于节省内存是必不可少的。 * 原因是内存中可能有几百个时间层,每个时间层都有自己的三角图,如果每个时间层有很多单元,可能需要大量的内存。在所有时间层上总共有100.000.000个单元的情况并不罕见,这使得这个标志可以理解。 * */ const bool delete_and_rebuild_tria; /** * 这个数字表示 @p wake_up * 函数的参数,它应该在这个参数上重建网格。显然,它应小于或等于传递给时间步长管理对象的 * @p look_ahead * 数字;如果它相等,那么网格将在第一次调用 @p wake_up * 函数时重建。如果 @p delete_and_rebuild_tria 是 @p false, * 这个数字没有意义。 * */ const unsigned int wakeup_level_to_build_grid; /** * 这是一个与上面相反的标志:它决定了在调用 @p sleep * 时,网格应被删除。 * */ const unsigned int sleep_level_to_delete_grid; }; /** * 这个结构是用来告诉TimeStepBase_Tria()类应该如何完善网格的。在我们解释所有不同的变量之前,先握紧一些术语。 <ul> <li> 修正:在对三角形的一些单元进行了遵循某种给定标准的标记后,我们可能想根据另一种标准改变这个网格上的标记单元的数量,这个单元的数量可能只比之前的网格上的单元数量多或少一定的分数。这种细化标志的改变在后面将被称为 "修正"。 <li> 适应:为了使一个网格和下一个网格之间的变化不大,我们可能想在两个网格中的一个上标记一些额外的单元格,这样就不会有太严重的差异。这个过程将被称为 "适应"。 </ul> <h3>Description of flags</h3> <ul> <li> @p max_refinement_level: 切断某一级别的单元的细化。这个标志并不影响单元的标记,所以在较粗的层次上并没有比平时更多的单元被标记。相反,标志都被设置,但是当涉及到实际细化时,最大细化水平被截断。 这个选项只有在你想比较全局细化和自适应细化时才真正有用,因为你不希望后者的细化程度超过全局细化。 <li> @p first_sweep_with_correction: 当使用上面定义的单元数校正时,可能值得只在以后的扫描中开始使用,而不是已经在第一次扫描中开始。如果这个变量是零,那么就从第一次扫描开始,否则就从更高的扫描开始。只从后面开始的理由是,我们不想在一开始就阻止网格的发展,而只在我们开始对计算的实际结果感兴趣的扫描中施加限制。 <li> @p min_cells_for_correction: 如果我们想要一个更自由的网格发展过程,我们可能希望对单元数少的网格也施加较少的规则。这个变量为要进行修正的网格的单元数设定了一个下限。 <li> @p cell_number_corridor_top: 一个网格的单元数可能高于前一个网格的单元数的分数。常见值为10%(即0.1)。该变量的命名源于为细化后的单元格数量定义一个目标走廊的目标。 <li> @p cell_number_corridor_bottom: 一个网格的单元数可能低于前一个网格的单元数的分数。常见值为5%(即0.05)。通常这个数字会小于 @p cell_number_corridor_top ,因为单元格数量的增加是无害的(尽管它增加了解决问题所需的数字工作量),而急剧减少可能会降低最终结果的精度,即使在减少之前计算的时间步数是以高精确度计算的。 但是请注意,如果你也计算对偶问题,那么时间方向是相反的,所以定义单元数走廊的两个值应该是差不多的。 <li> @p correction_relaxations: 这是一个数字对的列表,其含义如下:正如 @p min_cells_for_correction, 一样,如果网格的单元数很少,可能值得减少对网格的要求。 本变量存储了一个单元格编号的列表以及一些数值,这些数值告诉我们,单元格编号的走廊应该被放大一定的系数。例如,如果这个列表是<tt>((100 5) (200 3) (500 2))</tt>,这将意味着对于单元数低于100的网格,<tt>cell_number_corridor_*</tt>变量在应用前要乘以5,对于单元数低于200的网格,要乘以3,以此类推。 @p correction_relaxations 实际上是这种列表的一个向量。这个向量中的每个条目都表示一个扫描的放松规则。最后一个条目定义了所有后续扫描的松弛规则。采用这种方案是为了允许在以后的扫描中进行更严格的修正,而在第一次扫描中的放松可能更宽松。 有一个静态变量 @p default_correction_relaxations ,你可以把它作为一个默认值。它是一个空列表,因此没有定义放宽。 <li> @p cell_number_correction_steps: 通常情况下,如果你想修正单元格的数量,会计算单元格数量的目标走廊,并对一些额外的单元格进行标记或去除标记。但由于标记和除旗后产生的单元格数不容易计算,通常不会在走廊内。因此,我们需要迭代来达到我们的目标。通常需要三到四次迭代,但使用这个变量,你可以减少允许的迭代次数;在两次迭代后打破循环,经常会产生好的结果。将该变量设置为零将导致完全没有修正步骤。 <li> @p mirror_flags_to_previous_grid: 如果当前网格上的一个单元被标记为细化,也要标记前一个网格上的相应单元。例如,如果计算时空单元的误差指标,但只存储在第二个网格中,这就很有用。现在,由于第一个网格对指标的贡献与第二个网格相同,如果有必要,对这两个网格进行标记可能是有用的。如果设置了本变量就可以做到这一点。 <li> @p adapt_grids: 在上面定义的意义上,使现在的网格与以前的网格相适应。这里实际做的是:如果从以前的网格到现在的网格会导致某些单元的双倍细化或双倍粗化,那么我们就尝试标记这些单元进行细化或粗化,从而避免双倍步骤。 显然,超过两次的细化和粗化也会被发现。 网格自适应可以尝试避免两个网格之间的这种变化,但它永远不能保证不发生这种变化。这是因为下一个网格可能会改变现在的网格,但同样地,现在的网格和上一个网格之间的细化水平可能会有跳跃;这只能通过反复循环所有的网格来避免,来回循环,直到没有任何变化为止,如果有很多时间步长的非常大的网格,这显然是不可能的。 </ul> * */ template <int dim> struct RefinementFlags { /** * 描述校正过程的一些放松的数据类型的类型定义。更多信息见该类的一般描述。 * */ using CorrectionRelaxations = std::vector<std::vector<std::pair<unsigned int, double>>>; /** * 松弛的默认值:没有松弛。 * */ static CorrectionRelaxations default_correction_relaxations; /** * 构造函数。默认值的选择是对网格细化几乎没有限制的。 * */ RefinementFlags(const unsigned int max_refinement_level = 0, const unsigned int first_sweep_with_correction = 0, const unsigned int min_cells_for_correction = 0, const double cell_number_corridor_top = (1 << dim), const double cell_number_corridor_bottom = 1, const CorrectionRelaxations &correction_relaxations = CorrectionRelaxations(), const unsigned int cell_number_correction_steps = 0, const bool mirror_flags_to_previous_grid = false, const bool adapt_grids = false); /** * 一个时间层次的三角形中的单元的最大层次。如果它被设置为零,那么对一个粗网格单元可能进行的细化次数没有限制。通常情况下,如果出于某种原因,你想在自适应过程中限制细化,例如避免单元数量过大,或者与有一定细化次数的网格进行比较,就会使用这个字段。 * */ const unsigned int max_refinement_level; /** * 第一次扫面执行单元格数量校正步骤;对于之前的扫面,单元格只被标记,不执行对之前网格的数量校正。 * */ const unsigned int first_sweep_with_correction; /** * 仅当有超过此数量的细胞时,才应用前一时间水平的细胞数校正。 * */ const unsigned int min_cells_for_correction; /** * 一个时间层上的细胞数可能与前一个时间层上的细胞数不同的分数(第一:上偏差,第二:下偏差)。 * */ const double cell_number_corridor_top; /** * @ref cell_number_corridor_top * */ const double cell_number_corridor_bottom; /** * 对校正步骤的放松列表。 * */ const std::vector<std::vector<std::pair<unsigned int, double>>> correction_relaxations; /** * 为了将某一时间层的单元格数量调整到上一时间层的单元格数量,要进行的迭代次数。零意味着:不做这样的迭代。 * */ const unsigned int cell_number_correction_steps; /** * 标记所有在这个时间段被标记的单元格,以便在上一个时间段也进行细化。这在误差指标是通过对时间空间单元的积分计算出来的,但现在与离散时间层面上的网格相关联的情况下很有用。然而,由于误差贡献来自于两个网格,因此对两个网格进行细化是合适的。 * 由于前一个网格并没有将标志映照到前一个网格上,所以这并不会导致单元数几乎无限增长。然而,你应该只在开启单元格号校正的情况下使用这个标志。 * 镜像是在细胞数校正完成后,但在网格适应前完成的,所以这个网格上的细胞数不会明显受到前一个网格上额外标记的细胞的影响。 * */ const bool mirror_flags_to_previous_grid; /** * 使这个网格与前一个网格相适应。 * */ const bool adapt_grids; /** * 异常情况 * */ DeclException1(ExcInvalidValue, double, << "The value " << arg1 << " for the cell number corridor does not fulfill " "its natural requirements."); }; /** * 给予实际细化函数的结构,告诉它在粗化和细化时要采取哪些阈值。实际的细化标准是通过调用虚拟函数 * @p get_tria_refinement_criteria加载的。 * */ template <int dim> struct RefinementData { /** * 构造函数 * */ RefinementData(const double refinement_threshold, const double coarsening_threshold = 0); /** * 细化的阈值:具有较大数值的单元格将被细化(至少在第一轮;细化过程的后续步骤可能也会标记其他单元格,或者从具有高于该阈值的标准的单元格中移除标记)。 * */ const double refinement_threshold; /** * 粗化的相同阈值:如果可能的话,阈值较小的单元将被粗化。 * */ const double coarsening_threshold; /** * 异常情况 * */ DeclException1(ExcInvalidValue, double, << "The value " << arg1 << " for the cell refinement thresholds does not fulfill " "its natural requirements."); }; } // namespace TimeStepBase_Tria_Flags /** * TimeStepBase的特殊化,解决了网格处理的某些方面。特别是,这个类被认为可以处理网格,这些网格可以在每个时间步长上分别进行自适应的细化,或者在时间步长之间进行松散耦合。通过基类中声明的 * @p sleep 和 @p wake_up * 函数,它还负责在内存资源是一个点时删除和重建网格。 * 除此之外,它还提供了一些函数,对与时间有关的问题做了一些相当棘手的细化规则,试图避免在随后的时间层之间的网格有太多的变化,同时也试图保留单独细化每个网格的自由。有很多控制这个函数的标志和数字,它们可能会极大地改变这个函数的行为 * * - 进一步的信息见标志的描述。 * * */ template <int dim> class TimeStepBase_Tria : public TimeStepBase { public: /** * 将TimeStepBase_Tria_Flags()命名空间的数据类型类型化为本地范围。 * */ using Flags = typename TimeStepBase_Tria_Flags::Flags<dim>; using RefinementFlags = typename TimeStepBase_Tria_Flags::RefinementFlags<dim>; using RefinementData = typename TimeStepBase_Tria_Flags::RefinementData<dim>; /** * 扩展基类中的枚举,表示下一个要做的动作。 * */ enum SolutionState { /** * 接下来执行网格细化。 * */ grid_refinement = 0x1000 }; /** * 默认构造函数。什么都不做,只是抛出一个异常。我们需要有这样一个构造函数,以满足派生类的需要,它们把这个类作为一个虚拟基类,不需要调用这个构造函数,因为它们不是终端类。编译器希望知道一个可以调用的构造函数,因为它不能知道这个类不是终端类。 * */ TimeStepBase_Tria(); /** * 构造函数。接受一个粗略的网格,这个时间层的网格将从这个粗略的网格派生出来,还有一些引导这个对象的行为的标志。 * 粗略网格的所有权保留在这个对象的创建者那里。 * 然而,它被锁定,不会被破坏,以保证粗略网格的寿命比这个对象需要的时间长。 * 你需要给这个函数提供一般的标志结构,因为它无论如何都需要;如果你不打算调用这个类的细化函数,细化标志可以省略。 * */ TimeStepBase_Tria( const double time, const Triangulation<dim, dim> &coarse_grid, const Flags & flags, const RefinementFlags & refinement_flags = RefinementFlags()); /** * 解构器。目前,这不过是释放给构造函数的粗略网格三角的锁。 * */ virtual ~TimeStepBase_Tria() override; /** * 重建这个时间层所需的所有数据。这个函数的作用是在所有的变量和数据结构被送入睡眠状态后,或者在我们第一次访问这个时间层时,让它们重新开始工作。特别是,它被用来重建三角形、自由度处理程序,在数据向量被存储到磁盘的情况下重新加载它们,等等。默认情况下,如果在 * @p sleep * 函数中设置了相应的标志来破坏三角形,该函数将重建三角形。它也会在我们第一次碰到这个函数并且 * @p wakeup_level * 等于<tt>flags.wakeup_level_to_build_grid</tt>时这样做,与上述标志的值无关。(实际上,只要三角形指针等于Null指针并且 * @p wakeup_level 的值是正确的,它就会这样做)。 * 由于这是一项重要的任务,如果你选择在自己的类中重载这个函数(很可能是这样),你应该从自己的函数中调用这个函数,最好是在开始的时候,这样你的函数就可以对已经存在的三角关系生效。 * */ virtual void wake_up(const unsigned int wakeup_level) override; /** * 这是一个与 @p wake_up. * 相反的函数,它用于删除数据或在当前扫描不再需要它们时将其保存到磁盘。 * 典型的数据种类是数据向量、自由度处理程序、三角测量对象等,它们占据了大量的内存,因此可以被外部化。 * 默认情况下,如果用户在此对象的标志中这样指定,三角测量将被删除,细化历史将被保存,以便相应的 * @p wake_up * 函数可以重建它。因此,你应该从你的重载版本中调用这个函数,最好是在最后,这样你的函数就可以在你需要的时候使用三角测量。 * */ virtual void sleep(const unsigned int) override; /** * 根据传递给这个对象的构造函数的标志和传递给这个函数的数据进行细化。关于这个函数的工作描述,请参考这个类的一般文档。 * 事实上,这个函数实际上并没有细化或粗化三角形,而只是设置各自的标志。这样做的原因是,通常你不会在事后立即需要这个网格,而是在下一次扫描时才需要,所以只需存储这些标志,并在下次需要时重建它。另外,可能下一步会想增加或删除一些标志,所以我们无论如何都要使用这个网格来等待。 * */ void refine_grid(const RefinementData data); /** * 细化循环的相应初始函数;除了将 @p next_action 设置为 @p * grid_refinement外,在默认实现中不做任何事情,但可以被重载。 * */ virtual void init_for_refinement(); /** * 虚拟函数,应该用当前三角形的细化标准填充向量。它在 * @p refine_grid * 函数内使用,以获得当前时间步长的标准,因为在使用时间步长管理对象的循环时,它们不能通过其参数传递。 * */ virtual void get_tria_refinement_criteria(Vector<float> &criteria) const = 0; /** * 三角形的细化标志被存储在一个局部变量中,因此可以进行恢复。粗化标志也被存储。 * */ void save_refine_flags(); /** * 确定这个对象的内存消耗(以字节为单位)的估计值。 * 你要在派生类中重载这个函数来计算派生类所使用的内存量,并将这个函数的结果加到你的结果中。 * */ virtual std::size_t memory_consumption() const override; /** * 异常情况 * */ DeclExceptionMsg(ExcGridNotDeleted, "When calling restore_grid(), you must have previously " "deleted the triangulation."); protected: /** * 在这个时间层次上使用的三角法。由于这是每一个时间步进方案都需要有的东西,我们可以安全地把它放到基类中。请注意,如果在 * @p flags 结构中指定了这样的行为,三角形会经常被 @p * sleep 和 @p wake_up 函数删除和重建以节省内存。 * */ SmartPointer<Triangulation<dim, dim>, TimeStepBase_Tria<dim>> tria; /** * 指向一个网格的指针,该网格将被用作该时间层的粗略网格。 * 这个指针是通过构造函数设置的;所有权仍然属于这个管理对象的所有者。 * */ SmartPointer<const Triangulation<dim, dim>, TimeStepBase_Tria<dim>> coarse_grid; /** * 一些关于这个时间级别应如何表现的标志。参见此结构的文档以了解更多信息。 * */ const Flags flags; /** * 控制细化过程的标志;更多信息请参见相应结构的文档。 * */ const RefinementFlags refinement_flags; private: /** * 保存该时间层次上不同扫描的细化和粗化标志的向量。因此,这些向量保存了网格的历史。 * */ std::vector<std::vector<bool>> refine_flags; /** * @ref refine_flags * */ std::vector<std::vector<bool>> coarsen_flags; /** * 根据保存的数据恢复网格。为此,粗略的网格被复制,并使用保存的标志逐步重建网格。 * */ void restore_grid(); }; /*--------------------------- template functions ----------------------------*/ template <typename InitFunctionObject, typename LoopFunctionObject> void TimeDependent::do_loop(InitFunctionObject init_function, LoopFunctionObject loop_function, const TimeSteppingData &timestepping_data, const Direction direction) { // the following functions looks quite // disrupted due to the recurring switches // for forward and backward running loops. // // I chose to switch at every place where // it is needed, since it is so easy // to overlook something when you change // some code at one place when it needs // to be changed at a second place, here // for the other direction, also. const unsigned int n_timesteps = timesteps.size(); // initialize the time steps for // a round of this loop for (unsigned int step = 0; step < n_timesteps; ++step) switch (direction) { case forward: init_function((&*timesteps[step])); break; case backward: init_function((&*timesteps[n_timesteps - step - 1])); break; }; // wake up the first few time levels for (int step = -static_cast<int>(timestepping_data.look_ahead); step < 0; ++step) for (int look_ahead = 0; look_ahead <= static_cast<int>(timestepping_data.look_ahead); ++look_ahead) switch (direction) { case forward: if (step + look_ahead >= 0) timesteps[step + look_ahead]->wake_up(look_ahead); break; case backward: if (n_timesteps - (step + look_ahead) < n_timesteps) timesteps[n_timesteps - (step + look_ahead)]->wake_up(look_ahead); break; }; for (unsigned int step = 0; step < n_timesteps; ++step) { // first thing: wake up the // timesteps ahead as necessary for (unsigned int look_ahead = 0; look_ahead <= timestepping_data.look_ahead; ++look_ahead) switch (direction) { case forward: if (step + look_ahead < n_timesteps) timesteps[step + look_ahead]->wake_up(look_ahead); break; case backward: if (n_timesteps > (step + look_ahead)) timesteps[n_timesteps - (step + look_ahead) - 1]->wake_up( look_ahead); break; }; // actually do the work switch (direction) { case forward: loop_function((&*timesteps[step])); break; case backward: loop_function((&*timesteps[n_timesteps - step - 1])); break; }; // let the timesteps behind sleep for (unsigned int look_back = 0; look_back <= timestepping_data.look_back; ++look_back) switch (direction) { case forward: if (step >= look_back) timesteps[step - look_back]->sleep(look_back); break; case backward: if (n_timesteps - (step - look_back) <= n_timesteps) timesteps[n_timesteps - (step - look_back) - 1]->sleep( look_back); break; } } // make the last few timesteps sleep for (int step = n_timesteps; step < static_cast<int>(n_timesteps + timestepping_data.look_back); ++step) for (int look_back = 0; look_back <= static_cast<int>(timestepping_data.look_back); ++look_back) switch (direction) { case forward: if ((step - look_back >= 0) && (step - look_back < static_cast<int>(n_timesteps))) timesteps[step - look_back]->sleep(look_back); break; case backward: if ((step - look_back >= 0) && (step - look_back < static_cast<int>(n_timesteps))) timesteps[n_timesteps - (step - look_back) - 1]->sleep(look_back); break; }; } DEAL_II_NAMESPACE_CLOSE /*---------------------------- time-dependent.h ---------------------------*/ #endif /*---------------------------- time-dependent.h ---------------------------*/
26.996263
2,379
0.659422
02da72a5975a750734a3e337256e30ba46dbbe68
497
h
C
OmniKitUI/OmniKitUI.h
jbayart/rileylink_ios
bfcc69346631a22f44d2e42f447c5b067e66766b
[ "MIT" ]
137
2021-03-31T15:38:38.000Z
2022-03-27T14:26:55.000Z
OmniKitUI/OmniKitUI.h
jbayart/rileylink_ios
bfcc69346631a22f44d2e42f447c5b067e66766b
[ "MIT" ]
312
2015-08-18T14:37:54.000Z
2022-03-17T11:57:46.000Z
OmniKitUI/OmniKitUI.h
jbayart/rileylink_ios
bfcc69346631a22f44d2e42f447c5b067e66766b
[ "MIT" ]
230
2015-08-22T06:52:34.000Z
2022-01-30T23:21:18.000Z
// // OmniKitUI.h // OmniKitUI // // Created by Pete Schwamb on 8/26/18. // Copyright © 2018 Pete Schwamb. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for OmniKitUI. FOUNDATION_EXPORT double OmniKitUIVersionNumber; //! Project version string for OmniKitUI. FOUNDATION_EXPORT const unsigned char OmniKitUIVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <OmniKitUI/PublicHeader.h>
24.85
134
0.758551
f36096d93f5302b0e2f9329a9d8de9a178063620
4,954
h
C
lib/include/clu/overload.h
Chlorie/clu
a09a50e5658761c522cf5131e710ee17bd80fa0a
[ "MIT" ]
3
2020-08-30T13:21:58.000Z
2020-12-21T06:46:18.000Z
lib/include/clu/overload.h
Chlorie/clu
a09a50e5658761c522cf5131e710ee17bd80fa0a
[ "MIT" ]
8
2021-08-13T08:22:26.000Z
2022-03-31T09:28:32.000Z
lib/include/clu/overload.h
Chlorie/clu
a09a50e5658761c522cf5131e710ee17bd80fa0a
[ "MIT" ]
2
2020-12-21T06:46:19.000Z
2021-03-13T16:33:16.000Z
// Rough implementation of P0051R3: C++ generic overload function #pragma once #include <functional> #include "type_traits.h" #include "invocable_wrapper.h" namespace clu { namespace detail { template <typename... Fs> struct overload_t : invocable_wrapper<Fs>... { using invocable_wrapper<Fs>::operator()...; }; template <typename... Fs> class first_overload_t : public invocable_wrapper<Fs>... { private: struct not_callable_t {}; template <typename FirstBase, typename... Bases, typename Self, typename... Args> constexpr static auto call_result_impl(Self&& self, Args&&... args) noexcept { using base = copy_cvref_t<Self&&, FirstBase>; if constexpr (std::is_invocable_v<base, Args&&...>) return std::invoke_result<base, Args&&...>{}; else if constexpr (sizeof...(Bases) > 0) return call_result_impl<Bases...>(static_cast<Self&&>(self), static_cast<Args&&>(args)...); else return not_callable_t{}; } template <typename FirstBase, typename... Bases, typename Self, typename... Args> constexpr static auto is_nothrow_callable_impl(Self&& self, Args&&... args) noexcept { using base = copy_cvref_t<Self&&, FirstBase>; if constexpr (std::is_invocable_v<base, Args&&...>) return std::is_nothrow_invocable<base, Args&&...>{}; else if constexpr (sizeof...(Bases) > 0) return is_nothrow_callable_impl<Bases...>(static_cast<Self&&>(self), static_cast<Args&&>(args)...); else return std::false_type{}; } template <typename Self, typename... Args> using call_result = decltype(call_result_impl<invocable_wrapper<Fs>...>(std::declval<Self>(), std::declval<Args&&>()...)); template <typename Self, typename... Args> using call_result_t = typename call_result<Self, Args...>::type; template <typename Self, typename... Args> static constexpr bool is_callable_v = !std::is_same_v<not_callable_t, call_result<Self, Args...>>; template <typename Self, typename... Args> static constexpr bool is_nothrow_callable_v = decltype(is_nothrow_callable_impl<invocable_wrapper<Fs>...>( std::declval<Self>(), std::declval<Args&&>()...))::value; template <typename FirstBase, typename... Bases, typename Self, typename... Args> constexpr static decltype(auto) call_impl(Self&& self, Args&&... args) noexcept(is_nothrow_callable_v<Self, Args...>) { using base = copy_cvref_t<Self&&, FirstBase>; if constexpr (std::is_invocable_v<base, Args&&...>) return static_cast<Self&&>(self).FirstBase::operator()(static_cast<Args&&>(args)...); else if constexpr (sizeof...(Bases) > 0) return call_impl<Bases...>(static_cast<Self&&>(self), static_cast<Args&&>(args)...); else static_assert(dependent_false<Self>); } public: #define CLU_FIRST_OVERLOAD_CALL_DEF(cnst, ref) \ template <typename... Args> requires is_callable_v<cnst first_overload_t ref, Args&&...> \ constexpr call_result_t<cnst first_overload_t ref, Args&&...> operator()(Args&&... args) cnst ref \ noexcept(is_nothrow_callable_v<cnst first_overload_t ref, Args&&...>) \ { \ return call_impl<invocable_wrapper<Fs>...>( \ static_cast<cnst first_overload_t ref>(*this), \ static_cast<Args&&>(args)...); \ } static_assert(true) CLU_FIRST_OVERLOAD_CALL_DEF(, &); CLU_FIRST_OVERLOAD_CALL_DEF(, &&); CLU_FIRST_OVERLOAD_CALL_DEF(const, &); CLU_FIRST_OVERLOAD_CALL_DEF(const, &&); #undef CLU_FIRST_OVERLOAD_CALL_DEF }; } template <typename... Fs> constexpr auto overload(Fs&&... fns) { return detail::overload_t<std::decay_t<Fs>...>( invocable_wrapper<std::decay_t<Fs>>(static_cast<Fs&&>(fns))...); } template <typename... Fs> constexpr auto first_overload(Fs&&... fns) { return detail::first_overload_t<std::decay_t<Fs>...>( invocable_wrapper<std::decay_t<Fs>>(static_cast<Fs&&>(fns))...); } }
47.180952
134
0.534518
b626cafecfdfc61faa080ecaa79e70c159e575fb
15,812
c
C
lightningd/options.c
segwit/atbcoin-lightning
e8bea05a3bccddcce4ab7216b35bd42d152df03f
[ "MIT" ]
1
2017-12-30T19:27:09.000Z
2017-12-30T19:27:09.000Z
lightningd/options.c
segwit/atbcoin-lightning
e8bea05a3bccddcce4ab7216b35bd42d152df03f
[ "MIT" ]
null
null
null
lightningd/options.c
segwit/atbcoin-lightning
e8bea05a3bccddcce4ab7216b35bd42d152df03f
[ "MIT" ]
null
null
null
#include <arpa/inet.h> #include <bitcoin/chainparams.h> #include <ccan/err/err.h> #include <ccan/opt/opt.h> #include <ccan/short_types/short_types.h> #include <ccan/tal/grab_file/grab_file.h> #include <ccan/tal/str/str.h> #include <common/configdir.h> #include <common/version.h> #include <errno.h> #include <inttypes.h> #include <lightningd/bitcoind.h> #include <lightningd/chaintopology.h> #include <lightningd/lightningd.h> #include <lightningd/log.h> #include <lightningd/opt_time.h> #include <lightningd/options.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <wire/wire.h> /* Tal wrappers for opt. */ static void *opt_allocfn(size_t size) { return tal_alloc_(NULL, size, false, false, TAL_LABEL("opt_allocfn", "")); } static void *tal_reallocfn(void *ptr, size_t size) { if (!ptr) return opt_allocfn(size); tal_resize_(&ptr, 1, size, false); return ptr; } static void tal_freefn(void *ptr) { tal_free(ptr); } /* FIXME: Put into ccan/time. */ #define TIME_FROM_SEC(sec) { { .tv_nsec = 0, .tv_sec = sec } } #define TIME_FROM_MSEC(msec) \ { { .tv_nsec = ((msec) % 1000) * 1000000, .tv_sec = (msec) / 1000 } } static char *opt_set_u64(const char *arg, u64 *u) { char *endp; unsigned long long l; /* This is how the manpage says to do it. Yech. */ errno = 0; l = strtoull(arg, &endp, 0); if (*endp || !arg[0]) return tal_fmt(NULL, "'%s' is not a number", arg); *u = l; if (errno || *u != l) return tal_fmt(NULL, "'%s' is out of range", arg); return NULL; } static char *opt_set_u32(const char *arg, u32 *u) { char *endp; unsigned long l; /* This is how the manpage says to do it. Yech. */ errno = 0; l = strtoul(arg, &endp, 0); if (*endp || !arg[0]) return tal_fmt(NULL, "'%s' is not a number", arg); *u = l; if (errno || *u != l) return tal_fmt(NULL, "'%s' is out of range", arg); return NULL; } static char *opt_set_u16(const char *arg, u16 *u) { char *endp; unsigned long l; /* This is how the manpage says to do it. Yech. */ errno = 0; l = strtoul(arg, &endp, 0); if (*endp || !arg[0]) return tal_fmt(NULL, "'%s' is not a number", arg); *u = l; if (errno || *u != l) return tal_fmt(NULL, "'%s' is out of range", arg); return NULL; } static char *opt_set_s32(const char *arg, s32 *u) { char *endp; long l; /* This is how the manpage says to do it. Yech. */ errno = 0; l = strtol(arg, &endp, 0); if (*endp || !arg[0]) return tal_fmt(NULL, "'%s' is not a number", arg); *u = l; if (errno || *u != l) return tal_fmt(NULL, "'%s' is out of range", arg); return NULL; } static char *opt_set_ipaddr(const char *arg, struct ipaddr *addr) { struct in6_addr v6; struct in_addr v4; char *err = NULL; memset(&addr->addr, 0, sizeof(addr->addr)); if (inet_pton(AF_INET, arg, &v4) == 1) { addr->type = ADDR_TYPE_IPV4; addr->addrlen = 4; memcpy(&addr->addr, &v4, addr->addrlen); } else if (inet_pton(AF_INET6, arg, &v6) == 1) { addr->type = ADDR_TYPE_IPV6; addr->addrlen = 16; memcpy(&addr->addr, &v6, addr->addrlen); } else { err = tal_fmt(NULL, "Unable to parse IP address '%s'", arg); } return err; } static void opt_show_u64(char buf[OPT_SHOW_LEN], const u64 *u) { snprintf(buf, OPT_SHOW_LEN, "%"PRIu64, *u); } static void opt_show_u32(char buf[OPT_SHOW_LEN], const u32 *u) { snprintf(buf, OPT_SHOW_LEN, "%"PRIu32, *u); } static void opt_show_s32(char buf[OPT_SHOW_LEN], const s32 *u) { snprintf(buf, OPT_SHOW_LEN, "%"PRIi32, *u); } static void opt_show_u16(char buf[OPT_SHOW_LEN], const u16 *u) { snprintf(buf, OPT_SHOW_LEN, "%u", *u); } static char *opt_set_network(const char *arg, struct lightningd *ld) { ld->topology->bitcoind->chainparams = chainparams_for_network(arg); if (!ld->topology->bitcoind->chainparams) return tal_fmt(NULL, "Unknown network name '%s'", arg); return NULL; } /* FIXME: Uncomment once legacy daemon has been removed */ /* static void opt_show_network(char buf[OPT_SHOW_LEN], const struct lightningd *ld) { snprintf(buf, OPT_SHOW_LEN, "%s", ld->chainparams->network_name); } */ static void config_register_opts(struct lightningd *ld) { opt_register_arg("--locktime-blocks", opt_set_u32, opt_show_u32, &ld->config.locktime_blocks, "Blocks before peer can unilaterally spend funds"); opt_register_arg("--max-locktime-blocks", opt_set_u32, opt_show_u32, &ld->config.locktime_max, "Maximum seconds peer can lock up our funds"); opt_register_arg("--anchor-onchain", opt_set_u32, opt_show_u32, &ld->config.anchor_onchain_wait, "Blocks before we give up on pending anchor transaction"); opt_register_arg("--anchor-confirms", opt_set_u32, opt_show_u32, &ld->config.anchor_confirms, "Confirmations required for anchor transaction"); opt_register_arg("--max-anchor-confirms", opt_set_u32, opt_show_u32, &ld->config.anchor_confirms_max, "Maximum confirmations other side can wait for anchor transaction"); opt_register_arg("--forever-confirms", opt_set_u32, opt_show_u32, &ld->config.forever_confirms, "Confirmations after which we consider a reorg impossible"); opt_register_arg("--commit-fee-min=<percent>", opt_set_u32, opt_show_u32, &ld->config.commitment_fee_min_percent, "Minimum percentage of fee to accept for commitment"); opt_register_arg("--commit-fee-max=<percent>", opt_set_u32, opt_show_u32, &ld->config.commitment_fee_max_percent, "Maximum percentage of fee to accept for commitment (0 for unlimited)"); opt_register_arg("--commit-fee=<percent>", opt_set_u32, opt_show_u32, &ld->config.commitment_fee_percent, "Percentage of fee to request for their commitment"); opt_register_arg("--override-fee-rate", opt_set_u64, opt_show_u64, &ld->topology->override_fee_rate, "Force a specific rate in satoshis per kb regardless of estimated fees"); opt_register_arg("--default-fee-rate", opt_set_u64, opt_show_u64, &ld->topology->default_fee_rate, "Satoshis per kb if can't estimate fees"); opt_register_arg("--min-htlc-expiry", opt_set_u32, opt_show_u32, &ld->config.min_htlc_expiry, "Minimum number of blocks to accept an HTLC before expiry"); opt_register_arg("--max-htlc-expiry", opt_set_u32, opt_show_u32, &ld->config.max_htlc_expiry, "Maximum number of blocks to accept an HTLC before expiry"); opt_register_arg("--deadline-blocks", opt_set_u32, opt_show_u32, &ld->config.deadline_blocks, "Number of blocks before HTLC timeout before we drop connection"); opt_register_arg("--bitcoind-poll", opt_set_time, opt_show_time, &ld->config.poll_time, "Time between polling for new transactions"); opt_register_arg("--commit-time", opt_set_time, opt_show_time, &ld->config.commit_time, "Time after changes before sending out COMMIT"); opt_register_arg("--fee-base", opt_set_u32, opt_show_u32, &ld->config.fee_base, "Millisatoshi minimum to charge for HTLC"); opt_register_arg("--fee-per-satoshi", opt_set_s32, opt_show_s32, &ld->config.fee_per_satoshi, "Microsatoshi fee for every satoshi in HTLC"); opt_register_noarg("--ignore-dbversion", opt_set_bool, &ld->config.db_version_ignore, "Continue despite invalid database version (DANGEROUS!)"); opt_register_arg("--ipaddr", opt_set_ipaddr, NULL, &ld->config.ipaddr, "Set the IP address (v4 or v6) to announce to the network for incoming connections"); /* FIXME: Register opt_show_network with the option */ opt_register_early_arg("--network", opt_set_network, NULL, ld, "Select the network parameters (bitcoin, testnet, " "regtest, or litecoin)"); } static void dev_register_opts(struct lightningd *ld) { opt_register_noarg("--dev-no-broadcast", opt_set_bool, &ld->topology->dev_no_broadcast, opt_hidden); } static const struct config testnet_config = { /* 6 blocks to catch cheating attempts. */ .locktime_blocks = 6, /* They can have up to 3 days. */ .locktime_max = 3 * 6 * 24, /* Testnet can have long runs of empty blocks. */ .anchor_onchain_wait = 100, /* We're fairly trusting, under normal circumstances. */ .anchor_confirms = 1, /* More than 10 confirms seems overkill. */ .anchor_confirms_max = 10, /* At some point, you've got to let it go... */ /* FIXME-OLD #onchain: * * Outputs... are considered *irrevocably resolved* once they * are included in a block at least 100 deep on the most-work * blockchain. 100 blocks is far greater than the longest * known bitcoin fork, and the same value used to wait for * confirmations of miner's rewards[1]. */ .forever_confirms = 10, /* Testnet fees are crazy, allow infinite feerange. */ .commitment_fee_min_percent = 0, .commitment_fee_max_percent = 0, /* We offer to pay 5 times 2-block fee */ .commitment_fee_percent = 500, /* Don't bother me unless I have 6 hours to collect. */ .min_htlc_expiry = 6 * 6, /* Don't lock up channel for more than 5 days. */ .max_htlc_expiry = 5 * 6 * 24, /* If we're closing on HTLC expiry, and you're unresponsive, we abort. */ .deadline_blocks = 4, /* How often to bother bitcoind. */ .poll_time = TIME_FROM_SEC(10), /* Send commit 10msec after receiving; almost immediately. */ .commit_time = TIME_FROM_MSEC(10), /* Allow dust payments */ .fee_base = 1, /* Take 0.001% */ .fee_per_satoshi = 10, /* Don't ignore database version */ .db_version_ignore = false, /* Do not advertise any IP */ .ipaddr.type = 0, }; /* aka. "Dude, where's my coins?" */ static const struct config mainnet_config = { /* ~one day to catch cheating attempts. */ .locktime_blocks = 6 * 24, /* They can have up to 3 days. */ .locktime_max = 3 * 6 * 24, /* You should get in within 10 blocks. */ .anchor_onchain_wait = 10, /* We're fairly trusting, under normal circumstances. */ .anchor_confirms = 3, /* More than 10 confirms seems overkill. */ .anchor_confirms_max = 10, /* At some point, you've got to let it go... */ /* FIXME-OLD #onchain: * * Outputs... are considered *irrevocably resolved* once they * are included in a block at least 100 deep on the most-work * blockchain. 100 blocks is far greater than the longest * known bitcoin fork, and the same value used to wait for * confirmations of miner's rewards[1]. */ .forever_confirms = 100, /* Insist between 2 and 20 times the 2-block fee. */ .commitment_fee_min_percent = 200, .commitment_fee_max_percent = 2000, /* We offer to pay 5 times 2-block fee */ .commitment_fee_percent = 500, /* Don't bother me unless I have 6 hours to collect. */ .min_htlc_expiry = 6 * 6, /* Don't lock up channel for more than 5 days. */ .max_htlc_expiry = 5 * 6 * 24, /* If we're closing on HTLC expiry, and you're unresponsive, we abort. */ .deadline_blocks = 10, /* How often to bother bitcoind. */ .poll_time = TIME_FROM_SEC(30), /* Send commit 10msec after receiving; almost immediately. */ .commit_time = TIME_FROM_MSEC(10), /* Discourage dust payments */ .fee_base = 546000, /* Take 0.001% */ .fee_per_satoshi = 10, /* Don't ignore database version */ .db_version_ignore = false, /* Do not advertise any IP */ .ipaddr.type = 0, }; static void check_config(struct lightningd *ld) { /* We do this by ensuring it's less than the minimum we would accept. */ if (ld->config.commitment_fee_max_percent != 0 && ld->config.commitment_fee_max_percent < ld->config.commitment_fee_min_percent) fatal("Commitment fee invalid min-max %u-%u", ld->config.commitment_fee_min_percent, ld->config.commitment_fee_max_percent); if (ld->config.forever_confirms < 100 && !get_chainparams(ld)->testnet) log_unusual(ld->log, "Warning: forever-confirms of %u is less than 100!", ld->config.forever_confirms); if (ld->config.anchor_confirms == 0) fatal("anchor-confirms must be greater than zero"); /* FIXME-OLD #2: * * a node MUST estimate the deadline for successful redemption * for each HTLC it offers. A node MUST NOT offer a HTLC * after this deadline */ if (ld->config.deadline_blocks >= ld->config.min_htlc_expiry) fatal("Deadline %u can't be more than minimum expiry %u", ld->config.deadline_blocks, ld->config.min_htlc_expiry); } static void setup_default_config(struct lightningd *ld) { if (get_chainparams(ld)->testnet) ld->config = testnet_config; else ld->config = mainnet_config; } /* FIXME: make this nicer! */ static void config_log_stderr_exit(const char *fmt, ...) { char *msg; va_list ap; va_start(ap, fmt); /* This is the format we expect: mangle it to remove '--'. */ if (streq(fmt, "%s: %.*s: %s")) { const char *argv0 = va_arg(ap, const char *); unsigned int len = va_arg(ap, unsigned int); const char *arg = va_arg(ap, const char *); const char *problem = va_arg(ap, const char *); msg = tal_fmt(NULL, "%s line %s: %.*s: %s", argv0, arg+strlen(arg)+1, len-2, arg+2, problem); } else { msg = tal_vfmt(NULL, fmt, ap); } va_end(ap); fatal("%s", msg); } /* We turn the config file into cmdline arguments. */ static void opt_parse_from_config(struct lightningd *ld) { char *contents, **lines; char **argv; int i, argc; contents = grab_file(ld, "config"); /* Doesn't have to exist. */ if (!contents) { if (errno != ENOENT) fatal("Opening and reading config: %s", strerror(errno)); /* Now we can set up defaults, since no config file. */ setup_default_config(ld); return; } lines = tal_strsplit(contents, contents, "\r\n", STR_NO_EMPTY); /* We have to keep argv around, since opt will point into it */ argv = tal_arr(ld, char *, argc = 1); argv[0] = "lightning config file"; for (i = 0; i < tal_count(lines) - 1; i++) { if (strstarts(lines[i], "#")) continue; /* Only valid forms are "foo" and "foo=bar" */ tal_resize(&argv, argc+1); /* Stash line number after nul. */ argv[argc++] = tal_fmt(argv, "--%s%c%u", lines[i], 0, i+1); } tal_resize(&argv, argc+1); argv[argc] = NULL; opt_early_parse(argc, argv, config_log_stderr_exit); /* Now we can set up defaults, depending on whether testnet or not */ setup_default_config(ld); opt_parse(&argc, argv, config_log_stderr_exit); tal_free(contents); } void register_opts(struct lightningd *ld) { opt_set_alloc(opt_allocfn, tal_reallocfn, tal_freefn); opt_register_early_noarg("--help|-h", opt_usage_and_exit, "\n" "A bitcoin lightning daemon.", "Print this message."); opt_register_arg("--port", opt_set_u16, opt_show_u16, &ld->portnum, "Port to bind to (0 means don't listen)"); opt_register_arg("--bitcoin-datadir", opt_set_charp, NULL, &ld->topology->bitcoind->datadir, "-datadir arg for atbcoin-cli"); opt_register_logging(ld->log); opt_register_version(); configdir_register_opts(ld, &ld->config_dir, &ld->rpc_filename); config_register_opts(ld); dev_register_opts(ld); } bool handle_opts(struct lightningd *ld, int argc, char *argv[]) { bool newdir = false; /* Get any configdir/testnet options first. */ opt_early_parse(argc, argv, opt_log_stderr_exit); /* Move to config dir, to save ourselves the hassle of path manip. */ if (chdir(ld->config_dir) != 0) { log_unusual(ld->log, "Creating lightningd dir %s" " (because chdir gave %s)", ld->config_dir, strerror(errno)); if (mkdir(ld->config_dir, 0700) != 0) fatal("Could not make directory %s: %s", ld->config_dir, strerror(errno)); if (chdir(ld->config_dir) != 0) fatal("Could not change directory %s: %s", ld->config_dir, strerror(errno)); newdir = true; } /* Now look for config file */ opt_parse_from_config(ld); ld->config.ipaddr.port = ld->portnum; opt_parse(&argc, argv, opt_log_stderr_exit); if (argc != 1) errx(1, "no arguments accepted"); check_config(ld); return newdir; }
29.94697
91
0.686757
2a3efdd1ff00c2d753a4daa4c63715abcc0847b0
1,158
h
C
code/HeaderHeaven/include/LanguageComponents.h
kamac/HeaderHeaven
a8d4ed64ebbf47fdc165f0431273d040464c3a63
[ "MIT" ]
null
null
null
code/HeaderHeaven/include/LanguageComponents.h
kamac/HeaderHeaven
a8d4ed64ebbf47fdc165f0431273d040464c3a63
[ "MIT" ]
null
null
null
code/HeaderHeaven/include/LanguageComponents.h
kamac/HeaderHeaven
a8d4ed64ebbf47fdc165f0431273d040464c3a63
[ "MIT" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef HHEAVEN_LANGUAGE_COMPONENTS_H #define HHEAVEN_LANGUAGE_COMPONENTS_H #include "Common.h" struct Variable { std::string returnType, name; }; struct Function { Variable declaration; std::vector<Variable> arguments; std::string nameSpace = ""; bool hasBody, isConst = false; uint32_t endIndex; }; struct Class { std::string name; std::vector<Function> methods; std::vector<Class> classes; std::string nameSpace = ""; }; #endif
29.692308
81
0.753022
cc0df9ca2de6cb2d1111abaf9ccfa4dca4ae9fc7
129
h
C
classes/characters/Dragon.h
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
classes/characters/Dragon.h
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
classes/characters/Dragon.h
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
// // Created by glados on 4/6/15. // #ifndef CC3K_DRAGON_H #define CC3K_DRAGON_H class Dragon { }; #endif //CC3K_DRAGON_H
8.6
31
0.682171
a4ff4199ebacc36ff28440008feb26345fe6dfc6
204
h
C
LGWNetworking/LGWNetworking.h
magic3584/LGWNetworking
0c2dad605cd1d20585ffb1dd6e0041889889a03e
[ "MIT" ]
null
null
null
LGWNetworking/LGWNetworking.h
magic3584/LGWNetworking
0c2dad605cd1d20585ffb1dd6e0041889889a03e
[ "MIT" ]
null
null
null
LGWNetworking/LGWNetworking.h
magic3584/LGWNetworking
0c2dad605cd1d20585ffb1dd6e0041889889a03e
[ "MIT" ]
null
null
null
// // LGWNetworking.h // LGWNetworkingDemo // // Created by Lugick Wang on 2020/11/18. // #ifndef LGWNetworking_h #define LGWNetworking_h #import "LGWNetworkManager.h" #endif /* LGWNetworking_h */
13.6
41
0.715686
62694d997cb04b61fcba29a21acfbaee00f44549
2,853
h
C
chrome/browser/metrics/variations/variations_registry_syncer_win.h
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-03-10T13:08:49.000Z
2018-03-10T13:08:49.000Z
chrome/browser/metrics/variations/variations_registry_syncer_win.h
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/metrics/variations/variations_registry_syncer_win.h
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:19:31.000Z
2020-11-04T07:19:31.000Z
// Copyright (c) 2013 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_METRICS_VARIATIONS_VARIATIONS_REGISTRY_SYNCER_WIN_H_ #define CHROME_BROWSER_METRICS_VARIATIONS_VARIATIONS_REGISTRY_SYNCER_WIN_H_ #include <string> #include "base/metrics/field_trial.h" #include "base/string16.h" #include "base/timer.h" #include "chrome/common/metrics/variations/variation_ids.h" namespace chrome_variations { // This class manages synchronizing active VariationIDs with the Google Update // experiment_labels value in the registry. class VariationsRegistrySyncer { public: VariationsRegistrySyncer(); ~VariationsRegistrySyncer(); // Starts a timer that, when it expires, updates the registry with the current // Variations associated with Google Update. If the timer is already running, // calling this just resets the timer. void RequestRegistrySync(); // Takes the list of active groups and builds the label for the ones that have // Google Update VariationID associated with them. This will return an empty // string if there are no such groups. // Note that |active_groups| is passed in separately rather than being fetched // here for testing. static string16 BuildGoogleUpdateExperimentLabel( base::FieldTrial::ActiveGroups& active_groups); // Creates a final combined experiment labels string with |variation_labels| // and |other_labels|, appropriately appending a separator based on their // contents. It is assumed that |variation_labels| and |other_labels| do not // have leading or trailing separators. static string16 CombineExperimentLabels(const string16& variation_labels, const string16& other_labels); // Takes the value of experiment_labels from the registry and returns a valid // experiment_labels string value containing only the labels that are not // associated with Chrome Variations. This is exposed as static for testing. static string16 ExtractNonVariationLabels(const string16& labels); private: // Perform the actual synchronization process with the registry. void SyncWithRegistry(); // A timer used to delay the writes to the registry. This is done to optimize // the case where lazy-loaded features start their field trials some time // after initial batch of field trials are created, and also to avoid blocking // the UI thread. The timer effectively allows this class to batch together // update requests, to avoid reading and writing from the registry too much. base::OneShotTimer<VariationsRegistrySyncer> timer_; DISALLOW_COPY_AND_ASSIGN(VariationsRegistrySyncer); }; } // namespace chrome_variations #endif // CHROME_BROWSER_METRICS_VARIATIONS_VARIATIONS_REGISTRY_SYNCER_WIN_H_
43.227273
80
0.777427
6d5ed5f1a5272b86d92143d7a4813fa4c62222fd
1,037
c
C
srcs/search/search_utils.c
vdedios/minishell
5c812ada9b549a26c22f9a9af466409dc99a1e78
[ "MIT" ]
3
2021-05-05T19:44:10.000Z
2021-05-19T15:48:10.000Z
srcs/search/search_utils.c
vdedios/minishell
5c812ada9b549a26c22f9a9af466409dc99a1e78
[ "MIT" ]
null
null
null
srcs/search/search_utils.c
vdedios/minishell
5c812ada9b549a26c22f9a9af466409dc99a1e78
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* search.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: migferna <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/12 10:08:20 by migferna #+# #+# */ /* Updated: 2021/02/22 17:15:31 by migferna ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" void to_lower_in(char *input) { size_t it; it = -1; while (input[++it]) { input[it] = ft_tolower(input[it]); } }
41.48
80
0.172613
28e491fe992a7e9828bdb0687fd9a3b14cb747fd
4,094
c
C
examples/sprites/src/sprites/sprites.c
flynn-nrg/tornado-amiga
bb973063b44ee217b7c9b6f9afcdf4bd1e0beee9
[ "BSD-2-Clause" ]
31
2019-06-23T15:16:45.000Z
2022-02-18T16:45:42.000Z
examples/sprites/src/sprites/sprites.c
flynn-nrg/tornado-amiga
bb973063b44ee217b7c9b6f9afcdf4bd1e0beee9
[ "BSD-2-Clause" ]
1
2019-10-26T18:11:37.000Z
2019-10-26T18:11:37.000Z
examples/sprites/src/sprites/sprites.c
flynn-nrg/tornado-amiga
bb973063b44ee217b7c9b6f9afcdf4bd1e0beee9
[ "BSD-2-Clause" ]
5
2019-10-26T12:48:39.000Z
2021-12-01T20:16:07.000Z
/* Copyright (c) 2019, Miguel Mendez. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <assets.h> #include <canvas.h> #include <chrono.h> #include <debug.h> #include <display.h> #include <imgui_overlay.h> #include <memory.h> #include <prof.h> #include <telemetry.h> #include <tndo_assert.h> #include <tornado_settings.h> #include <demo.h> #include "sprites.h" static const char *assetList[] = { "data/Capsule_logo.tndo", // Compressed raw pixel data and palette. "data/sprite.tndo", // Sprite that will overlayed on top of the background. }; static int displayInstance; static char *background; static uint32_t pal[256]; static sprite_options so; void flipSprites(int requires_forefront) { if (requires_forefront) { display_forefront(displayInstance); } display_flip(displayInstance); } void initSprites(unsigned int tornadoOptions, tornadoEffect *effect) { static int init = 0; if (init) return; init = 1; effect->numAssets = sizeof(assetList) / sizeof(char *); effect->Assets = (void **)tndo_malloc(sizeof(void *) * effect->numAssets, 0); effect->assetSizes = (int *)tndo_malloc(sizeof(int) * effect->numAssets, 0); if (!loadAssets(effect->Assets, &assetList[0], effect->assetSizes, effect->numAssets, tornadoOptions, 0)) { tndo_memory_shutdown(tornadoOptions); if (tornadoOptions & LOGGING) { printf("FATAL - Asset loading failed!\n"); } exit(1); } // Palette is stored in LoadRGB32 format so we need to convert it first. loadRGB32toRGB((uint32_t *)effect->Assets[0], pal); // Set up our sprites... so.num_sprites = 4; so.spritesX[0] = 850; so.spritesX[1] = so.spritesX[0]; so.spritesX[2] = so.spritesX[0] + 256; so.spritesX[3] = so.spritesX[0] + 256; so.spritesY[0] = 0x52 + 64; so.spritesY[1] = so.spritesY[0]; so.spritesY[2] = so.spritesY[0]; so.spritesY[3] = so.spritesY[0]; so.spritesAttach[0] = 0; so.spritesAttach[1] = 1; so.spritesAttach[2] = 0; so.spritesAttach[3] = 1; so.spr_data = (t_bpl_head *)effect->Assets[1]; // 320x256 8 bitplanes. No padding. Sprites. displayInstance = display_init(pal, tornadoOptions, SCR_NORMAL, 0, 0, &so); // The first 3080 bytes are the palette in LoadRGB32 format. background = (char *)effect->Assets[0] + 3080; } t_canvas *renderSprites(int frame) { t_canvas *c = display_get(displayInstance); unsigned char *chunky = c->p.pix8; // Trivial copy... memcpy(chunky, background, 320 * 256); return c; } void vblSprites(int frame) { so.spritesX[0] = 850 + (int)(250.0f * sin(((float)frame) * 0.1f)); so.spritesX[1] = so.spritesX[0]; so.spritesX[2] = so.spritesX[0] + 256; so.spritesX[3] = so.spritesX[0] + 256; display_set_sprites_pos(displayInstance, &so); } void freeSprites(tornadoEffect *effect) {}
32.492063
80
0.722032
2f3a76856a60ca8b115ae12b25152545fd699004
624
c
C
test/expected_ast/arr_assign1.ast.c
clementval/fc
a5b444963c1b46e4eb34d938d992836d718010f7
[ "BSD-2-Clause" ]
null
null
null
test/expected_ast/arr_assign1.ast.c
clementval/fc
a5b444963c1b46e4eb34d938d992836d718010f7
[ "BSD-2-Clause" ]
null
null
null
test/expected_ast/arr_assign1.ast.c
clementval/fc
a5b444963c1b46e4eb34d938d992836d718010f7
[ "BSD-2-Clause" ]
null
null
null
Program: arr_assign1.f90 // GlobalScope, Parent: None SymbolTable Global { // Symbol List: // (1, 9) // ID: 1, NonConstant, NonAllocatable, NonTarget, NonPointer, Alloc_None, Intent_None, Global (int32)() arr1 } // MainProgram int32 arr1() { // MainProgramScope, Parent: GlobalScope SymbolTable arr1 { // Symbol List: // (2, 13) // ID: 2, NonConstant, NonAllocatable, NonTarget, NonPointer, StaticLocal, Intent_None, arr1 int32[1:2, 1:2] a } // Specification Constructs: EntityDeclList { } // Execution Constructs: // (3, 3) a(1, 1) = 10 // (4, 3) printf(a(1, 1)) }
17.828571
96
0.628205
13bd1d39b2fc2950ae6c39636c666a70c70c46c2
1,862
h
C
include/c/sk_runtimeeffect.h
natinusala/skia
0b75be78f543651c26e49c6c15030c107a16e299
[ "BSD-3-Clause" ]
54
2016-04-05T17:45:19.000Z
2022-01-31T06:27:33.000Z
include/c/sk_runtimeeffect.h
natinusala/skia
0b75be78f543651c26e49c6c15030c107a16e299
[ "BSD-3-Clause" ]
25
2016-03-18T04:01:06.000Z
2020-06-27T15:39:35.000Z
include/c/sk_runtimeeffect.h
natinusala/skia
0b75be78f543651c26e49c6c15030c107a16e299
[ "BSD-3-Clause" ]
50
2016-03-03T20:31:58.000Z
2022-03-31T18:26:13.000Z
/* * Copyright 2020 Microsoft Corporation. All rights reserved. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef sk_runtimeeffect_DEFINED #define sk_runtimeeffect_DEFINED #include "include/c/sk_types.h" SK_C_PLUS_PLUS_BEGIN_GUARD // sk_runtimeeffect_t SK_C_API sk_runtimeeffect_t* sk_runtimeeffect_make(sk_string_t* sksl, sk_string_t* error); SK_C_API void sk_runtimeeffect_unref(sk_runtimeeffect_t* effect); SK_C_API sk_shader_t* sk_runtimeeffect_make_shader(sk_runtimeeffect_t* effect, sk_data_t* uniforms, sk_shader_t** children, size_t childCount, const sk_matrix_t* localMatrix, bool isOpaque); SK_C_API sk_colorfilter_t* sk_runtimeeffect_make_color_filter(sk_runtimeeffect_t* effect, sk_data_t* uniforms, sk_colorfilter_t** children, size_t childCount); SK_C_API size_t sk_runtimeeffect_get_uniform_size(const sk_runtimeeffect_t* effect); SK_C_API size_t sk_runtimeeffect_get_uniforms_count(const sk_runtimeeffect_t* effect); SK_C_API void sk_runtimeeffect_get_uniform_name(const sk_runtimeeffect_t* effect, int index, sk_string_t* name); SK_C_API const sk_runtimeeffect_uniform_t* sk_runtimeeffect_get_uniform_from_index(const sk_runtimeeffect_t* effect, int index); SK_C_API const sk_runtimeeffect_uniform_t* sk_runtimeeffect_get_uniform_from_name(const sk_runtimeeffect_t* effect, const char* name, size_t len); SK_C_API size_t sk_runtimeeffect_get_children_count(const sk_runtimeeffect_t* effect); SK_C_API void sk_runtimeeffect_get_child_name(const sk_runtimeeffect_t* effect, int index, sk_string_t* name); // sk_runtimeeffect_uniform_t SK_C_API size_t sk_runtimeeffect_uniform_get_offset(const sk_runtimeeffect_uniform_t* variable); SK_C_API size_t sk_runtimeeffect_uniform_get_size_in_bytes(const sk_runtimeeffect_uniform_t* variable); SK_C_PLUS_PLUS_END_GUARD #endif
50.324324
190
0.85768
d8fcb947053048f9eb141366d6cecc00ce4475a0
5,516
h
C
parser/Parser.h
rlannon/SINx86
b94b5bbcc516cd2fa17c7093e4c6e0f391265063
[ "MIT" ]
null
null
null
parser/Parser.h
rlannon/SINx86
b94b5bbcc516cd2fa17c7093e4c6e0f391265063
[ "MIT" ]
16
2020-01-10T16:46:02.000Z
2021-04-11T22:35:01.000Z
parser/Parser.h
rlannon/SINx86
b94b5bbcc516cd2fa17c7093e4c6e0f391265063
[ "MIT" ]
null
null
null
/* SIN Toolchain Parser.h Copyright 2019 Riley Lannon The definition of the Parser class, which is responsible for taking a list of tokens generated by the Lexer and generating a parse tree. Note that: - Parser.cpp contains the implementation of some of our general/utility functions - ParseStatement.cpp contains the implementation of the statement parsing functions - ParseExpression.cpp contains the implementation of the expression parsing functions, such as parse_expression and maybe_binary */ #pragma once #include <iostream> #include <fstream> #include <memory> #include <vector> #include <string> #include <tuple> #include <unordered_map> #include "type_deduction.h" #include "Statement.h" #include "Expression.h" #include "Lexer.h" #include "../util/Exceptions.h" // ParserException #include "../util/DataType.h" // type information #include "../util/general_utilities.h" #include "../util/EnumeratedTypes.h" class Parser { // token trackers std::vector<lexeme> tokens; size_t position; size_t num_tokens; // the name of the file being parsed std::string filename; // Sentinel variable bool quit; // translates an operator character into an exp_operator type static exp_operator translate_operator(std::string op_string); // given the string name for an exp_operator, returns that exp_operator static bool is_valid_copy_assignment_operator(exp_operator op); static bool is_valid_move_assignment_operator(exp_operator op); exp_operator read_operator(bool peek); // our operator and precedence handlers static const std::unordered_map<exp_operator, size_t> op_precedence; // todo: create operator class static size_t get_precedence(std::string symbol, size_t line = 0); static size_t get_precedence(exp_operator op, size_t line = 0); // Some utility functions bool is_at_end(); // tells us whether we have run out of tokens lexeme peek(); // get next token without moving the position lexeme next(); // get next token lexeme current_token(); // get token at current position lexeme previous(); // similar to peek; get previous token without moving back lexeme back(); // move backward one void skipPunc(char punc); // skips the specified punctuation mark static bool is_type(std::string lex_value); static std::string get_closing_grouping_symbol(std::string beginning_symbol); static bool is_opening_grouping_symbol(std::string to_test); static bool has_return(StatementBlock to_test); static exp_operator get_unary_operator(std::string s); // located in ParserUtil.cpp static bool is_valid_operator(lexeme l); // get the appropriate SymbolQuality member from the lexeme containing it static SymbolQuality get_quality(lexeme quality_token); // we have to fetch a type (and its qualities) more than once; use a tuple for this DataType get_type(std::string grouping_symbol = ""); DataType parse_subtype(std::string grouping_symbol = ""); symbol_qualities get_prefix_qualities(std::string grouping_symbol = ""); symbol_qualities get_postfix_qualities(std::string grouping_symbol=""); // symbol qualities can be placed after an allocation using the & operator // A utility function to give a calling convention from symbol qualities static calling_convention get_calling_convention(symbol_qualities sq, unsigned int line); // Parsing statements -- each statement type will use its own function to return a statement of that type std::unique_ptr<Statement> parse_statement(const bool is_function_parameter = false); // entry function to parse a statement std::unique_ptr<Statement> parse_include(lexeme current_lex); std::unique_ptr<Statement> parse_declaration(lexeme current_lex, bool is_function_parameter = false); std::unique_ptr<Statement> parse_ite(lexeme current_lex); std::unique_ptr<Statement> parse_allocation(lexeme current_lex, bool is_function_parameter = false); std::unique_ptr<Statement> parse_assignment(lexeme current_lex); std::unique_ptr<Statement> parse_move(lexeme current_lex); std::unique_ptr<Statement> parse_return(lexeme current_lex); std::unique_ptr<Statement> parse_while(lexeme current_lex); // We have a few different types of definitions we could parse; delegate std::unique_ptr<Statement> parse_definition(lexeme current_lex); std::unique_ptr<Statement> parse_function_definition(lexeme current_lex); std::unique_ptr<Statement> parse_struct_definition(lexeme current_lex); std::unique_ptr<Statement> parse_function_call(lexeme current_lex); // Parsing expressions /* put default argument here because we call "parse_expression" in "maybe_binary"; as a reuslt, "his_prec" appears as if it is being passed to the next maybe_binary, but isn't because we parse an expression before we parse the binary, meaning my_prec gets set to 0, and not to his_prec as it should Note we also have a 'not_binary' flag here; if the expression is indexed, we may not want to have a binary expression parsed */ std::unique_ptr<Expression> parse_expression( const size_t prec=0, std::string grouping_symbol = "(", bool not_binary = false, const bool omit_equals = false ); std::unique_ptr<Expression> maybe_binary( std::unique_ptr<Expression> left, const size_t my_prec, const std::string& grouping_symbol = "(", const bool omit_equals = false ); // check to see if we need to fashion a binary expression static exp_operator get_compound_arithmetic_op(const exp_operator op); public: // our entry function StatementBlock create_ast(); Parser(const std::string& filename); ~Parser(); };
41.787879
296
0.784627
fa11c87be04c6d52db010b023cbbf75303af1a87
4,406
h
C
3rd_party/physx3.4/Include/pvd/PxPvdSceneClient.h
THISISAGOODNAME/phsyxOpenGL
41564c07d6c86c71b711136cbe9d4ac8fe01204d
[ "MIT" ]
22
2017-05-06T18:08:48.000Z
2022-01-12T02:10:22.000Z
3rd_party/physx3.4/Include/pvd/PxPvdSceneClient.h
THISISAGOODNAME/phsyxOpenGL
41564c07d6c86c71b711136cbe9d4ac8fe01204d
[ "MIT" ]
136
2018-05-10T08:47:58.000Z
2018-06-15T09:38:10.000Z
3rd_party/physx3.4/Include/pvd/PxPvdSceneClient.h
THISISAGOODNAME/phsyxOpenGL
41564c07d6c86c71b711136cbe9d4ac8fe01204d
[ "MIT" ]
4
2020-12-16T16:23:00.000Z
2021-01-25T01:29:09.000Z
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PVD_SCENE_CLIENT_H #define PX_PVD_SCENE_CLIENT_H /** \addtogroup pvd @{ */ #include "foundation/PxFlags.h" namespace physx { namespace pvdsdk { class PvdClient; struct PvdDebugPoint; struct PvdDebugLine; struct PvdDebugTriangle; struct PvdDebugText; } } #if !PX_DOXYGEN namespace physx { #endif /** \brief PVD scene Flags. They are disabled by default, and only works if PxPvdInstrumentationFlag::eDEBUG is set. */ struct PxPvdSceneFlag { enum Enum { eTRANSMIT_CONTACTS = (1 << 0), //! Transmits contact stream to PVD. eTRANSMIT_SCENEQUERIES = (1 << 1), //! Transmits scene query stream to PVD. eTRANSMIT_CONSTRAINTS = (1 << 2) //! Transmits constraints visualize stream to PVD. }; }; /** \brief Bitfield that contains a set of raised flags defined in PxPvdSceneFlag. @see PxPvdSceneFlag */ typedef PxFlags<PxPvdSceneFlag::Enum, PxU8> PxPvdSceneFlags; PX_FLAGS_OPERATORS(PxPvdSceneFlag::Enum, PxU8) /** \brief Special client for PxScene. It provides access to the PxPvdSceneFlag. It also provides simple user debug services that associated scene position such as immediate rendering and camera updates. */ class PxPvdSceneClient { public: /** Sets the PVD flag. See PxPvdSceneFlag. \param flag Flag to set. \param value value the flag gets set to. */ virtual void setScenePvdFlag(PxPvdSceneFlag::Enum flag, bool value) = 0; /** Sets the PVD flags. See PxPvdSceneFlags. \param flags Flags to set. */ virtual void setScenePvdFlags(PxPvdSceneFlags flags) = 0; /** Retrieves the PVD flags. See PxPvdSceneFlags. */ virtual PxPvdSceneFlags getScenePvdFlags() const = 0; /** update camera on PVD application's DirectX render window */ virtual void updateCamera(const char* name, const PxVec3& origin, const PxVec3& up, const PxVec3& target) = 0; /** draw points on PVD application's DirectX render window */ virtual void drawPoints(const physx::pvdsdk::PvdDebugPoint* points, PxU32 count) = 0; /** draw lines on PVD application's DirectX render window */ virtual void drawLines(const physx::pvdsdk::PvdDebugLine* lines, PxU32 count) = 0; /** draw triangles on PVD application's DirectX render window */ virtual void drawTriangles(const physx::pvdsdk::PvdDebugTriangle* triangles, PxU32 count) = 0; /** draw text on PVD application's DirectX render window */ virtual void drawText(const physx::pvdsdk::PvdDebugText& text) = 0; /** get the underlying client, for advanced users */ virtual physx::pvdsdk::PvdClient* getClientInternal() = 0; protected: virtual ~PxPvdSceneClient(){} }; #if !PX_DOXYGEN } // namespace physx #endif /** @} */ #endif // PX_PVD_SCENE_CLIENT_H
30.811189
122
0.758511
36c33c7e3bc85c723586550affdac53154c2977c
7,479
h
C
libraries/nacl_sdk/pepper_49/toolchain/win_pnacl/include/clang/Frontend/CodeGenOptions.h
Enime-Project/mpv.js
5d80165419a043ac61c29567c58fcae6af3e1f1b
[ "CC0-1.0" ]
null
null
null
libraries/nacl_sdk/pepper_49/toolchain/win_pnacl/include/clang/Frontend/CodeGenOptions.h
Enime-Project/mpv.js
5d80165419a043ac61c29567c58fcae6af3e1f1b
[ "CC0-1.0" ]
null
null
null
libraries/nacl_sdk/pepper_49/toolchain/win_pnacl/include/clang/Frontend/CodeGenOptions.h
Enime-Project/mpv.js
5d80165419a043ac61c29567c58fcae6af3e1f1b
[ "CC0-1.0" ]
null
null
null
//===--- CodeGenOptions.h ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the CodeGenOptions interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_CODEGENOPTIONS_H #define LLVM_CLANG_FRONTEND_CODEGENOPTIONS_H #include "clang/Basic/Sanitizers.h" #include "llvm/Support/Regex.h" #include <memory> #include <string> #include <vector> namespace clang { /// \brief Bitfields of CodeGenOptions, split out from CodeGenOptions to ensure /// that this large collection of bitfields is a trivial class type. class CodeGenOptionsBase { public: #define CODEGENOPT(Name, Bits, Default) unsigned Name : Bits; #define ENUM_CODEGENOPT(Name, Type, Bits, Default) #include "clang/Frontend/CodeGenOptions.def" protected: #define CODEGENOPT(Name, Bits, Default) #define ENUM_CODEGENOPT(Name, Type, Bits, Default) unsigned Name : Bits; #include "clang/Frontend/CodeGenOptions.def" }; /// CodeGenOptions - Track various options which control how the code /// is optimized and passed to the backend. class CodeGenOptions : public CodeGenOptionsBase { public: enum InliningMethod { NoInlining, // Perform no inlining whatsoever. NormalInlining, // Use the standard function inlining pass. OnlyAlwaysInlining // Only run the always inlining pass. }; enum VectorLibrary { NoLibrary, // Don't use any vector library. Accelerate // Use the Accelerate framework. }; enum ObjCDispatchMethodKind { Legacy = 0, NonLegacy = 1, Mixed = 2 }; enum DebugInfoKind { NoDebugInfo, /// Don't generate debug info. LocTrackingOnly, /// Emit location information but do not generate /// debug info in the output. This is useful in /// cases where the backend wants to track source /// locations for instructions without actually /// emitting debug info for them (e.g., when -Rpass /// is used). DebugLineTablesOnly, /// Emit only debug info necessary for generating /// line number tables (-gline-tables-only). LimitedDebugInfo, /// Limit generated debug info to reduce size /// (-fno-standalone-debug). This emits /// forward decls for types that could be /// replaced with forward decls in the source /// code. For dynamic C++ classes type info /// is only emitted int the module that /// contains the classe's vtable. FullDebugInfo /// Generate complete debug info. }; enum TLSModel { GeneralDynamicTLSModel, LocalDynamicTLSModel, InitialExecTLSModel, LocalExecTLSModel }; enum FPContractModeKind { FPC_Off, // Form fused FP ops only where result will not be affected. FPC_On, // Form fused FP ops according to FP_CONTRACT rules. FPC_Fast // Aggressively fuse FP ops (E.g. FMA). }; enum StructReturnConventionKind { SRCK_Default, // No special option was passed. SRCK_OnStack, // Small structs on the stack (-fpcc-struct-return). SRCK_InRegs // Small structs in registers (-freg-struct-return). }; /// The code model to use (-mcmodel). std::string CodeModel; /// The filename with path we use for coverage files. The extension will be /// replaced. std::string CoverageFile; /// The version string to put into coverage files. char CoverageVersion[4]; /// Enable additional debugging information. std::string DebugPass; /// The string to embed in debug information as the current working directory. std::string DebugCompilationDir; /// The string to embed in the debug information for the compile unit, if /// non-empty. std::string DwarfDebugFlags; /// The ABI to use for passing floating point arguments. std::string FloatABI; /// The float precision limit to use, if non-empty. std::string LimitFloatPrecision; /// The name of the bitcode file to link before optzns. std::string LinkBitcodeFile; /// The user provided name for the "main file", if non-empty. This is useful /// in situations where the input file name does not match the original input /// file, for example with -save-temps. std::string MainFileName; /// The name for the split debug info file that we'll break out. This is used /// in the backend for setting the name in the skeleton cu. std::string SplitDwarfFile; /// The name of the relocation model to use. std::string RelocationModel; /// The thread model to use std::string ThreadModel; /// If not an empty string, trap intrinsics are lowered to calls to this /// function instead of to trap instructions. std::string TrapFuncName; /// A list of command-line options to forward to the LLVM backend. std::vector<std::string> BackendOptions; /// A list of dependent libraries. std::vector<std::string> DependentLibraries; /// Name of the profile file to use with -fprofile-sample-use. std::string SampleProfileFile; /// Name of the profile file to use as input for -fprofile-instr-use std::string InstrProfileInput; /// Regular expression to select optimizations for which we should enable /// optimization remarks. Transformation passes whose name matches this /// expression (and support this feature), will emit a diagnostic /// whenever they perform a transformation. This is enabled by the /// -Rpass=regexp flag. std::shared_ptr<llvm::Regex> OptimizationRemarkPattern; /// Regular expression to select optimizations for which we should enable /// missed optimization remarks. Transformation passes whose name matches this /// expression (and support this feature), will emit a diagnostic /// whenever they tried but failed to perform a transformation. This is /// enabled by the -Rpass-missed=regexp flag. std::shared_ptr<llvm::Regex> OptimizationRemarkMissedPattern; /// Regular expression to select optimizations for which we should enable /// optimization analyses. Transformation passes whose name matches this /// expression (and support this feature), will emit a diagnostic /// whenever they want to explain why they decided to apply or not apply /// a given transformation. This is enabled by the -Rpass-analysis=regexp /// flag. std::shared_ptr<llvm::Regex> OptimizationRemarkAnalysisPattern; /// Set of files definining the rules for the symbol rewriting. std::vector<std::string> RewriteMapFiles; /// Set of sanitizer checks that are non-fatal (i.e. execution should be /// continued when possible). SanitizerSet SanitizeRecover; public: // Define accessors/mutators for code generation options of enumeration type. #define CODEGENOPT(Name, Bits, Default) #define ENUM_CODEGENOPT(Name, Type, Bits, Default) \ Type get##Name() const { return static_cast<Type>(Name); } \ void set##Name(Type Value) { Name = static_cast<unsigned>(Value); } #include "clang/Frontend/CodeGenOptions.def" CodeGenOptions(); }; } // end namespace clang #endif
36.305825
80
0.67255
36cd7dd08a7ce6303653f18c71208b652eae8fee
541
h
C
agent/mibgroup/host/hr_filesys.h
jridky/net-snmp
1bb941d6fcd7ac2db5a54b95ee0ed07ec9861e70
[ "Net-SNMP" ]
3
2019-10-02T01:43:05.000Z
2021-12-18T23:32:41.000Z
agent/mibgroup/host/hr_filesys.h
jridky/net-snmp
1bb941d6fcd7ac2db5a54b95ee0ed07ec9861e70
[ "Net-SNMP" ]
null
null
null
agent/mibgroup/host/hr_filesys.h
jridky/net-snmp
1bb941d6fcd7ac2db5a54b95ee0ed07ec9861e70
[ "Net-SNMP" ]
null
null
null
/* * Host Resources MIB - file system device group interface - hr_filesys.h * */ #ifndef _MIBGROUP_HRFSYS_H #define _MIBGROUP_HRFSYS_H extern void init_hr_filesys(void); extern void Init_HR_FileSys(void); extern FindVarMethod var_hrfilesys; extern int Get_Next_HR_FileSys(void); extern int Check_HR_FileSys_NFS(void); extern int Check_HR_FileSys_AutoFs(void); extern int Get_FSIndex(char *); extern long Get_FSSize(char *); /* Temporary */ #endif /* _MIBGROUP_HRFSYS_H */
27.05
74
0.695009
9adc17936c4aee13b5dbac6bd59e03db1ec52426
913
c
C
blpv3e/client1.c
yuweijun/books
5be0fec3adce236875fef0f9e1ed8d91ef4acbfe
[ "MIT" ]
1
2018-07-02T12:03:02.000Z
2018-07-02T12:03:02.000Z
blpv3e/client1.c
yuweijun/books
5be0fec3adce236875fef0f9e1ed8d91ef4acbfe
[ "MIT" ]
null
null
null
blpv3e/client1.c
yuweijun/books
5be0fec3adce236875fef0f9e1ed8d91ef4acbfe
[ "MIT" ]
null
null
null
/* Make the necessary includes and set up the variables. */ #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <sys/un.h> #include <unistd.h> int main() { int sockfd; int len; struct sockaddr_un address; int result; char ch = 'A'; /* Create a socket for the client. */ sockfd = socket(AF_UNIX, SOCK_STREAM, 0); /* Name the socket, as agreed with the server. */ address.sun_family = AF_UNIX; strcpy(address.sun_path, "server_socket"); len = sizeof(address); /* Now connect our socket to the server's socket. */ result = connect(sockfd, (struct sockaddr*)&address, len); if (result == -1) { perror("oops: client1"); exit(1); } /* We can now read/write via sockfd. */ write(sockfd, &ch, 1); read(sockfd, &ch, 1); printf("char from server = %c\n", ch); close(sockfd); exit(0); }
25.361111
62
0.599124
2c795e15548eeec8d7cf02707dfcb83e4ddec64e
3,692
h
C
chromium/third_party/WebKit/Source/core/css/StyleRuleImport.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/core/css/StyleRuleImport.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/core/css/StyleRuleImport.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
/* * (C) 1999-2003 Lars Knoll (knoll@kde.org) * (C) 2002-2003 Dirk Mueller (mueller@kde.org) * Copyright (C) 2002, 2006, 2008, 2012 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef StyleRuleImport_h #define StyleRuleImport_h #include "core/css/StyleRule.h" #include "core/fetch/ResourcePtr.h" #include "core/fetch/StyleSheetResourceClient.h" #include "platform/heap/Handle.h" namespace blink { class CSSStyleSheetResource; class MediaQuerySet; class StyleSheetContents; class StyleRuleImport : public StyleRuleBase { USING_FAST_MALLOC_WILL_BE_REMOVED(StyleRuleImport); public: static PassRefPtrWillBeRawPtr<StyleRuleImport> create(const String& href, PassRefPtrWillBeRawPtr<MediaQuerySet>); ~StyleRuleImport(); StyleSheetContents* parentStyleSheet() const { return m_parentStyleSheet; } void setParentStyleSheet(StyleSheetContents* sheet) { ASSERT(sheet); m_parentStyleSheet = sheet; } void clearParentStyleSheet() { m_parentStyleSheet = nullptr; } String href() const { return m_strHref; } StyleSheetContents* styleSheet() const { return m_styleSheet.get(); } bool isLoading() const; MediaQuerySet* mediaQueries() { return m_mediaQueries.get(); } void requestStyleSheet(); DECLARE_TRACE_AFTER_DISPATCH(); private: // FIXME: inherit from StyleSheetResourceClient directly to eliminate raw back pointer, as there are no space savings in this. // NOTE: We put the StyleSheetResourceClient in a member instead of inheriting from it // to avoid adding a vptr to StyleRuleImport. class ImportedStyleSheetClient final : public StyleSheetResourceClient { DISALLOW_NEW(); public: ImportedStyleSheetClient(StyleRuleImport* ownerRule) : m_ownerRule(ownerRule) { } ~ImportedStyleSheetClient() override { } void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* sheet) override { m_ownerRule->setCSSStyleSheet(href, baseURL, charset, sheet); } String debugName() const override { return "ImportedStyleSheetClient"; } DEFINE_INLINE_TRACE() { visitor->trace(m_ownerRule); } private: RawPtrWillBeMember<StyleRuleImport> m_ownerRule; }; void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*); friend class ImportedStyleSheetClient; StyleRuleImport(const String& href, PassRefPtrWillBeRawPtr<MediaQuerySet>); RawPtrWillBeMember<StyleSheetContents> m_parentStyleSheet; ImportedStyleSheetClient m_styleSheetClient; String m_strHref; RefPtrWillBeMember<MediaQuerySet> m_mediaQueries; RefPtrWillBeMember<StyleSheetContents> m_styleSheet; ResourcePtr<CSSStyleSheetResource> m_resource; bool m_loading; }; DEFINE_STYLE_RULE_TYPE_CASTS(Import); } // namespace blink #endif
36.554455
138
0.746208
829095bc3a4e4cf2564ae662b3f73c4c464b7206
10,631
h
C
src/net/base/ip_address.h
godfo/naiveproxy
369269a12832bf34bf01c7b0e7ca121555abd3eb
[ "BSD-3-Clause" ]
1
2021-03-21T10:43:16.000Z
2021-03-21T10:43:16.000Z
src/net/base/ip_address.h
wclmgcd/naiveproxy
e32a3afb76fd21207c322f2d5e794c4f5505fb59
[ "BSD-3-Clause" ]
null
null
null
src/net/base/ip_address.h
wclmgcd/naiveproxy
e32a3afb76fd21207c322f2d5e794c4f5505fb59
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_BASE_IP_ADDRESS_H_ #define NET_BASE_IP_ADDRESS_H_ #include <stddef.h> #include <stdint.h> #include <array> #include <string> #include <vector> #include "base/compiler_specific.h" #include "base/strings/string_piece.h" #include "net/base/net_export.h" namespace net { // Helper class to represent the sequence of bytes in an IP address. // A vector<uint8_t> would be simpler but incurs heap allocation, so // IPAddressBytes uses a fixed size array. class NET_EXPORT IPAddressBytes { public: IPAddressBytes(); IPAddressBytes(const uint8_t* data, size_t data_len); IPAddressBytes(const IPAddressBytes& other); ~IPAddressBytes(); // Copies |data_len| elements from |data| into this object. void Assign(const uint8_t* data, size_t data_len); // Returns the number of elements in the underlying array. size_t size() const { return size_; } // Sets the size to be |size|. Does not actually change the size // of the underlying array or zero-initialize the bytes. void Resize(size_t size) { DCHECK_LE(size, 16u); size_ = static_cast<uint8_t>(size); } // Returns true if the underlying array is empty. bool empty() const { return size_ == 0; } // Returns a pointer to the underlying array of bytes. const uint8_t* data() const { return bytes_.data(); } uint8_t* data() { return bytes_.data(); } // Returns a pointer to the first element. const uint8_t* begin() const { return data(); } uint8_t* begin() { return data(); } // Returns a pointer past the last element. const uint8_t* end() const { return data() + size_; } uint8_t* end() { return data() + size_; } // Returns a reference to the last element. uint8_t& back() { DCHECK(!empty()); return bytes_[size_ - 1]; } const uint8_t& back() const { DCHECK(!empty()); return bytes_[size_ - 1]; } // Appends |val| to the end and increments the size. void push_back(uint8_t val) { DCHECK_GT(16, size_); bytes_[size_++] = val; } // Returns a reference to the byte at index |pos|. uint8_t& operator[](size_t pos) { DCHECK_LT(pos, size_); return bytes_[pos]; } const uint8_t& operator[](size_t pos) const { DCHECK_LT(pos, size_); return bytes_[pos]; } bool operator<(const IPAddressBytes& other) const; bool operator!=(const IPAddressBytes& other) const; bool operator==(const IPAddressBytes& other) const; private: // Underlying sequence of bytes std::array<uint8_t, 16> bytes_; // Number of elements in |bytes_|. Should be either kIPv4AddressSize // or kIPv6AddressSize or 0. uint8_t size_; }; class NET_EXPORT IPAddress { public: enum : size_t { kIPv4AddressSize = 4, kIPv6AddressSize = 16 }; // Creates a zero-sized, invalid address. IPAddress(); IPAddress(const IPAddress& other); // Copies the input address to |ip_address_|. explicit IPAddress(const IPAddressBytes& address); // Copies the input address to |ip_address_|. The input is expected to be in // network byte order. template <size_t N> IPAddress(const uint8_t(&address)[N]) : IPAddress(address, N) {} // Copies the input address to |ip_address_| taking an additional length // parameter. The input is expected to be in network byte order. IPAddress(const uint8_t* address, size_t address_len); // Initializes |ip_address_| from the 4 bX bytes to form an IPv4 address. // The bytes are expected to be in network byte order. IPAddress(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3); // Initializes |ip_address_| from the 16 bX bytes to form an IPv6 address. // The bytes are expected to be in network byte order. IPAddress(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4, uint8_t b5, uint8_t b6, uint8_t b7, uint8_t b8, uint8_t b9, uint8_t b10, uint8_t b11, uint8_t b12, uint8_t b13, uint8_t b14, uint8_t b15); ~IPAddress(); // Returns true if the IP has |kIPv4AddressSize| elements. bool IsIPv4() const; // Returns true if the IP has |kIPv6AddressSize| elements. bool IsIPv6() const; // Returns true if the IP is either an IPv4 or IPv6 address. This function // only checks the address length. bool IsValid() const; // Returns true if the IP is not in a range reserved by the IANA for // local networks. Works with both IPv4 and IPv6 addresses. // IPv4-mapped-to-IPv6 addresses are considered publicly routable. bool IsPubliclyRoutable() const; // Returns true if the IP is "zero" (e.g. the 0.0.0.0 IPv4 address). bool IsZero() const; // Returns true if |ip_address_| is an IPv4-mapped IPv6 address. bool IsIPv4MappedIPv6() const; // Returns true if |ip_address_| is 127.0.0.1/8 or ::1/128 bool IsLoopback() const; // Returns true if |ip_address_| is 169.254.0.0/16 or fe80::/10, or // ::ffff:169.254.0.0/112 (IPv4 mapped IPv6 link-local). bool IsLinkLocal() const; // The size in bytes of |ip_address_|. size_t size() const { return ip_address_.size(); } // Returns true if the IP is an empty, zero-sized (invalid) address. bool empty() const { return ip_address_.empty(); } // Returns the canonical string representation of an IP address. // For example: "192.168.0.1" or "::1". Returns the empty string when // |ip_address_| is invalid. std::string ToString() const; // Parses an IP address literal (either IPv4 or IPv6) to its numeric value. // Returns true on success and fills |ip_address_| with the numeric value. // // When parsing fails, the original value of |this| will be overwritten such // that |this->empty()| and |!this->IsValid()|. bool AssignFromIPLiteral(const base::StringPiece& ip_literal) WARN_UNUSED_RESULT; // Returns the underlying bytes. const IPAddressBytes& bytes() const { return ip_address_; } // Copies the bytes to a new vector. Generally callers should be using // |bytes()| and the IPAddressBytes abstraction. This method is provided as a // convenience for call sites that existed prior to the introduction of // IPAddressBytes. std::vector<uint8_t> CopyBytesToVector() const; // Returns an IPAddress instance representing the 127.0.0.1 address. static IPAddress IPv4Localhost(); // Returns an IPAddress instance representing the ::1 address. static IPAddress IPv6Localhost(); // Returns an IPAddress made up of |num_zero_bytes| zeros. static IPAddress AllZeros(size_t num_zero_bytes); // Returns an IPAddress instance representing the 0.0.0.0 address. static IPAddress IPv4AllZeros(); // Returns an IPAddress instance representing the :: address. static IPAddress IPv6AllZeros(); bool operator==(const IPAddress& that) const; bool operator!=(const IPAddress& that) const; bool operator<(const IPAddress& that) const; private: IPAddressBytes ip_address_; // This class is copyable and assignable. }; using IPAddressList = std::vector<IPAddress>; // Returns the canonical string representation of an IP address along with its // port. For example: "192.168.0.1:99" or "[::1]:80". NET_EXPORT std::string IPAddressToStringWithPort(const IPAddress& address, uint16_t port); // Returns the address as a sequence of bytes in network-byte-order. NET_EXPORT std::string IPAddressToPackedString(const IPAddress& address); // Converts an IPv4 address to an IPv4-mapped IPv6 address. // For example 192.168.0.1 would be converted to ::ffff:192.168.0.1. NET_EXPORT IPAddress ConvertIPv4ToIPv4MappedIPv6(const IPAddress& address); // Converts an IPv4-mapped IPv6 address to IPv4 address. Should only be called // on IPv4-mapped IPv6 addresses. NET_EXPORT IPAddress ConvertIPv4MappedIPv6ToIPv4(const IPAddress& address); // Compares an IP address to see if it falls within the specified IP block. // Returns true if it does, false otherwise. // // The IP block is given by (|ip_prefix|, |prefix_length_in_bits|) -- any // IP address whose |prefix_length_in_bits| most significant bits match // |ip_prefix| will be matched. // // In cases when an IPv4 address is being compared to an IPv6 address prefix // and vice versa, the IPv4 addresses will be converted to IPv4-mapped // (IPv6) addresses. NET_EXPORT bool IPAddressMatchesPrefix(const IPAddress& ip_address, const IPAddress& ip_prefix, size_t prefix_length_in_bits); // Parses an IP block specifier from CIDR notation to an // (IP address, prefix length) pair. Returns true on success and fills // |*ip_address| with the numeric value of the IP address and sets // |*prefix_length_in_bits| with the length of the prefix. On failure, // |ip_address| will be cleared to an empty value. // // CIDR notation literals can use either IPv4 or IPv6 literals. Some examples: // // 10.10.3.1/20 // a:b:c::/46 // ::1/128 NET_EXPORT bool ParseCIDRBlock(const std::string& cidr_literal, IPAddress* ip_address, size_t* prefix_length_in_bits); // Parses a URL-safe IP literal (see RFC 3986, Sec 3.2.2) to its numeric value. // Returns true on success, and fills |ip_address| with the numeric value. // In other words, |hostname| must be an IPv4 literal, or an IPv6 literal // surrounded by brackets as in [::1]. On failure |ip_address| may have been // overwritten and could contain an invalid IPAddress. NET_EXPORT bool ParseURLHostnameToAddress(const base::StringPiece& hostname, IPAddress* ip_address) WARN_UNUSED_RESULT; // Returns number of matching initial bits between the addresses |a1| and |a2|. NET_EXPORT size_t CommonPrefixLength(const IPAddress& a1, const IPAddress& a2); // Computes the number of leading 1-bits in |mask|. NET_EXPORT size_t MaskPrefixLength(const IPAddress& mask); // Checks whether |address| starts with |prefix|. This provides similar // functionality as IPAddressMatchesPrefix() but doesn't perform automatic IPv4 // to IPv4MappedIPv6 conversions and only checks against full bytes. template <size_t N> bool IPAddressStartsWith(const IPAddress& address, const uint8_t (&prefix)[N]) { if (address.size() < N) return false; return std::equal(prefix, prefix + N, address.bytes().begin()); } } // namespace net #endif // NET_BASE_IP_ADDRESS_H_
35.318937
80
0.697959
82f59929c88504c122148a9870e683a8784f2202
57,933
c
C
src/http.c
kncofficial/kore
dcb34033fae65a43eb28404c6c1698d459444b89
[ "ISC" ]
null
null
null
src/http.c
kncofficial/kore
dcb34033fae65a43eb28404c6c1698d459444b89
[ "ISC" ]
null
null
null
src/http.c
kncofficial/kore
dcb34033fae65a43eb28404c6c1698d459444b89
[ "ISC" ]
1
2020-08-20T18:15:03.000Z
2020-08-20T18:15:03.000Z
/* * Copyright (c) 2013-2020 Joris Vink <joris@coders.se> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/param.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <ctype.h> #include <fcntl.h> #include <inttypes.h> #include <float.h> #include <time.h> #include <stdio.h> #include <string.h> #include "kore.h" #include "http.h" #if defined(KORE_USE_PYTHON) #include "python_api.h" #endif #if defined(KORE_USE_PGSQL) #include "pgsql.h" #endif #if defined(KORE_USE_TASKS) #include "tasks.h" #endif #if defined(KORE_USE_CURL) #include "curl.h" #endif static struct { const char *ext; const char *type; } builtin_media[] = { { "gif", "image/gif" }, { "png", "image/png" }, { "jpeg", "image/jpeg" }, { "jpg", "image/jpeg" }, { "zip", "application/zip" }, { "pdf", "application/pdf" }, { "json", "application/json" }, { "js", "application/javascript" }, { "htm", "text/html" }, { "txt", "text/plain" }, { "css", "text/css" }, { "html", "text/html" }, { NULL, NULL }, }; #define HTTP_MAP_LIMIT 127 /* * token = 1*<any CHAR except CTLs or separators> * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ static const char http_token[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, '!' , 0x00, '#' , '$' , '%' , '&' , '\'', 0x00, 0x00, '*' , '+' , 0x00, '-' , '.' , 0x00, '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' , 0x00, 0x00, 0x00, '^' , '_' , '`' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' , 0x00, '|' , 0x00, '~' , 0x00 }; /* * field-content = <the OCTETs making up the field-value * and consisting of either *TEXT or combinations * of token, separators, and quoted-string> */ static const char http_field_content[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ' ' , '!' , '"' , '#' , '$' , '%' , '&' , '\'', '(' , ')' , '*' , '+' , ',' , '-' , '.' , '/' , '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , ':' , ';' , '<' , '=' , '>' , '?' , '@' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' , '[' , '\\', ']' , '^' , '_' , '`' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' , '{' , '|' , '}' , '~' , 0x00 }; /* * Fixed "pretty" HTTP error HTML page. */ static const char *pretty_error_fmt = "<html>\n<head>\n\t<title>%d %s</title>" "</head>\n<body>\n\t" "<h1>%d %s</h1>\n" "</body>\n</html>\n"; static int http_body_recv(struct netbuf *); static void http_error_response(struct connection *, int); static void http_write_response_cookie(struct http_cookie *); static void http_argument_add(struct http_request *, char *, char *, int, int); static int http_check_redirect(struct http_request *, struct kore_domain *); static void http_response_normal(struct http_request *, struct connection *, int, const void *, size_t); static void multipart_add_field(struct http_request *, struct kore_buf *, char *, const char *, const int); static void multipart_file_add(struct http_request *, struct kore_buf *, const char *, const char *, const char *, const int); static int multipart_find_data(struct kore_buf *, struct kore_buf *, size_t *, struct http_request *, const void *, size_t); static int multipart_parse_headers(struct http_request *, struct kore_buf *, struct kore_buf *, const char *, const int); static struct http_request *http_request_new(struct connection *, const char *, const char *, char *, const char *); static struct kore_buf *header_buf; static struct kore_buf *ckhdr_buf; static char http_version[64]; static u_int16_t http_version_len; static TAILQ_HEAD(, http_request) http_requests; static TAILQ_HEAD(, http_request) http_requests_sleeping; static LIST_HEAD(, http_media_type) http_media_types; static struct kore_pool http_request_pool; static struct kore_pool http_cookie_pool; static struct kore_pool http_body_path; static struct kore_pool http_rlq_pool; struct kore_pool http_header_pool; int http_pretty_error = 0; u_int32_t http_request_count = 0; u_int32_t http_request_ms = HTTP_REQUEST_MS; u_int16_t http_body_timeout = HTTP_BODY_TIMEOUT; u_int32_t http_request_limit = HTTP_REQUEST_LIMIT; u_int64_t http_hsts_enable = HTTP_HSTS_ENABLE; u_int16_t http_header_max = HTTP_HEADER_MAX_LEN; u_int16_t http_keepalive_time = HTTP_KEEPALIVE_TIME; u_int16_t http_header_timeout = HTTP_HEADER_TIMEOUT; size_t http_body_max = HTTP_BODY_MAX_LEN; char *http_body_disk_path = HTTP_BODY_DISK_PATH; u_int64_t http_body_disk_offload = HTTP_BODY_DISK_OFFLOAD; void http_parent_init(void) { LIST_INIT(&http_media_types); } void http_init(void) { int prealloc, l, i; TAILQ_INIT(&http_requests); TAILQ_INIT(&http_requests_sleeping); header_buf = kore_buf_alloc(HTTP_HEADER_BUFSIZE); ckhdr_buf = kore_buf_alloc(HTTP_COOKIE_BUFSIZE); if (!http_version_len) { l = snprintf(http_version, sizeof(http_version), "server: kore (%s)\r\n", kore_version); if (l == -1 || (size_t)l >= sizeof(http_version)) fatal("http_init(): http_version buffer too small"); http_version_len = l; } prealloc = MIN((worker_max_connections / 10), 1000); kore_pool_init(&http_request_pool, "http_request_pool", sizeof(struct http_request), http_request_limit); kore_pool_init(&http_header_pool, "http_header_pool", sizeof(struct http_header), prealloc * HTTP_REQ_HEADER_MAX); kore_pool_init(&http_cookie_pool, "http_cookie_pool", sizeof(struct http_cookie), prealloc * HTTP_MAX_COOKIES); kore_pool_init(&http_rlq_pool, "http_rlq_pool", sizeof(struct http_runlock_queue), http_request_limit); kore_pool_init(&http_body_path, "http_body_path", HTTP_BODY_PATH_MAX, prealloc); for (i = 0; builtin_media[i].ext != NULL; i++) { if (!http_media_register(builtin_media[i].ext, builtin_media[i].type)) { fatal("duplicate media type for %s", builtin_media[i].ext); } } } void http_cleanup(void) { if (header_buf != NULL) { kore_buf_free(header_buf); header_buf = NULL; } if (ckhdr_buf != NULL) { kore_buf_free(ckhdr_buf); ckhdr_buf = NULL; } kore_pool_cleanup(&http_request_pool); kore_pool_cleanup(&http_header_pool); kore_pool_cleanup(&http_body_path); } void http_server_version(const char *version) { int l; l = snprintf(http_version, sizeof(http_version), "server: %s\r\n", version); if (l == -1 || (size_t)l >= sizeof(http_version)) fatal("http_server_version(): http_version buffer too small"); http_version_len = l; } int http_check_timeout(struct connection *c, u_int64_t now) { u_int64_t d; if (c->http_timeout == 0) return (KORE_RESULT_OK); if (now > c->http_start) d = now - c->http_start; else d = 0; if (d >= c->http_timeout) { http_error_response(c, 408); kore_connection_disconnect(c); return (KORE_RESULT_ERROR); } return (KORE_RESULT_OK); } void http_request_sleep(struct http_request *req) { if (!(req->flags & HTTP_REQUEST_SLEEPING)) { kore_debug("http_request_sleep: %p napping", req); req->flags |= HTTP_REQUEST_SLEEPING; TAILQ_REMOVE(&http_requests, req, list); TAILQ_INSERT_TAIL(&http_requests_sleeping, req, list); } } void http_request_wakeup(struct http_request *req) { if (req->flags & HTTP_REQUEST_SLEEPING) { kore_debug("http_request_wakeup: %p woke up", req); req->flags &= ~HTTP_REQUEST_SLEEPING; TAILQ_REMOVE(&http_requests_sleeping, req, list); TAILQ_INSERT_TAIL(&http_requests, req, list); } } void http_process(void) { u_int64_t total; struct http_request *req, *next; total = 0; for (req = TAILQ_FIRST(&http_requests); req != NULL; req = next) { if (total >= http_request_ms) break; next = TAILQ_NEXT(req, list); if (req->flags & HTTP_REQUEST_DELETE) { http_request_free(req); continue; } /* Sleeping requests should be in http_requests_sleeping. */ if (req->flags & HTTP_REQUEST_SLEEPING) fatal("http_process: sleeping request on list"); if (!(req->flags & HTTP_REQUEST_COMPLETE)) continue; http_process_request(req); total += req->ms; if (req->flags & HTTP_REQUEST_DELETE) http_request_free(req); } } void http_process_request(struct http_request *req) { int r; kore_debug("http_process_request: %p->%p (%s)", req->owner, req, req->path); if (req->flags & HTTP_REQUEST_DELETE || req->hdlr == NULL) return; req->start = kore_time_ms(); if (req->hdlr->auth != NULL && !(req->flags & HTTP_REQUEST_AUTHED)) r = kore_auth_run(req, req->hdlr->auth); else r = KORE_RESULT_OK; switch (r) { case KORE_RESULT_OK: r = kore_runtime_http_request(req->hdlr->rcall, req); break; case KORE_RESULT_RETRY: break; case KORE_RESULT_ERROR: /* * Set r to KORE_RESULT_OK so we can properly * flush the result from kore_auth_run(). */ r = KORE_RESULT_OK; break; default: fatal("kore_auth() returned unknown %d", r); } req->end = kore_time_ms(); req->ms = req->end - req->start; req->total += req->ms; switch (r) { case KORE_RESULT_OK: r = net_send_flush(req->owner); if (r == KORE_RESULT_ERROR) kore_connection_disconnect(req->owner); break; case KORE_RESULT_ERROR: kore_connection_disconnect(req->owner); break; case KORE_RESULT_RETRY: return; default: fatal("A page handler returned an unknown result: %d", r); } if (req->hdlr->dom->accesslog) kore_accesslog(req); req->flags |= HTTP_REQUEST_DELETE; } void http_response_header(struct http_request *req, const char *header, const char *value) { struct http_header *hdr; kore_debug("http_response_header(%p, %s, %s)", req, header, value); hdr = kore_pool_get(&http_header_pool); hdr->header = kore_strdup(header); hdr->value = kore_strdup(value); TAILQ_INSERT_TAIL(&(req->resp_headers), hdr, list); } void http_request_free(struct http_request *req) { #if defined(KORE_USE_TASKS) struct kore_task *t, *nt; int pending_tasks; #endif #if defined(KORE_USE_PGSQL) struct kore_pgsql *pgsql; #endif #if defined(KORE_USE_CURL) struct kore_curl *client; #endif struct http_file *f, *fnext; struct http_arg *q, *qnext; struct http_header *hdr, *next; struct http_cookie *ck, *cknext; if (req->onfree != NULL) req->onfree(req); if (req->runlock != NULL) { LIST_REMOVE(req->runlock, list); req->runlock = NULL; } #if defined(KORE_USE_TASKS) pending_tasks = 0; for (t = LIST_FIRST(&(req->tasks)); t != NULL; t = nt) { nt = LIST_NEXT(t, rlist); if (!kore_task_finished(t)) { pending_tasks++; } else { kore_task_destroy(t); } } if (pending_tasks) { kore_debug("http_request_free %d pending tasks", pending_tasks); return; } #endif #if defined(KORE_USE_PYTHON) if (req->py_coro != NULL) { kore_python_coro_delete(req->py_coro); req->py_coro = NULL; } if (req->py_validator != NULL) { kore_python_coro_delete(req->py_validator); req->py_validator = NULL; } Py_XDECREF(req->py_req); #endif #if defined(KORE_USE_PGSQL) while (!LIST_EMPTY(&(req->pgsqls))) { pgsql = LIST_FIRST(&(req->pgsqls)); kore_pgsql_cleanup(pgsql); } #endif #if defined(KORE_USE_CURL) while (!LIST_EMPTY(&req->chandles)) { client = LIST_FIRST(&req->chandles); kore_curl_cleanup(client); } #endif kore_debug("http_request_free: %p->%p", req->owner, req); kore_free(req->headers); req->host = NULL; req->path = NULL; req->headers = NULL; TAILQ_REMOVE(&http_requests, req, list); if (req->owner != NULL) TAILQ_REMOVE(&(req->owner->http_requests), req, olist); for (hdr = TAILQ_FIRST(&(req->resp_headers)); hdr != NULL; hdr = next) { next = TAILQ_NEXT(hdr, list); TAILQ_REMOVE(&(req->resp_headers), hdr, list); kore_free(hdr->header); kore_free(hdr->value); kore_pool_put(&http_header_pool, hdr); } for (hdr = TAILQ_FIRST(&(req->req_headers)); hdr != NULL; hdr = next) { next = TAILQ_NEXT(hdr, list); TAILQ_REMOVE(&(req->req_headers), hdr, list); kore_pool_put(&http_header_pool, hdr); } for (ck = TAILQ_FIRST(&(req->resp_cookies)); ck != NULL; ck = cknext) { cknext = TAILQ_NEXT(ck, list); TAILQ_REMOVE(&(req->resp_cookies), ck, list); kore_free(ck->name); kore_free(ck->value); kore_free(ck->path); kore_free(ck->domain); kore_pool_put(&http_cookie_pool, ck); } for (ck = TAILQ_FIRST(&(req->req_cookies)); ck != NULL; ck = cknext) { cknext = TAILQ_NEXT(ck, list); TAILQ_REMOVE(&(req->req_cookies), ck, list); kore_free(ck->name); kore_free(ck->value); kore_pool_put(&http_cookie_pool, ck); } for (q = TAILQ_FIRST(&(req->arguments)); q != NULL; q = qnext) { qnext = TAILQ_NEXT(q, list); TAILQ_REMOVE(&(req->arguments), q, list); kore_free(q->name); kore_free(q->s_value); kore_free(q); } for (f = TAILQ_FIRST(&(req->files)); f != NULL; f = fnext) { fnext = TAILQ_NEXT(f, list); TAILQ_REMOVE(&(req->files), f, list); kore_free(f->filename); kore_free(f->name); kore_free(f); } if (req->http_body != NULL) kore_buf_free(req->http_body); if (req->http_body_fd != -1) (void)close(req->http_body_fd); if (req->http_body_path != NULL) { if (unlink(req->http_body_path) == -1 && errno != ENOENT) { kore_log(LOG_NOTICE, "failed to unlink %s: %s", req->http_body_path, errno_s); } kore_pool_put(&http_body_path, req->http_body_path); } if (req->hdlr_extra != NULL && !(req->flags & HTTP_REQUEST_RETAIN_EXTRA)) kore_free(req->hdlr_extra); kore_pool_put(&http_request_pool, req); http_request_count--; } void http_serveable(struct http_request *req, const void *data, size_t len, const char *etag, const char *type) { const char *match; if (req->method != HTTP_METHOD_GET) { http_response_header(req, "allow", "get"); http_response(req, HTTP_STATUS_BAD_REQUEST, NULL, 0); return; } if (http_request_header(req, "if-none-match", &match)) { if (!strcmp(match, etag)) { http_response(req, HTTP_STATUS_NOT_MODIFIED, NULL, 0); return; } } http_response_header(req, "etag", etag); http_response_header(req, "content-type", type); http_response(req, HTTP_STATUS_OK, data, len); } void http_response(struct http_request *req, int status, const void *d, size_t l) { if (req->owner == NULL) return; kore_debug("http_response(%p, %d, %p, %zu)", req, status, d, l); req->status = status; switch (req->owner->proto) { case CONN_PROTO_HTTP: case CONN_PROTO_WEBSOCKET: http_response_normal(req, req->owner, status, d, l); break; default: fatal("http_response() bad proto %d", req->owner->proto); /* NOTREACHED. */ } } void http_response_stream(struct http_request *req, int status, void *base, size_t len, int (*cb)(struct netbuf *), void *arg) { struct netbuf *nb; if (req->owner == NULL) return; req->status = status; switch (req->owner->proto) { case CONN_PROTO_HTTP: http_response_normal(req, req->owner, status, NULL, len); break; default: fatal("http_response_stream() bad proto %d", req->owner->proto); /* NOTREACHED. */ } if (req->method != HTTP_METHOD_HEAD) { net_send_stream(req->owner, base, len, cb, &nb); nb->extra = arg; } } void http_response_fileref(struct http_request *req, int status, struct kore_fileref *ref) { struct tm *tm; time_t mtime; char tbuf[128]; const char *media_type, *modified; if (req->owner == NULL) return; media_type = http_media_type(ref->path); if (media_type != NULL) http_response_header(req, "content-type", media_type); if (http_request_header(req, "if-modified-since", &modified)) { mtime = kore_date_to_time(modified); if (mtime == ref->mtime_sec) { kore_fileref_release(ref); http_response(req, HTTP_STATUS_NOT_MODIFIED, NULL, 0); return; } } if ((tm = gmtime(&ref->mtime_sec)) != NULL) { if (strftime(tbuf, sizeof(tbuf), "%a, %d %b %Y %H:%M:%S GMT", tm) > 0) { http_response_header(req, "last-modified", tbuf); } } req->status = status; switch (req->owner->proto) { case CONN_PROTO_HTTP: http_response_normal(req, req->owner, status, NULL, ref->size); break; default: fatal("http_response_fd() bad proto %d", req->owner->proto); /* NOTREACHED. */ } if (req->method != HTTP_METHOD_HEAD) net_send_fileref(req->owner, ref); else kore_fileref_release(ref); } int http_request_header(struct http_request *req, const char *header, const char **out) { struct http_header *hdr; TAILQ_FOREACH(hdr, &(req->req_headers), list) { if (!strcasecmp(hdr->header, header)) { *out = hdr->value; return (KORE_RESULT_OK); } } if (!strcasecmp(header, "host")) { *out = req->host; return (KORE_RESULT_OK); } return (KORE_RESULT_ERROR); } int http_request_cookie(struct http_request *req, const char *cookie, char **out) { struct http_cookie *ck; TAILQ_FOREACH(ck, &(req->req_cookies), list) { if (!strcasecmp(ck->name, cookie)) { *out = ck->value; return (KORE_RESULT_OK); } } return (KORE_RESULT_ERROR); } int http_header_recv(struct netbuf *nb) { struct connection *c; size_t len; ssize_t ret; struct http_header *hdr; struct http_request *req; const char *clp; u_int64_t bytes_left; u_int8_t *end_headers; int h, i, v, skip, l; char *headers[HTTP_REQ_HEADER_MAX]; char *value, *host, *request[4], *hbuf; c = nb->owner; kore_debug("http_header_recv(%p)", nb); if (nb->b_len < 4) return (KORE_RESULT_OK); skip = 4; end_headers = kore_mem_find(nb->buf, nb->s_off, "\r\n\r\n", 4); if (end_headers == NULL) { end_headers = kore_mem_find(nb->buf, nb->s_off, "\n\n", 2); if (end_headers == NULL) return (KORE_RESULT_OK); skip = 2; } *end_headers = '\0'; end_headers += skip; len = end_headers - nb->buf; hbuf = (char *)nb->buf; h = kore_split_string(hbuf, "\r\n", headers, HTTP_REQ_HEADER_MAX); if (h < 2) { http_error_response(c, 400); return (KORE_RESULT_OK); } v = kore_split_string(headers[0], " ", request, 4); if (v != 3) { http_error_response(c, 400); return (KORE_RESULT_OK); } skip = 0; host = NULL; for (i = 0; i < h; i++) { if (strncasecmp(headers[i], "host", 4)) continue; if ((host = http_validate_header(headers[i])) == NULL) { http_error_response(c, 400); return (KORE_RESULT_OK); } if (*host == '\0') { http_error_response(c, 400); return (KORE_RESULT_OK); } skip = i; break; } if (host == NULL) { http_error_response(c, 400); return (KORE_RESULT_OK); } req = http_request_new(c, host, request[0], request[1], request[2]); if (req == NULL) return (KORE_RESULT_OK); /* take full ownership of the buffer. */ req->headers = nb->buf; nb->buf = NULL; nb->m_len = 0; for (i = 1; i < h; i++) { if (i == skip) continue; if ((value = http_validate_header(headers[i])) == NULL) { req->flags |= HTTP_REQUEST_DELETE; http_error_response(c, 400); return (KORE_RESULT_OK); } if (*value == '\0') { req->flags |= HTTP_REQUEST_DELETE; http_error_response(c, 400); return (KORE_RESULT_OK); } hdr = kore_pool_get(&http_header_pool); hdr->header = headers[i]; hdr->value = value; TAILQ_INSERT_TAIL(&(req->req_headers), hdr, list); if (req->agent == NULL && !strcasecmp(hdr->header, "user-agent")) req->agent = hdr->value; if (req->referer == NULL && !strcasecmp(hdr->header, "referer")) req->referer = hdr->value; } if (req->flags & HTTP_REQUEST_EXPECT_BODY) { if (http_body_max == 0) { req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 405); return (KORE_RESULT_OK); } if (!http_request_header(req, "content-length", &clp)) { kore_debug("expected body but no content-length"); req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 411); return (KORE_RESULT_OK); } req->content_length = kore_strtonum(clp, 10, 0, LONG_MAX, &v); if (v == KORE_RESULT_ERROR) { kore_debug("content-length invalid: %s", clp); req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 411); return (KORE_RESULT_OK); } if (req->content_length == 0) { req->flags |= HTTP_REQUEST_COMPLETE; req->flags &= ~HTTP_REQUEST_EXPECT_BODY; return (KORE_RESULT_OK); } if (req->content_length > http_body_max) { kore_log(LOG_NOTICE, "body too large (%zu > %zu)", req->content_length, http_body_max); req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 413); return (KORE_RESULT_OK); } req->http_body_length = req->content_length; if (http_body_disk_offload > 0 && req->content_length > http_body_disk_offload) { req->http_body_path = kore_pool_get(&http_body_path); l = snprintf(req->http_body_path, HTTP_BODY_PATH_MAX, "%s/http_body.XXXXXX", http_body_disk_path); if (l == -1 || (size_t)l >= HTTP_BODY_PATH_MAX) { req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 500); return (KORE_RESULT_ERROR); } req->http_body = NULL; req->http_body_fd = mkstemp(req->http_body_path); if (req->http_body_fd == -1) { req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 500); return (KORE_RESULT_OK); } ret = write(req->http_body_fd, end_headers, (nb->s_off - len)); if (ret == -1 || (size_t)ret != (nb->s_off - len)) { req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 500); return (KORE_RESULT_OK); } } else { req->http_body_fd = -1; req->http_body = kore_buf_alloc(req->content_length); kore_buf_append(req->http_body, end_headers, (nb->s_off - len)); } SHA256_Init(&req->hashctx); SHA256_Update(&req->hashctx, end_headers, (nb->s_off - len)); bytes_left = req->content_length - (nb->s_off - len); if (bytes_left > 0) { kore_debug("%ld/%ld (%ld - %ld) more bytes for body", bytes_left, req->content_length, nb->s_off, len); net_recv_reset(c, MIN(bytes_left, NETBUF_SEND_PAYLOAD_MAX), http_body_recv); c->rnb->extra = req; http_request_sleep(req); req->content_length = bytes_left; c->http_timeout = http_body_timeout * 1000; } else { c->http_timeout = 0; req->flags |= HTTP_REQUEST_COMPLETE; req->flags &= ~HTTP_REQUEST_EXPECT_BODY; SHA256_Final(req->http_body_digest, &req->hashctx); if (!http_body_rewind(req)) { req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 500); return (KORE_RESULT_OK); } } } else { c->http_timeout = 0; } return (KORE_RESULT_OK); } int http_argument_get(struct http_request *req, const char *name, void **out, void *nout, int type) { struct http_arg *q; TAILQ_FOREACH(q, &(req->arguments), list) { if (strcmp(q->name, name)) continue; switch (type) { case HTTP_ARG_TYPE_RAW: *out = q->s_value; return (KORE_RESULT_OK); case HTTP_ARG_TYPE_BYTE: COPY_ARG_TYPE(*(u_int8_t *)q->s_value, u_int8_t); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_INT16: COPY_AS_INTTYPE(SHRT_MIN, SHRT_MAX, int16_t); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_UINT16: COPY_AS_INTTYPE(0, USHRT_MAX, u_int16_t); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_INT32: COPY_AS_INTTYPE(INT_MIN, INT_MAX, int32_t); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_UINT32: COPY_AS_INTTYPE(0, UINT_MAX, u_int32_t); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_INT64: COPY_AS_INTTYPE_64(int64_t, 1); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_UINT64: COPY_AS_INTTYPE_64(u_int64_t, 0); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_FLOAT: COPY_ARG_DOUBLE(-FLT_MAX, FLT_MAX, float); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_DOUBLE: COPY_ARG_DOUBLE(-DBL_MAX, DBL_MAX, double); return (KORE_RESULT_OK); case HTTP_ARG_TYPE_STRING: *out = q->s_value; return (KORE_RESULT_OK); default: break; } return (KORE_RESULT_ERROR); } return (KORE_RESULT_ERROR); } int http_argument_urldecode(char *arg) { u_int8_t v; int err; size_t len; char *p, *in, h[5]; p = arg; in = arg; len = strlen(arg); while (*p != '\0' && p < (arg + len)) { if (*p == '+') *p = ' '; if (*p != '%') { *in++ = *p++; continue; } if ((p + 2) >= (arg + len)) { kore_debug("overflow in '%s'", arg); return (KORE_RESULT_ERROR); } if (!isxdigit(*(p + 1)) || !isxdigit(*(p + 2))) { *in++ = *p++; continue; } h[0] = '0'; h[1] = 'x'; h[2] = *(p + 1); h[3] = *(p + 2); h[4] = '\0'; v = kore_strtonum(h, 16, 0x0, 0xff, &err); if (err != KORE_RESULT_OK) return (err); if (v <= 0x1f || v == 0x7f) return (KORE_RESULT_ERROR); *in++ = (char)v; p += 3; } *in = '\0'; return (KORE_RESULT_OK); } struct http_file * http_file_lookup(struct http_request *req, const char *name) { struct http_file *f; TAILQ_FOREACH(f, &(req->files), list) { if (!strcmp(f->name, name)) return (f); } return (NULL); } ssize_t http_file_read(struct http_file *file, void *buf, size_t len) { ssize_t ret; size_t toread, off; if (file->length < file->offset) return (-1); if ((file->offset + len) < file->offset) return (-1); if ((file->position + file->offset) < file->position) return (-1); off = file->position + file->offset; toread = MIN(len, (file->length - file->offset)); if (toread == 0) return (0); if (file->req->http_body_fd != -1) { if (lseek(file->req->http_body_fd, off, SEEK_SET) == -1) { kore_log(LOG_ERR, "http_file_read: lseek(%s): %s", file->req->http_body_path, errno_s); return (-1); } for (;;) { ret = read(file->req->http_body_fd, buf, toread); if (ret == -1) { if (errno == EINTR) continue; kore_log(LOG_ERR, "failed to read %s: %s", file->req->http_body_path, errno_s); return (-1); } if (ret == 0) return (0); break; } } else if (file->req->http_body != NULL) { if (off > file->req->http_body->length) return (0); memcpy(buf, file->req->http_body->data + off, toread); ret = toread; } else { kore_log(LOG_ERR, "http_file_read: called without body"); return (-1); } file->offset += (size_t)ret; return (ret); } void http_file_rewind(struct http_file *file) { file->offset = 0; } void http_response_cookie(struct http_request *req, const char *name, const char *val, const char *path, time_t expires, u_int32_t maxage, struct http_cookie **out) { char *p; struct http_cookie *ck; if (name == NULL || val == NULL) fatal("http_response_cookie: invalid parameters"); ck = kore_pool_get(&http_cookie_pool); ck->maxage = maxage; ck->expires = expires; ck->name = kore_strdup(name); ck->value = kore_strdup(val); ck->domain = kore_strdup(req->host); ck->flags = HTTP_COOKIE_HTTPONLY | HTTP_COOKIE_SECURE; if ((p = strrchr(ck->domain, ':')) != NULL) *p = '\0'; if (path != NULL) ck->path = kore_strdup(path); else ck->path = NULL; TAILQ_INSERT_TAIL(&(req->resp_cookies), ck, list); if (out != NULL) *out = ck; } void http_populate_cookies(struct http_request *req) { struct http_cookie *ck; const char *hdr; int i, v, n; char *c, *header, *pair[3]; char *cookies[HTTP_MAX_COOKIES]; if (!http_request_header(req, "cookie", &hdr)) return; header = kore_strdup(hdr); v = kore_split_string(header, ";", cookies, HTTP_MAX_COOKIES); for (i = 0; i < v; i++) { for (c = cookies[i]; isspace(*(unsigned char *)c); c++) ; n = kore_split_string(c, "=", pair, 3); if (n != 2) continue; ck = kore_pool_get(&http_cookie_pool); ck->name = kore_strdup(pair[0]); ck->value = kore_strdup(pair[1]); TAILQ_INSERT_TAIL(&(req->req_cookies), ck, list); } kore_free(header); } void http_populate_post(struct http_request *req) { ssize_t ret; int i, v; struct kore_buf *body; char data[BUFSIZ]; char *args[HTTP_MAX_QUERY_ARGS], *val[3], *string; if (req->method != HTTP_METHOD_POST) return; if (req->http_body != NULL) { body = NULL; req->http_body->offset = req->content_length; string = kore_buf_stringify(req->http_body, NULL); req->http_body_length = 0; req->http_body_offset = 0; } else { body = kore_buf_alloc(128); for (;;) { ret = http_body_read(req, data, sizeof(data)); if (ret == -1) goto out; if (ret == 0) break; kore_buf_append(body, data, ret); } string = kore_buf_stringify(body, NULL); } v = kore_split_string(string, "&", args, HTTP_MAX_QUERY_ARGS); for (i = 0; i < v; i++) { kore_split_string(args[i], "=", val, 3); if (val[0] != NULL && val[1] != NULL) http_argument_add(req, val[0], val[1], 0, 1); } out: if (body != NULL) kore_buf_free(body); } void http_populate_qs(struct http_request *req) { int i, v; char *query, *args[HTTP_MAX_QUERY_ARGS], *val[3]; if (req->query_string == NULL) return; query = kore_strdup(req->query_string); v = kore_split_string(query, "&", args, HTTP_MAX_QUERY_ARGS); for (i = 0; i < v; i++) { kore_split_string(args[i], "=", val, 3); if (val[0] != NULL && val[1] != NULL) http_argument_add(req, val[0], val[1], 1, 1); } kore_free(query); } void http_populate_multipart_form(struct http_request *req) { const char *hdr; int h, blen; struct kore_buf in, out; char *type, *val, *args[3]; char boundary[HTTP_BOUNDARY_MAX]; if (req->method != HTTP_METHOD_POST) return; if (!http_request_header(req, "content-type", &hdr)) return; kore_buf_init(&in, 128); kore_buf_init(&out, 128); type = kore_strdup(hdr); h = kore_split_string(type, ";", args, 3); if (h != 2) goto cleanup; if (strcasecmp(args[0], "multipart/form-data")) goto cleanup; if ((val = strchr(args[1], '=')) == NULL) goto cleanup; val++; blen = snprintf(boundary, sizeof(boundary), "--%s", val); if (blen == -1 || (size_t)blen >= sizeof(boundary)) goto cleanup; if (!multipart_find_data(&in, NULL, NULL, req, boundary, blen)) goto cleanup; for (;;) { if (!multipart_find_data(&in, NULL, NULL, req, "\r\n", 2)) break; if (in.offset < 4 && req->http_body_length == 0) break; if (!multipart_find_data(&in, &out, NULL, req, "\r\n\r\n", 4)) break; if (!multipart_parse_headers(req, &in, &out, boundary, blen)) break; kore_buf_reset(&out); } cleanup: kore_free(type); kore_buf_cleanup(&in); kore_buf_cleanup(&out); } int http_body_rewind(struct http_request *req) { if (req->http_body_fd != -1) { if (lseek(req->http_body_fd, 0, SEEK_SET) == -1) { kore_log(LOG_ERR, "lseek(%s) failed: %s", req->http_body_path, errno_s); return (KORE_RESULT_ERROR); } } else if (req->http_body != NULL) { kore_buf_reset(req->http_body); } req->http_body_offset = 0; req->http_body_length = req->content_length; return (KORE_RESULT_OK); } int http_body_digest(struct http_request *req, char *out, size_t len) { size_t idx; int slen; if (len != HTTP_BODY_DIGEST_STRLEN) { fatal("http_body_digest: bad len:%zu wanted:%zu", len, HTTP_BODY_DIGEST_STRLEN); } if (!(req->flags & HTTP_REQUEST_COMPLETE)) return (KORE_RESULT_ERROR); for (idx = 0; idx < sizeof(req->http_body_digest); idx++) { slen = snprintf(out + (idx * 2), len - (idx * 2), "%02x", req->http_body_digest[idx]); if (slen == -1 || (size_t)slen >= len) fatal("failed to create hex string"); } return (KORE_RESULT_OK); } ssize_t http_body_read(struct http_request *req, void *out, size_t len) { ssize_t ret; size_t toread; toread = MIN(req->http_body_length, len); if (toread == 0) return (0); if (req->http_body_fd != -1) { for (;;) { ret = read(req->http_body_fd, out, toread); if (ret == -1) { if (errno == EINTR) continue; kore_log(LOG_ERR, "failed to read %s: %s", req->http_body_path, errno_s); return (-1); } if (ret == 0) return (0); break; } } else if (req->http_body != NULL) { memcpy(out, (req->http_body->data + req->http_body->offset), toread); req->http_body->offset += toread; ret = toread; } else { kore_log(LOG_ERR, "http_body_read: called without body"); return (-1); } req->http_body_length -= (size_t)ret; req->http_body_offset += (size_t)ret; return (ret); } int http_state_run(struct http_state *states, u_int8_t elm, struct http_request *req) { int r, done; done = 0; while (!done) { if (req->fsm_state >= elm) { fatal("http_state_run: fsm_state > elm (%d/%d)", req->fsm_state, elm); } kore_debug("http_state_run: running %s", states[req->fsm_state].name); r = states[req->fsm_state].cb(req); switch (r) { case HTTP_STATE_ERROR: return (KORE_RESULT_OK); case HTTP_STATE_RETRY: return (KORE_RESULT_RETRY); case HTTP_STATE_CONTINUE: break; case HTTP_STATE_COMPLETE: done = 1; break; default: fatal("http_state_run: unknown return value %d", r); } } req->fsm_state = 0; kore_debug("http_state_run(%p): done", req); return (KORE_RESULT_OK); } int http_state_exists(struct http_request *req) { return (req->hdlr_extra != NULL); } void * http_state_create(struct http_request *req, size_t len, void (*onfree)(struct http_request *)) { if (req->hdlr_extra != NULL) fatal("http_state_create: state already exists"); req->state_len = len; req->onfree = onfree; req->hdlr_extra = kore_calloc(1, len); return (req->hdlr_extra); } void * http_state_get(struct http_request *req) { return (req->hdlr_extra); } void http_state_cleanup(struct http_request *req) { kore_free(req->hdlr_extra); req->hdlr_extra = NULL; } void http_start_recv(struct connection *c) { c->http_start = kore_time_ms(); c->http_timeout = http_header_timeout * 1000; net_recv_reset(c, http_header_max, http_header_recv); (void)net_recv_flush(c); } void http_runlock_init(struct http_runlock *lock) { lock->owner = NULL; LIST_INIT(&lock->queue); } int http_runlock_acquire(struct http_runlock *lock, struct http_request *req) { if (lock->owner != NULL) { if (req->runlock != NULL) fatal("%s: request already waiting on lock", __func__); req->runlock = kore_pool_get(&http_rlq_pool); req->runlock->req = req; LIST_INSERT_HEAD(&lock->queue, req->runlock, list); http_request_sleep(req); return (KORE_RESULT_ERROR); } lock->owner = req; return (KORE_RESULT_OK); } void http_runlock_release(struct http_runlock *lock, struct http_request *req) { struct http_runlock_queue *next; struct http_request *nextreq; if (lock->owner != req) fatal("%s: calling request != owner of runlock", __func__); lock->owner = NULL; if ((next = LIST_FIRST(&lock->queue)) != NULL) { LIST_REMOVE(next, list); nextreq = next->req; nextreq->runlock = NULL; http_request_wakeup(nextreq); kore_pool_put(&http_rlq_pool, next); } } int http_redirect_add(struct kore_domain *dom, const char *path, int status, const char *target) { struct http_redirect *rdr; rdr = kore_calloc(1, sizeof(*rdr)); if (regcomp(&(rdr->rctx), path, REG_EXTENDED)) { kore_free(rdr); return (KORE_RESULT_ERROR); } rdr->status = status; if (target != NULL) rdr->target = kore_strdup(target); else rdr->target = NULL; TAILQ_INSERT_TAIL(&dom->redirects, rdr, list); return (KORE_RESULT_OK); } static int http_check_redirect(struct http_request *req, struct kore_domain *dom) { int idx; struct http_redirect *rdr; const char *uri; char key[4]; struct kore_buf location; TAILQ_FOREACH(rdr, &dom->redirects, list) { if (!regexec(&(rdr->rctx), req->path, HTTP_CAPTURE_GROUPS, req->cgroups, 0)) break; } if (rdr == NULL) return (KORE_RESULT_ERROR); uri = NULL; kore_buf_init(&location, 128); if (rdr->target) { kore_buf_appendf(&location, "%s", rdr->target); if (req->query_string != NULL) { kore_buf_replace_string(&location, "$qs", req->query_string, strlen(req->query_string)); } /* Starts at 1 to skip the full path. */ for (idx = 1; idx < HTTP_CAPTURE_GROUPS - 1; idx++) { if (req->cgroups[idx].rm_so == -1 || req->cgroups[idx].rm_eo == -1) break; (void)snprintf(key, sizeof(key), "$%d", idx); kore_buf_replace_string(&location, key, req->path + req->cgroups[idx].rm_so, req->cgroups[idx].rm_eo - req->cgroups[idx].rm_so); } uri = kore_buf_stringify(&location, NULL); } if (uri) http_response_header(req, "location", uri); http_response(req, rdr->status, NULL, 0); kore_buf_cleanup(&location); if (dom->accesslog) kore_accesslog(req); return (KORE_RESULT_OK); } static struct http_request * http_request_new(struct connection *c, const char *host, const char *method, char *path, const char *version) { struct kore_domain *dom; struct http_request *req; char *p, *hp; int m, flags; size_t hostlen, pathlen, qsoff; if (http_request_count >= http_request_limit) { http_error_response(c, 503); return (NULL); } kore_debug("http_request_new(%p, %s, %s, %s, %s)", c, host, method, path, version); if ((hostlen = strlen(host)) >= KORE_DOMAINNAME_LEN - 1) { http_error_response(c, 400); return (NULL); } if ((pathlen = strlen(path)) >= HTTP_URI_LEN - 1) { http_error_response(c, 414); return (NULL); } if (strcasecmp(version, "http/1.1")) { if (strcasecmp(version, "http/1.0")) { http_error_response(c, 505); return (NULL); } flags = HTTP_VERSION_1_0; } else { flags = HTTP_VERSION_1_1; } if ((p = strchr(path, '?')) != NULL) { qsoff = p - path; } else { qsoff = 0; } hp = NULL; switch (c->family) { case AF_INET6: if (*host == '[') { if ((hp = strrchr(host, ']')) == NULL) { http_error_response(c, 400); return (NULL); } hp++; if (*hp == ':') *hp = '\0'; else hp = NULL; } break; default: if ((hp = strrchr(host, ':')) != NULL) *hp = '\0'; break; } if (c->owner->server->tls && c->tls_sni != NULL) { if (strcasecmp(c->tls_sni, host)) { http_error_response(c, HTTP_STATUS_MISDIRECTED_REQUEST); return (NULL); } } if ((dom = kore_domain_lookup(c->owner->server, host)) == NULL) { http_error_response(c, HTTP_STATUS_NOT_FOUND); return (NULL); } if (dom->cafile != NULL && c->cert == NULL) { http_error_response(c, HTTP_STATUS_FORBIDDEN); return (NULL); } if (hp != NULL) *hp = ':'; if (!strcasecmp(method, "get")) { m = HTTP_METHOD_GET; flags |= HTTP_REQUEST_COMPLETE; } else if (!strcasecmp(method, "delete")) { m = HTTP_METHOD_DELETE; flags |= HTTP_REQUEST_COMPLETE; } else if (!strcasecmp(method, "post")) { m = HTTP_METHOD_POST; flags |= HTTP_REQUEST_EXPECT_BODY; } else if (!strcasecmp(method, "put")) { m = HTTP_METHOD_PUT; flags |= HTTP_REQUEST_EXPECT_BODY; } else if (!strcasecmp(method, "head")) { m = HTTP_METHOD_HEAD; flags |= HTTP_REQUEST_COMPLETE; } else if (!strcasecmp(method, "options")) { m = HTTP_METHOD_OPTIONS; flags |= HTTP_REQUEST_COMPLETE; } else if (!strcasecmp(method, "patch")) { m = HTTP_METHOD_PATCH; flags |= HTTP_REQUEST_EXPECT_BODY; } else { http_error_response(c, 400); return (NULL); } if (flags & HTTP_VERSION_1_0) { if (m != HTTP_METHOD_GET && m != HTTP_METHOD_POST && m != HTTP_METHOD_HEAD) { http_error_response(c, HTTP_STATUS_METHOD_NOT_ALLOWED); return (NULL); } } req = kore_pool_get(&http_request_pool); req->end = 0; req->total = 0; req->start = 0; req->owner = c; req->status = 0; req->method = m; req->agent = NULL; req->onfree = NULL; req->referer = NULL; req->runlock = NULL; req->flags = flags; req->fsm_state = 0; req->http_body = NULL; req->http_body_fd = -1; req->hdlr_extra = NULL; req->query_string = NULL; req->http_body_length = 0; req->http_body_offset = 0; req->http_body_path = NULL; req->host = host; req->path = path; #if defined(KORE_USE_PYTHON) req->py_req = NULL; req->py_coro = NULL; req->py_rqnext = NULL; req->py_validator = NULL; #endif if (qsoff > 0) { req->query_string = path + qsoff; *(req->query_string)++ = '\0'; } else { req->query_string = NULL; } /* Checked further down below if we need to 404. */ req->hdlr = kore_module_handler_find(req, dom); TAILQ_INIT(&(req->resp_headers)); TAILQ_INIT(&(req->req_headers)); TAILQ_INIT(&(req->resp_cookies)); TAILQ_INIT(&(req->req_cookies)); TAILQ_INIT(&(req->arguments)); TAILQ_INIT(&(req->files)); #if defined(KORE_USE_TASKS) LIST_INIT(&(req->tasks)); #endif #if defined(KORE_USE_PGSQL) LIST_INIT(&(req->pgsqls)); #endif http_request_count++; TAILQ_INSERT_HEAD(&http_requests, req, list); TAILQ_INSERT_TAIL(&(c->http_requests), req, olist); if (http_check_redirect(req, dom)) { http_request_free(req); return (NULL); } if (req->hdlr == NULL) { http_request_free(req); http_error_response(c, HTTP_STATUS_NOT_FOUND); return (NULL); } if (!(req->hdlr->methods & m)) { http_request_free(req); http_error_response(c, HTTP_STATUS_METHOD_NOT_ALLOWED); return (NULL); } return (req); } static int multipart_find_data(struct kore_buf *in, struct kore_buf *out, size_t *olen, struct http_request *req, const void *needle, size_t len) { ssize_t ret; size_t left; u_int8_t *p, first, data[4096]; if (olen != NULL) *olen = 0; first = *(const u_int8_t *)needle; for (;;) { if (in->offset < len) { ret = http_body_read(req, data, sizeof(data)); if (ret == -1) return (KORE_RESULT_ERROR); if (ret == 0) return (KORE_RESULT_ERROR); kore_buf_append(in, data, ret); continue; } p = kore_mem_find(in->data, in->offset, &first, 1); if (p == NULL) { if (out != NULL) kore_buf_append(out, in->data, in->offset); if (olen != NULL) *olen += in->offset; kore_buf_reset(in); continue; } left = in->offset - (p - in->data); if (left < len) { if (out != NULL) kore_buf_append(out, in->data, (p - in->data)); if (olen != NULL) *olen += (p - in->data); memmove(in->data, p, left); in->offset = left; continue; } if (!memcmp(p, needle, len)) { if (out != NULL) kore_buf_append(out, in->data, p - in->data); if (olen != NULL) *olen += (p - in->data); in->offset = left - len; if (in->offset > 0) memmove(in->data, p + len, in->offset); return (KORE_RESULT_OK); } if (out != NULL) kore_buf_append(out, in->data, (p - in->data) + 1); if (olen != NULL) *olen += (p - in->data) + 1; in->offset = left - 1; if (in->offset > 0) memmove(in->data, p + 1, in->offset); } return (KORE_RESULT_ERROR); } static int multipart_parse_headers(struct http_request *req, struct kore_buf *in, struct kore_buf *hbuf, const char *boundary, const int blen) { int h, c, i; char *headers[5], *args[5], *opt[5]; char *d, *val, *name, *fname, *string; string = kore_buf_stringify(hbuf, NULL); h = kore_split_string(string, "\r\n", headers, 5); for (i = 0; i < h; i++) { c = kore_split_string(headers[i], ":", args, 5); if (c != 2) continue; /* Ignore other headers for now. */ if (strcasecmp(args[0], "content-disposition")) continue; for (d = args[1]; isspace(*(unsigned char *)d); d++) ; c = kore_split_string(d, ";", opt, 5); if (c < 2) continue; if (strcasecmp(opt[0], "form-data")) continue; if ((val = strchr(opt[1], '=')) == NULL) continue; if (strlen(val) < 3) continue; val++; kore_strip_chars(val, '"', &name); if (opt[2] == NULL) { multipart_add_field(req, in, name, boundary, blen); kore_free(name); continue; } for (d = opt[2]; isspace(*(unsigned char *)d); d++) ; if (!strncasecmp(d, "filename=", 9)) { if ((val = strchr(d, '=')) == NULL) { kore_free(name); continue; } val++; kore_strip_chars(val, '"', &fname); if (strlen(fname) > 0) { multipart_file_add(req, in, name, fname, boundary, blen); } kore_free(fname); } else { kore_debug("got unknown: %s", opt[2]); } kore_free(name); } return (KORE_RESULT_OK); } static void multipart_add_field(struct http_request *req, struct kore_buf *in, char *name, const char *boundary, const int blen) { struct kore_buf *data; char *string; data = kore_buf_alloc(128); if (!multipart_find_data(in, data, NULL, req, boundary, blen)) { kore_buf_free(data); return; } if (data->offset < 3) { kore_buf_free(data); return; } data->offset -= 2; string = kore_buf_stringify(data, NULL); http_argument_add(req, name, string, 0, 0); kore_buf_free(data); } static void multipart_file_add(struct http_request *req, struct kore_buf *in, const char *name, const char *fname, const char *boundary, const int blen) { struct http_file *f; size_t position, len; position = req->http_body_offset - in->offset; if (!multipart_find_data(in, NULL, &len, req, boundary, blen)) return; if (len < 3) return; len -= 2; f = kore_malloc(sizeof(struct http_file)); f->req = req; f->offset = 0; f->length = len; f->position = position; f->name = kore_strdup(name); f->filename = kore_strdup(fname); TAILQ_INSERT_TAIL(&(req->files), f, list); } static void http_argument_add(struct http_request *req, char *name, char *value, int qs, int decode) { struct http_arg *q; struct kore_handler_params *p; if (decode) { if (!http_argument_urldecode(name)) return; } TAILQ_FOREACH(p, &(req->hdlr->params), list) { if (qs == 1 && !(p->flags & KORE_PARAMS_QUERY_STRING)) continue; if (qs == 0 && (p->flags & KORE_PARAMS_QUERY_STRING)) continue; if (p->method != req->method) continue; if (strcmp(p->name, name)) continue; if (decode) { if (!http_argument_urldecode(value)) return; } if (!kore_validator_check(req, p->validator, value)) break; q = kore_malloc(sizeof(struct http_arg)); q->name = kore_strdup(name); q->s_value = kore_strdup(value); TAILQ_INSERT_TAIL(&(req->arguments), q, list); break; } } static int http_body_recv(struct netbuf *nb) { ssize_t ret; u_int64_t bytes_left; struct http_request *req = (struct http_request *)nb->extra; SHA256_Update(&req->hashctx, nb->buf, nb->s_off); if (req->http_body_fd != -1) { ret = write(req->http_body_fd, nb->buf, nb->s_off); if (ret == -1 || (size_t)ret != nb->s_off) { req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 500); return (KORE_RESULT_ERROR); } } else if (req->http_body != NULL) { kore_buf_append(req->http_body, nb->buf, nb->s_off); } else { req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 500); return (KORE_RESULT_ERROR); } req->content_length -= nb->s_off; if (req->content_length == 0) { nb->extra = NULL; http_request_wakeup(req); req->flags |= HTTP_REQUEST_COMPLETE; req->flags &= ~HTTP_REQUEST_EXPECT_BODY; req->content_length = req->http_body_length; if (!http_body_rewind(req)) { req->flags |= HTTP_REQUEST_DELETE; http_error_response(req->owner, 500); return (KORE_RESULT_ERROR); } SHA256_Final(req->http_body_digest, &req->hashctx); net_recv_reset(nb->owner, http_header_max, http_header_recv); } else { bytes_left = req->content_length; net_recv_reset(nb->owner, MIN(bytes_left, NETBUF_SEND_PAYLOAD_MAX), http_body_recv); } return (KORE_RESULT_OK); } static void http_error_response(struct connection *c, int status) { kore_debug("http_error_response(%p, %d)", c, status); c->flags |= CONN_CLOSE_EMPTY; switch (c->proto) { case CONN_PROTO_HTTP: http_response_normal(NULL, c, status, NULL, 0); break; default: fatal("http_error_response() bad proto %d", c->proto); /* NOTREACHED. */ } if (!net_send_flush(c)) kore_connection_disconnect(c); } static void http_response_normal(struct http_request *req, struct connection *c, int status, const void *d, size_t len) { struct kore_buf buf; struct http_cookie *ck; struct http_header *hdr; char version; const char *conn, *text; int connection_close, send_body; send_body = 1; text = http_status_text(status); kore_buf_init(&buf, 1024); kore_buf_reset(header_buf); if (req != NULL) { if (req->flags & HTTP_VERSION_1_0) version = '0'; else version = '1'; } else { version = '1'; } kore_buf_appendf(header_buf, "HTTP/1.%c %d %s\r\n", version, status, text); kore_buf_append(header_buf, http_version, http_version_len); if ((c->flags & CONN_CLOSE_EMPTY) || (req != NULL && (req->flags & HTTP_VERSION_1_0))) { connection_close = 1; } else { connection_close = 0; } if (connection_close == 0 && req != NULL) { if (http_request_header(req, "connection", &conn)) { if ((*conn == 'c' || *conn == 'C') && !strcasecmp(conn, "close")) { connection_close = 1; } } } /* Note that req CAN be NULL. */ if (req == NULL || req->owner->proto != CONN_PROTO_WEBSOCKET) { if (http_keepalive_time && connection_close == 0) { kore_buf_appendf(header_buf, "connection: keep-alive\r\n"); kore_buf_appendf(header_buf, "keep-alive: timeout=%d\r\n", http_keepalive_time); } else { c->flags |= CONN_CLOSE_EMPTY; kore_buf_appendf(header_buf, "connection: close\r\n"); } } if (http_hsts_enable) { kore_buf_appendf(header_buf, "strict-transport-security: "); kore_buf_appendf(header_buf, "max-age=%" PRIu64 "; includeSubDomains\r\n", http_hsts_enable); } if (http_pretty_error && d == NULL && status >= 400) { kore_buf_appendf(&buf, pretty_error_fmt, status, text, status, text); d = buf.data; len = buf.offset; } if (req != NULL) { TAILQ_FOREACH(ck, &(req->resp_cookies), list) http_write_response_cookie(ck); TAILQ_FOREACH(hdr, &(req->resp_headers), list) { kore_buf_appendf(header_buf, "%s: %s\r\n", hdr->header, hdr->value); } if (status != 204 && status >= 200 && !(req->flags & HTTP_REQUEST_NO_CONTENT_LENGTH)) { kore_buf_appendf(header_buf, "content-length: %zu\r\n", len); } } else { if (status != 204 && status >= 200) { kore_buf_appendf(header_buf, "content-length: %zu\r\n", len); } } kore_buf_append(header_buf, "\r\n", 2); net_send_queue(c, header_buf->data, header_buf->offset); if (req != NULL && req->method == HTTP_METHOD_HEAD) send_body = 0; if (d != NULL && send_body) net_send_queue(c, d, len); if (!(c->flags & CONN_CLOSE_EMPTY) && !(c->flags & CONN_IS_BUSY)) http_start_recv(c); if (req != NULL) req->content_length = len; kore_buf_cleanup(&buf); } static void http_write_response_cookie(struct http_cookie *ck) { struct tm tm; char expires[HTTP_DATE_MAXSIZE]; kore_buf_reset(ckhdr_buf); kore_buf_appendf(ckhdr_buf, "%s=%s", ck->name, ck->value); if (ck->path != NULL) kore_buf_appendf(ckhdr_buf, "; Path=%s", ck->path); if (ck->domain != NULL) kore_buf_appendf(ckhdr_buf, "; Domain=%s", ck->domain); if (ck->expires > 0) { if (gmtime_r(&ck->expires, &tm) == NULL) { kore_log(LOG_ERR, "gmtime_r(): %s", errno_s); return; } if (strftime(expires, sizeof(expires), "%a, %d %b %y %H:%M:%S GMT", &tm) == 0) { kore_log(LOG_ERR, "strftime(): %s", errno_s); return; } kore_buf_appendf(ckhdr_buf, "; Expires=%s", expires); } if (ck->maxage > 0) kore_buf_appendf(ckhdr_buf, "; Max-Age=%u", ck->maxage); if (ck->flags & HTTP_COOKIE_HTTPONLY) kore_buf_appendf(ckhdr_buf, "; HttpOnly"); if (ck->flags & HTTP_COOKIE_SECURE) kore_buf_appendf(ckhdr_buf, "; Secure"); kore_buf_appendf(header_buf, "set-cookie: %s\r\n", kore_buf_stringify(ckhdr_buf, NULL)); } const char * http_status_text(int status) { const char *r; switch (status) { case HTTP_STATUS_CONTINUE: r = "Continue"; break; case HTTP_STATUS_SWITCHING_PROTOCOLS: r = "Switching Protocols"; break; case HTTP_STATUS_OK: r = "OK"; break; case HTTP_STATUS_CREATED: r = "Created"; break; case HTTP_STATUS_ACCEPTED: r = "Accepted"; break; case HTTP_STATUS_NON_AUTHORITATIVE: r = "Non-Authoritative Information"; break; case HTTP_STATUS_NO_CONTENT: r = "No Content"; break; case HTTP_STATUS_RESET_CONTENT: r = "Reset Content"; break; case HTTP_STATUS_PARTIAL_CONTENT: r = "Partial Content"; break; case HTTP_STATUS_MULTIPLE_CHOICES: r = "Multiple Choices"; break; case HTTP_STATUS_MOVED_PERMANENTLY: r = "Moved Permanently"; break; case HTTP_STATUS_FOUND: r = "Found"; break; case HTTP_STATUS_SEE_OTHER: r = "See Other"; break; case HTTP_STATUS_NOT_MODIFIED: r = "Not Modified"; break; case HTTP_STATUS_USE_PROXY: r = "Use Proxy"; break; case HTTP_STATUS_TEMPORARY_REDIRECT: r = "Temporary Redirect"; break; case HTTP_STATUS_BAD_REQUEST: r = "Bad Request"; break; case HTTP_STATUS_UNAUTHORIZED: r = "Unauthorized"; break; case HTTP_STATUS_PAYMENT_REQUIRED: r = "Payment Required"; break; case HTTP_STATUS_FORBIDDEN: r = "Forbidden"; break; case HTTP_STATUS_NOT_FOUND: r = "Not Found"; break; case HTTP_STATUS_METHOD_NOT_ALLOWED: r = "Method Not Allowed"; break; case HTTP_STATUS_NOT_ACCEPTABLE: r = "Not Acceptable"; break; case HTTP_STATUS_PROXY_AUTH_REQUIRED: r = "Proxy Authentication Required"; break; case HTTP_STATUS_REQUEST_TIMEOUT: r = "Request Time-out"; break; case HTTP_STATUS_CONFLICT: r = "Conflict"; break; case HTTP_STATUS_GONE: r = "Gone"; break; case HTTP_STATUS_LENGTH_REQUIRED: r = "Length Required"; break; case HTTP_STATUS_PRECONDITION_FAILED: r = "Precondition Failed"; break; case HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE: r = "Request Entity Too Large"; break; case HTTP_STATUS_REQUEST_URI_TOO_LARGE: r = "Request-URI Too Large"; break; case HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: r = "Unsupported Media Type"; break; case HTTP_STATUS_REQUEST_RANGE_INVALID: r = "Requested range not satisfiable"; break; case HTTP_STATUS_EXPECTATION_FAILED: r = "Expectation Failed"; break; case HTTP_STATUS_MISDIRECTED_REQUEST: r = "Misdirected Request"; break; case HTTP_STATUS_INTERNAL_ERROR: r = "Internal Server Error"; break; case HTTP_STATUS_NOT_IMPLEMENTED: r = "Not Implemented"; break; case HTTP_STATUS_BAD_GATEWAY: r = "Bad Gateway"; break; case HTTP_STATUS_SERVICE_UNAVAILABLE: r = "Service Unavailable"; break; case HTTP_STATUS_GATEWAY_TIMEOUT: r = "Gateway Time-out"; break; case HTTP_STATUS_BAD_VERSION: r = "HTTP Version not supported"; break; default: r = ""; break; } return (r); } const char * http_method_text(int method) { char *r; switch(method) { case HTTP_METHOD_GET: r = "GET"; break; case HTTP_METHOD_POST: r = "POST"; break; case HTTP_METHOD_PUT: r = "PUT"; break; case HTTP_METHOD_DELETE: r = "DELETE"; break; case HTTP_METHOD_HEAD: r = "HEAD"; break; case HTTP_METHOD_OPTIONS: r = "OPTIONS"; break; case HTTP_METHOD_PATCH: r = "PATCH"; break; default: r = ""; break; } return (r); } int http_method_value(const char *method) { if (!strcasecmp(method, "GET")) return (HTTP_METHOD_GET); if (!strcasecmp(method, "POST")) return (HTTP_METHOD_POST); if (!strcasecmp(method, "PUT")) return (HTTP_METHOD_PUT); if (!strcasecmp(method, "DELETE")) return (HTTP_METHOD_DELETE); if (!strcasecmp(method, "HEAD")) return (HTTP_METHOD_HEAD); if (!strcasecmp(method, "OPTIONS")) return (HTTP_METHOD_OPTIONS); if (!strcasecmp(method, "PATCH")) return (HTTP_METHOD_PATCH); return (0); } int http_media_register(const char *ext, const char *type) { struct http_media_type *media; LIST_FOREACH(media, &http_media_types, list) { if (!strcasecmp(media->ext, ext)) return (KORE_RESULT_ERROR); } media = kore_calloc(1, sizeof(*media)); media->ext = kore_strdup(ext); media->type = kore_strdup(type); LIST_INSERT_HEAD(&http_media_types, media, list); return (KORE_RESULT_OK); } const char * http_media_type(const char *path) { const char *p; struct http_media_type *media; if ((p = strrchr(path, '.')) == NULL) return (NULL); p++; if (*p == '\0') return (NULL); LIST_FOREACH(media, &http_media_types, list) { if (!strcasecmp(media->ext, p)) return (media->type); } return (NULL); } char * http_validate_header(char *header) { u_int8_t idx; char *p, *value; for (p = header; *p != '\0'; p++) { idx = *p; if (idx > HTTP_MAP_LIMIT) return (NULL); if (*p == ':') { *(p)++ = '\0'; break; } if (http_token[idx] == 0x00) return (NULL); } while (isspace(*(unsigned char *)p)) p++; if (*p == '\0') return (NULL); value = p; while (*p != '\0') { idx = *p; if (idx > HTTP_MAP_LIMIT) return (NULL); if (http_field_content[idx] == 0x00) return (NULL); p++; } return (value); }
23.0625
78
0.651252
d20108c499d77262fc8c0cbbfbe5f7fb8c5762de
168
c
C
28Jan/1.c
s10singh97/OpearingSystem
b8ca5a05bb4f2716329fa77c635d6667dc5009be
[ "Apache-2.0" ]
null
null
null
28Jan/1.c
s10singh97/OpearingSystem
b8ca5a05bb4f2716329fa77c635d6667dc5009be
[ "Apache-2.0" ]
null
null
null
28Jan/1.c
s10singh97/OpearingSystem
b8ca5a05bb4f2716329fa77c635d6667dc5009be
[ "Apache-2.0" ]
null
null
null
// Exploring fork() #include<stdio.h> #include<unistd.h> #include<sys/types.h> int main() { fork(); fork(); fork(); printf("Hello\n"); return 0; }
12
22
0.559524
32649f28109342eeb3a2e498a375b67248d0517a
1,894
c
C
mDNSMacOSX/xpc_services/xpc_services.c
olivierlevon/mdnsresponder-1
c2a146765c5a8a392842bc97be04418039b00a20
[ "Apache-2.0" ]
4
2017-09-30T05:49:14.000Z
2020-01-18T12:26:10.000Z
mDNSMacOSX/xpc_services/xpc_services.c
olivierlevon/mdnsresponder-1
c2a146765c5a8a392842bc97be04418039b00a20
[ "Apache-2.0" ]
1
2018-08-21T04:12:55.000Z
2018-08-21T04:12:55.000Z
mDNSMacOSX/xpc_services/xpc_services.c
olivierlevon/mdnsresponder-1
c2a146765c5a8a392842bc97be04418039b00a20
[ "Apache-2.0" ]
2
2018-08-22T03:43:37.000Z
2019-11-01T19:09:18.000Z
/* * Copyright (c) 2019 Apple Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xpc_services.h" #include <xpc/private.h> // xpc_connection_copy_entitlement_value #include "mDNSMacOSX.h" // KQueueLock/KQueueUnlock #include "dnsproxy.h" // DNSProxyInit/ProxyUDPCallback/ProxyTCPCallback #include "xpc_service_dns_proxy.h" // init_dnsproxy_service #include "xpc_service_log_utility.h" // init_dnsctl_service extern mDNS mDNSStorage; mDNSexport void xpc_server_init() { // add XPC Services here init_dnsproxy_service(); init_log_utility_service(); } // Utilities mDNSexport mDNSBool IsEntitled(xpc_connection_t conn, const char *entitlement_name) { mDNSBool entitled = mDNSfalse; xpc_object_t entitled_obj = xpc_connection_copy_entitlement_value(conn, entitlement_name); if (entitled_obj) { if (xpc_get_type(entitled_obj) == XPC_TYPE_BOOL && xpc_bool_get_value(entitled_obj)) { entitled = mDNStrue; } xpc_release(entitled_obj); } else { LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "IsEntitled: Client Entitlement is NULL"); } if (!entitled) { LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "IsEntitled: Client is missing Entitlement!"); } return entitled; }
33.821429
109
0.712777
192ace2508dcfed5befb4124a20df454ed295826
6,353
c
C
EmbeddedPkg/Library/PrePiLib/PrePiLib.c
Bhaskers-Blu-Org2/mu_tiano_plus
054176f1f64b51d25d80da4bbd16aac9e3b40095
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
24
2019-06-11T02:47:59.000Z
2022-03-17T08:29:03.000Z
EmbeddedPkg/Library/PrePiLib/PrePiLib.c
Bhaskers-Blu-Org2/mu_tiano_plus
054176f1f64b51d25d80da4bbd16aac9e3b40095
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
5
2019-06-25T07:09:23.000Z
2021-03-30T01:04:59.000Z
EmbeddedPkg/Library/PrePiLib/PrePiLib.c
microsoft/mu_tiano_plus
46bfc9cff4a6960a2d021de92d875ed67915e081
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
19
2019-10-31T13:23:21.000Z
2022-03-11T05:58:36.000Z
/** @file Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PrePi.h> // // Hack to work in NT32 // EFI_STATUS EFIAPI SecWinNtPeiLoadFile ( IN VOID *Pe32Data, IN EFI_PHYSICAL_ADDRESS *ImageAddress, IN UINT64 *ImageSize, IN EFI_PHYSICAL_ADDRESS *EntryPoint ); STATIC VOID* EFIAPI AllocateCodePages ( IN UINTN Pages ) { VOID *Alloc; EFI_PEI_HOB_POINTERS Hob; Alloc = AllocatePages (Pages); if (Alloc == NULL) { return NULL; } // find the HOB we just created, and change the type to EfiBootServicesCode Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); while (Hob.Raw != NULL) { if (Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress == (UINTN)Alloc) { Hob.MemoryAllocation->AllocDescriptor.MemoryType = EfiBootServicesCode; return Alloc; } Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, GET_NEXT_HOB (Hob)); } ASSERT (FALSE); FreePages (Alloc, Pages); return NULL; } EFI_STATUS EFIAPI LoadPeCoffImage ( IN VOID *PeCoffImage, OUT EFI_PHYSICAL_ADDRESS *ImageAddress, OUT UINT64 *ImageSize, OUT EFI_PHYSICAL_ADDRESS *EntryPoint ) { RETURN_STATUS Status; PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; VOID *Buffer; ZeroMem (&ImageContext, sizeof (ImageContext)); ImageContext.Handle = PeCoffImage; ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory; Status = PeCoffLoaderGetImageInfo (&ImageContext); ASSERT_EFI_ERROR (Status); // // Allocate Memory for the image // Buffer = AllocateCodePages (EFI_SIZE_TO_PAGES((UINT32)ImageContext.ImageSize)); ASSERT (Buffer != 0); ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; // // Load the image to our new buffer // Status = PeCoffLoaderLoadImage (&ImageContext); ASSERT_EFI_ERROR (Status); // // Relocate the image in our new buffer // Status = PeCoffLoaderRelocateImage (&ImageContext); ASSERT_EFI_ERROR (Status); *ImageAddress = ImageContext.ImageAddress; *ImageSize = ImageContext.ImageSize; *EntryPoint = ImageContext.EntryPoint; // // Flush not needed for all architectures. We could have a processor specific // function in this library that does the no-op if needed. // InvalidateInstructionCacheRange ((VOID *)(UINTN)*ImageAddress, (UINTN)*ImageSize); return Status; } typedef VOID (EFIAPI *DXE_CORE_ENTRY_POINT) ( IN VOID *HobStart ); EFI_STATUS EFIAPI LoadDxeCoreFromFfsFile ( IN EFI_PEI_FILE_HANDLE FileHandle, IN UINTN StackSize ) { EFI_STATUS Status; VOID *PeCoffImage; EFI_PHYSICAL_ADDRESS ImageAddress; UINT64 ImageSize; EFI_PHYSICAL_ADDRESS EntryPoint; VOID *BaseOfStack; VOID *TopOfStack; VOID *Hob; EFI_FV_FILE_INFO FvFileInfo; Status = FfsFindSectionData (EFI_SECTION_PE32, FileHandle, &PeCoffImage); if (EFI_ERROR (Status)) { return Status; } Status = LoadPeCoffImage (PeCoffImage, &ImageAddress, &ImageSize, &EntryPoint); // For NT32 Debug Status = SecWinNtPeiLoadFile (PeCoffImage, &ImageAddress, &ImageSize, &EntryPoint); ASSERT_EFI_ERROR (Status); // // Extract the DxeCore GUID file name. // Status = FfsGetFileInfo (FileHandle, &FvFileInfo); ASSERT_EFI_ERROR (Status); BuildModuleHob (&FvFileInfo.FileName, (EFI_PHYSICAL_ADDRESS)(UINTN)ImageAddress, EFI_SIZE_TO_PAGES ((UINT32) ImageSize) * EFI_PAGE_SIZE, EntryPoint); DEBUG ((EFI_D_INFO | EFI_D_LOAD, "Loading DxeCore at 0x%10p EntryPoint=0x%10p\n", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)EntryPoint)); Hob = GetHobList (); if (StackSize == 0) { // User the current stack ((DXE_CORE_ENTRY_POINT)(UINTN)EntryPoint) (Hob); } else { // // Allocate 128KB for the Stack // BaseOfStack = AllocatePages (EFI_SIZE_TO_PAGES (StackSize)); ASSERT (BaseOfStack != NULL); // // Compute the top of the stack we were allocated. Pre-allocate a UINTN // for safety. // TopOfStack = (VOID *) ((UINTN) BaseOfStack + EFI_SIZE_TO_PAGES (StackSize) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT); // // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore. // UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN) BaseOfStack, StackSize); SwitchStack ( (SWITCH_STACK_ENTRY_POINT)(UINTN)EntryPoint, Hob, NULL, TopOfStack ); } // Should never get here as DXE Core does not return DEBUG ((EFI_D_ERROR, "DxeCore returned\n")); ASSERT (FALSE); return EFI_DEVICE_ERROR; } EFI_STATUS EFIAPI LoadDxeCoreFromFv ( IN UINTN *FvInstance, OPTIONAL IN UINTN StackSize ) { EFI_STATUS Status; EFI_PEI_FV_HANDLE VolumeHandle; EFI_PEI_FILE_HANDLE FileHandle = NULL; if (FvInstance != NULL) { // // Caller passed in a specific FV to try, so only try that one // Status = FfsFindNextVolume (*FvInstance, &VolumeHandle); if (!EFI_ERROR (Status)) { Status = FfsFindNextFile (EFI_FV_FILETYPE_DXE_CORE, VolumeHandle, &FileHandle); } } else { Status = FfsAnyFvFindFirstFile (EFI_FV_FILETYPE_DXE_CORE, &VolumeHandle, &FileHandle); } if (!EFI_ERROR (Status)) { return LoadDxeCoreFromFfsFile (FileHandle, StackSize); } return Status; } EFI_STATUS EFIAPI DecompressFirstFv ( VOID ) { EFI_STATUS Status; EFI_PEI_FV_HANDLE VolumeHandle; EFI_PEI_FILE_HANDLE FileHandle; Status = FfsAnyFvFindFirstFile (EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, &VolumeHandle, &FileHandle); if (!EFI_ERROR (Status)) { Status = FfsProcessFvFile (FileHandle, VolumeHandle); // MU_CHANGE } return Status; }
25.210317
152
0.641429
d2980575688d6fa3ac547fdbe63eadef440a8ace
555
h
C
PonyChatUI/Classes/User Interface/Interactor/PCULinkMessageItemInteractor.h
PonyGroup/PonyChatUIV2
35f71fc672dc094d56726d7a3f8355375d53d272
[ "MIT" ]
121
2015-07-09T00:55:37.000Z
2020-10-08T19:36:10.000Z
PonyChatUI/Classes/User Interface/Interactor/PCULinkMessageItemInteractor.h
200895045/PonyChatUIV2
35f71fc672dc094d56726d7a3f8355375d53d272
[ "MIT" ]
null
null
null
PonyChatUI/Classes/User Interface/Interactor/PCULinkMessageItemInteractor.h
200895045/PonyChatUIV2
35f71fc672dc094d56726d7a3f8355375d53d272
[ "MIT" ]
36
2015-07-08T23:36:51.000Z
2021-01-28T09:46:08.000Z
// // PCULinkMessageItemInteractor.h // PonyChatUIV2 // // Created by 崔 明辉 on 15/9/14. // Copyright © 2015年 PonyCui. All rights reserved. // #import <Foundation/Foundation.h> #import "PCUMessageItemInteractor.h" @interface PCULinkMessageItemInteractor : PCUMessageItemInteractor @property (nonatomic, copy) NSString *titleString; @property (nonatomic, copy) NSString *subTitleString; @property (nonatomic, copy) NSString *thumbURLString; @property (nonatomic, copy) NSString *linkURLString; @property (nonatomic, assign) BOOL largerLink; @end
22.2
66
0.765766
d2a892eb75c82e8b92c18ad5b782e2b41f479337
991
h
C
src/tmbasic/UndoStack.h
sdizdarevic/tmbasic
fac8edd931eb1a457b93a783bd43134fc76debc5
[ "MIT" ]
49
2020-11-26T10:50:04.000Z
2022-03-29T13:54:51.000Z
src/tmbasic/UndoStack.h
sdizdarevic/tmbasic
fac8edd931eb1a457b93a783bd43134fc76debc5
[ "MIT" ]
5
2020-11-20T23:17:46.000Z
2022-03-31T04:50:03.000Z
src/tmbasic/UndoStack.h
sdizdarevic/tmbasic
fac8edd931eb1a457b93a783bd43134fc76debc5
[ "MIT" ]
5
2021-06-29T13:48:29.000Z
2022-03-10T23:22:18.000Z
#pragma once #include "../common.h" namespace tmbasic { const size_t kUndoStackLimit = 100; template <typename TDocument> class UndoStack { public: bool canUndo() { return !_undos.empty(); } bool canRedo() { return !_redos.empty(); } void push(TDocument document) { _redos = {}; _undos.push_back(std::move(document)); if (_undos.size() > kUndoStackLimit) { _undos.erase(_undos.begin()); } } void abandon() { _undos.pop_back(); } TDocument undo(TDocument current) { _redos.push(std::move(current)); auto doc = std::move(_undos.at(_undos.size() - 1)); _undos.pop_back(); return doc; } TDocument redo(TDocument current) { _undos.push_back(std::move(current)); auto doc = std::move(_redos.top()); _redos.pop(); return doc; } private: std::vector<TDocument> _undos{}; std::stack<TDocument> _redos{}; }; } // namespace tmbasic
21.543478
59
0.588295
d2c742b1d4b543b8ddd0816cda9dfa83b4fb6da4
1,407
h
C
Source/Math/Inc/Math/Plane.h
vasumahesh1/azura
80aa23e2fb498e6288484bc49b0d5b8889db6ebb
[ "MIT" ]
12
2019-01-08T23:10:37.000Z
2021-06-04T09:48:42.000Z
Source/Math/Inc/Math/Plane.h
vasumahesh1/azura
80aa23e2fb498e6288484bc49b0d5b8889db6ebb
[ "MIT" ]
38
2017-04-05T00:27:24.000Z
2018-12-25T08:34:04.000Z
Source/Math/Inc/Math/Plane.h
vasumahesh1/azura
80aa23e2fb498e6288484bc49b0d5b8889db6ebb
[ "MIT" ]
4
2019-03-27T10:07:32.000Z
2021-07-15T03:22:27.000Z
#pragma once #include "Math/Core.h" #include "Math/Geometry.h" #include <vector> namespace Azura { namespace Math { class Plane final : public Geometry { public: Plane(const Vector2f& boundMin , const Vector2f& boundMax); Plane(const Vector2f& boundMin , const Vector2f& boundMax, const Vector2u& subDivisions, const Vector2u& uvScale); U32 VertexDataSize() const override; U32 IndexDataSize() const override; U32 UVDataSize() const override; const U8* VertexData() const override; const U8* IndexData() const override; const U8* UVData() const override; RawStorageFormat GetVertexFormat() const override; RawStorageFormat GetIndexFormat() const override; U32 GetVertexCount() const override; U32 GetIndexCount() const override; U32 TotalDataSize() const override; const std::vector<Vector4f>& GetVertices() const; std::vector<Vector4f>& GetVertices(); const std::vector<Vector3f>& GetNormals() const; std::vector<Vector3f>& GetNormals(); U32 NormalDataSize() const override; const U8* NormalData() const override; RawStorageFormat GetNormalFormat() const override; RawStorageFormat GetUVFormat() const override; private: std::vector<Vector4f> m_vertices; std::vector<Vector2f> m_uv; std::vector<Vector3f> m_normals{}; std::vector<Vector3u> m_triangles; }; } // namespace Math } // namespace Azura
29.3125
117
0.721393
c5714e75ecf4c86bbef912eee06103d25a063832
3,582
h
C
Source/WebCore/Modules/geolocation/Coordinates.h
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
Source/WebCore/Modules/geolocation/Coordinates.h
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebCore/Modules/geolocation/Coordinates.h
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2009 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <wtf/Optional.h> #include <wtf/Ref.h> #include <wtf/RefCounted.h> namespace WebCore { class Coordinates : public RefCounted<Coordinates> { public: static Ref<Coordinates> create(double latitude, double longitude, bool providesAltitude, double altitude, double accuracy, bool providesAltitudeAccuracy, double altitudeAccuracy, bool providesHeading, double heading, bool providesSpeed, double speed) { return adoptRef(*new Coordinates(latitude, longitude, providesAltitude, altitude, accuracy, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed)); } Ref<Coordinates> isolatedCopy() const { return Coordinates::create(m_latitude, m_longitude, m_canProvideAltitude, m_altitude, m_accuracy, m_canProvideAltitudeAccuracy, m_altitudeAccuracy, m_canProvideHeading, m_heading, m_canProvideSpeed, m_speed); } double latitude() const { return m_latitude; } double longitude() const { return m_longitude; } std::optional<double> altitude() const; double accuracy() const { return m_accuracy; } std::optional<double> altitudeAccuracy() const; std::optional<double> heading() const; std::optional<double> speed() const; private: Coordinates(double latitude, double longitude, bool providesAltitude, double altitude, double accuracy, bool providesAltitudeAccuracy, double altitudeAccuracy, bool providesHeading, double heading, bool providesSpeed, double speed) : m_latitude(latitude) , m_longitude(longitude) , m_altitude(altitude) , m_accuracy(accuracy) , m_altitudeAccuracy(altitudeAccuracy) , m_heading(heading) , m_speed(speed) , m_canProvideAltitude(providesAltitude) , m_canProvideAltitudeAccuracy(providesAltitudeAccuracy) , m_canProvideHeading(providesHeading) , m_canProvideSpeed(providesSpeed) { } double m_latitude; double m_longitude; double m_altitude; double m_accuracy; double m_altitudeAccuracy; double m_heading; double m_speed; bool m_canProvideAltitude; bool m_canProvideAltitudeAccuracy; bool m_canProvideHeading; bool m_canProvideSpeed; }; } // namespace WebCore
43.682927
444
0.749302
3068497a1285ff1b6fd00966fce40a9eddf0d66d
884
h
C
Other/Headers/WAAppAuthorizationCellView.h
XWJACK/WeChatPlugin-MacOS
4241ddb10ccce9484fcf6d5bd51a6afa3b446632
[ "MIT" ]
2
2019-01-11T02:02:55.000Z
2020-04-23T02:42:01.000Z
Other/Headers/WAAppAuthorizationCellView.h
XWJACK/WeChatPlugin-MacOS
4241ddb10ccce9484fcf6d5bd51a6afa3b446632
[ "MIT" ]
null
null
null
Other/Headers/WAAppAuthorizationCellView.h
XWJACK/WeChatPlugin-MacOS
4241ddb10ccce9484fcf6d5bd51a6afa3b446632
[ "MIT" ]
1
2021-01-09T14:54:27.000Z
2021-01-09T14:54:27.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <AppKit/NSTableCellView.h> @class ITSwitch, MMUILabel; @protocol WAAppAuthorizationCellViewDelegate; @interface WAAppAuthorizationCellView : NSTableCellView { id <WAAppAuthorizationCellViewDelegate> _delegate; MMUILabel *_titleLabel; ITSwitch *_authSwitch; } @property(retain, nonatomic) ITSwitch *authSwitch; // @synthesize authSwitch=_authSwitch; @property(retain, nonatomic) MMUILabel *titleLabel; // @synthesize titleLabel=_titleLabel; @property(nonatomic) __weak id <WAAppAuthorizationCellViewDelegate> delegate; // @synthesize delegate=_delegate; - (void).cxx_destruct; - (void)onSwitchChange:(id)arg1; - (void)initViews; - (id)initWithFrame:(struct CGRect)arg1; @end
30.482759
112
0.760181
d04f50bb6e9a09ecad585e38892418cb0a12fc0e
926
c
C
UVa/UVa105/105.c
mythnc/online-judge-solved-lists
c8db91674298f74539312a763ff52c2ba0d9794d
[ "MIT" ]
null
null
null
UVa/UVa105/105.c
mythnc/online-judge-solved-lists
c8db91674298f74539312a763ff52c2ba0d9794d
[ "MIT" ]
null
null
null
UVa/UVa105/105.c
mythnc/online-judge-solved-lists
c8db91674298f74539312a763ff52c2ba0d9794d
[ "MIT" ]
null
null
null
/* ACM 105 The Skyline Problem * mythnc * 2012/01/07 09:19:19 * run time: 0.02 */ #include <stdio.h> #define MAXH 10000 typedef struct build { int s, e, h; } Build; void update(Build); void print(void); int sky[MAXH]; int main(void) { Build x; while (scanf("%d %d %d", &x.s, &x.h, &x.e) == 3) update(x); print(); return 0; } /* update: update sky line */ void update(Build x) { int i; for (i = x.s; i < x.e; i++) if (x.h > sky[i]) sky[i] = x.h; } /* print: print out result */ void print(void) { int i, h; /* find the first building */ for (i = h = 0; i < MAXH; i++) if (sky[i] != h) { printf("%d %d", i, sky[i]); h = sky[i]; break; } for (i++; i < MAXH; i++) if (sky[i] != h) { printf(" %d %d", i, sky[i]); h = sky[i]; } putchar('\n'); }
15.433333
52
0.441685
aa198cc4481c80a82e34c98b22e8f4a2ee112329
15,534
c
C
examples/enjoy/audio_udp/audio_udp/main.c
jsaiko/framework-bouffalo-sdk
dff9054b3ebfa9008ce747c5e347829b89247faa
[ "Apache-2.0" ]
1
2022-02-21T04:38:23.000Z
2022-02-21T04:38:23.000Z
examples/enjoy/audio_udp/audio_udp/main.c
Community-BL-IOT/framework-bouffalo-sdk
dff9054b3ebfa9008ce747c5e347829b89247faa
[ "Apache-2.0" ]
null
null
null
examples/enjoy/audio_udp/audio_udp/main.c
Community-BL-IOT/framework-bouffalo-sdk
dff9054b3ebfa9008ce747c5e347829b89247faa
[ "Apache-2.0" ]
null
null
null
#include <FreeRTOS.h> #include <task.h> #include <timers.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <vfs.h> #include <aos/kernel.h> #include <aos/yloop.h> #include <event_device.h> #include <cli.h> #include <lwip/tcpip.h> #include <lwip/sockets.h> #include <lwip/netdb.h> #include <lwip/tcp.h> #include <lwip/err.h> #include <http_client.h> #include <netutils/netutils.h> #include <bl602_glb.h> #include <bl602_hbn.h> #include <bl_sys.h> #include <bl_uart.h> #include <bl_chip.h> #include <bl_wifi.h> #include <hal_wifi.h> #include <bl_sec.h> #include <bl_cks.h> #include <bl_irq.h> #include <bl_dma.h> #include <bl_gpio_cli.h> #include <bl_wdt_cli.h> #include <hal_sys.h> #include <hal_gpio.h> #include <hal_boot2.h> #include <hal_board.h> #include <looprt.h> #include <loopset.h> #include <sntp.h> #include <bl_sys_time.h> #include <bl_sys_ota.h> #include <bl_romfs.h> #include <fdt.h> #include <easyflash.h> #include <bl60x_fw_api.h> #include <wifi_mgmr_ext.h> #include <utils_log.h> #include <libfdt.h> #include <blog.h> #include "audio_tts.h" #define TASK_PRIORITY_FW ( 30 ) #define mainHELLO_TASK_PRIORITY ( 20 ) #define UART_ID_2 (2) #define WIFI_AP_PSM_INFO_SSID "conf_ap_ssid" #define WIFI_AP_PSM_INFO_PASSWORD "conf_ap_psk" #define WIFI_AP_PSM_INFO_PMK "conf_ap_pmk" #define WIFI_AP_PSM_INFO_BSSID "conf_ap_bssid" #define WIFI_AP_PSM_INFO_CHANNEL "conf_ap_channel" #define WIFI_AP_PSM_INFO_IP "conf_ap_ip" #define WIFI_AP_PSM_INFO_MASK "conf_ap_mask" #define WIFI_AP_PSM_INFO_GW "conf_ap_gw" #define WIFI_AP_PSM_INFO_DNS1 "conf_ap_dns1" #define WIFI_AP_PSM_INFO_DNS2 "conf_ap_dns2" #define WIFI_AP_PSM_INFO_IP_LEASE_TIME "conf_ap_ip_lease_time" #define WIFI_AP_PSM_INFO_GW_MAC "conf_ap_gw_mac" #define CLI_CMD_AUTOSTART1 "cmd_auto1" #define CLI_CMD_AUTOSTART2 "cmd_auto2" extern void ble_stack_start(void); static wifi_conf_t conf = { .country_code = "CN", }; static wifi_interface_t wifi_interface; static unsigned char char_to_hex(char asccode) { unsigned char ret; if('0'<=asccode && asccode<='9') ret=asccode-'0'; else if('a'<=asccode && asccode<='f') ret=asccode-'a'+10; else if('A'<=asccode && asccode<='F') ret=asccode-'A'+10; else ret=0; return ret; } static void _chan_str_to_hex(uint8_t *chan_band, uint16_t *chan_freq, char *chan) { int i, freq_len, base=1; uint8_t band; uint16_t freq = 0; char *p, *q; /*should have the following format * 2412|0 * */ p = strchr(chan, '|') + 1; if (NULL == p) { return; } band = char_to_hex(p[0]); (*chan_band) = band; freq_len = strlen(chan) - strlen(p) - 1; q = chan; q[freq_len] = '\0'; for (i=0; i< freq_len; i++) { freq = freq + char_to_hex(q[freq_len-1-i]) * base; base = base * 10; } (*chan_freq) = freq; } static void bssid_str_to_mac(uint8_t *hex, char *bssid, int len) { unsigned char l4,h4; int i,lenstr; lenstr = len; if(lenstr%2) { lenstr -= (lenstr%2); } if(lenstr==0){ return; } for(i=0; i < lenstr; i+=2) { h4=char_to_hex(bssid[i]); l4=char_to_hex(bssid[i+1]); hex[i/2]=(h4<<4)+l4; } } static void _connect_wifi() { /*XXX caution for BIG STACK*/ char pmk[66], bssid[32], chan[10]; char ssid[33], password[66]; char val_buf[66]; char val_len = sizeof(val_buf) - 1; uint8_t mac[6]; uint8_t band = 0; uint16_t freq = 0; wifi_interface = wifi_mgmr_sta_enable(); printf("[APP] [WIFI] [T] %lld\r\n" "[APP] Get STA %p from Wi-Fi Mgmr, pmk ptr %p, ssid ptr %p, password %p\r\n", aos_now_ms(), wifi_interface, pmk, ssid, password ); memset(pmk, 0, sizeof(pmk)); memset(ssid, 0, sizeof(ssid)); memset(password, 0, sizeof(password)); memset(bssid, 0, sizeof(bssid)); memset(mac, 0, sizeof(mac)); memset(chan, 0, sizeof(chan)); memset(val_buf, 0, sizeof(val_buf)); ef_get_env_blob((const char *)WIFI_AP_PSM_INFO_SSID, val_buf, val_len, NULL); if (val_buf[0]) { /*We believe that when ssid is set, wifi_confi is OK*/ strncpy(ssid, val_buf, sizeof(ssid) - 1); } else { /*Won't connect, since ssid config is empty*/ puts("[APP] Empty Config\r\n"); puts("[APP] Try to set the following ENV with psm_set command, then reboot\r\n"); puts("[APP] NOTE: " WIFI_AP_PSM_INFO_PMK " MUST be psm_unset when conf is changed\r\n"); puts("[APP] env: " WIFI_AP_PSM_INFO_SSID "\r\n"); puts("[APP] env: " WIFI_AP_PSM_INFO_PASSWORD "\r\n"); puts("[APP] env(optinal): " WIFI_AP_PSM_INFO_PMK "\r\n"); return; } memset(val_buf, 0, sizeof(val_buf)); ef_get_env_blob((const char *)WIFI_AP_PSM_INFO_PASSWORD, val_buf, val_len, NULL); if (val_buf[0]) { strncpy(password, val_buf, sizeof(password) - 1); } memset(val_buf, 0, sizeof(val_buf)); ef_get_env_blob((const char *)WIFI_AP_PSM_INFO_PMK, val_buf, val_len, NULL); if (val_buf[0]) { strncpy(pmk, val_buf, sizeof(pmk) - 1); } if (0 == pmk[0]) { printf("[APP] [WIFI] [T] %lld\r\n", aos_now_ms() ); puts("[APP] Re-cal pmk\r\n"); /*At lease pmk is not illegal, we re-cal now*/ //XXX time consuming API, so consider lower-prirotiy for cal PSK to avoid sound glitch wifi_mgmr_psk_cal( password, ssid, strlen(ssid), pmk ); ef_set_env(WIFI_AP_PSM_INFO_PMK, pmk); ef_save_env(); } memset(val_buf, 0, sizeof(val_buf)); ef_get_env_blob((const char *)WIFI_AP_PSM_INFO_CHANNEL, val_buf, val_len, NULL); if (val_buf[0]) { strncpy(chan, val_buf, sizeof(chan) - 1); printf("connect wifi channel = %s\r\n", chan); _chan_str_to_hex(&band, &freq, chan); } memset(val_buf, 0, sizeof(val_buf)); ef_get_env_blob((const char *)WIFI_AP_PSM_INFO_BSSID, val_buf, val_len, NULL); if (val_buf[0]) { strncpy(bssid, val_buf, sizeof(bssid) - 1); printf("connect wifi bssid = %s\r\n", bssid); bssid_str_to_mac(mac, bssid, strlen(bssid)); printf("mac = %02X:%02X:%02X:%02X:%02X:%02X\r\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] ); } printf("[APP] [WIFI] [T] %lld\r\n" "[APP] SSID %s\r\n" "[APP] SSID len %d\r\n" "[APP] password %s\r\n" "[APP] password len %d\r\n" "[APP] pmk %s\r\n" "[APP] bssid %s\r\n" "[APP] channel band %d\r\n" "[APP] channel freq %d\r\n", aos_now_ms(), ssid, strlen(ssid), password, strlen(password), pmk, bssid, band, freq ); //wifi_mgmr_sta_connect(wifi_interface, ssid, pmk, NULL); wifi_mgmr_sta_connect(wifi_interface, ssid, password, pmk, mac, band, freq); } static void wifi_sta_connect(char *ssid, char *password) { wifi_interface_t wifi_interface; wifi_interface = wifi_mgmr_sta_enable(); wifi_mgmr_sta_connect(wifi_interface, ssid, password, NULL, NULL, 0, 0); } static void event_cb_wifi_event(input_event_t *event, void *private_data) { static char *ssid; static char *password; switch (event->code) { case CODE_WIFI_ON_INIT_DONE: { printf("[APP] [EVT] INIT DONE %lld\r\n", aos_now_ms()); wifi_mgmr_start_background(&conf); } break; case CODE_WIFI_ON_MGMR_DONE: { printf("[APP] [EVT] MGMR DONE %lld\r\n", aos_now_ms()); _connect_wifi(); } break; case CODE_WIFI_ON_SCAN_DONE: { printf("[APP] [EVT] SCAN Done %lld, SCAN Result: %s\r\n", aos_now_ms(), WIFI_SCAN_DONE_EVENT_OK == event->value ? "OK" : "Busy now" ); wifi_mgmr_cli_scanlist(); } break; case CODE_WIFI_ON_DISCONNECT: { printf("[APP] [EVT] disconnect %lld, Reason: %s\r\n", aos_now_ms(), wifi_mgmr_status_code_str(event->value) ); } break; case CODE_WIFI_ON_CONNECTING: { printf("[APP] [EVT] Connecting %lld\r\n", aos_now_ms()); } break; case CODE_WIFI_CMD_RECONNECT: { printf("[APP] [EVT] Reconnect %lld\r\n", aos_now_ms()); } break; case CODE_WIFI_ON_CONNECTED: { printf("[APP] [EVT] connected %lld\r\n", aos_now_ms()); } break; case CODE_WIFI_ON_PRE_GOT_IP: { printf("[APP] [EVT] connected %lld\r\n", aos_now_ms()); } break; case CODE_WIFI_ON_GOT_IP: { printf("[APP] [EVT] GOT IP %lld\r\n", aos_now_ms()); printf("[SYS] Memory left is %d Bytes\r\n", xPortGetFreeHeapSize()); } break; case CODE_WIFI_ON_PROV_SSID: { printf("[APP] [EVT] [PROV] [SSID] %lld: %s\r\n", aos_now_ms(), event->value ? (const char*)event->value : "UNKNOWN" ); if (ssid) { vPortFree(ssid); ssid = NULL; } ssid = (char*)event->value; } break; case CODE_WIFI_ON_PROV_BSSID: { printf("[APP] [EVT] [PROV] [BSSID] %lld: %s\r\n", aos_now_ms(), event->value ? (const char*)event->value : "UNKNOWN" ); if (event->value) { vPortFree((void*)event->value); } } break; case CODE_WIFI_ON_PROV_PASSWD: { printf("[APP] [EVT] [PROV] [PASSWD] %lld: %s\r\n", aos_now_ms(), event->value ? (const char*)event->value : "UNKNOWN" ); if (password) { vPortFree(password); password = NULL; } password = (char*)event->value; } break; case CODE_WIFI_ON_PROV_CONNECT: { printf("[APP] [EVT] [PROV] [CONNECT] %lld\r\n", aos_now_ms()); printf("connecting to %s:%s...\r\n", ssid, password); wifi_sta_connect(ssid, password); } break; case CODE_WIFI_ON_PROV_DISCONNECT: { printf("[APP] [EVT] [PROV] [DISCONNECT] %lld\r\n", aos_now_ms()); } break; default: { printf("[APP] [EVT] Unknown code %u, %lld\r\n", event->code, aos_now_ms()); /*nothing*/ } } } static void cmd_stack_wifi(char *buf, int len, int argc, char **argv) { /*wifi fw stack and thread stuff*/ static uint8_t stack_wifi_init = 0; if (1 == stack_wifi_init) { puts("Wi-Fi Stack Started already!!!\r\n"); return; } stack_wifi_init = 1; hal_wifi_start_firmware_task(); /*Trigger to start Wi-Fi*/ aos_post_event(EV_WIFI, CODE_WIFI_ON_INIT_DONE, 0); } static audio_tts_dev_t audio; #define IPERF_PORT_LOCAL 5002 #define IPERF_PORT 10500 #define IPERF_BUFSZ (4 * 256) #define IPERF_BUFSZ_UDP (1 * 256) #define DEBUG_HEADER "[NET] [IPC] " //#define DEFAULT_HOST_IP "192.168.55.109" static void __udp_task (void *p_arg) { int sock = 0; int ret; int fd_audio; uint64_t num_int; int num_decimal; romfs_filebuf_t filebuf1, filebuf2; struct sockaddr_in laddr; uint8_t *recv_buf; num_int =0; num_decimal = 0; int bl602_dac_device_fake(void); bl602_dac_device_fake(); fd_audio = aos_open("/romfs/voice", 0); if (fd_audio < 0) { printf("open failed\r\n"); } aos_ioctl(fd_audio, IOCTL_ROMFS_GET_FILEBUF, (long unsigned int)&filebuf1); aos_close(fd_audio); fd_audio = aos_open("/romfs/yuan", 0); if (fd_audio < 0) { printf("open failed\r\n"); } aos_ioctl(fd_audio, IOCTL_ROMFS_GET_FILEBUF, (long unsigned int)&filebuf2); aos_close(fd_audio); audio_tts_init(&audio, "bl602_dac"); cmd_stack_wifi(NULL, 0, NULL, NULL); vTaskDelay(2000); aos_cli_input_direct("wifi_ap_start\r\n", strlen("wifi_ap_start\r\n")); vTaskDelay(2000); recv_buf = (uint8_t *) pvPortMalloc (IPERF_BUFSZ_UDP); if (!recv_buf) { vPortFree(p_arg); goto __exit; } sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock < 0) { printf("create socket failed!\r\n"); vTaskDelay(1000); vPortFree(p_arg); goto __exit; } memset(&laddr, 0, sizeof(struct sockaddr_in)); laddr.sin_family = PF_INET; laddr.sin_port = htons(IPERF_PORT_LOCAL); laddr.sin_addr.s_addr = inet_addr("0.0.0.0"); ret = bind(sock, (struct sockaddr*)&laddr, sizeof(laddr)); if (ret == -1) { printf("Bind failed!\r\n"); lwip_close(sock); vTaskDelay(1000); vPortFree(p_arg); goto __exit; } printf("bind UDP socket successfully!\r\n"); while (1) { num_int = 0; num_decimal = 0; memset(recv_buf, 0, sizeof(recv_buf)); ret = recv(sock, recv_buf, 40, 0); if (ret > 0) { sscanf((const char *)recv_buf, "%lld.%02d", &num_int, &num_decimal); audio_tts_characters_play(&audio, &filebuf1, NULL, NULL); audio_tts_num_play(&audio, num_int, num_decimal, NULL, NULL); audio_tts_characters_play(&audio, &filebuf2, NULL, NULL); audio_tts_start(&audio); printf("receive %lld.%02d\r\n", num_int, num_decimal); } vTaskDelay(10); } __exit: lwip_close(sock); vTaskDelay(1000*2); vTaskDelete(NULL); } static void _cli_init() { /*Put CLI which needs to be init here*/ easyflash_cli_init(); network_netutils_iperf_cli_register(); sntp_cli_init(); bl_sys_time_cli_init(); bl_sys_ota_cli_init(); blfdt_cli_init(); wifi_mgmr_cli_init(); bl_wdt_cli_init(); bl_gpio_cli_init(); looprt_test_cli_init(); } static void proc_main_entry(void *pvParameters) { static StackType_t udp_stack[1024]; static StaticTask_t udp_task; _cli_init(); aos_register_event_filter(EV_WIFI, event_cb_wifi_event, NULL); xTaskCreateStatic(__udp_task, (char*)"udp", 1024, NULL, 15, udp_stack, &udp_task); vTaskDelete(NULL); } static void system_thread_init() { /*nothing here*/ } void main() { static StaticTask_t proc_main_task; static StackType_t proc_main_stack[1024]; bl_sys_init(); system_thread_init(); puts("[OS] proc_main_entry task...\r\n"); xTaskCreateStatic(proc_main_entry, (char*)"main_entry", 1024, NULL, 15, proc_main_stack, &proc_main_task); puts("[OS] Starting TCP/IP Stack...\r\n"); tcpip_init(NULL, NULL); }
27.348592
110
0.56798
a60f277cdbec7cad9d1ebf3051282ffc84f3c93b
1,644
c
C
JLFGameplayKit/JLFGKGeometry.c
mohiji/JLFGameplayKit
0fcd58d9d37133b14cce346c6d4d2521c9a19059
[ "BSD-3-Clause" ]
30
2015-07-24T06:23:02.000Z
2018-11-13T19:35:40.000Z
JLFGameplayKit/JLFGKGeometry.c
mohiji/JLFGameplayKit
0fcd58d9d37133b14cce346c6d4d2521c9a19059
[ "BSD-3-Clause" ]
null
null
null
JLFGameplayKit/JLFGKGeometry.c
mohiji/JLFGameplayKit
0fcd58d9d37133b14cce346c6d4d2521c9a19059
[ "BSD-3-Clause" ]
5
2015-06-27T15:52:33.000Z
2020-10-09T18:33:12.000Z
// // JLFGKGeometry.c // JLFGameplayKit // // Created by Jonathan Fischer on 7/16/15. // #include "JLFGKGeometry.h" #include <math.h> // This is adapted from the wonderful StackOverflow answer here:' // http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect bool line_segments_intersect(vector_float2 p1, vector_float2 p2, vector_float2 q1, vector_float2 q2) { vector_float2 r = {p2.x - p1.x, p2.y - p1.y}; vector_float2 s = {q2.x - q1.x, q2.y - q1.y}; vector_float2 q_minus_p = {q1.x - p1.x, q1.y - p1.y}; float r_cross_s = vector_cross(r, s).z; float q_minus_p_cross_r = vector_cross(q_minus_p, r).z; float q_minus_p_cross_s = vector_cross(q_minus_p, s).z; if (q_minus_p_cross_r == 0 && r_cross_s == 0) { // The lines are colinear float magnitude_r = vector_length(r); float s_dot_r = vector_dot(s, r); float t0 = vector_dot(q_minus_p, r) / magnitude_r; float t1 = t0 + s_dot_r / magnitude_r; return ((t0 >= 0 && t0 <= 1) || (t1 >= 0 && t1 <= 1)); } else if (r_cross_s == 0 && q_minus_p_cross_r != 0) { // The lines are parallel and non-intersecting return false; } else if (r_cross_s != 0) { float t = q_minus_p_cross_s / r_cross_s; float u = q_minus_p_cross_r / r_cross_s; // Normally you'd want to test for 0 <= t <= 1 && 0 <= u <= 1, but // that would mean that two lines that share the same endpoint are // marked as intersecting, which isn't what we want for our use case. return t > 0 && t < 1 && u > 0 && u < 1; } return false; }
36.533333
100
0.623479
802f0a325a7cb116d6e2680b26d5df519664bbb3
3,899
c
C
test/core/shared-bus.c
sailfishos-mirror/dbus-glib
6ab7c2c6a2a389d6bf01387966e9debbb6b6ee77
[ "AFL-2.1" ]
8
2018-12-04T08:55:46.000Z
2021-08-08T01:43:53.000Z
test/core/shared-bus.c
sailfishos-mirror/dbus-glib
6ab7c2c6a2a389d6bf01387966e9debbb6b6ee77
[ "AFL-2.1" ]
null
null
null
test/core/shared-bus.c
sailfishos-mirror/dbus-glib
6ab7c2c6a2a389d6bf01387966e9debbb6b6ee77
[ "AFL-2.1" ]
null
null
null
/* Regression test for the shared bus instance. * This test is expected to "leak" the shared connection. * * Copyright © 2006-2010 Red Hat, Inc. * Copyright © 2006-2008 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright © 2011 Nokia Corporation * * SPDX-License-Identifier: AFL-2.1 OR GPL-2.0-or-later * * Licensed under the Academic Free License version 2.1 * * 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 */ #include <config.h> #undef G_DISABLE_ASSERT #include <glib.h> #include <dbus/dbus-glib.h> #include <dbus/dbus-glib-lowlevel.h> GMainLoop *loop = NULL; typedef struct { DBusGConnection *bus; DBusGConnection *priv; GError *error; } Fixture; static void destroy_cb (DBusGProxy *proxy G_GNUC_UNUSED, gpointer user_data) { gboolean *disconnected = user_data; *disconnected = TRUE; } static void disconnect (DBusGConnection **bus) { DBusGProxy *proxy; gboolean disconnected = FALSE; g_printerr ("Disconnecting... "); dbus_connection_set_exit_on_disconnect (dbus_g_connection_get_connection (*bus), FALSE); proxy = dbus_g_proxy_new_for_peer (*bus, "/", "org.freedesktop.DBus.Peer"); g_signal_connect (G_OBJECT (proxy), "destroy", G_CALLBACK (destroy_cb), &disconnected); dbus_connection_close (dbus_g_connection_get_connection (*bus)); while (!disconnected) { g_printerr ("."); g_main_context_iteration (NULL, TRUE); } g_signal_handlers_disconnect_by_func (proxy, destroy_cb, &disconnected); g_object_unref (proxy); dbus_g_connection_unref (*bus); *bus = NULL; g_printerr (" disconnected\n"); } static void setup (Fixture *f, gconstpointer test_data G_GNUC_UNUSED) { } static void teardown (Fixture *f, gconstpointer test_data G_GNUC_UNUSED) { if (f->bus != NULL) dbus_g_connection_unref (f->bus); if (f->priv != NULL) disconnect (&f->priv); g_clear_error (&f->error); dbus_shutdown (); } static void test_shared_bus (Fixture *f, gconstpointer test_data G_GNUC_UNUSED) { f->bus = dbus_g_bus_get (DBUS_BUS_SESSION, &f->error); g_assert_no_error (f->error); g_assert_nonnull (f->bus); dbus_connection_set_exit_on_disconnect (dbus_g_connection_get_connection (f->bus), FALSE); g_assert_true (f->bus == dbus_g_bus_get (DBUS_BUS_SESSION, NULL)); g_assert_true (f->bus == dbus_g_bus_get (DBUS_BUS_SESSION, NULL)); g_assert_true (f->bus == dbus_g_bus_get (DBUS_BUS_SESSION, NULL)); f->priv = dbus_g_bus_get_private (DBUS_BUS_SESSION, NULL, &f->error); g_assert_no_error (f->error); g_assert_nonnull (f->priv); g_assert_true (f->priv != f->bus); dbus_connection_set_exit_on_disconnect (dbus_g_connection_get_connection (f->priv), FALSE); } int main (int argc, char **argv) { g_type_init (); g_log_set_always_fatal (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL); g_test_bug_base ("https://bugs.freedesktop.org/show_bug.cgi?id="); g_test_init (&argc, &argv, NULL); g_test_add ("/shared-bus", Fixture, NULL, setup, test_shared_bus, teardown); return g_test_run (); }
28.05036
85
0.690946
341671e8ea443eabfad63d52532d82af0bc6cd2a
28,902
c
C
zthin-parts/zthin/src/smcliProfile.c
jasealpers/python-zvm-sdk
feb19dd40915b1a6cad74e7ccda17bc76d015ea5
[ "Apache-2.0" ]
15
2019-08-14T20:15:17.000Z
2020-09-28T01:09:48.000Z
zthin-parts/zthin/src/smcliProfile.c
jasealpers/python-zvm-sdk
feb19dd40915b1a6cad74e7ccda17bc76d015ea5
[ "Apache-2.0" ]
179
2019-09-05T03:53:10.000Z
2020-10-09T07:21:40.000Z
zthin-parts/zthin/src/smcliProfile.c
jasealpers/python-zvm-sdk
feb19dd40915b1a6cad74e7ccda17bc76d015ea5
[ "Apache-2.0" ]
50
2019-06-14T16:51:53.000Z
2020-08-27T05:36:38.000Z
/** * Copyright 2017 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "smcliProfile.h" #include "wrapperutils.h" int profileCreateDM(int argC, char* argV[], struct _vmApiInternalContext* vmapiContextP) { const char * MY_API_NAME = "Profile_Create_DM"; int rc; int option; int recordCount = 0; int c; char * profile = NULL; char * profileFile = NULL; FILE * fp = NULL; vmApiProfileCreateDmOutput* output; opterr = 0; // 0 =>Tell getopt to not display a mesage const char * argumentsRequired = "Tf"; char tempStr[1]; char strMsg[250]; // Options that have arguments are followed by a : character while ((option = getopt(argC, argV, "-T:f:h?")) != -1) switch (option) { case 'T': profile = optarg; break; case 'f': profileFile = optarg; break; case 'h': DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); printf("NAME\n" " Profile_Create_DM\n\n" "SYNOPSIS\n" " smcli Profile_Create_DM [-T] profile_name [-f] profile_file\n\n" "DESCRIPTION\n" " Use Profile_Create_DM to create a profile directory entry to be included\n" " in the definition of a virtual image in the directory.\n\n" " The following options are required:\n" " -T The name of the profile to be created\n" " -f The profile directory entry file\n"); printRCheaderHelp(); return 0; case '?': DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); if (isprint (optopt)) { sprintf(tempStr,"%c", optopt); if (strstr(argumentsRequired, tempStr)) { printf("This option requires an argument: -%c\n", optopt); } else { printf("Unknown option -%c\n", optopt); } } else { printf("Unknown option character \\x%x\n", optopt); } return 1; case 1: // API name type data(other non option element key data) break; default: DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); return 1; } if (!profile || !profileFile) { DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); printf("ERROR: Missing required options\n"); return 1; } // Open the user entry file fp = fopen(profileFile, "r"); if (fp != NULL) { // Count the number of lines and set the record count to it while ((c = fgetc(fp)) != EOF) { if (c == '\n') { recordCount++; } } } else { printAndLogProcessingErrors("Profile_Create_DM", PROCESSING_ERROR, vmapiContextP, "", 0); printf("\nERROR: Failed to open file %s\n", profileFile); return 1; } // Reset position to start of file rewind(fp); // Create image record vmApiProfileRecord record[recordCount]; int i = 0, LINE_SIZE = 72; char line[recordCount][LINE_SIZE]; char * ptr; while (fgets(line[i], LINE_SIZE, fp) != NULL) { // Replace newline with null terminator ptr = strstr(line[i], "\n"); if (ptr != NULL) strncpy(ptr, "\0", 1); record[i].profileRecordLength = strlen(line[i]); record[i].recordData = line[i]; i++; } // Close file fclose(fp); // If they want special output header as first output, then we need to pass this // string on RC call so it is handled correctly for both cases. snprintf(strMsg, sizeof(strMsg), "Creating profile directory entry %s... ", profile); rc = smProfile_Create_DM(vmapiContextP, "", 0, "", // Authorizing user, password length, password profile, recordCount, (vmApiProfileRecord *) record, // Image record &output); if (rc) { printAndLogProcessingErrors("Profile_Create_DM", rc, vmapiContextP, strMsg, 0); } else { // Handle SMAPI return code and reason code rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Create_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, strMsg); } return rc; } int profileDeleteDM(int argC, char* argV[], struct _vmApiInternalContext* vmapiContextP) { const char * MY_API_NAME = "Profile_Delete_DM"; int rc; int option; char * profile = NULL; vmApiProfileDeleteDmOutput* output; opterr = 0; // 0 =>Tell getopt to not display a mesage const char * argumentsRequired = "T"; char tempStr[1]; char strMsg[250]; // Options that have arguments are followed by a : character while ((option = getopt(argC, argV, "-T:h?")) != -1) switch (option) { case 'T': profile = optarg; break; case 'h': DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); printf("NAME\n" " Profile_Delete_DM\n\n" "SYNOPSIS\n" " smcli Profile_Delete_DM [-T] profile_name\n\n" "DESCRIPTION\n" " Use Profile_Delete_DM to delete a profile directory entry.\n\n" " The following options are required:\n" " -T The name of the profile to be deleted\n"); printRCheaderHelp(); return 0; case '?': DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); if (isprint (optopt)) { sprintf(tempStr,"%c", optopt); if (strstr(argumentsRequired, tempStr)) { printf("This option requires an argument: -%c\n", optopt); } else { printf("Unknown option -%c\n", optopt); } } else { printf("Unknown option character \\x%x\n", optopt); } return 1; case 1: // API name type data(other non option element key data) break; default: DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); return 1; } if (!profile) { DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); printf("ERROR: Missing required options\n"); return 1; } // If they want special output header as first output, then we need to pass this // string on RC call so it is handled correctly for both cases. snprintf(strMsg, sizeof(strMsg), "Deleting profile directory entry %s... ", profile); rc = smProfile_Delete_DM(vmapiContextP, "", 0, "", // Authorizing user, password length, password profile, &output); if (rc) { printAndLogProcessingErrors("Profile_Delete_DM", rc, vmapiContextP, strMsg, 0); } else { // Handle SMAPI return code and reason code rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Delete_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, strMsg); } return rc; } int profileLockDM(int argC, char* argV[], struct _vmApiInternalContext* vmapiContextP) { const char * MY_API_NAME = "Profile_Lock_DM"; int rc; int option; char * profile = NULL; vmApiProfileLockDmOutput* output; opterr = 0; // 0 =>Tell getopt to not display a mesage const char * argumentsRequired = "T"; char tempStr[1]; char strMsg[250]; // Options that have arguments are followed by a : character while ((option = getopt(argC, argV, "-T:h?")) != -1) switch (option) { case 'T': profile = optarg; break; case 'h': DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); printf("NAME\n" " Profile_Lock_DM\n\n" "SYNOPSIS\n" " smcli Profile_Lock_DM [-T] profile_name\n\n" "DESCRIPTION\n" " Use Profile_Lock_DM to lock a profile directory entry.\n\n" " The following options are required:\n" " -T The name of the profile to be locked.\n"); printRCheaderHelp(); return 0; case '?': DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); if (isprint (optopt)) { sprintf(tempStr,"%c", optopt); if (strstr(argumentsRequired, tempStr)) { printf("This option requires an argument: -%c\n", optopt); } else { printf("Unknown option -%c\n", optopt); } } else { printf("Unknown option character \\x%x\n", optopt); } return 1; case 1: // API name type data(other non option element key data) break; default: DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); return 1; } if (!profile) { DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); printf("ERROR: Missing required options\n"); return 1; } // If they want special output header as first output, then we need to pass this // string on RC call so it is handled correctly for both cases. snprintf(strMsg, sizeof(strMsg), "Locking profile directory entry %s... ", profile); rc = smProfile_Lock_DM(vmapiContextP, "", 0, "", // Authorizing user, password length, password profile, &output); if (rc) { printAndLogProcessingErrors("Profile_Lock_DM", rc, vmapiContextP, strMsg, 0); } else { // Handle SMAPI return code and reason code rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Lock_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, strMsg); } return rc; } int profileLockQueryDM(int argC, char* argV[], struct _vmApiInternalContext* vmapiContextP) { const char * MY_API_NAME = "Profile_Lock_Query_DM"; int rc; int option; int i; int devAddressDevLockedBySize; char * profile = NULL; char *token; char * buffer; // Character pointer whose value is preserved between successive related calls to strtok_r char * blank = " "; char lockedType[7 + 1]; char profileLockedBy[8 + 1]; char devAddress[4 + 1]; char devLockedBy[8 + 1]; char tempBuff[14]; vmApiProfileLockQueryDmOutput * output; opterr = 0; // 0 =>Tell getopt to not display a mesage const char * argumentsRequired = "T"; char tempStr[1]; char strMsg[250]; // These variables hold output messages until the end smMessageCollector saveMsgs; char msgBuff[MESSAGE_BUFFER_SIZE]; INIT_MESSAGE_BUFFER(&saveMsgs, MESSAGE_BUFFER_SIZE, msgBuff) ; // Options that have arguments are followed by a : character while ((option = getopt(argC, argV, "-T:h?")) != -1) switch (option) { case 'T': profile = optarg; break; case 'h': DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); printf("NAME\n" " Profile_Lock_Query_DM\n\n" "SYNOPSIS\n" " smcli Profile_Lock_Query_DM [-T] profile_name\n\n" "DESCRIPTION\n" " Use Profile_Lock_Query_DM to query the status of whether a directory manager\n" " lock is in effect for a specific profile.\n\n" " The following options are required:\n" " -T The name of the profile for which the directory lock status is being\n" " queried.\n"); printRCheaderHelp(); return 0; case '?': DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); if (isprint (optopt)) { sprintf(tempStr,"%c", optopt); if (strstr(argumentsRequired, tempStr)) { printf("This option requires an argument: -%c\n", optopt); } else { printf("Unknown option -%c\n", optopt); } } else { printf("Unknown option character \\x%x\n", optopt); } return 1; case 1: // API name type data(other non option element key data) break; default: DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); return 1; } if (!profile) { DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); printf("ERROR: Missing required options\n"); return 1; } rc = smProfile_Lock_Query_DM(vmapiContextP, "", 0, "", // Authorizing user, password length, password profile, // Profile name &output); if (rc) { printAndLogProcessingErrors("Profile_Lock_Query_DM", rc, vmapiContextP, "", 0); } else if ((output->common.returnCode == 0) && (output->common.reasonCode == 12 )) { // Obtain lockedType token = strtok_r(output->lockedTypeProfileLockedBy, blank, &buffer); if (token != NULL) { strcpy(lockedType, token); } else { rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Lock_Query_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, ""); printf("ERROR: lockedType is NULL\n"); return 1; } if (strcmp(lockedType, "PROFILE") == 0) { // Obtain profileLockedBy token = strtok_r(NULL, "\0", &buffer); if (token != NULL) { strcpy(profileLockedBy, token); } else { rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Lock_Query_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, ""); printf("ERROR: profileLockedBy is NULL\n"); return 1; } snprintf(strMsg, sizeof(strMsg), "Locked type: %s\n" "Image locked by: %s\n", lockedType, profileLockedBy); if (0 != (rc = addMessageToBuffer(&saveMsgs, strMsg))) { goto endRS12; } } else { snprintf(strMsg, sizeof(strMsg), "Locked type: %s\n", lockedType); if (0 != (rc = addMessageToBuffer(&saveMsgs, strMsg))) { goto endRS12; } } for (i = 0; i < output->profileDevLockInfoRecordCount; i++) { memset(tempBuff, 0x00, 14); devAddressDevLockedBySize = strlen((char *)output->lockDevList[i].devAddressDevLockedBy); strncpy(tempBuff, (char *)output->lockDevList[i].devAddressDevLockedBy, devAddressDevLockedBySize); trim(tempBuff); tempBuff[devAddressDevLockedBySize + 1] = '\0'; // Get devAddress token = strtok_r(tempBuff, blank, &buffer); if (token != NULL) { strcpy(devAddress, token); } else { printf("Error devAddress is NULL!!\n"); if (0 == (rc = addMessageToBuffer(&saveMsgs, "Error devAddress is NULL!!\n"))) { rc = OUTPUT_ERRORS_FOUND; } goto endRS12; } // Obtain devLockedBy token = strtok_r(NULL, "\0", &buffer); if (token != NULL) { strcpy(devLockedBy, token); } else { printf("ERROR: devLockedBy is NULL\n"); if (0 == (rc = addMessageToBuffer(&saveMsgs, "*+++?ERROR:"))) { rc = OUTPUT_ERRORS_FOUND; } goto endRS12; } snprintf(strMsg, sizeof(strMsg), "Device address: %s\n" "Device locked by: %s\n\n", devAddress, devLockedBy); if (0 != (rc = addMessageToBuffer(&saveMsgs, strMsg))) { goto endRS12; } } endRS12: if (rc) { if (rc == OUTPUT_ERRORS_FOUND) { DOES_CALLER_WANT_RC_HEADER_FOR_OUTPUT_ERRORS(vmapiContextP, MY_API_NAME); } else { printAndLogProcessingErrors(MY_API_NAME, rc, vmapiContextP, "", 0); } } else { DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); } printMessageBuffersAndRelease(&saveMsgs); } else if ((output->common.returnCode == 0) && (output->common.reasonCode == 24)) { DOES_CALLER_WANT_RC_HEADER_SMAPI_RC0_RS(vmapiContextP, output->common.returnCode, output->common.reasonCode); printf("%s is Unlocked...\n", profile); } else { // Handle SMAPI return code and reason code rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Lock_Query_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, ""); } return rc; } int profileQueryDM(int argC, char* argV[], struct _vmApiInternalContext* vmapiContextP) { const char * MY_API_NAME = "Profile_Query_DM"; int rc; int option; int recCount; int i; char line[72+1]; char * profile = NULL; vmApiProfileQueryDmOutput * output; opterr = 0; // 0 =>Tell getopt to not display a mesage const char * argumentsRequired = "T"; char tempStr[1]; // Options that have arguments are followed by a : character while ((option = getopt(argC, argV, "-T:h?")) != -1) switch (option) { case 'T': profile = optarg; break; case 'h': DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); printf("NAME\n" " Profile_Query_DM\n\n" "SYNOPSIS\n" " smcli Profile_Query_DM [-T] profile_name\n\n" "DESCRIPTION\n" " Use Profile_Query_DM to query a profile directory entry.\n\n" " The following options are required:\n" " -T The name of the profile being queried\n"); printRCheaderHelp(); return 0; case '?': DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); if (isprint (optopt)) { sprintf(tempStr,"%c", optopt); if (strstr(argumentsRequired, tempStr)) { printf("This option requires an argument: -%c\n", optopt); } else { printf("Unknown option -%c\n", optopt); } } else { printf("Unknown option character \\x%x\n", optopt); } return 1; case 1: // API name type data(other non option element key data) break; default: DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); return 1; } if (!profile) { DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); printf("ERROR: Missing required options\n"); return 1; } rc = smProfile_Query_DM(vmapiContextP, "", 0, "", // Authorizing user, password length, password profile, // Profile name &output); if (rc) { printAndLogProcessingErrors("Profile_Query_DM", rc, vmapiContextP, "", 0); } else if (output->common.returnCode || output->common.reasonCode) { // Handle SMAPI return code and reason code rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Query_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, ""); } else { DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); // Print out directory profile recCount = output->profileRecordCount; if (recCount > 0) { printf("\n"); // Loop through profile records and print out profile entry for (i = 0; i < output->profileRecordCount; i++) { memset(line, 0, 73); memcpy(line, output->profileRecordList[i].recordData, 72); trim(line); printf("%s\n", line); } } } return rc; } int profileReplaceDM(int argC, char* argV[], struct _vmApiInternalContext* vmapiContextP) { const char * MY_API_NAME = "Profile_Replace_DM"; int rc; int option; int recordCount = 0; int c; char * profile = NULL; char * profileFile = NULL; FILE * fp = NULL; vmApiProfileReplaceDmOutput* output; opterr = 0; // 0 =>Tell getopt to not display a mesage const char * argumentsRequired = "Tf"; char tempStr[1]; char strMsg[250]; // Options that have arguments are followed by a : character while ((option = getopt(argC, argV, "-T:f:h?")) != -1) switch (option) { case 'T': profile = optarg; break; case 'f': profileFile = optarg; break; case 'h': DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); printf("NAME\n" " Profile_Replace_DM\n\n" "SYNOPSIS\n" " smcli Profile_Replace_DM [-T] profile_name [-f] profile_file\n\n" "DESCRIPTION\n" " Use Profile_Replace_DM to replace the definition of a profile to be\n" " included in a virtual image in the directory.\n\n" " The following options are required:\n" " -T The name of the profile directory entry to be replaced\n" " -f The profile directory entry file"); printRCheaderHelp(); return 0; case '?': DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); if (isprint (optopt)) { sprintf(tempStr,"%c", optopt); if (strstr(argumentsRequired, tempStr)) { printf("This option requires an argument: -%c\n", optopt); } else { printf("Unknown option -%c\n", optopt); } } else { printf("Unknown option character \\x%x\n", optopt); } return 1; case 1: // API name type data(other non option element key data) break; default: DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); return 1; } if (!profile || !profileFile) { DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); printf("ERROR: Missing required options\n"); return 1; } // Open the user entry file fp = fopen(profileFile, "r"); if (fp != NULL) { // Count the number of lines and set the record count to it while ((c = fgetc(fp)) != EOF) { if (c == '\n') { recordCount++; } } } else { printAndLogProcessingErrors("Profile_Replace_DM", PROCESSING_ERROR, vmapiContextP, "", 0); printf("\nERROR: Failed to open file %s\n", profileFile); return 1; } // Reset position to start of file rewind(fp); // Create image record vmApiProfileRecord record[recordCount]; int i = 0, LINE_SIZE = 72; char line[recordCount][LINE_SIZE]; char * ptr; while (fgets(line[i], LINE_SIZE, fp) != NULL) { // Replace newline with null terminator ptr = strstr(line[i], "\n"); if (ptr != NULL) strncpy(ptr, "\0", 1); record[i].profileRecordLength = strlen(line[i]); record[i].recordData = line[i]; i++; } // Close file fclose(fp); // If they want special output header as first output, then we need to pass this // string on RC call so it is handled correctly for both cases. snprintf(strMsg, sizeof(strMsg), "Replacing definition of %s... ", profile); rc = smProfile_Replace_DM(vmapiContextP, "", 0, "", // Authorizing user, password length, password profile, recordCount, (vmApiProfileRecord *) record, // Image record &output); if (rc) { printAndLogProcessingErrors("Profile_Replace_DM", rc, vmapiContextP, strMsg, 0); } else { // Handle SMAPI return code and reason code rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Replace_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, strMsg); } return rc; } int profileUnlockDM(int argC, char* argV[], struct _vmApiInternalContext* vmapiContextP) { const char * MY_API_NAME = "Profile_Unlock_DM"; int rc; int option; char * profile = NULL; vmApiProfileUnlockDmOutput* output; opterr = 0; // 0 =>Tell getopt to not display a mesage const char * argumentsRequired = "T"; char tempStr[1]; char strMsg[250]; // Options that have arguments are followed by a : character while ((option = getopt(argC, argV, "-T:h?")) != -1) switch (option) { case 'T': profile = optarg; break; case 'h': DOES_CALLER_WANT_RC_HEADER_ALLOK(vmapiContextP); printf("NAME\n" " Profile_Unlock_DM\n\n" "SYNOPSIS\n" " smcli Profile_Unlock_DM [-T] profile_name\n\n" "DESCRIPTION\n" " Use Profile_Unlock_DM to unlock a profile directory entry.\n\n" " The following options are required:\n" " -T The name of the profile to be unlocked.\n"); printRCheaderHelp(); return 0; case '?': DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); if (isprint (optopt)) { sprintf(tempStr,"%c", optopt); if (strstr(argumentsRequired, tempStr)) { printf("This option requires an argument: -%c\n", optopt); } else { printf("Unknown option -%c\n", optopt); } } else { printf("Unknown option character \\x%x\n", optopt); } return 1; case 1: // API name type data(other non option element key data) break; default: DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); return 1; } if (!profile) { DOES_CALLER_WANT_RC_HEADER_SYNTAX_ERROR(vmapiContextP); printf("ERROR: Missing required options\n"); return 1; } // If they want special output header as first output, then we need to pass this // string on RC call so it is handled correctly for both cases. snprintf(strMsg, sizeof(strMsg), "UnLocking profile directory entry %s... ", profile); rc = smProfile_Unlock_DM(vmapiContextP, "", 0, "", // Authorizing user, password length, password profile, &output); if (rc) { printAndLogProcessingErrors("Profile_Unlock_DM", rc, vmapiContextP, strMsg, 0); } else { // Handle SMAPI return code and reason code rc = printAndLogSmapiReturnCodeReasonCodeDescription("Profile_Unlock_DM", output->common.returnCode, output->common.reasonCode, vmapiContextP, strMsg); } return rc; }
37.486381
120
0.548267
a14a67468b745c50ce626a72b653ebc365858743
11,504
h
C
utility/Dictionary.h
salsanci/YRShell
7a6073651d2ddef0c258c9943a5f9fd88068a561
[ "MIT" ]
2
2017-09-09T15:18:44.000Z
2020-02-02T17:08:40.000Z
utility/Dictionary.h
salsanci/YRShell
7a6073651d2ddef0c258c9943a5f9fd88068a561
[ "MIT" ]
39
2017-10-19T00:44:17.000Z
2019-01-19T19:20:24.000Z
utility/Dictionary.h
salsanci/YRShell
7a6073651d2ddef0c258c9943a5f9fd88068a561
[ "MIT" ]
null
null
null
#ifndef Dictionary_h #define Dictionary_h #include "HardwareSpecific.h" #include <stdint.h> #include <stdbool.h> #include <string.h> #include "YRShellDefines.h" class YRShellInterpreter; class DictionaryError { public: DictionaryError( void); virtual ~DictionaryError( void); virtual void shellERROR( const char* name, unsigned line); }; /** \brief Base class for all the dictionaries used by the interpreter This class is not meant to be instatiated. */ class Dictionary { protected: uint16_t m_mask; /**< The mask applied to the tokens in this dictionary. */ public: static DictionaryError* s_DictionaryError; /**< The global error reporting object for dictionaires. */ static void setDictionaryError( DictionaryError* e); /** \brief Constructor. Default constructor, no parameters are required. */ Dictionary( void); /** \brief Destructor. Default destructor. */ virtual ~Dictionary( void); /** \brief Returns the mask. Returns the mask value applied to the tokens in this dictionary. */ inline uint16_t getMask( void) { return m_mask; } /** \brief Should not be called. Will be handled by subclasses as applicable. */ virtual uint16_t getFirstEntry( void); /** \brief Should not be called. Will be handled by subclasses as applicable. */ virtual uint16_t getNextEntry( uint16_t index); /** \brief Should not be called. Will be handled by subclasses as applicable. */ virtual uint16_t getToken( uint16_t index); /** \brief Should not be called. Will be handled by subclasses as applicable. */ virtual uint16_t getNameAddressToken( uint16_t index); /** \brief Should not be called. Will be handled by subclasses as applicable. */ virtual uint16_t getWord( uint16_t index); /** \brief Should not be called. Will be handled by subclasses as applicable. */ virtual const char* getAddress( uint16_t index); /** \brief Should not be called. Will be handled by subclasses as applicable. */ virtual uint16_t find( const char* name); /** \brief Should not be called. Will be handled by subclasses as applicable. */ virtual uint16_t findEntry( const char* name) {return 0;} /** \brief Error routine for dictionaries Error routine for dictionaries. */ void shellERROR( const char* name, unsigned line); /** \brief Returns the length required to store ths string in uin16_t words. All strings (includes trminating 0) in the dictionaries are stored as a sequence uint16_t words. This returns the number of words necessary to store the string. */ static uint16_t nameLength( const char* name) { size_t len = strlen( name) + 1; return (uint16_t) (len/2 + (len & 1)); } }; /** \brief Maps from text to a function number. The function numbers along with the dictionary mask are used as tokens by the interpreters to call C code. Staticall declared in most applications. */ typedef struct { const uint16_t m_functionNumber; /**< The funtion number. One of the following enums: YRShellInterpreter::SI_CC_functions, YRShell::S_CC_functions, or MyYRShell::SE_CC_functions */ const char *M_functionName; /**< The text string which is the name of the function. */ inline bool isValid( void) const { return M_functionName != NULL; } /**< Whether the entry is a valid entry. The last entry in a list is an invalid entry. */ inline bool isMatch( const char* name) const { return !strcmp(M_functionName, name); } /**< If the entry matches the name. */ inline uint16_t getFunctionNumber( void) const { return m_functionNumber; } /**< The function token for this function. */ inline const char* getName( void) const { return M_functionName; } /**< The text name for this function. */ } FunctionEntry; /** \brief Dictionary to map native functions. Is initialized with an array of FunctionEntry and a size. Provides functionality for searching and listing. */ class FunctionDictionary : public Dictionary { protected: const FunctionEntry* M_dictionary; /**< Pointer to the array of FunctionEntry */ uint16_t m_size; /**< The size of the FunctionEntry array. */ public: FunctionDictionary( const FunctionEntry* dict, uint16_t mask); /** \brief Returns an index pointing to the first dictionary entry. Returns an index pointing to the first dictionary entry. Returns YRSHELL_DICTIONARY_INVALID if there is no valid first entry. */ uint16_t getFirstEntry( void); /** \brief Given an index , returns an index pointing to the next dictionary entry. Given an index , returns an index pointing to the next dictionary entry. Returns YRSHELL_DICTIONARY_INVALID if there is no valid next entry. */ uint16_t getNextEntry( uint16_t index); /** \brief Given an index, returns the token. Given an index, returns the token. Returns YRSHELL_DICTIONARY_INVALID for an invalid index. */ uint16_t getToken( uint16_t index); /** \brief Given an index, returns the token for the address of the name. Given an index, returns the token for the address of the name. Returns YRSHELL_DICTIONARY_INVALID for an invalid index. */ uint16_t getNameAddressToken( uint16_t index); /** \brief Given an index, returns the address for the address of the name. Returns NULL for an invalid index. Given an index, returns the address for he name. */ const char* getAddress( uint16_t index); /** \brief Given a name, returns a token for the corresponding entry. Given a name, returns a token for the corresponding entry. Returns YRSHELL_DICTIONARY_INVALID if a corresponding entry is not found. */ uint16_t find( const char* name); /** \brief Given a name, returns a name token for the corresponding entry. Given a name, returns a name token for the corresponding entry. Returns YRSHELL_DICTIONARY_INVALID if a corresponding entry is not found. */ uint16_t findEntry( const char* name); }; /** \brief A compiled dictionary. A compiled dictionary. */ class CompiledDictionary : public Dictionary { protected: uint16_t* m_dictionary; /**< Pointer to the array of uint16_t which is the compiled dictionary. */ uint16_t m_lastWord; /**< Index of the last entry in the dictionary*/ uint16_t m_size; /**< The size of the dictionary. */ /** \brief Given a name, returns an execution token for the corresponding entry. Given a name, returns an execution token for the corresponding entry. Returns YRSHELL_DICTIONARY_INVALID if a corresponding entry is not found. */ uint16_t findInternal( const char* name, uint16_t link); /** \brief Given a name, returns a name token for the corresponding entry. Given a name, returns a name token for the corresponding entry. Returns YRSHELL_DICTIONARY_INVALID if a corresponding entry is not found. */ uint16_t findInternalEntry( const char* name, uint16_t link); public: CompiledDictionary( void); CompiledDictionary( const uint16_t* dict, uint16_t lastWord, uint16_t size, uint16_t mask); uint16_t getSize( void) { return m_size; } /** \brief Returns an index pointing to the first dictionary entry. Returns an index pointing to the first dictionary entry. Returns YRSHELL_DICTIONARY_INVALID if there is no valid first entry. */ uint16_t getFirstEntry( void); /** \brief Given an index , returns an index pointing to the next dictionary entry. Given an index , returns an index pointing to the next dictionary entry. Returns YRSHELL_DICTIONARY_INVALID if there is no valid next entry. */ uint16_t getNextEntry( uint16_t index); /** \brief Given an index, returns the token. Given an index, returns the token. Returns YRSHELL_DICTIONARY_INVALID for an invalid index. */ uint16_t getToken( uint16_t index); /** \brief Given an index, returns the token for the address of the name. Given an index, returns the token for the address of the name. Returns YRSHELL_DICTIONARY_INVALID for an invalid index. */ uint16_t getNameAddressToken( uint16_t index); /** \brief Given an index, returns the uint16_t word at the index. Given an index, returns the uint16_t word at the index. Returns YRSHELL_DICTIONARY_INVALID for an invalid index. */ uint16_t getWord( uint16_t index); /** \brief Given an index, returns the address for the address of the name. Returns NULL for an invalid index. Given an index, returns the address for he name. */ const char* getAddress( uint16_t index); /** \brief Given a name, returns an execution token for the corresponding entry. Given a name, returns an execution token for the corresponding entry. Returns YRSHELL_DICTIONARY_INVALID if a corresponding entry is not found. */ uint16_t find( const char* name); /** \brief Given a name, returns a name token for the corresponding entry. Given a name, returns a name token for the corresponding entry. Returns YRSHELL_DICTIONARY_INVALID if a corresponding entry is not found. */ uint16_t findEntry( const char* name); /** \brief Returns an index past the last entry in the dictionary. Returns an index past the last entry in the dictionary. */ uint16_t getWordEnd( void); }; /** \brief A compiled dictionary, which is dynamic. A compiled dictionary, which is dynamic. */ class CurrentVariableDictionary : public CompiledDictionary { protected: uint16_t m_dictionaryBackupLastWord; uint16_t m_dictionaryBackupWordEnd; uint16_t m_dictionaryCurrentWordEnd; public: CurrentVariableDictionary( void); CurrentVariableDictionary( uint16_t* dict, uint16_t size); /** \brief Returns an index pointing to the first dictionary entry. Returns an index pointing to the first dictionary entry. Returns YRSHELL_DICTIONARY_INVALID if there is no valid first entry. */ uint16_t getFirstEntry( void); uint16_t getWord( uint16_t index); const char* getAddress( uint16_t index); /** \brief Given a name, returns a token for the corresponding entry. Given a name, returns a token for the corresponding entry. Returns YRSHELL_DICTIONARY_INVALID if a corresponding entry is not found. */ uint16_t find( const char* name); bool newCompile( const char* name); bool addToken( uint16_t token); bool setToken( uint16_t address, uint16_t token); void rollBack( void); void newCompileDone( void); inline uint16_t getWordEnd( void) { return m_dictionaryCurrentWordEnd; } inline uint16_t getBackupLastWord( void) { return m_dictionaryBackupLastWord; } inline uint16_t getBackupWordEnd( void) { return m_dictionaryBackupWordEnd; } virtual void reset( void); }; template<unsigned SHELL_DICTIONARY_SIZE> class CurrentDictionary : public CurrentVariableDictionary { protected: uint16_t m_dictionaryBuffer[ SHELL_DICTIONARY_SIZE]; public: CurrentDictionary( void) { reset(); } virtual void reset( void) { m_mask = YRSHELL_DICTIONARY_CURRENT; m_size = SHELL_DICTIONARY_SIZE; m_dictionary = m_dictionaryBuffer; CurrentVariableDictionary::reset( ); } }; #endif
38.734007
187
0.70758
2c2c0776d5a2a59a9115d8a783319df38b05c82f
5,265
h
C
include/configs/afeb9260.h
WA2301/uboot-2011.06
0afa645d678b19206669ef606884bce5e3332077
[ "Intel", "Unlicense" ]
null
null
null
include/configs/afeb9260.h
WA2301/uboot-2011.06
0afa645d678b19206669ef606884bce5e3332077
[ "Intel", "Unlicense" ]
null
null
null
include/configs/afeb9260.h
WA2301/uboot-2011.06
0afa645d678b19206669ef606884bce5e3332077
[ "Intel", "Unlicense" ]
null
null
null
/* * (C) Copyright 2008 Sergey Lapin <slapin@ossfans.org> * * Configuation settings for the AFEB9260 board. * Based on configuration for AT91SAM9260-EK * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef __CONFIG_H #define __CONFIG_H #define CONFIG_AT91SAM9260 /* Atmel AT91SAM9260 SoC*/ #include <asm/arch/hardware.h> #define CONFIG_SYS_TEXT_BASE 0x21f00000 /* ARM asynchronous clock */ #define CONFIG_SYS_AT91_MAIN_CLOCK 18429952 /* from 18.432 MHz crystal */ #define CONFIG_SYS_AT91_SLOW_CLOCK 32768 #define CONFIG_SYS_HZ 1000 #define CONFIG_BOARD_EARLY_INIT_F #define CONFIG_DISPLAY_CPUINFO #define CONFIG_AFEB9260 /* AFEB9260 Board */ #define CONFIG_ARCH_CPU_INIT #define CONFIG_CMDLINE_TAG 1 /* enable passing of ATAGs */ #define CONFIG_SETUP_MEMORY_TAGS 1 #define CONFIG_INITRD_TAG 1 #define CONFIG_SKIP_LOWLEVEL_INIT /* * Hardware drivers */ #define CONFIG_ATMEL_LEGACY #define CONFIG_AT91_GPIO #define CONFIG_AT91_PULLUP 1 #define CONFIG_ATMEL_USART #define CONFIG_USART_BASE ATMEL_BASE_DBGU #define CONFIG_USART_ID ATMEL_ID_SYS #define CONFIG_USART3 /* USART 3 is DBGU */ #define CONFIG_BOOTDELAY 3 /* * BOOTP options */ #define CONFIG_BOOTP_BOOTFILESIZE 1 #define CONFIG_BOOTP_BOOTPATH 1 #define CONFIG_BOOTP_GATEWAY 1 #define CONFIG_BOOTP_HOSTNAME 1 /* * Command line configuration. */ #include <config_cmd_default.h> #undef CONFIG_CMD_BDI #undef CONFIG_CMD_FPGA #undef CONFIG_CMD_IMI #undef CONFIG_CMD_IMLS #undef CONFIG_CMD_LOADS #undef CONFIG_CMD_SOURCE #define CONFIG_CMD_PING #define CONFIG_CMD_DHCP #define CONFIG_CMD_NAND #define CONFIG_CMD_USB /* SDRAM */ #define CONFIG_NR_DRAM_BANKS 1 #define CONFIG_SYS_SDRAM_BASE ATMEL_BASE_CS1 #define CONFIG_SYS_SDRAM_SIZE 0x04000000 /* 64 megs */ /* DataFlash */ #define CONFIG_ATMEL_DATAFLASH_SPI #define CONFIG_HAS_DATAFLASH #define CONFIG_SYS_SPI_WRITE_TOUT (5 * CONFIG_SYS_HZ) #define CONFIG_SYS_MAX_DATAFLASH_BANKS 2 #define CONFIG_SYS_DATAFLASH_LOGIC_ADDR_CS0 0xC0000000 /* CS0 */ #define CONFIG_SYS_DATAFLASH_LOGIC_ADDR_CS1 0xD0000000 /* CS1 */ #define AT91_SPI_CLK 15000000 #define DATAFLASH_TCSS (0x1a << 16) #define DATAFLASH_TCHS (0x1 << 24) /* NAND flash */ #ifdef CONFIG_CMD_NAND #define CONFIG_NAND_ATMEL #define CONFIG_SYS_MAX_NAND_DEVICE 1 #define CONFIG_SYS_NAND_BASE ATMEL_BASE_CS3 #define CONFIG_SYS_NAND_DBW_8 /* our ALE is AD21 */ #define CONFIG_SYS_NAND_MASK_ALE (1 << 21) /* our CLE is AD22 */ #define CONFIG_SYS_NAND_MASK_CLE (1 << 22) #define CONFIG_SYS_NAND_ENABLE_PIN AT91_PIN_PC14 #define CONFIG_SYS_NAND_READY_PIN AT91_PIN_PC13 #endif /* NOR flash - no real flash on this board */ #define CONFIG_SYS_NO_FLASH /* Ethernet */ #define CONFIG_MACB #define CONFIG_RESET_PHY_R #define CONFIG_NET_MULTI #define CONFIG_NET_RETRY_COUNT 20 /* USB */ #define CONFIG_USB_ATMEL #define CONFIG_USB_OHCI_NEW #define CONFIG_DOS_PARTITION #define CONFIG_SYS_USB_OHCI_CPU_INIT #define CONFIG_SYS_USB_OHCI_REGS_BASE 0x00500000 /* AT91SAM9260_UHP_BASE */ #define CONFIG_SYS_USB_OHCI_SLOT_NAME "at91sam9260" #define CONFIG_SYS_USB_OHCI_MAX_ROOT_PORTS 1 #define CONFIG_USB_STORAGE #define CONFIG_SYS_LOAD_ADDR 0x21000000 /* load address */ #define CONFIG_SYS_MEMTEST_START CONFIG_SYS_SDRAM_BASE #define CONFIG_SYS_MEMTEST_END 0x21e00000 #define CONFIG_SYS_USE_DATAFLASH_CS1 #define CONFIG_SYS_INIT_SP_ADDR (ATMEL_BASE_SRAM1 + 0x1000 -\ GENERATED_GBL_DATA_SIZE) /* bootstrap + u-boot + env + linux in dataflash on CS1 */ #define CONFIG_ENV_IS_IN_DATAFLASH #define CONFIG_SYS_MONITOR_BASE (CONFIG_SYS_DATAFLASH_LOGIC_ADDR_CS1 + 0x8400) #define CONFIG_ENV_OFFSET 0x4200 #define CONFIG_ENV_ADDR (CONFIG_SYS_DATAFLASH_LOGIC_ADDR_CS1 + CONFIG_ENV_OFFSET) #define CONFIG_ENV_SIZE 0x4200 #define CONFIG_BOOTCOMMAND "nand read 0x21000000 0xa0000 0x200000; bootm" #define CONFIG_BOOTARGS "console=ttyS0,115200 " \ "root=/dev/mtdblock2 " \ "rw rootfstype=jffs2 panic=20" #define CONFIG_BAUDRATE 115200 #define CONFIG_SYS_BAUDRATE_TABLE {115200 , 19200, 38400, 57600, 9600 } #define CONFIG_SYS_PROMPT "U-Boot> " #define CONFIG_SYS_CBSIZE 256 #define CONFIG_SYS_MAXARGS 16 #define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE + sizeof(CONFIG_SYS_PROMPT) + 16) #define CONFIG_SYS_LONGHELP #define CONFIG_CMDLINE_EDITING /* * Size of malloc() pool */ #define CONFIG_SYS_MALLOC_LEN ROUND(3 * CONFIG_ENV_SIZE + 128*1024, 0x1000) #define CONFIG_STACKSIZE (32 * 1024) /* regular stack */ #ifdef CONFIG_USE_IRQ #error CONFIG_USE_IRQ not supported #endif #endif
29.088398
82
0.795821
080299a4b7e1bef3470aa063e98a38e7337d0e58
520
h
C
ProjectEngine/src/Core/Core/MouseButtonCodes.h
DavidConsidine/Project-Engine
127f52be58c9a7f92137bd23fc94c5c7b5ede53a
[ "Apache-2.0" ]
null
null
null
ProjectEngine/src/Core/Core/MouseButtonCodes.h
DavidConsidine/Project-Engine
127f52be58c9a7f92137bd23fc94c5c7b5ede53a
[ "Apache-2.0" ]
null
null
null
ProjectEngine/src/Core/Core/MouseButtonCodes.h
DavidConsidine/Project-Engine
127f52be58c9a7f92137bd23fc94c5c7b5ede53a
[ "Apache-2.0" ]
null
null
null
#pragma once // glfw3.h #define PE_MOUSE_BUTTON_1 0 #define PE_MOUSE_BUTTON_2 1 #define PE_MOUSE_BUTTON_3 2 #define PE_MOUSE_BUTTON_4 3 #define PE_MOUSE_BUTTON_5 4 #define PE_MOUSE_BUTTON_6 5 #define PE_MOUSE_BUTTON_7 6 #define PE_MOUSE_BUTTON_8 7 #define PE_MOUSE_BUTTON_LAST PE_MOUSE_BUTTON_8 #define PE_MOUSE_BUTTON_LEFT PE_MOUSE_BUTTON_1 #define PE_MOUSE_BUTTON_RIGHT PE_MOUSE_BUTTON_2 #define PE_MOUSE_BUTTON_MIDDLE PE_MOUSE_BUTTON_3
34.666667
51
0.736538
ae7994321b76816b9fd20c5ce03423c6c7f58101
491
h
C
RelevanceEngine.framework/RECompanionAppUsagePredictor.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
4
2021-10-06T12:15:26.000Z
2022-02-21T02:26:00.000Z
RelevanceEngine.framework/RECompanionAppUsagePredictor.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
null
null
null
RelevanceEngine.framework/RECompanionAppUsagePredictor.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/RelevanceEngine.framework/RelevanceEngine */ @interface RECompanionAppUsagePredictor : REPredictor { NSDictionary * _predictions; } + (double)updateInterval; - (void).cxx_destruct; - (void)_loadStoreIfNeeded; - (void)collectLoggableState:(id /* block */)arg1; - (void)dealloc; - (id)featureValueForFeature:(id)arg1 element:(id)arg2 engine:(id)arg3 trainingContext:(id)arg4; - (id)init; - (void)update; @end
24.55
96
0.753564
b7f68e75f103ee56db035161a8a57c8796bbb6d8
928
h
C
lib/unixprimwrap/include/unixprimwrap/errors.h
nickeskov/AdvCpp_hw
0495ba68e66c43116143087dd5dffcf708fe2e3e
[ "BSD-3-Clause" ]
null
null
null
lib/unixprimwrap/include/unixprimwrap/errors.h
nickeskov/AdvCpp_hw
0495ba68e66c43116143087dd5dffcf708fe2e3e
[ "BSD-3-Clause" ]
null
null
null
lib/unixprimwrap/include/unixprimwrap/errors.h
nickeskov/AdvCpp_hw
0495ba68e66c43116143087dd5dffcf708fe2e3e
[ "BSD-3-Clause" ]
null
null
null
#ifndef UNIXPRIMWRAP_UNIXPRIMWRAP_ERRORS_H #define UNIXPRIMWRAP_UNIXPRIMWRAP_ERRORS_H #include <cerrno> #include <stdexcept> #include <string_view> namespace unixprimwrap::errors { class RuntimeError : public std::runtime_error { public: explicit RuntimeError(std::string_view what_arg); [[nodiscard]] int errno_code() const noexcept; ~RuntimeError() override = default; private: int errno_code_ = errno; }; class PipeError : public RuntimeError { public: explicit PipeError(std::string_view what_arg); }; class DescriptorError : public RuntimeError { public: explicit DescriptorError(std::string_view what_arg); }; class PipeCreationError : public PipeError { public: explicit PipeCreationError(std::string_view what_arg); }; class DupError : public DescriptorError { public: explicit DupError(std::string_view what_arg); }; } #endif //UNIXPRIMWRAP_UNIXPRIMWRAP_ERRORS_H
20.622222
58
0.756466
d9622ee95e0b04c0e1f5857674d4be0b08507b60
21,600
h
C
include/3rdparty/am/judyhash/judyarray/judy_mapset_common.h
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
31
2015-03-03T19:13:42.000Z
2020-09-03T08:11:56.000Z
include/3rdparty/am/judyhash/judyarray/judy_mapset_common.h
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
1
2016-12-24T00:12:11.000Z
2016-12-24T00:12:11.000Z
include/3rdparty/am/judyhash/judyarray/judy_mapset_common.h
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
8
2015-09-06T01:55:21.000Z
2021-12-20T02:16:13.000Z
/* * Copyright (c) 2006, Aleksey Cheusov <vle@gmx.net> * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without * fee, provided that the above copyright notice appear in all copies * and that both that copyright notice and this permission notice * appear in supporting documentation. I make no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied * warranty. * */ #ifndef _JUDY_MAPSET_COMMON_H_ #define _JUDY_MAPSET_COMMON_H_ #include <assert.h> #include <stddef.h> #include <list> #include <utility> #include <set> #include "judy_common.h" #include "judy_funcs_wrappers.h" #ifndef JUDYARRAY_HASH_MASK #define JUDYARRAY_HASH_MASK 0xFFFFFFFF #endif template < typename TKey, typename TData, typename THashFunc, typename TEqualFunc, typename TAllocator, typename TTraits> class __judy_mapset_base : private TTraits { private: typedef TTraits __base; // types public: typedef TEqualFunc key_equal; typedef THashFunc hasher; typedef TAllocator allocator_type; typedef __judy_mapset_base <TKey, TData, THashFunc, TEqualFunc, TAllocator, TTraits> __this_type; __JUDYARRAY_TYPEDEFS(__base) struct debug_info { // a number of values (actually, pointer to value) // stored in JudyL cells int m_value_count; // a number of allocated std::list objects int m_list_count; // a number of values (actually, pointer to value) // stored in std::list objects int m_list_item_count; debug_info () { m_value_count = 0; m_list_count = 0; m_list_item_count = 0; } debug_info (const debug_info &a) { m_value_count = a.m_value_count; m_list_count = a.m_list_count; m_list_item_count = a.m_list_item_count; } }; debug_info m_debug_info; // private: typedef typename TTraits::pointers_list_type pointers_list_type; typedef std::set <pointers_list_type *> allocated_lists_type; Pvoid_t m_judy; size_type m_size; THashFunc m_hash_func; TEqualFunc m_eq_func; allocator_type m_alloc; unsigned m_hash_mask; inline pointer allocate (const value_type &v) { #ifdef JUDYHASH_USE_NEW return new value_type (v); #else pointer p = m_alloc.allocate (1); return new (p) value_type (v); #endif } inline void deallocate (pointer p) { #ifdef JUDYHASH_USE_NEW delete p; #else p -> ~value_type (); m_alloc.deallocate (p, 1); #endif } // public: __judy_mapset_base () { m_judy = 0; m_size = 0; m_hash_mask = JUDYARRAY_HASH_MASK; } __judy_mapset_base ( size_type n, const hasher& h, const key_equal& k, const allocator_type& a) : m_hash_func (h), m_eq_func (k), m_alloc (a) { m_judy = 0; m_size = 0; m_hash_mask = JUDYARRAY_HASH_MASK; } template <class Tit> __judy_mapset_base ( Tit beg, Tit end, size_type, const hasher& h, const key_equal& k, const allocator_type& a) : m_hash_func (h), m_eq_func (k), m_alloc (a) { m_judy = 0; m_size = 0; m_hash_mask = JUDYARRAY_HASH_MASK; insert (beg, end); } __judy_mapset_base (const __this_type& a) : m_hash_func (a.m_hash_func), m_eq_func (a.m_eq_func), m_alloc (a.m_alloc) { m_judy = 0; m_size = 0; m_hash_mask = JUDYARRAY_HASH_MASK; // optimize me!!! insert (a.begin (), a.end ()); } ~__judy_mapset_base () { clear (); assert (!m_debug_info.m_value_count); assert (!m_debug_info.m_list_count); assert (!m_debug_info.m_list_item_count); assert (!m_judy); } void clear () { #ifdef JUDYARRAY_DEBUG // Slow implementation which allows better // inconsistency checking erase (begin (), end ()); #else // !JUDYARRAY_DEBUG // Much faster implementation // Deleting object from lists // typename allocated_lists_type::iterator f, l; // f = m_allocated_lists.begin (); // l = m_allocated_lists.end (); // for (; f != l; ++f){ #ifdef JUDYARRAY_DEBUGINFO // m_debug_info.m_list_count -= 1; // m_debug_info.m_list_item_count -= (*f) -> size (); #endif //JUDYARRAY_DEBUGINFO // delete *f; // } // Deleting the set of allocated lists // m_allocated_lists.clear (); // Deleting object from JudyL cells Word_t index = 0; judyarray_union_type *pvalue = (judyarray_union_type *) judyl_first (m_judy, &index); while (pvalue){ if (pvalue -> m_judy_int & 1){ pvalue -> m_judy_int &= ~1; typename pointers_list_type::iterator beg = pvalue -> m_list -> begin (); typename pointers_list_type::iterator end = pvalue -> m_list -> end (); #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_list_count -= 1; #endif //JUDYARRAY_DEBUGINFO for (; beg != end; ++beg){ #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_list_item_count -= 1; #endif //JUDYARRAY_DEBUGINFO deallocate (*beg); } delete pvalue -> m_list; }else{ #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_value_count -= 1; #endif //JUDYARRAY_DEBUGINFO deallocate (pvalue -> m_pointer); } pvalue = (judyarray_union_type *) judyl_next (m_judy, &index); } judyl_freearray (m_judy); #endif // JUDYARRAY_DEBUG m_size = 0; } __judy_mapset_base& operator = (const __this_type& a) { // exception-safe implementation if (this != &a){ clear (); __this_type temp (a); swap (temp); } return *this; } template <class Tit> void insert (Tit beg, Tit end) { while (beg != end){ insert (*beg); ++beg; } } bool empty () const { return m_size == 0; } size_type bucket_count () const { return m_size; } void swap (__this_type& a) { std::swap (m_judy, a.m_judy); std::swap (m_size, a.m_size); std::swap (m_hash_func, a.m_hash_func); std::swap (m_debug_info, a.m_debug_info); std::swap (m_alloc, a.m_alloc); } size_type size () const { return m_size; } hasher hash_funct () const { return m_hash_func; } key_equal key_eq () const { return m_eq_func; } size_type max_size () const { return size_type (-1); } void set_hash_mask (unsigned mask) { m_hash_mask = mask; } unsigned get_hash_mask () const { return m_hash_mask; } private: union judyarray_union_type { Word_t m_judy_int; PWord_t m_judy_ptr; pointer m_pointer; pointers_list_type *m_list; }; class iterator_base : private TTraits { public: __JUDYARRAY_TYPEDEFS(TTraits) Pcvoid_t *m_pjudy; Word_t m_index; judyarray_union_type m_value; bool m_end; bool m_inside_list; typename pointers_list_type::iterator m_list_it; void init_list_it () { m_inside_list = false; if (m_value.m_judy_int & 1){ pointers_list_type *lst = (pointers_list_type *) (m_value.m_judy_int & ~1); m_inside_list = true; m_list_it = lst -> begin (); assert (m_list_it != lst -> end ()); } } void init () { m_pjudy = NULL; m_index = 0; m_value.m_judy_int = 0; m_end = true; m_inside_list = false; } void make_end () { m_end = true; } reference at () const { if (m_inside_list){ return * (*m_list_it); }else{ return * m_value.m_pointer; } } iterator_base () { init (); } iterator_base (const iterator_base &a) { init (); operator = (a); } iterator_base (Pcvoid_t * pjudy, Word_t index, Word_t value) : m_pjudy (pjudy), m_index (index), m_end (false) { m_value.m_judy_int = value; init_list_it (); } iterator_base (Pcvoid_t *pjudy, Word_t index, Word_t value, typename pointers_list_type::iterator it) : m_pjudy (pjudy), m_index (index), m_end (false), m_inside_list (true), m_list_it (it) { m_value.m_judy_int = value; } iterator_base (Pcvoid_t *pjudy) { init (); m_end = false; m_pjudy = pjudy; m_value.m_judy_ptr = (PWord_t) judyl_first (*m_pjudy, &m_index); if (m_value.m_judy_ptr){ m_value.m_judy_int = *m_value.m_judy_ptr; init_list_it (); }else{ m_end = true; } } iterator_base & operator = (const iterator_base& a) { if (this == &a) return *this; m_index = a.m_index; m_value = a.m_value; m_pjudy = a.m_pjudy; m_end = a.m_end; m_inside_list = a.m_inside_list; m_list_it = a.m_list_it; return *this; } reference operator * () { return at (); } const_reference operator * () const { return at (); } iterator_base& operator ++ () { if (m_end) abort (); bool goto_next_judy_cell = false; if (m_inside_list){ assert ((m_value.m_judy_int & 1) == 1); pointers_list_type *lst = (pointers_list_type *) (m_value.m_judy_int & ~1); goto_next_judy_cell = (lst -> end () == ++m_list_it); }else{ goto_next_judy_cell = true; } if (goto_next_judy_cell){ m_value.m_judy_ptr = (PWord_t) judyl_next (*m_pjudy, &m_index); if (m_value.m_judy_ptr){ m_value.m_judy_int = *m_value.m_judy_ptr; init_list_it (); }else{ m_end = true; } } return *this; } bool operator == (const iterator_base& i) const { if (this == &i) return true; if (m_end != i.m_end) return false; if (m_end && i.m_end) return true; if (m_pjudy != i.m_pjudy) return false; return (m_index == i.m_index) && (m_inside_list == i.m_inside_list) && (m_list_it == i.m_list_it); } }; public: class const_iterator; class iterator { private: iterator_base m_it; friend class const_iterator; friend class __judy_mapset_base; public: __JUDYARRAY_TYPEDEFS(iterator_base) typedef std::forward_iterator_tag iterator_category; iterator () { } iterator (const iterator_base &a) : m_it (a) { } iterator (const iterator &a) : m_it (a.m_it) { } iterator (Pcvoid_t *pjudy) : m_it (pjudy) { } iterator & operator = (const iterator& a) { m_it = a.m_it; return *this; } reference operator * () { return m_it.operator * (); } const_reference operator * () const { return m_it.operator * (); } iterator operator ++ (int) { iterator ret = *this; m_it.operator ++ (); return ret; } iterator& operator ++ () { m_it.operator ++ (); return *this; } bool operator == (const iterator& a) const { return m_it == a.m_it; } bool operator != (const iterator& a) const { return !(m_it == a.m_it); } pointer operator -> () { return &m_it.operator * (); } const_pointer operator -> () const { return &m_it.operator * (); } }; class const_iterator { private: iterator_base m_it; friend class __judy_mapset_base; public: __JUDYARRAY_TYPEDEFS(iterator_base) typedef std::forward_iterator_tag iterator_category; const_iterator () { } const_iterator (const iterator_base &a) : m_it (a) { } const_iterator (const const_iterator &a) : m_it (a.m_it) { } const_iterator (const iterator &a) : m_it (a.m_it) { } const_iterator (Pcvoid_t *pjudy) : m_it (pjudy) { } const_iterator & operator = (const const_iterator& a) { m_it = a.m_it; return *this; } reference operator * () { return m_it.operator * (); } const_reference operator * () const { return m_it.operator * (); } const_iterator operator ++ (int) { const_iterator ret = *this; m_it.operator ++ (); return ret; } const_iterator& operator ++ () { m_it.operator ++ (); return *this; } bool operator == (const const_iterator& a) const { return m_it == a.m_it; } bool operator != (const const_iterator& a) const { return !(m_it == a.m_it); } pointer operator -> () { return &m_it.operator * (); } const_pointer operator -> () const { return &m_it.operator * (); } }; void erase (const key_type& key) { iterator e (find (key)); if (e != end ()) erase (e); } void erase (iterator f, iterator l) { while (f != l){ erase (f++); } } void erase (iterator it) { if (it.m_it.m_end){ // C++ standard says about undefined behaviour in such // situations :-(. I assume, 'return' is much better return; } assert (&m_judy == it.m_it.m_pjudy); if (it.m_it.m_inside_list){ assert ((it.m_it.m_value.m_judy_int & 1) == 1); m_size -= 1; deallocate (*it.m_it.m_list_it); #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_list_item_count -= 1; #endif pointers_list_type *lst = (pointers_list_type *) (it.m_it.m_value.m_judy_int & ~1); lst -> erase (it.m_it.m_list_it); if (lst -> empty ()){ delete lst; judyl_del (m_judy, it.m_it.m_index); #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_list_count -= 1; #endif } }else{ assert ((it.m_it.m_value.m_judy_int & 1) == 0); m_size -= 1; deallocate (it.m_it.m_value.m_pointer); #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_value_count -= 1; #endif judyl_del (m_judy, it.m_it.m_index); } } private: iterator find_base (const key_type& key) const { unsigned long h = m_hash_func (key) & m_hash_mask; judyarray_union_type *ptr = (judyarray_union_type *) judyl_get (m_judy, h); if (!ptr || !ptr -> m_judy_int){ return iterator (); }else{ judyarray_union_type value; value.m_judy_int = ptr -> m_judy_int; if ((value.m_judy_int & 1) == 0){ if (m_eq_func (value2key (*value.m_pointer), key)){ return iterator (iterator_base ((Pcvoid_t *) &m_judy, h, value.m_judy_int)); }else{ iterator ret (iterator_base ((Pcvoid_t *) &m_judy, h, value.m_judy_int)); ret.m_it.make_end (); return ret; } }else{ pointers_list_type *lst = (pointers_list_type *) (value.m_judy_int & ~1); typename pointers_list_type::iterator end = lst -> end (); #if 1 typename pointers_list_type::iterator found = lst -> find (key); if (found != end){ return iterator (iterator_base ((Pcvoid_t *) &m_judy, h, value.m_judy_int, found)); } #else typename pointers_list_type::iterator beg = lst -> begin (); for (; !(beg == end); ++beg){ if (m_eq_func (value2key (**beg), key)){ return iterator (iterator_base ((Pcvoid_t *) &m_judy, h, value.m_judy_int, beg)); } } #endif iterator ret (iterator_base ((Pcvoid_t *) &m_judy, h, value.m_judy_int, end)); ret.m_it.make_end (); return ret; } } } public: const_iterator find (const key_type& key) const { return find_base (key); } iterator find (const key_type& key) { return find_base (key); } size_type count (const key_type& key) const { const_iterator e = end (); size_type c = 0; // optimize me!!! for ( const_iterator found = find (key); !(found == e) && m_eq_func (value2key (*found), key); ++found) { ++c; } return c; } std::pair <iterator, bool> insert (const value_type& value) { const TKey &key = value2key (value); Word_t h = m_hash_func (key) & m_hash_mask; judyarray_union_type *ptr = (judyarray_union_type *) judyl_ins (m_judy, h); assert (ptr); if (ptr -> m_judy_int){ // JudyL cell was already initialized if ((ptr -> m_judy_int & 1) == 0){ if (m_eq_func ( value2key (*ptr -> m_pointer), key)) { // JudyL cell points to the same value return std::make_pair (iterator (iterator_base ((Pcvoid_t *) &m_judy, h, ptr -> m_judy_int)), false); }else{ // collision is detected. // We create list object here pointer copy = ptr -> m_pointer; pointers_list_type *lst = ptr -> m_list = new pointers_list_type; #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_list_count += 1; m_debug_info.m_list_item_count += 2; m_debug_info.m_value_count -= 1; #endif lst -> insert (copy); typename pointers_list_type::iterator ret_it = lst -> insert (allocate (value)).first; ++m_size; ptr -> m_judy_int |= 1; return std::make_pair ( iterator (iterator_base ( (Pcvoid_t *) &m_judy, h, ptr -> m_judy_int, ret_it)), true); } }else{ // Collision is detected. // List object is already created. pointers_list_type *lst = (pointers_list_type *) (ptr -> m_judy_int & ~1); // typename pointers_list_type::iterator beg, end; // beg = lst -> begin (); // end = lst -> end (); // Look for 'value' in the list // for (; !(beg == end); ++beg){ // if (m_eq_func (value2key (**beg), key)){ // found // return std::make_pair ( // iterator (iterator_base ( // this, h, ptr -> m_judy_int, beg)), // false); // } // } // ++m_size; // Add new 'value' to the list std::pair <typename pointers_list_type::iterator, bool> ret_it = lst -> insert (allocate (value)); if (ret_it.second){ ++m_size; #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_list_item_count += 1; #endif } return std::make_pair ( iterator (iterator_base ( (Pcvoid_t *) &m_judy, h, ptr -> m_judy_int, ret_it.first )), ret_it.second); } }else{ // Created JudyL cell is new one. #ifdef JUDYARRAY_DEBUGINFO m_debug_info.m_value_count += 1; #endif ptr -> m_pointer = allocate (value); ++m_size; return std::make_pair ( iterator (iterator_base ((Pcvoid_t *) &m_judy, h, ptr -> m_judy_int)), true); } } iterator begin () { return iterator (iterator_base ((Pcvoid_t *) &m_judy)); } const_iterator begin () const { return const_iterator (iterator_base ((Pcvoid_t *) &m_judy)); } iterator end () { return iterator (); } const_iterator end () const { return const_iterator (); } }; // Unfortunately the following code doesn't work. // template <typename T> // typedef std::pair <T1, char> pair_first_is_char; // This is why this loooong macros is used here. #define REMAP_FUNCALLS(macrosarg__base, macrosarg__class_name, macrosarg__to_member)\ typedef typename macrosarg__base::key_equal key_equal;\ typedef typename macrosarg__base::hasher hasher;\ typedef typename macrosarg__base::allocator_type allocator_type;\ \ typedef typename macrosarg__base::iterator iterator;\ typedef typename macrosarg__base::const_iterator const_iterator;\ \ typedef typename macrosarg__base::debug_info debug_info;\ \ macrosarg__class_name ()\ {\ }\ \ macrosarg__class_name (\ size_type n,\ const hasher& h = hasher (), \ const key_equal& k = key_equal (),\ const allocator_type& a = allocator_type ())\ :\ macrosarg__to_member (n, h, k, a)\ {\ }\ \ template <class Tit>\ macrosarg__class_name (\ Tit beg, Tit end,\ size_type n = 0,\ const hasher& h = hasher (), \ const key_equal& k = key_equal (),\ const allocator_type& a = allocator_type ())\ :\ macrosarg__to_member (beg, end, n, h, k, a)\ {\ }\ \ macrosarg__class_name (const __this_type& a)\ :\ macrosarg__to_member (a.macrosarg__to_member)\ {\ }\ \ ~macrosarg__class_name ()\ {\ }\ \ void clear ()\ {\ macrosarg__to_member.clear ();\ }\ \ std::pair <iterator, bool> insert (const value_type& value)\ {\ return macrosarg__to_member.insert (value);\ }\ \ template <class Tit>\ void insert (Tit beg, Tit end)\ {\ while (beg != end){\ macrosarg__to_member.insert (*beg);\ \ ++beg;\ }\ }\ \ bool empty () const\ {\ return macrosarg__to_member.empty ();\ }\ \ size_type bucket_count () const\ {\ return macrosarg__to_member.bucket_count ();\ }\ \ void swap (__this_type& a)\ {\ macrosarg__to_member.swap (a.macrosarg__to_member);\ }\ \ size_type size () const\ {\ return macrosarg__to_member.size ();\ }\ \ hasher hash_funct () const\ {\ return macrosarg__to_member.hash_funct ();\ }\ \ key_equal key_eq () const\ {\ return macrosarg__to_member.key_eq ();\ }\ \ void resize (size_type n)\ {\ }\ \ size_type max_size () const\ {\ return macrosarg__to_member.max_size ();\ }\ \ void erase (const key_type& key)\ {\ macrosarg__to_member.erase (key);\ }\ \ void erase (iterator f, iterator l)\ {\ macrosarg__to_member.erase (f, l);\ }\ \ void erase (iterator it)\ {\ macrosarg__to_member.erase (it);\ }\ \ const_iterator find (const key_type& key) const\ {\ return macrosarg__to_member.find (key);\ }\ iterator find (const key_type& key)\ {\ return macrosarg__to_member.find (key);\ }\ \ size_type count (const key_type& key) const\ {\ return macrosarg__to_member.count (key);\ }\ \ iterator begin ()\ {\ return macrosarg__to_member.begin ();\ }\ const_iterator begin () const\ {\ return macrosarg__to_member.begin ();\ }\ \ iterator end ()\ {\ return macrosarg__to_member.end ();\ }\ const_iterator end () const\ {\ return macrosarg__to_member.end ();\ }\ \ const debug_info &get_debug_info () const\ {\ return macrosarg__to_member.m_debug_info;\ }\ void set_hash_mask (unsigned mask)\ {\ macrosarg__to_member.set_hash_mask (mask);\ }\ unsigned get_hash_mask () const\ {\ return macrosarg__to_member.get_hash_mask ();\ } #endif // _JUDY_MAPSET_COMMON_H_
19.834711
98
0.625509
cae47166852df878f934be2ee3335a8fbc926c75
3,427
c
C
dcMotorV3/motorDriver.X/source/qei.c
Roboy/motorDriver
5d44e2b61bd18d0251601aee7b61df9f47be7def
[ "BSD-3-Clause" ]
null
null
null
dcMotorV3/motorDriver.X/source/qei.c
Roboy/motorDriver
5d44e2b61bd18d0251601aee7b61df9f47be7def
[ "BSD-3-Clause" ]
null
null
null
dcMotorV3/motorDriver.X/source/qei.c
Roboy/motorDriver
5d44e2b61bd18d0251601aee7b61df9f47be7def
[ "BSD-3-Clause" ]
null
null
null
/* Alexander Lenz Bristol Robotics Laboratory 33f QEI initialisation intial release: 2012-09-06 */ #include <p33FJ128MC802.h> #include "initIO.h" //file global long rotationCount; //long currentEncoderPosition; #include "qei.h" #include "motorControl.h" #include <math.h> //****************************************************************INITIALISE CAN************************ void initQEI1( unsigned int startPos) { QEI1CONbits.QEISIDL = 1; // discontinue module operation in idle mode QEI1CONbits.QEIM = 0b111;// Quadrature Encoder Interface enabled (x4mode) with position counter reset by match (MAX1CNT) QEI1CONbits.SWPAB = 1; // Phase A and B swapped QEI1CONbits.PCDOUT = 0; // disable position counter direction pin QEI1CONbits.TQGATE = 0; // timer gated time acc disabled QEI1CONbits.POSRES = 0; // index does not reset position counter QEI1CONbits.TQCS = 0; // internal clock source (Tcy)) QEI1CONbits.UPDN_SRC = 0; // direction of position counter determined using internal logic MAXCNT = 0xffff; POSCNT = startPos; IFS3bits.QEI1IF = 0; // clear interrupt flag IEC3bits.QEI1IE = 1; // enable interrupt IPC14bits.QEI1IP = 5; } void initQEI2( unsigned int startPos) { QEI2CONbits.QEISIDL = 1; // discontinue module operation in idle mode QEI2CONbits.QEIM = 0b111;// Quadrature Encoder Interface enabled (x4mode) with position counter reset by match (MAX1CNT) QEI2CONbits.SWPAB = 1; // Phase A and B swapped QEI2CONbits.PCDOUT = 0; // disable position counter direction pin QEI2CONbits.TQGATE = 0; // timer gated time acc disabled QEI2CONbits.POSRES = 0; // index does not reset position counter QEI2CONbits.TQCS = 0; // internal clock source (Tcy)) QEI2CONbits.UPDN_SRC = 0; // direction of position counter determined using internal logic MAX2CNT = 0xffff; POS2CNT = startPos; IFS4bits.QEI2IF = 0; // clear interrupt flag IEC4bits.QEI2IE = 1; // enable interrupt IPC18bits.QEI2IP = 5; } void __attribute__((__interrupt__, auto_psv)) _QEI1Interrupt(void) { // Interrupt generated by QEI roll over/under IFS3bits.QEI1IF = 0; // clear interrupt //LED1=~LED1; if (POSCNT < 32768) { rotationCount=rotationCount+ (long) 0x10000; //we had a positive roll-over } else { rotationCount=rotationCount- (long) 0x10000;//we had a negative roll-over } } void __attribute__((__interrupt__, auto_psv)) _QEI2Interrupt(void) { // Interrupt generated by QEI roll over/under IFS4bits.QEI2IF = 0; // clear interrupt //LED1=~LED1; } float getPositionInRad() { long currentEncoderPosition; //disable interrupts to make sure we have consistent data _NSTDIS=1; GET_ENCODER (currentEncoderPosition); //disable interrupts to make sure we have consistent data _NSTDIS=0; return MYO_PI*2*currentEncoderPosition/eePromData.EncoderCountsPerRevolution; } float getVelocityInRadPerSecond() { static long oldPosition; float velocity; long currentPosition; //disable interrupts to make sure we have consistent data _NSTDIS=1; GET_ENCODER (currentPosition); _NSTDIS=0; velocity=MYO_PI*2* ((currentPosition-oldPosition)*getOneOverDeltaTime()) /eePromData.EncoderCountsPerRevolution ; oldPosition=currentPosition; return velocity; }
26.984252
124
0.684272
e7e0a2fab4a8b72cdda4baa4bc521e379640278b
975
h
C
src/cpp/toolkit/engine/rendering/buffer_layout.h
ismacaulay/code-adventures
05296f5bb873d7b0d2bda0303510bc90d7c467f4
[ "MIT" ]
1
2021-02-25T22:37:08.000Z
2021-02-25T22:37:08.000Z
src/cpp/toolkit/engine/rendering/buffer_layout.h
ismacaulay/code-adventures
05296f5bb873d7b0d2bda0303510bc90d7c467f4
[ "MIT" ]
11
2020-01-12T22:47:12.000Z
2021-02-01T01:23:44.000Z
src/cpp/toolkit/engine/rendering/buffer_layout.h
ismacaulay/code-adventures
05296f5bb873d7b0d2bda0303510bc90d7c467f4
[ "MIT" ]
null
null
null
#pragma once #include "shader_data_type.h" #include <initializer_list> #include <string> namespace tk { namespace engine { struct BufferElement { ShaderDataType type; std::string name; uint32_t size; size_t offset; bool normalized; uint8_t count; BufferElement() = default; BufferElement(ShaderDataType type, const std::string& name) : type(type) , name(name) , size(get_size_for_type(type)) , offset(0) , normalized(false) , count(get_count_for_type(type)) {} }; class BufferLayout { public: explicit BufferLayout() = default; BufferLayout(const std::initializer_list<BufferElement>& elements); uint32_t stride() const; const std::vector<BufferElement>& elements() const; private: std::vector<BufferElement> elements_; uint32_t stride_; }; } }
22.159091
75
0.588718
f0552a37413963ef4f7a5056c246331bfeb3f0ef
4,318
c
C
firmware/keyboard/hhkb/keymap_hhkb.c
blueshaedow/Polarbear
49a3905fa5a7833ad84180e48fd478c1b67e20ff
[ "MIT" ]
null
null
null
firmware/keyboard/hhkb/keymap_hhkb.c
blueshaedow/Polarbear
49a3905fa5a7833ad84180e48fd478c1b67e20ff
[ "MIT" ]
1
2016-06-27T06:18:12.000Z
2016-06-27T06:18:12.000Z
firmware/keyboard/hhkb/keymap_hhkb.c
blueshaedow/Polarbear
49a3905fa5a7833ad84180e48fd478c1b67e20ff
[ "MIT" ]
null
null
null
/* * HHKB Layout */ #include "keymap_common.h" #ifdef KEYMAP_SECTION_ENABLE const uint8_t keymaps[][MATRIX_ROWS][MATRIX_COLS] __attribute__ ((section (".keymap.keymaps"))) = { #else const uint8_t keymaps[][MATRIX_ROWS][MATRIX_COLS] PROGMEM = { #endif /* Layer 0: Default Layer * ,-----------------------------------------------------------. * |Esc| 1| 2| 3| 4| 5| 6| 7| 8| 9| 0| -| =| \| `| * |-----------------------------------------------------------| * |Tab | Q| W| E| R| T| Y| U| I| O| P| [| ]|Backs| * |-----------------------------------------------------------| * |Contro| A| S| D| F| G| H| J| K| L| ;| '|Enter | * |-----------------------------------------------------------| * |Shift | Z| X| C| V| B| N| M| ,| .| /|Shift |Fn0| * `-----------------------------------------------------------' * |Alt|Gui | Space |Gui |Alt| * `-------------------------------------------' */ KEYMAP(ESC, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, MINS,EQL, BSLS,GRV, \ TAB, Q, W, E, R, T, Y, U, I, O, P, LBRC,RBRC,BSPC, \ LCTL,A, S, D, F, G, H, J, K, L, SCLN,QUOT,ENT, \ LSFT,Z, X, C, V, B, N, M, COMM,DOT, SLSH,RSFT,FN0, \ LALT,LGUI, SPC, RGUI,RALT), /* Layer 1: HHKB mode (HHKB Fn) * ,-----------------------------------------------------------. * |Pwr| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del| * |-----------------------------------------------------------| * |Caps | | | | | | | |Psc|Slk|Pus|Up | |Backs| * |-----------------------------------------------------------| * | |VoD|VoU|Mut| | | *| /|Hom|PgU|Lef|Rig|Enter | * |-----------------------------------------------------------| * | | | | | | | +| -|End|PgD|Dow| | | * `-----------------------------------------------------------' * | | | | | | * `-------------------------------------------' */ KEYMAP(PWR, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, INS, DEL, \ CAPS,TRNS,TRNS,TRNS,TRNS,TRNS,TRNS,TRNS,PSCR,SLCK,PAUS, UP, TRNS, BSPC, \ TRNS,VOLD,VOLU,MUTE,TRNS,TRNS,PAST,PSLS,HOME,PGUP,LEFT,RGHT,PENT, \ TRNS,TRNS,TRNS,TRNS,TRNS,TRNS,PPLS,PMNS,END, PGDN,DOWN,TRNS,TRNS, \ TRNS,TRNS, TRNS, TRNS,TRNS), }; /* * Fn action definition */ #ifdef KEYMAP_SECTION_ENABLE const uint16_t fn_actions[] __attribute__ ((section (".keymap.fn_actions"))) = { [0] = ACTION_LAYER_MOMENTARY(1), [1] = ACTION_LAYER_MOMENTARY(2), [2] = ACTION_LAYER_MOMENTARY(3), [3] = ACTION_LAYER_MOMENTARY(4), [4] = ACTION_LAYER_MOMENTARY(5), [5] = ACTION_LAYER_MOMENTARY(6), [6] = ACTION_LAYER_MOMENTARY(7), [7] = ACTION_LAYER_TOGGLE(1), [8] = ACTION_LAYER_TOGGLE(2), [9] = ACTION_LAYER_TOGGLE(3), [10] = ACTION_LAYER_TAP_TOGGLE(1), [11] = ACTION_LAYER_TAP_TOGGLE(2), [12] = ACTION_LAYER_TAP_TOGGLE(3), [13] = ACTION_LAYER_TAP_KEY(1, KC_A), [14] = ACTION_LAYER_TAP_KEY(2, KC_F), [15] = ACTION_LAYER_TAP_KEY(3, KC_J), [16] = ACTION_LAYER_TAP_KEY(4, KC_SPACE), [17] = ACTION_LAYER_TAP_KEY(5, KC_SCOLON), [18] = ACTION_LAYER_TAP_KEY(6, KC_QUOTE), [19] = ACTION_LAYER_TAP_KEY(7, KC_SLASH), [20] = ACTION_MODS_TAP_KEY(MOD_LSFT, KC_SPACE), [21] = ACTION_MODS_TAP_KEY(MOD_LCTL, KC_SPACE), [22] = ACTION_MODS_TAP_KEY(MOD_RCTL, KC_QUOTE), [23] = ACTION_MODS_TAP_KEY(MOD_RCTL, KC_ENTER), [24] = ACTION_MODS_TAP_KEY(MOD_LCTL, KC_ESC), [25] = ACTION_MODS_TAP_KEY(MOD_LCTL, KC_BSPACE), [26] = ACTION_MODS_ONESHOT(MOD_LCTL), [27] = ACTION_MODS_TAP_KEY(MOD_LSFT, KC_ESC), [28] = ACTION_MODS_TAP_KEY(MOD_LSFT, KC_BSPACE), [29] = ACTION_MODS_ONESHOT(MOD_LSFT), [30] = ACTION_MODS_TAP_KEY(MOD_RSFT, KC_GRAVE), [31] = ACTION_MODS_TAP_KEY(MOD_RSFT, KC_BSLASH), }; #else const uint16_t fn_actions[] PROGMEM = { [0] = ACTION_LAYER_MOMENTARY(1), }; #endif
44.979167
99
0.431218
bb2a8409b9852b7c3e0e7e780d3512229a94b104
755
h
C
src/Providers/UNIXProviders/DiskPartition/UNIX_DiskPartitionPrivate.h
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/DiskPartition/UNIX_DiskPartitionPrivate.h
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/DiskPartition/UNIX_DiskPartitionPrivate.h
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#if defined(PEGASUS_OS_HPUX) # include "UNIX_DiskPartitionPrivate_HPUX.h" #elif defined(PEGASUS_OS_LINUX) # include "UNIX_DiskPartitionPrivate_LINUX.h" #elif defined(PEGASUS_OS_DARWIN) # include "UNIX_DiskPartitionPrivate_DARWIN.h" #elif defined(PEGASUS_OS_AIX) # include "UNIX_DiskPartitionPrivate_AIX.h" #elif defined(PEGASUS_OS_FREEBSD) # include "UNIX_DiskPartitionPrivate_FREEBSD.h" #elif defined(PEGASUS_OS_SOLARIS) # include "UNIX_DiskPartitionPrivate_SOLARIS.h" #elif defined(PEGASUS_OS_ZOS) # include "UNIX_DiskPartitionPrivate_ZOS.h" #elif defined(PEGASUS_OS_VMS) # include "UNIX_DiskPartitionPrivate_VMS.h" #elif defined(PEGASUS_OS_TRU64) # include "UNIX_DiskPartitionPrivate_TRU64.h" #else # include "UNIX_DiskPartitionPrivate_STUB.h" #endif
32.826087
47
0.84106
c0adbc9559533e4c0c2c618f64641ed30543a9d3
3,694
h
C
src/FuGPS.h
alhirzel/FuGPS
36a548fbfa7a067b811f359feda514436f582316
[ "MIT" ]
11
2019-05-18T21:28:55.000Z
2021-09-17T19:19:01.000Z
src/FuGPS.h
alhirzel/FuGPS
36a548fbfa7a067b811f359feda514436f582316
[ "MIT" ]
7
2018-11-02T22:15:18.000Z
2020-07-26T22:17:15.000Z
src/FuGPS.h
alhirzel/FuGPS
36a548fbfa7a067b811f359feda514436f582316
[ "MIT" ]
5
2019-05-30T09:01:45.000Z
2021-11-02T11:36:21.000Z
/** * FuGPS Library for Arduino * Copyright (c) 2018 Mariusz Kacki * The MIT License (MIT) * https://github.com/fu-hsi/fugps */ #ifndef _FUGPS_h #define _FUGPS_h #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #define FUGPS_PMTK_CMD_HOT_START "$PMTK101*32" #define FUGPS_PMTK_CMD_WARM_START "$PMTK102*31" #define FUGPS_PMTK_CMD_COLD_START "$PMTK103*30" #define FUGPS_PMTK_CMD_FULL_COLD_START "$PMTK104*37" #define FUGPS_PMTK_API_SET_NMEA_OUTPUT_DEFAULT "$PMTK314,-1*04" #define FUGPS_PMTK_API_SET_NMEA_OUTPUT_RMCGGA "$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28" #define FUGPS_PMTK_API_SET_NMEA_OUTPUT_NONE "$PMTK314,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28" #define FUGPS_PMTK_SET_NMEA_BAUDRATE_DEFAULT "$PMTK251,0*28" #define FUGPS_PMTK_SET_NMEA_BAUDRATE_4800 "$PMTK251,4800*14" #define FUGPS_PMTK_SET_NMEA_BAUDRATE_9600 "$PMTK251,9600*17" #define FUGPS_PMTK_SET_NMEA_BAUDRATE_14400 "$PMTK251,14400*29" #define FUGPS_PMTK_SET_NMEA_BAUDRATE_19200 "$PMTK251,19200*22" #define FUGPS_PMTK_SET_NMEA_BAUDRATE_38400 "$PMTK251,38400*27" #define FUGPS_PMTK_SET_NMEA_BAUDRATE_57600 "$PMTK251,57600*2C" #define FUGPS_PMTK_SET_NMEA_BAUDRATE_115200 "$PMTK251,115200*1F" #define FUGPS_PMTK_SET_NMEA_UPDATERATE_1HZ "$PMTK220,1000*1F" #define FUGPS_PMTK_SET_NMEA_UPDATERATE_5HZ "$PMTK220,200*2C" #define FUGPS_PMTK_SET_NMEA_UPDATERATE_10HZ "$PMTK220,100*2F" // 80 characters of visible text (plus the line terminators). #define FUGPS_NMEA_BUFFER_LENGTH 82 // 20 is more than we need for GGA and RMC #define FUGPS_MAX_TOKENS 20 // Uncomment for debug // #define FUGPS_DEBUG // From larryd, Arduino Forum #ifdef FUGPS_DEBUG #define DPRINT(...) Serial.print(__VA_ARGS__) #define DPRINTLN(...) Serial.println(__VA_ARGS__) #else #define DPRINT(...) #define DPRINTLN(...) #endif class FuGPS { private: Stream & _stream; char _currentBuff[FUGPS_NMEA_BUFFER_LENGTH + 1]; char _sentenceBuff[FUGPS_NMEA_BUFFER_LENGTH + 1]; char * _tokens[FUGPS_MAX_TOKENS]; byte _state = 0; byte _tokensCount; bool _fix; unsigned long _lastRead; protected: void process(); public: #ifdef FUGPS_DEBUG static unsigned int gga_counter; static unsigned int rmc_counter; #endif FuGPS(Stream & _stream); static byte checksum(const char * sentence); static void parseDateTime(float data, byte & val1, byte & val2, byte & val3); static float toDecimal(float coordinate, char coordinateRef); void sendCommand(const char* command); // Comma separated fields (Zero-based numbering) const char * getField(byte index); byte getFieldCount() const; // E.g. GPRMC const char * getMessageId(); // E.g. RMC const char * getSentenceId(); // Based on GGA and RMC messages data bool hasFix(); // Checks whether module still sends valid data (no matter what message) bool isAlive(unsigned int timeout = 10000); // Checks if we have valid NMEA message (see isAlive()) bool isValid(); // Reads one char (non blocking) bool read(); byte Hours, Minutes, Seconds; byte Days, Months, Years; // Fix Quality byte Quality; // Number of Satellites byte Satellites; // Horizontal Dilution of Precision (HDOP) float Accuracy; // Altitude above mean sea level (m or ft) float Altitude; // Latitude (decimal degrees) float Latitude; // Longitude (decimal degrees) float Longitude; // Speed in knots float Speed; // True course (Track) float Course; }; #endif
26.198582
99
0.701137
9d889c4e296f16924e2ef32e58284e3ed27d7130
675
h
C
filesystem.h
fjtrujy/libretro-lutro
81e078f29795b89d597ab93ebf56d35fe72be99d
[ "MIT" ]
134
2015-03-01T12:53:01.000Z
2022-01-15T15:29:57.000Z
filesystem.h
fjtrujy/libretro-lutro
81e078f29795b89d597ab93ebf56d35fe72be99d
[ "MIT" ]
115
2015-03-11T01:52:35.000Z
2022-03-06T17:41:59.000Z
filesystem.h
fjtrujy/libretro-lutro
81e078f29795b89d597ab93ebf56d35fe72be99d
[ "MIT" ]
56
2015-03-10T18:08:15.000Z
2021-07-08T17:36:39.000Z
#ifndef FILESYSTEM_H #define FILESYSTEM_H #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include "runtime.h" void lutro_filesystem_init(); void lutro_filesystem_deinit(); int lutro_filesystem_preload(lua_State *L); int fs_read(lua_State *L); int fs_write(lua_State *L); int fs_load(lua_State *L); int fs_getRequirePath(lua_State *L); int fs_setRequirePath(lua_State *L); int fs_exists(lua_State *L); int fs_setIdentity(lua_State *L); int fs_isFile(lua_State *L); int fs_isDirectory(lua_State *L); int fs_createDirectory(lua_State *L); int fs_getUserDirectory(lua_State *L); int fs_getDirectoryItems(lua_State *L); #endif // FILESYSTEM_H
24.107143
43
0.782222
53e212b6d250da165ab508d58f12396826a198e4
122
c
C
regression/goto-instrument/ensure-one-backedge-per-target-while-loop/test.c
tobireinhard/cbmc
fc165c119985adf8db9a13493f272a2def4e79fa
[ "BSD-4-Clause" ]
412
2016-04-02T01:14:27.000Z
2022-03-27T09:24:09.000Z
regression/goto-instrument/ensure-one-backedge-per-target-while-loop/test.c
tobireinhard/cbmc
fc165c119985adf8db9a13493f272a2def4e79fa
[ "BSD-4-Clause" ]
4,671
2016-02-25T13:52:16.000Z
2022-03-31T22:14:46.000Z
regression/goto-instrument/ensure-one-backedge-per-target-while-loop/test.c
tobireinhard/cbmc
fc165c119985adf8db9a13493f272a2def4e79fa
[ "BSD-4-Clause" ]
266
2016-02-23T12:48:00.000Z
2022-03-22T18:15:51.000Z
int main(int argc, char **argv) { int i = 0; while(i < 10) { ++i; if(i == 5) continue; ++i; } }
10.166667
31
0.401639
3ef73b697791012cf9d20ccc5ce605911a8ae32c
1,554
h
C
mt-drivers/mt7603e/src/mt7603_wifi/include/mac/mac_mt/top.h
bearking1069/openwrt-packages
eb78e080d5e3a022aa5a3acaff492283306cfc6b
[ "Apache-2.0" ]
4
2020-12-30T12:46:48.000Z
2021-01-04T08:28:13.000Z
mt-drivers/mt7603e/src/mt7603_wifi/include/mac/mac_mt/top.h
bearking1069/openwrt-packages
eb78e080d5e3a022aa5a3acaff492283306cfc6b
[ "Apache-2.0" ]
null
null
null
mt-drivers/mt7603e/src/mt7603_wifi/include/mac/mac_mt/top.h
bearking1069/openwrt-packages
eb78e080d5e3a022aa5a3acaff492283306cfc6b
[ "Apache-2.0" ]
1
2021-11-20T13:44:32.000Z
2021-11-20T13:44:32.000Z
/* *************************************************************************** * MediaTek Inc. * * All rights reserved. source code is an unpublished work and the * use of a copyright notice does not imply otherwise. This source code * contains confidential trade secret material of MediaTek. Any attemp * or participation in deciphering, decoding, reverse engineering or in any * way altering the source code is stricitly prohibited, unless the prior * written consent of MediaTek, Inc. is obtained. *************************************************************************** Module Name: top.h */ #ifndef __TOP_H__ #define __TOP_H__ #define TOP_CFG_BASE 0x0000 #define TOP_HVR (TOP_CFG_BASE + 0x1000) #define HW_VER_MASK (0xffff) #define GET_HW_VER(p) (((p) & HW_VER_MASK)) #define RESC_CID_MASK (0xf << 28) #define GET_RESC_CID(p) (((p) & RESC_CID_MASK) >> 28) #define TOP_FVR (TOP_CFG_BASE + 0x1004) #define FW_VER_MASK (0xffff) #define GET_FW_VER(p) (((p) & FW_VER_MASK)) #define TOP_HCR (TOP_CFG_BASE + 0x1008) #define HW_CODE_MASK (0xffff) #define GET_HW_CODE(p) (((p) & HW_CODE_MASK)) #define STRAP_STA (TOP_CFG_BASE + 0x1010) #define XTAL_SEL_MASK (0x3) #define GET_XTAL_SEL(p) (((p) & XTAL_SEL_MASK)) #define EEPROM_SEL (1 << 2) #define GET_EEPROM_SEL(p) (((p) & EEPROM_SEL) >> 2) #define CO_CLOCK_SEL (1 << 8) #define GET_CO_CLOCK_SEL(p) (((p) & CO_CLOCK_SEL) >> 8) #define ONE_ANT (1 << 24) #define GET_ONE_ANT(p) (((p) & ONE_ANT) >> 24) #define USB_MODE (1 << 25) #define GET_USB_MODE(p) (((p) & USB_MODE) >> 25 #endif
31.714286
76
0.646718
124995a6426a318d9ba09cf68a29684d85517e6c
56
c
C
keyboards/handwired/trackpoint/trackpoint.c
fzf/qmk_toolbox
10d6b425bd24b45002555022baf16fb11254118b
[ "MIT" ]
null
null
null
keyboards/handwired/trackpoint/trackpoint.c
fzf/qmk_toolbox
10d6b425bd24b45002555022baf16fb11254118b
[ "MIT" ]
null
null
null
keyboards/handwired/trackpoint/trackpoint.c
fzf/qmk_toolbox
10d6b425bd24b45002555022baf16fb11254118b
[ "MIT" ]
null
null
null
#include "trackpoint.h" void matrix_init_kb(void) { }
9.333333
27
0.714286
85519ef7c8da8663184e1d45825a275ca1f55d0e
2,794
h
C
Samples/Win7Samples/multimedia/windowsmediaservices9/authentication/AuthenticateContext.h
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/multimedia/windowsmediaservices9/authentication/AuthenticateContext.h
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/multimedia/windowsmediaservices9/authentication/AuthenticateContext.h
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows Media Technologies // Copyright (C) Microsoft Corporation. All rights reserved. // // File: AuthenticateContext.h // // Contents: // //-------------------------------------------------------------------------- #if !defined(AFX_AUTHENTICATECONTEXT_H__D5FB96E8_39EB_4691_B4CA_6340014B116B__INCLUDED_) #define AFX_AUTHENTICATECONTEXT_H__D5FB96E8_39EB_4691_B4CA_6340014B116B__INCLUDED_ #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CAuthenticateContext class ATL_NO_VTABLE CAuthenticateContext : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CAuthenticateContext, &CLSID_AuthenticateContext>, public IWMSAuthenticationContext { public: CAuthenticateContext(); ~CAuthenticateContext(); DECLARE_REGISTRY_RESOURCEID(IDR_AUTHENTICATECONTEXT) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CAuthenticateContext) COM_INTERFACE_ENTRY(IWMSAuthenticationContext) END_COM_MAP() public: STDMETHOD( Initialize )( IWMSAuthenticationPlugin* pAuthenticator ); // IWMSAuthenticationContext methods STDMETHOD( GetAuthenticationPlugin )( IWMSAuthenticationPlugin **ppAuthenPlugin ); STDMETHOD( Authenticate )( VARIANT ResponseBlob, IWMSContext *pUserCtx, IWMSContext *pPresentationCtx, IWMSCommandContext *pCommandContext, IWMSAuthenticationCallback *pCallback, VARIANT Context ); STDMETHOD( GetLogicalUserID )( BSTR* bstrUserID ); STDMETHOD( GetImpersonationAccountName )( BSTR* bstrAccountName ); STDMETHOD( GetImpersonationToken )( long* Token ); private: BOOL IsValidUser( char* pszUserName, char* pszPassword ); IWMSAuthenticationPlugin *m_pWMSAuthenticationPlugin; CRITICAL_SECTION m_CritSec; HANDLE m_hToken; DWORD m_State; CComBSTR m_bstrUsername; }; class CSafeArrayOfBytes { public: CSafeArrayOfBytes(VARIANT* pVariant); ~CSafeArrayOfBytes(); BOOL HasValidData(); DWORD GetLength(); BYTE* GetData(); HRESULT SetData(BYTE* blob, DWORD len); private: SAFEARRAY* m_psaBlob; BYTE* m_dataPtr; VARIANT* m_pVariant; }; inline DWORD base64DecodeNeedLength( DWORD BufEncodedLen ) { return( ( ( BufEncodedLen + 3 ) / 4 ) * 3 ); } #endif // !defined(AFX_AUTHENTICATECONTEXT_H__D5FB96E8_39EB_4691_B4CA_6340014B116B__INCLUDED_)
31.044444
95
0.613099
3f61274604fa04277e38c3d71ecfd1c516cc36bd
26,480
h
C
include/libpolypasswordhasher.h
LolalyLuo/PolyPasswordHasher
c1924e339905978e26fed8a3a795907bd18aabcd
[ "MIT" ]
null
null
null
include/libpolypasswordhasher.h
LolalyLuo/PolyPasswordHasher
c1924e339905978e26fed8a3a795907bd18aabcd
[ "MIT" ]
null
null
null
include/libpolypasswordhasher.h
LolalyLuo/PolyPasswordHasher
c1924e339905978e26fed8a3a795907bd18aabcd
[ "MIT" ]
null
null
null
/* * This file is Copyright Santiago Torres Arias <torresariass@gmail.com> 2014 * * 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 LIBPOLYPASSHASH_H #define LIBPOLYPASSHASH_H #include "libgfshare.h" #include <openssl/evp.h> #include <openssl/sha.h> #include <openssl/aes.h> #include <openssl/rand.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <stdbool.h> // constants declaration // the length of our share buffers #define SHARE_LENGTH 256/8 #define DIGEST_LENGTH SHARE_LENGTH // the maximum number of shares to use in this framework. #define MAX_NUMBER_OF_SHARES 255 // these constants are set to meet the password hashing competition guidelines #define MAX_USERNAME_LENGTH 128 #define MAX_SALT_LENGTH 16 #define MAX_PASSWORD_LENGTH 128 // the pph secret contains a specific signature to be able to discern from a // valid secret to an invalid one. This signature corresponds to the following // layout: [random_bytes][hash_of_random_bytes]. We define here the length of // the first and two sections of the secret. #define SIGNATURE_HASH_BYTE_LENGTH 4 #define SIGNATURE_RANDOM_BYTE_LENGTH DIGEST_LENGTH-SIGNATURE_HASH_BYTE_LENGTH #define SIGNATURE_HASH_ITERATIONS 10000 /* The number of iterations should be set higher */ #define ICB_HASH_ITERATIONS 10000 // Account type defines, for readability #define SHIELDED_ACCOUNT 0 #define BOOTSTRAP_ACCOUNT -1 /* Custom types */ typedef unsigned char uint8; /* enums */ typedef enum{ // all goes good PPH_ERROR_OK = 0, // accounts go bad PPH_USERNAME_IS_TOO_LONG, PPH_PASSWORD_IS_TOO_LONG, PPH_ACCOUNT_IS_INVALID, PPH_ACCOUNT_EXISTS, PPH_WRONG_SHARE_COUNT, PPH_CONTEXT_IS_LOCKED, PPH_VALUE_OUT_OF_RANGE, PPH_SECRET_IS_INVALID, // system or user is being brilliant. PPH_FILE_ERR, PPH_NO_MEM, PPH_BAD_PTR, // developer is not brilliant PPH_ERROR_UNKNOWN, } PPH_ERROR; /* structure definitions */ // this will help us keeping the code tidier, a pph_entry is a protector // value, it's associated sharenumber, the salt length and the salt for it. typedef struct _pph_entry{ // the share number that belongs to this entry short share_number; // information about the salt uint8 salt[MAX_SALT_LENGTH]; unsigned int salt_length; // information about the password, this is either the xored hash of the // password or the encrypted hash of the password. uint8 sharexorhash[DIGEST_LENGTH]; uint8 isolated_check_bits[DIGEST_LENGTH]; struct _pph_entry *next; } pph_entry; // This holds information about a single username. typedef struct _pph_account{ // information about the username stream. unsigned char username[MAX_USERNAME_LENGTH]; unsigned int username_length; // information about the entries associated with this username. uint8 number_of_entries; pph_entry *entries; } pph_account; // this is a helper structure to hold the user nodes. typedef struct _pph_account_node{ struct _pph_account_node* next; pph_account account; } pph_account_node; // we will have a data structure for previous logins typedef struct _pph_previous_login{ pph_entry *entry; uint8 digest[DIGEST_LENGTH]; struct _pph_previous_login *next; } pph_previous_login; // we will have a data structure for bootstrap entries to update them // after bootstrapping. typedef struct _pph_bootstrap_entry { pph_entry *entry; struct _pph_bootstrap_entry *next; } pph_bootstrap_entry; // The context structure defines all of what's needed to handle a polypasswordhasher // store. typedef struct _pph_context{ // this share context manages the share generation and secret recombination gfshare_ctx *share_context; uint8 threshold; // This is the max number of available shares for this context. Next entry // will allocate the shares in a round-robin fashion. uint8 available_shares; uint8 next_entry; // this is a boolean flag to indicate if the secret is available. bool is_normal_operation; // if the context is under normal operation, these will point to the secret // and the AES key uint8 *AES_key; uint8 *secret; uint8 secret_integrity[DIGEST_LENGTH]; /* we will store the whole integrity check now */ // This is the number of isolated-check-bits associated with the context. // If isolated-check-bits is 0, isolated validation is disabled. uint8 isolated_check_bits; // this points to the account nodes currently available. pph_account_node* account_data; // we will populate a list of previous logins to fully verify after // bootstrapping pph_previous_login *previous_logins; // this will contain entries to be updated after bootstrapping. pph_bootstrap_entry *bootstrap_entries; } pph_context; /* Function Declarations */ /******************************************************************* * NAME : pph_init_context * * DESCRIPTION : Initialize a poly pass hash structure with everything * we need in order to work. The produced structure will * * This is the layout of the generated structure: * * typedef struct _pph_context{ * gfshare_ctx* share_context = new share context * uint8 threshold = threshold * uint8 available_shares; = MAX_NUMBER_OF_SHARES * uint8 next_entry; = 1 * bool is_normal_operation; = true * uint8 *AES_key; = will point to secret * uint8 *secret; = generated secret * uint8 isolated_check_bits; = isolated_check_bits * pph_account_node* account_data; = NULL * } pph_context; * * * INPUTS : * PARAMETERS: * uint8 threshold: The threshold for this * password storage. This is, the minimum * number of shares needed to transition to * normal operation upon reloading. The valid * ranges for the threshold go from 1 to * MAX_NUMBER_OF_SHARES; * however, a value of 1 is a bad idea. * * uint8 isolated_check_bits: The number of hashed-bytes to leak in order * to perform isolated validation. If * isolated_check_bits = 0, isolated validation * is disabled. isolated-check-bits should range * from 0 to DIGEST_LENGTH, but a value from 0 to * 4 is recommended. * OUTPUTS : * PARAMETERS: * None * * GLOBALS : * None * * RETURN : * Type: pph_context the resulting context or NULL when either * allocation fails or the input given is not * within the valid ranges. * PROCESS : * 1) verify arguments * 2) allocate data structures * 3) generate a custom random secret * 4) initialize the rest of the values * 5) initialize the secret generator. * 7) return * * CHANGES : * 21/04/2014: secret is no longer a parameter */ pph_context* pph_init_context(uint8 threshold, uint8 isolated_check_bits); /******************************************************************* * NAME : pph_destroy_context * * DESCRIPTION : Destroy an existing instance of pph_context, securely * destroying its resources. * * The structure will have to free the following elements * before it can be safely freed: * * typedef struct _pph_context{ * gfshare_ctx* share_context = needs freeing * uint8 threshold = * uint8 available_shares; = * uint8 next_entry; = * bool is_normal_operation; = * uint8 *AES_key; = needs freeing * uint8 *secret; = needs freeing * uint8 isolated_check_bits; = * pph_account_node* account_data; = needs freeing * } pph_context; * * INPUTS : * PARAMETERS: * pph_context *context: the context to destroy * * OUTPUTS : * PARAMETERS: * pph_context *context: the context to free/destroy. * * GLOBALS : * None * * RETURN : * Type: PPH_ERROR * value: when: * PPH_ERROR_OK the free process worked * * PPH_BAD_PTR if the pointer given is NULL * * PROCESS : * Basically destroy pointers in the structure and then free the structure * itself, doing sanity checks in between child and parent structure * destruction. * * CHANGES : * (03/17/14): Account freeing is done now. */ PPH_ERROR pph_destroy_context(pph_context *context); /******************************************************************* * NAME : pph_create_account * * DESCRIPTION : given a context and some other data, create a user * entry in the polypasswordhasher context with the desired * information. * * INPUTS : * PARAMETERS: * pph_context *ctx: This is the context in which the * account will be created * * uint8 *username: This is the desired username for the * new entry * * unsigned int username_length: The length of the username field, * this value should not exceed * MAX_USERNAME_LENGTH. * * uint8 *password: This is the password for the new entry * * unsgned int password_length: The length of the password field, this * value should not exceed * MAX_PASSWORD_LENGTH * * uint8 shares: This is the amount of shares we decide * to allocate to this new account. * OUTPUTS : * PARAMETERS: * None * * GLOBALS : * None * * RETURN : * Type: int PPH_ERROR * Values: When: * PPH_ERROR_OK The credentials provided are correct * * PPH_BAD_PTR One of the fields is unallocated * * PPH_ERROR_UNKNOWN When something unexpected happens. * * PPH_NO_MEM If malloc, calloc fails. * * PPH_USERNAME_IS_TOO_LONG When the value for username_length * is too long. * * PPH_PASSWORD_IS_TOO_LONG when the value for password_length * is too long * * PPH_CONTEXT_IS_LOCKED When the context is locked and, hence * he cannot create accounts * * PPH_ACCOUNT_IS_INVALID If the username provided already * exists * * PROCESS : * 1) Check for data sanity, and return errors * 2) Check the type of account requested * 3) Allocate a share/digest entry for the account * 4) Initialize the account data with the information provided * 5) Update the context information regarding the new account * 6) return * * CHANGES : * Added support for different length accounts */ PPH_ERROR pph_create_account(pph_context *ctx, const uint8 *username, unsigned int username_length, uint8 *password, unsigned int password_length, uint8 shares); /******************************************************************* * NAME : pph_check_login * * DESCRIPTION : Check whether a username and password combination exists * inside the loaded PPH context. * * INPUTS : * PARAMETERS: * pph_context *ctx: The context in which we are working * * const char *username: The username attempt * * unsigned int username_length: The length of the username field * * const char *password: The password attempt * * unsigned int password_length: the length of the password field * * OUTPUTS : * PARAMETERS: * None * * GLOBALS : * None * * RETURN : * Type: int PPH_ERROR * Values: When: * PPH_ACCOUNT_IS_INVALID The combination does not exist * * PPH_USERNAME_IS_TOO_LONG The username won't fit in the * buffer * * PPH_PASSWORD_IS_TOO_LONG The password won't fit in the * buffer associated to it. * * PPH_BAD_PTR When pointers are null or out * of range * * PPH_ERROR_UNKNOWN any time else * * PROCESS : * 1) Sanitize data and return errors * 2) try to find username in the context * 3) if found, decide how to verify his information based on the status * of the context (shielded, isolated validation, etc.) * 4) Do the corresponding check and return the proper error * * CHANGES : * (21/04/2014): Added support for non-null-terminated usernames and passwords. */ PPH_ERROR pph_check_login(pph_context *ctx, const char *username, unsigned int username_length, uint8 *password, unsigned int password_length); /******************************************************************* * NAME : pph_unlock_password_data * * DESCRIPTION : given a context and pairs of usernames and passwords, * unlock the password secret. * * INPUTS : * PARAMETERS: * pph_context *ctx: The context in which we are working * * unsigned int username_count: The length of the username/password arrays * * const char *usernames: The username attempts * * unsigned int username_lengths[]: The length of the username fields, * in the same order as the usernames. * * const char *passwords: The password attempts * * OUTPUTS : * PARAMETERS: * type: pph_context The context provided will be activated and * pointed to the secret if combination was * successful * * GLOBALS : * None * * RETURN : * Type: int PPH_ERROR * Values: When: * PPH_ACCOUNT_IS_INVALID We couldn't recombine with the * information given * * PPH_USERNAME_IS_TOO_LONG The username won't fit in the * buffer allocated to it. * * PPH_PASSOWRD_IS_TOO_LONG The password won't fit in it's * assigned buffer * * PPH_BAD_PTR When pointers are null or out * of range * * PPH_ERROR_UNKNOWN any time else * * PROCESS : * 1) Verify input sanity * 2) traverse user accounts searching for proposed username * 3) produce shares out of the password digest * 4) give shares to the recombination context * 5) attempt recombination * 6) verify correct recombination. * 7) if successful, transition from bootstrapping to normal operation. * 8) return error code * * CHANGES : * (03/25/14): Secret consistency check was added. */ PPH_ERROR pph_unlock_password_data(pph_context *ctx, unsigned int username_count, const uint8 *usernames[], unsigned int username_lengths[], const uint8 *passwords[], unsigned int password_lengths[]); /******************************************************************* * NAME : pph_store_context * * DESCRIPTION : store the information of the working context into a file. * Elements as the secret and the share context are not stored. * * * INPUTS : * PARAMETERS: * pph_context *ctx: The context in which we are working * * const unsigned char* filename: The filename of the datastore to use * OUTPUTS : * PARAMETERS: * None * * GLOBALS : * None * * RETURN : * Type: int PPH_ERROR * Values: When: * PPH_ERROR_OK When the file was stored * successfully. * * PPH_BAD_PTR When pointers are null or out * of range * * PPH_FILE_ERR when the file selected is non- * writable. * * PPH_ERROR_UNKNOWN any time else * * PROCESS : * * Sanitize the data (unset flags, point secret to NULL) * * open the selected file. * * traverse the dynamic linked lists storing everything * * close the file, return appropriate error * * CHANGES : * None as of this version */ PPH_ERROR pph_store_context(pph_context *ctx, const unsigned char *filename); /******************************************************************* * NAME : pph_reload_context * * DESCRIPTION : Reload a pph_context stored in a file, the secret is * unknown and the structure is locked by default. * pph_unlock_password_data should be called after this returns * a valid pointer * * INPUTS : * PARAMETERS: * const unsigned char* filename: The filename of the datastore to use * * OUTPUTS : * PARAMETERS: * None * * GLOBALS : * None * * RETURN : * Type: pph_context * * * Values: When: * NULL The file is not loadable * or data looks corrupted * * A valid pointer if everything went fine * * PROCESS : * * Sanitize the data (check the string is a good string) * * open the selected file. * * Build a dynamic list by traversing the file's contents * * close the file, return appropriate structure * * CHANGES : * None as of this version */ pph_context *pph_reload_context(const unsigned char *filename); /******************************************************************* * NAME : PHS * * DESCRIPTION : Generate a password hash, given the password, and salt. * This is a "virtual" interface and functions as a proof of * context for the password hashing competition. A context will * be initialized upon calling, and will be destroyed upon * return. No persistent setup is done in this function, and no * accounts are created. * * INPUTS : * PARAMETERS: * void *out: The resulting hash buffer. The resulting hash will be * copied here. * * size_t outlen: The size of the hash to produce, this version only * supports 32 byte-length outputs. * * const void *in: The input password to hash. * * size_t inlen: The length of the input, the maximum supported length * is 128. * * const void *salt: The salt to use with the password * * size_t saltlen: The length of the salt to use. The maximum supported * length is 16 * * int tcost: Time cost for this function. This parameter * translates directly to the threshold of the * generated context. With a bigger threshold, the time * to initialize a context rises. This value can't be 0. * * int mcost: Memory cost (unusable this time) * * OUTPUTS : * PARAMETERS: * None * * GLOBALS : * None * * RETURN : * Type: int * * Values: When: * 0 On error ok. * * !=0 In case of error. * * PROCESS * 1) verify the input. * 2) Generate a pph_context if there is none in memory * 3) Generate a protector entry * 4) Copy the protector value to the output buffer * 5) Return. * * CHANGES : * None as of this version */ int PHS(void *out, size_t outlen, const void *in, size_t inlen, const void* salt, size_t saltlen, int tcost, int mcost); // helper functions ////////////////////////// // used to generate a random secret and add its hash uint8 *generate_pph_secret( uint8 *integrity_check); // this checks whether a given secret matches the given integrity check (stored // in the context) at certain number of iterations PPH_ERROR check_pph_secret(uint8 *secret, uint8 *secret_integrity); // this function provides a protector entry given the input pph_entry *create_protector_entry(uint8 *password, unsigned int password_length, uint8 *salt, unsigned int salt_length, const void *share, unsigned int share_length, unsigned int isolated_check_bits); // this other function is the equivalent to the one in the top, but for // shielded accounts. pph_entry *create_shielded_entry(uint8 *password, unsigned int password_length, uint8* salt, unsigned int salt_length, uint8* AES_key, unsigned int key_length, unsigned int isolated_check_bits); // Finally, this function, creates an entry for an account that was created during // bootstrapping. pph_entry *create_bootstrap_entry(uint8 *password, unsigned int password_length, uint8 *salt, unsigned int salt_length); /* inline functions */ // These are most possibly private helpers that aid in readability // with the API functions. // xoring two streams of bytes. inline void _xor_share_with_digest(uint8 *result, uint8 *share, uint8 * digest,unsigned int length) { int i; unsigned int *xor_digest_pointer; unsigned int *xor_share_pointer; unsigned int *xor_result_pointer; int aligned_length = length/sizeof(*xor_result_pointer); int char_aligned_length = aligned_length * sizeof(*xor_result_pointer); int char_aligned_offset = length%sizeof(*xor_result_pointer); // xor the whole thing, we do this in an unsigned int fashion imagining // this is where usually where the processor aligns things and is, hence // faster xor_digest_pointer = (unsigned int*)digest; xor_share_pointer = (unsigned int*)share; xor_result_pointer = (unsigned int*)result; for(i=0;i<aligned_length;i++) { *(xor_result_pointer + i) = *(xor_share_pointer+i)^*(xor_digest_pointer +i); } // xor the rest, if we have a number that's not divisible by a word. for(i = char_aligned_length; i<char_aligned_length+char_aligned_offset;i++) { *(result+i) = *(share+i) ^ *(digest+i); } return; } // we will make an inline of the hash calculation, since it is done in many // places and looks too messy inline void _calculate_digest(uint8 *digest, const uint8 *password, unsigned int length) { EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); EVP_DigestInit_ex(&mctx, EVP_sha256(), NULL); EVP_DigestUpdate(&mctx, password, length); EVP_DigestFinal_ex(&mctx, digest, 0); EVP_MD_CTX_cleanup(&mctx); return; } // we will use an inline to encrypt a digest to make everything cleaner also //Add an additional input which is the IV that will be used by the CTR mode ~GA inline void _encrypt_digest(uint8 *result, uint8 *digest, uint8 *AES_key, uint8* iv) { EVP_CIPHER_CTX en_ctx; int c_len,f_len; // encrypt the generated digest EVP_CIPHER_CTX_init(&en_ctx); EVP_EncryptInit_ex(&en_ctx, EVP_aes_256_ctr(), NULL, AES_key, iv); EVP_EncryptUpdate(&en_ctx, result, &c_len, digest, DIGEST_LENGTH); EVP_EncryptFinal_ex(&en_ctx, result+c_len, &f_len); EVP_CIPHER_CTX_cleanup(&en_ctx); return; } // in the generate user event and when destroying a context object inline void _destroy_entry_list(pph_entry *head) { pph_entry *last; last=head; while(head!=NULL) { head=head->next; free(last); last=head; } return; } #endif /* LIBPOLYPASSHASH_H */
32.058111
91
0.587273
27601505bbc1a761d4b5ba5e1e56408926ce024f
469
c
C
Engine/Source/ThirdParty/MCPP/mcpp-2.7.2/cpp-test/test-t/n_dslcom.c
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
34
2021-06-15T10:24:49.000Z
2022-03-22T19:20:23.000Z
Engine/Source/ThirdParty/MCPP/mcpp-2.7.2/cpp-test/test-t/n_dslcom.c
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
9
2021-03-04T21:34:03.000Z
2021-05-04T18:33:47.000Z
Engine/Source/ThirdParty/MCPP/mcpp-2.7.2/cpp-test/test-t/n_dslcom.c
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2021-12-29T01:15:22.000Z
2022-02-01T10:53:15.000Z
/* n_dslcom.c: // is a comment of C++ and C99. */ /* a; */ a; // is a comment of C++ and C99 /* { dg-do preprocess } { dg-options "-std=c99" } { dg-final { if ![file exist n_dslcom.i] { return } } } { dg-final { if \{ [grep n_dslcom.i "^\[ \]*a;\[ \]*$"] != "" \} \{ } } { dg-final { return \} } } { dg-final { fail "n_dslcom.c: double slash comment" } } */
36.076923
79
0.394456
e94e9d020c78834d9386c2f1684d2fa33dbdb84e
1,784
h
C
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/BEERecentPHAssetObserver.h
ceekay1991/AliPayForDebug
5795e5db31e5b649d4758469b752585e63e84d94
[ "MIT" ]
5
2020-03-29T12:08:37.000Z
2021-05-26T05:20:11.000Z
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/BEERecentPHAssetObserver.h
ceekay1991/AliPayForDebug
5795e5db31e5b649d4758469b752585e63e84d94
[ "MIT" ]
null
null
null
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/BEERecentPHAssetObserver.h
ceekay1991/AliPayForDebug
5795e5db31e5b649d4758469b752585e63e84d94
[ "MIT" ]
5
2020-04-17T03:24:04.000Z
2022-03-30T05:42:17.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <objc/NSObject.h> #import "BEERecentPhotoObserver-Protocol.h" #import "PHPhotoLibraryChangeObserver-Protocol.h" @class NSMutableArray, NSOperationQueue, NSString, PHAsset, PHFetchResult; @interface BEERecentPHAssetObserver : NSObject <PHPhotoLibraryChangeObserver, BEERecentPhotoObserver> { _Bool _assetChanged; _Bool _isEnumeratingAssets; PHAsset *_recentAsset; NSMutableArray *_queryCompletionBlocks; PHFetchResult *_fetchResult; NSOperationQueue *_queue; } @property(retain, nonatomic) NSOperationQueue *queue; // @synthesize queue=_queue; @property(retain) PHFetchResult *fetchResult; // @synthesize fetchResult=_fetchResult; @property _Bool isEnumeratingAssets; // @synthesize isEnumeratingAssets=_isEnumeratingAssets; @property(retain) NSMutableArray *queryCompletionBlocks; // @synthesize queryCompletionBlocks=_queryCompletionBlocks; @property _Bool assetChanged; // @synthesize assetChanged=_assetChanged; @property(retain) PHAsset *recentAsset; // @synthesize recentAsset=_recentAsset; - (void).cxx_destruct; - (void)checkRecentAsset:(id)arg1; - (void)queryComplatedWithAsset:(id)arg1; - (void)photoLibraryDidChange:(id)arg1; - (void)unregistPhotoChangedNotification; - (void)registPhotoChangedNotification; - (void)queryRecentPhoto:(CDUnknownBlockType)arg1; - (id)recentPhoto; - (void)stopObserver; - (void)startObserver; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
35.68
117
0.786996
e960b5f4fac892b840ba1dd1cee18da65a1099dc
699
h
C
motor-controller-nucleo/tmc/ic/TMC262_1420/TMC262_1420_Constants.h
HEEV/motor-controller-2018-sw
7bc22e4c7ba330d9130cda98a54a56066df2200b
[ "MIT" ]
3
2018-12-29T13:33:32.000Z
2019-09-14T15:45:26.000Z
motor-controller-nucleo/tmc/ic/TMC262_1420/TMC262_1420_Constants.h
HEEV/motor-controller-2018-sw
7bc22e4c7ba330d9130cda98a54a56066df2200b
[ "MIT" ]
null
null
null
motor-controller-nucleo/tmc/ic/TMC262_1420/TMC262_1420_Constants.h
HEEV/motor-controller-2018-sw
7bc22e4c7ba330d9130cda98a54a56066df2200b
[ "MIT" ]
1
2019-06-06T03:28:05.000Z
2019-06-06T03:28:05.000Z
/* * TMC262_1420_Constants.h * * Created on: 25.06.2018 * Author: LK */ #ifndef TMC_IC_TMC262_1420_TMC262_1420_CONSTANTS_H_ #define TMC_IC_TMC262_1420_TMC262_1420_CONSTANTS_H_ #include "../../helpers/Constants.h" #define TMC262_1420_REGISTER_COUNT 8 #define TMC262_1420_MOTORS 1 #define TMC262_1420_ADDRESS_MASK 0x07 #define TMC262_1420_WRITE_BIT 0x08 // read addresses correspond with RDSEL, added latest to access latest data of common lower 7 bits #define TMC262_1420_RESPONSE0 0 #define TMC262_1420_RESPONSE1 1 #define TMC262_1420_RESPONSE2 2 #define TMC262_1420_RESPONSE_LATEST 3 #endif /* TMC_IC_TMC262_1420_TMC262_1420_CONSTANTS_H_ */
27.96
98
0.76824
e9ab4b9e60a8ceee70be0bd24d185a1f11e7a392
7,340
h
C
src/libYARP_OS/include/yarp/YARPBottleContent.h
robotology-legacy/yarp1
21434f5b776edea201b39a9644552dca59339dbc
[ "Artistic-1.0-Perl" ]
null
null
null
src/libYARP_OS/include/yarp/YARPBottleContent.h
robotology-legacy/yarp1
21434f5b776edea201b39a9644552dca59339dbc
[ "Artistic-1.0-Perl" ]
null
null
null
src/libYARP_OS/include/yarp/YARPBottleContent.h
robotology-legacy/yarp1
21434f5b776edea201b39a9644552dca59339dbc
[ "Artistic-1.0-Perl" ]
null
null
null
///////////////////////////////////////////////////////////////////////// /// /// /// /// /// This Academic Free License applies to any software and associated /// /// documentation (the "Software") whose owner (the "Licensor") has /// /// placed the statement "Licensed under the Academic Free License /// /// Version 1.0" immediately after the copyright notice that applies /// /// to the Software. /// /// Permission is hereby granted, free of charge, to any person /// /// obtaining a copy of the Software (1) to use, copy, modify, merge, /// /// publish, perform, distribute, sublicense, and/or sell copies of /// /// the Software, and to permit persons to whom the Software is /// /// furnished to do so, and (2) under patent claims owned or /// /// controlled by the Licensor that are embodied in the Software as /// /// furnished by the Licensor, to make, use, sell and offer for sale /// /// the Software and derivative works thereof, subject to the /// /// following conditions: /// /// Redistributions of the Software in source code form must retain /// /// all copyright notices in the Software as furnished by the /// /// Licensor, this list of conditions, and the following disclaimers. /// /// Redistributions of the Software in executable form must reproduce /// /// all copyright notices in the Software as furnished by the /// /// Licensor, this list of conditions, and the following disclaimers /// /// in the documentation and/or other materials provided with the /// /// distribution. /// /// /// /// Neither the names of Licensor, nor the names of any contributors /// /// to the Software, nor any of their trademarks or service marks, /// /// may be used to endorse or promote products derived from this /// /// Software without express prior written permission of the Licensor./// /// /// /// DISCLAIMERS: LICENSOR WARRANTS THAT THE COPYRIGHT IN AND TO THE /// /// SOFTWARE IS OWNED BY THE LICENSOR OR THAT THE SOFTWARE IS /// /// DISTRIBUTED BY LICENSOR UNDER A VALID CURRENT LICENSE. EXCEPT AS /// /// EXPRESSLY STATED IN THE IMMEDIATELY PRECEDING SENTENCE, THE /// /// SOFTWARE IS PROVIDED BY THE LICENSOR, CONTRIBUTORS AND COPYRIGHT /// /// OWNERS "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, /// /// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// /// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO /// /// EVENT SHALL THE LICENSOR, CONTRIBUTORS OR COPYRIGHT OWNERS 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. /// /// /// /// This license is Copyright (C) 2002 Lawrence E. Rosen. All rights /// /// reserved. Permission is hereby granted to copy and distribute /// /// this license without modification. This license may not be /// /// modified without the express written permission of its copyright /// /// owner. /// /// /// /// /// ///////////////////////////////////////////////////////////////////////// /// /// /// YARP - Yet Another Robotic Platform (c) 2001-2003 /// /// #nat# /// /// "Licensed under the Academic Free License Version 1.0" /// /// /// $Id: YARPBottleContent.h,v 2.1 2005-11-12 18:48:58 eshuy Exp $ /// /// #ifndef __YARPBOTTLEPORTCONTENT__ #define __YARPBOTTLEPORTCONTENT__ #include <yarp/YARPConfig.h> #include <ace/config.h> #ifdef YARP_HAS_PRAGMA_ONCE # pragma once #endif /** * \file YARPBottleContent.h Defines a class that allows sending the YARPBottle * through a port. This must always be included whenever sending bottles. It is * also included (circular include) from the YARPBottle.h just to make sure * the user doesn't forget to include it. */ #include <yarp/YARPBottle.h> #include <yarp/YARPPort.h> #include <yarp/YARPPortContent.h> /** * YARPBottleContent is the content type for sending bottles through ports. */ class YARPBottleContent : public YARPBottle, public YARPPortContent { public: /** * Default constructor. */ virtual ~YARPBottleContent () { ///ACE_DEBUG ((LM_DEBUG, "destroying a YARPBottleContent\n")); } /** * Reads a bottle from the network. It calls methods in YARPPortReader * to get buffers from the connection and traslates them into a * port. This method is automatically called by the Port code. * @param reader is the reference to the YARPPortReader object. * @return YARP_OK if successful. */ virtual int Read(YARPPortReader& reader) { // read id reader.Read((char*)(&id.length), sizeof(id.length)); reader.Read(id.text, id.length); // read id reader.Read((char*)(&len),sizeof(len)); text.reserve(len); text.resize(len); top = len; int result = reader.Read((char*)(&text[0]),len); rewind(); return result; } /** * Writes a bottle to the network. It calls methods in YARPPortWriter * to write buffers into the connection. This method is automatically called * by the Port code. * @param writer is the reference to the YARPPortWriter object. * @return YARP_OK if successful. */ virtual int Write(YARPPortWriter& writer) { writer.Write((char*)(&id.length),sizeof(id.length)); writer.Write((char*) id.text, id.length); len = top; writer.Write((char*)(&len),sizeof(len)); int r = writer.Write((char*)(&text[0]),len); return r; } /** * In case the content has to be reused. Resets the internal bottle object. */ virtual int Recycle() { reset(); top = 0; return 0; } /** * Copies operator. Useful for copying contents. * @param vec is the object reference to copy from. * @return a reference to this object. */ YARPBottle& operator=(const YARPBottle &vec) { return YARPBottle::operator= (vec); } }; template<> class YARPInputPortOf<YARPBottle> : public YARPBasicInputPort<YARPBottleContent> { public: YARPInputPortOf<YARPBottle>(int n_service_type = DEFAULT_BUFFERS, int n_protocol_type = YARP_DEFAULT_PROTOCOL) : YARPBasicInputPort<YARPBottleContent> (n_service_type, n_protocol_type) {} virtual ~YARPInputPortOf<YARPBottle> () { YARPPort::End(); } }; template<> class YARPOutputPortOf<YARPBottle> : public YARPBasicOutputPort<YARPBottleContent> { public: YARPOutputPortOf<YARPBottle>(int n_service_type = DEFAULT_OUTPUTS, int n_protocol_type = YARP_DEFAULT_PROTOCOL) : YARPBasicOutputPort<YARPBottleContent> (n_service_type, n_protocol_type) {} virtual ~YARPOutputPortOf<YARPBottle> () { YARPPort::End(); } }; #endif
40.777778
114
0.607221
aceab53dd011c3b4f9df5b82bae1b992ff92573c
666
h
C
lab_10/include/scheme.h
NeKp0T/cpp_homework
b121b9bbd638d9d06e65b2f5a53a2a8fd1965550
[ "MIT" ]
null
null
null
lab_10/include/scheme.h
NeKp0T/cpp_homework
b121b9bbd638d9d06e65b2f5a53a2a8fd1965550
[ "MIT" ]
null
null
null
lab_10/include/scheme.h
NeKp0T/cpp_homework
b121b9bbd638d9d06e65b2f5a53a2a8fd1965550
[ "MIT" ]
null
null
null
#pragma once #include "figure.h" class Scheme{ public: Scheme(int capacity); ~Scheme(); void push_back_figure(Figure* fg); void remove_figure(int id); // элементы смещаются влево void print_all_figures() const; void zoom_figure(int id, int factor); Figure* is_inside_figure(int x, int y) const; // если внутри нескольких фигур, то возвращается любая из них void move(int id, int new_x, int new_y); private: int find_figure(int id) const; // возвращает позицию фигуры в массиве, или -1 если такой нет. int capacity; int size; Figure **figures; // размер массива задается в конструкторе и больше не растет };
26.64
111
0.693694
3a1f4346ce0a47b154d6c3416fefb8009a673e2a
415
h
C
src/samples/ExplodingObjects/Mesh.h
int-Frank/DgLib-deprecated
2683c48d84b995b00c6fb13f9e02257d3c93e80c
[ "MIT" ]
null
null
null
src/samples/ExplodingObjects/Mesh.h
int-Frank/DgLib-deprecated
2683c48d84b995b00c6fb13f9e02257d3c93e80c
[ "MIT" ]
null
null
null
src/samples/ExplodingObjects/Mesh.h
int-Frank/DgLib-deprecated
2683c48d84b995b00c6fb13f9e02257d3c93e80c
[ "MIT" ]
null
null
null
#ifndef MESH_H #define MESH_H #include <string> #include "Types.h" #include <vector> #include "Types.h" struct Facet { vec4 points[3]; vec4 normals[3]; }; class Mesh { public: bool LoadOBJ(std::string const &); size_t NumberFacets() const { return m_facets.size(); } std::vector<Facet> const & Facets() const { return m_facets; } void Clear(); private: std::vector<Facet> m_facets; }; #endif
12.96875
64
0.66988
6b54089a79a5d4f1864be231949e430a085ee606
1,009
h
C
System/Library/PrivateFrameworks/CommunicationsSetupUI.framework/CKSettingsGenericAboutViewController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/CommunicationsSetupUI.framework/CKSettingsGenericAboutViewController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/CommunicationsSetupUI.framework/CKSettingsGenericAboutViewController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:17:15 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/CommunicationsSetupUI.framework/CommunicationsSetupUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <UIKitCore/UIViewController.h> @class UITextView; @interface CKSettingsGenericAboutViewController : UIViewController { UITextView* _aboutView; } @property (nonatomic,retain) UITextView * aboutView; //@synthesize aboutView=_aboutView - In the implementation block -(void)viewDidLoad; -(void)viewDidLayoutSubviews; -(void)done:(id)arg1 ; -(id)initWithTitle:(id)arg1 bodyText:(id)arg2 ; -(UITextView *)aboutView; -(void)setAboutView:(UITextView *)arg1 ; @end
36.035714
130
0.662042
580beb27e2938c07631ec77a44fb5781bc77b1f2
1,997
h
C
dev/Code/CryEngine/RenderDll/Common/RendElements/OpticsReference.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/CryEngine/RenderDll/Common/RendElements/OpticsReference.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/CryEngine/RenderDll/Common/RendElements/OpticsReference.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_CRYENGINE_RENDERDLL_COMMON_RENDELEMENTS_OPTICSREFERENCE_H #define CRYINCLUDE_CRYENGINE_RENDERDLL_COMMON_RENDELEMENTS_OPTICSREFERENCE_H #pragma once #include "IFlares.h" class COpticsReference : public IOpticsElementBase { public: #if defined(FLARES_SUPPORT_EDITING) DynArray<FuncVariableGroup> GetEditorParamGroups(); #endif COpticsReference(const char* name); ~COpticsReference(){} EFlareType GetType() { return eFT_Reference; } bool IsGroup() const { return false; } string GetName() const { return m_name; } void SetName(const char* ch_name) { m_name = ch_name; } void Load(IXmlNode* pNode); IOpticsElementBase* GetParent() const { return NULL; } bool IsEnabled() const { return true; } void SetEnabled(bool b) {} void AddElement(IOpticsElementBase* pElement); void InsertElement(int nPos, IOpticsElementBase* pElement); void Remove(int i); void RemoveAll(); int GetElementCount() const; IOpticsElementBase* GetElementAt(int i) const; void GetMemoryUsage(ICrySizer* pSizer) const; void Invalidate(); void Render(SLensFlareRenderParam* pParam, const Vec3& vPos); public: string m_name; std::vector<IOpticsElementBasePtr> m_OpticsList; }; #endif // CRYINCLUDE_CRYENGINE_RENDERDLL_COMMON_RENDELEMENTS_OPTICSREFERENCE_H
32.737705
85
0.734602
75262808f7f91de6bfeec368fdc9b5980b2715b1
587
c
C
sensor.c
troglobit/weatherd
0a3c6d883acda08d8787fa7401bdc35eab7e0d29
[ "0BSD" ]
1
2019-12-05T07:12:34.000Z
2019-12-05T07:12:34.000Z
sensor.c
troglobit/weatherd
0a3c6d883acda08d8787fa7401bdc35eab7e0d29
[ "0BSD" ]
null
null
null
sensor.c
troglobit/weatherd
0a3c6d883acda08d8787fa7401bdc35eab7e0d29
[ "0BSD" ]
null
null
null
#include <stdio.h> #include "sensor.h" int main(void) { float ch0, ch1; float temp, pressure, humidity; if (!tsl2561(&ch0, &ch1)) { printf("Full Spectrum(IR + Visible) : %.2f lux \n", ch0); printf("Infrared Value : %.2f lux \n", ch1); printf("Visible Value : %.2f lux \n", (ch0 - ch1)); } if (!bme280(&temp, &pressure, &humidity)) { printf("Temperature in Celsius : %.2f C \n", temp); printf("Temperature in Fahrenheit : %.2f F \n", temp * 1.8 + 32); printf("Pressure : %.2f hPa \n", pressure); printf("Relative Humidity : %.2f RH \n", humidity); } return 0; }
23.48
67
0.606474
0dd580893e8b00875096eb26fa7bb8bb5d6b0c7c
786
h
C
SFML/SuperMarioBros/EnemyGoomba.h
LinMAD/SimpleGames
69cb24a947d1da46729664d2d991b79ceb1146bd
[ "MIT" ]
null
null
null
SFML/SuperMarioBros/EnemyGoomba.h
LinMAD/SimpleGames
69cb24a947d1da46729664d2d991b79ceb1146bd
[ "MIT" ]
null
null
null
SFML/SuperMarioBros/EnemyGoomba.h
LinMAD/SimpleGames
69cb24a947d1da46729664d2d991b79ceb1146bd
[ "MIT" ]
1
2021-11-25T22:33:32.000Z
2021-11-25T22:33:32.000Z
#pragma once #include <SFML/Audio.hpp> #include "AbstractCharacter.h" #include "Level.h" #include "Props.h" namespace characters { class EnemyGoomba : public AbstractCharacter { protected: void UpdateOrderLogic(float deltaTime) override; void HandleAnimation(float deltaTime) override; void HandleCollisionOn(bool isCoordinateX) override; public: EnemyGoomba(Texture &tileSet, float *camOffseX, float *camOffseY) : AbstractCharacter(tileSet, camOffseX, camOffseY) { sprite.setTexture(tileSet); isDead = false; movmentHorizontal = 0.05; currentAnimationFrame = 0; } void Spawn(int x, int y) override; }; }
25.354839
74
0.608142
1dac9e2d756839633db75a64b65a6002dbc88453
5,856
c
C
nitan/maze/binghuodao/npc/shouwei.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/maze/binghuodao/npc/shouwei.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/maze/binghuodao/npc/shouwei.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
#include <ansi.h> inherit NPC; void create() { set_name(HIW "冰" HIR "火" HIC"守護神" NOR, ({ "binghuo shouhushen", "binghuo", "shouhushen" })); set("title", HIB "暗夜流星" NOR); set("long", HIC "傳説他就是冰火島的守護神,在這裏已經守護了千萬年。\n" NOR); set("gender", "男性"); set("age", 9999); set("str", 9999); set("int", 9999); set("con", 9999); set("dex", 9999); set("shen", 8000000); set_temp("apply/attack", 5000000); set_temp("apply/unarmed_damage", 5000000); set_temp("apply/damage", 5000000); set_temp("apply/armor", 200000); set_temp("apply/qy", 80); // 氣運 set_temp("apply/fy", 80); // 福緣 set("scborn/ok", 1); set("max_qi", 2100000000); set("eff_qi", 2100000000); set("qi", 2100000000); set("max_jing", 1000000000); set("jing", 1000000000); set("eff_jing", 1000000000); set("max_jingli", 1000000000); set("jingli", 1000000000); set("neili", 200000000); set("max_neili", 1000000); set("jiali", 20000); set("combat_exp", 2100000000); set_skill("unarmed", 9999); set_skill("finger", 9999); set_skill("claw", 9999); set_skill("strike", 9999); set_skill("hand", 9999); set_skill("cuff", 9999); set_skill("parry", 9999); set_skill("dodge", 9999); set_skill("force", 9999); set_skill("sword", 9999); set_skill("blade", 9999); set_skill("zuoyou-hubo", 9999); set_skill("daojian-guizhen", 9999); set_skill("jiuyang-shengong", 9999); set_skill("yinyang-shiertian", 9999); set_skill("qiankun-danuoyi", 9999); set_skill("martial-cognize", 9999); set_skill("qiankun-danuoyi", 9999); set_skill("lingbo-weibu", 9999); set_skill("literate", 9999); set_skill("huajia-su", 1000); set_skill("jingluo-xue", 9999); set("no_nuoyi", 1); // 不被挪移影響 map_skill("parry", "qiankun-danuoyi"); map_skill("force", "yinyang-shiertian"); map_skill("dodge", "lingbo-weibu"); map_skill("unarmed", "yinyang-shiertian"); map_skill("finger", "yinyang-shiertian"); map_skill("strike", "yinyang-shiertian"); map_skill("hand", "yinyang-shiertian"); map_skill("cuff", "yinyang-shiertian"); map_skill("claw", "yinyang-shiertian"); map_skill("sword", "daojian-guizhen"); map_skill("blade", "daojian-guizhen"); prepare_skill("finger", "yinyang-shiertian"); prepare_skill("unarmed", "yinyang-shiertian"); // yun perform set("chat_chance_combat", 120); set("chat_msg_combat", ({ // (: command("perform sword.ben twice") :), (: command("perform sword.ben and sword.tian") :), // 陰陽12t (: command("perform finger.tian twice") :), (: command("perform finger.zhen and finger.jiu") :), //(: exert_function, "roar" :), (: exert_function, "powerup" :), (: exert_function, "shield" :), (: exert_function, "recover" :), (: exert_function, "dispel" :), })); set("my_life", 1); // 當氣血低於10%的時候補滿一次,設置該參數為0 setup(); // 衣服 carry_object("/clone/cloth/bupao")->wear(); // 武器 carry_object("/clone/weapon/huoyun-dao")->wield(); } void heart_beat() { object ob; keep_heart_beat(); if( !environment(this_object()) ) return; // 解除不能perform yun的限制 if (random(10) == 1) { delete_temp("no_perform"); delete_temp("no_exert"); } return ::heart_beat(); } void init() { object me; me = this_player(); set("env/combatd", 4, me); } int accept_hit(object me) { this_object()->kill_ob(me); return 1; } int accept_fight(object me) { this_object()->kill_ob(me); return 1; } int accept_kill(object me) { this_object()->kill_ob(me); return 1; } void new_life() { object me = this_object(); // 補滿氣血 set("eff_qi",query("max_qi", me), me); set("qi",query("max_qi", me), me); set("eff_jing",query("max_jing", me), me); set("jing",query("max_jing", me), me); set("jingli",query("max_jingli", me), me); me->clear_condition(); me->interrupt_me(this_object()); delete_temp("no_perform", me); delete_temp("no_exert", me); set_temp("apply/attack", 1200000); set_temp("apply/unarmed_damage", 150000); set_temp("apply/damage", 150000); set_temp("apply/armor", 100000); set_temp("apply/qy", 70); // 氣運 set_temp("apply/fy", 70); // 福緣 delete("my_life", me); message_vision(HIG "\n$N" HIG "大喝一聲,目光頓時充滿殺意!\n\n" NOR, me); return; } void unconcious() { object ob; if( objectp(ob = previous_object(0)) && sscanf(base_name(ob), "/kungfu/skill/%*s") ) { full_self(); return; } die(query_last_damage_from()); } void die(object killer) { object ob; if( objectp(ob = previous_object(0)) && sscanf(base_name(ob), "/kungfu/skill/%*s") ) { full_self(); return; } // 如果還未重生,則重生一次 if (query("my_life")) { new_life(); return; } // 不給予獎勵 ::die(killer); return; }
26.026667
100
0.504611
dbb024a8b0e0b3fe544f1450a43e207a7f5789b5
427
h
C
src/resources.h
ShirasawaSama/edge-surf-game
bc1a8de938e5af399e884ae50cb807e03ee5446d
[ "MIT" ]
1
2021-05-24T15:07:20.000Z
2021-05-24T15:07:20.000Z
src/resources.h
ShirasawaSama/edge-surf-game
bc1a8de938e5af399e884ae50cb807e03ee5446d
[ "MIT" ]
null
null
null
src/resources.h
ShirasawaSama/edge-surf-game
bc1a8de938e5af399e884ae50cb807e03ee5446d
[ "MIT" ]
null
null
null
#pragma once #include "nanovg.h" #if defined DEBUG #define ASSETS_ROOT "../assets/" #else #define ASSETS_ROOT "./assets/" #endif #define ASSETS_PATH(TO) ASSETS_ROOT TO #define BGM_PATH ASSETS_PATH("bgm.mp3") extern int backgroundImage, surferImage, playerImage, boardImage, interfaceImage, naughtySurferImage, enemyImage; extern int objectTextures[]; void loadResources(NVGcontext* ctx); void freeResources(NVGcontext* ctx);
26.6875
113
0.789227
6de57447fe2b89457c2ccfdec15d710688172669
2,841
h
C
WSEExternal/include/Common/Base/Thread/Semaphore/hkSemaphoreBusyWait.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
WSEExternal/include/Common/Base/Thread/Semaphore/hkSemaphoreBusyWait.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
WSEExternal/include/Common/Base/Thread/Semaphore/hkSemaphoreBusyWait.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKBASE_HK_SEMAPHORE_BUSY_WAIT__H #define HKBASE_HK_SEMAPHORE_BUSY_WAIT__H #include <Common/Base/Config/hkConfigThread.h> #if ( defined(HK_PLATFORM_PS3_PPU) || defined(HK_PLATFORM_PS3_SPU)) && (HK_CONFIG_THREAD == HK_CONFIG_MULTI_THREADED) /// A wrapper class for a semaphore that can work on both SPU and PPU class hkSemaphoreBusyWait { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_BASE, hkSemaphoreBusyWait); /// Create a semaphore with an initial count and a maximum count. Max count currently ignored. hkSemaphoreBusyWait( int initialCount, int maxCount ); hkSemaphoreBusyWait( hkFinishLoadedObjectFlag f) {} /// Destruct the Semaphore ~hkSemaphoreBusyWait(); /// This call will block until the semaphore is released. void acquire(); /// Release the semaphore. Releases a thread blocked by acquire(). void release(int count = 1); // These static functions work on both spu and ppu. static void HK_CALL acquire(hkSemaphoreBusyWait* semaphoreOnPpu); static void HK_CALL release(hkSemaphoreBusyWait* semaphoreOnPpu, int count = 1); public: static HK_ALIGN( hkUint32 m_cacheLine[128/4], 128 ); protected: hkUint32 m_semphoreValue; // for PPU and SPU HK_CPU_PTR(hkUint32*) m_semaphore; // for SPU, points to shared int above hkUint32 m_ppuEventPort; // for sleeping PPU threads hkUint32 m_eventQueue; }; #else #include <Common/Base/Thread/Semaphore/hkSemaphore.h> // fallback for non Cell platforms, or non threaded Cell builds typedef hkSemaphore hkSemaphoreBusyWait; #endif #endif // HKBASE_HK_SEMAPHORE_BUSY_WAIT__H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20090704) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
35.5125
247
0.747976
ef56cb4668858c706e508ebfad4b422e6f08092d
2,392
h
C
ZoomSDK/ZoomSDK.framework/Versions/A/Headers/ZoomSDKLiveStreamHelper.h
s19urd/zoom-macsdk-electron
5903b63414fde9d39b0703f2d4ed14158d4c0da3
[ "RSA-MD" ]
null
null
null
ZoomSDK/ZoomSDK.framework/Versions/A/Headers/ZoomSDKLiveStreamHelper.h
s19urd/zoom-macsdk-electron
5903b63414fde9d39b0703f2d4ed14158d4c0da3
[ "RSA-MD" ]
null
null
null
ZoomSDK/ZoomSDK.framework/Versions/A/Headers/ZoomSDKLiveStreamHelper.h
s19urd/zoom-macsdk-electron
5903b63414fde9d39b0703f2d4ed14158d4c0da3
[ "RSA-MD" ]
null
null
null
// // ZoomSDKLiveSteamHelper.h // ZoomSDK // // Created by TOTTI on 10/07/2018. // Copyright © 2018 zoom.us. All rights reserved. // #import "ZoomSDKErrors.h" @interface ZoomSDKLiveStreamItem : NSObject { NSString* _streamURL; NSString* _streamURLDesc; } -(NSString*)getLiveStreamURL; -(NSString*)getLiveStreamURLDescription; @end @protocol ZoomSDKLiveStreamHelperDelegate <NSObject> -(void)onLiveStreamStatusChange:(LiveStreamStatus)status; @end @interface ZoomSDKLiveStreamHelper : NSObject { id<ZoomSDKLiveStreamHelperDelegate> _delegate; } @property(nonatomic, assign)id<ZoomSDKLiveStreamHelperDelegate> delegate; /** * @brief This method is used to check if user has priviledge to use live stream. * @return ZoomSDKError enum, ZoomSDKError_Success means function call successful, others will return failed reason. */ - (ZoomSDKError)canStartLiveStream; /** * @brief This method is used to get supported live stream item user can start. * @return A NSArray contains ZoomSDKLiveStreamItem object, or return nil when failed. */ -(NSArray*)getSupportLiveStreamItem; /** * @brief This method is used to start a live stream * @param item, the specific ZoomSDKLiveStreamItem object u can get from the above interface * @return ZoomSDKError enum, ZoomSDKError_Success means function call successful, others will return failed reason. */ -(ZoomSDKError)startLiveStream:(ZoomSDKLiveStreamItem*)item; /** * @brief This method is used to start a live stream use the URL user defined. * @param streamURL, the specific stream url of live stream * @param StreamKey, the specific stream key of live stream * @param broadcastURL, the specific broadcast url of live stream * @return ZoomSDKError enum, ZoomSDKError_Success means function call successful, others will return failed reason. */ -(ZoomSDKError)startLiveStreamByURL:(NSString*)streamURL StreamKey:(NSString*)key BroadcastURL:(NSString*)broadcastURL; /** * @brief This method is used to stop a live stream. * @return ZoomSDKError enum, ZoomSDKError_Success means function call successful, others will return failed reason. */ -(ZoomSDKError)stopLiveStream; /** * @brief This method is used to get current live stream status. * @return LiveStreamStatus enum, LiveStreamStatus_InProgress means successful, others will tell the failed reason. */ -(LiveStreamStatus)getLiveStreamStatus; @end
31.064935
119
0.77592
359c275d121ff34e6c83d1907449cd91eca22f8a
3,274
h
C
frameworks/cocos2d-x/cocos/editor-support/dragonbones/animation/TimelineState.h
TshineZheng/DragonbonesCocos2dx
cf5e251092d23161dd4876353fa26dfe6425ff18
[ "MIT" ]
7
2018-08-20T17:28:29.000Z
2020-09-05T15:19:31.000Z
frameworks/cocos2d-x/cocos/editor-support/dragonbones/animation/TimelineState.h
TshineZheng/DragonbonesCocos2dx
cf5e251092d23161dd4876353fa26dfe6425ff18
[ "MIT" ]
2
2017-02-10T03:48:11.000Z
2017-03-03T10:14:35.000Z
frameworks/cocos2d-x/cocos/editor-support/dragonbones/animation/TimelineState.h
TshineZheng/DragonbonesCocos2dx
cf5e251092d23161dd4876353fa26dfe6425ff18
[ "MIT" ]
5
2017-04-20T07:31:39.000Z
2022-01-16T15:38:14.000Z
#ifndef DRAGONBONES_TIMELINE_STATE_H #define DRAGONBONES_TIMELINE_STATE_H #include "BaseTimelineState.h" DRAGONBONES_NAMESPACE_BEGIN class Bone; class Slot; class AnimationTimelineState final : public TimelineState<AnimationFrameData, AnimationData> { BIND_CLASS_TYPE(AnimationTimelineState); private: bool _isStarted; public: AnimationTimelineState(); ~AnimationTimelineState(); private: DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(AnimationTimelineState); protected: void _onClear() override; void _onCrossFrame(AnimationFrameData* frame); public: void fadeIn(Armature* armature, AnimationState* animationState, AnimationData* timelineData, float time) override; void update(float time) override; void setCurrentTime(float value); }; class BoneTimelineState final : public TweenTimelineState<BoneFrameData, BoneTimelineData> { BIND_CLASS_TYPE(BoneTimelineState); public: Bone* bone; private: TweenType _tweenTransform; TweenType _tweenRotate; TweenType _tweenScale; Transform* _boneTransform; Transform* _originTransform; Transform _transform; Transform _currentTransform; Transform _durationTransform; public: BoneTimelineState(); ~BoneTimelineState(); private: DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(BoneTimelineState); protected: void _onClear() override; void _onArriveAtFrame(bool isUpdate) override; void _onUpdateFrame(bool isUpdate) override; public: void fadeIn(Armature* armature, AnimationState* animationState, BoneTimelineData* timelineData, float time) override; void fadeOut() override; void update(float time) override; }; class SlotTimelineState final : public TweenTimelineState<SlotFrameData, SlotTimelineData> { BIND_CLASS_TYPE(SlotTimelineState); public: Slot* slot; private: bool _colorDirty; TweenType _tweenColor; ColorTransform* _slotColor; ColorTransform _color; ColorTransform _durationColor; public: SlotTimelineState(); ~SlotTimelineState(); private: DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(SlotTimelineState); protected: void _onClear() override; void _onArriveAtFrame(bool isUpdate) override; void _onUpdateFrame(bool isUpdate) override; public: void fadeIn(Armature* armature, AnimationState* animationState, SlotTimelineData* timelineData, float time) override; void fadeOut() override; void update(float time) override; }; class FFDTimelineState final : public TweenTimelineState<ExtensionFrameData, FFDTimelineData> { BIND_CLASS_TYPE(FFDTimelineState); public: Slot* slot; private: TweenType _tweenFFD; std::vector<float>* _slotFFDVertices; ExtensionFrameData* _durationFFDFrame; std::vector<float> _ffdVertices; public: FFDTimelineState(); ~FFDTimelineState(); private: DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(FFDTimelineState); protected: void _onClear() override; void _onArriveAtFrame(bool isUpdate) override; void _onUpdateFrame(bool isUpdate) override; public: void fadeIn(Armature* armature, AnimationState* animationState, FFDTimelineData* timelineData, float time) override; void update(float time) override; }; DRAGONBONES_NAMESPACE_END #endif // DRAGONBONES_TIMELINE_STATE_H
24.616541
121
0.772755
72324e660723beeebbb01a940a23c6d1e4546a22
4,136
h
C
third_party/libkml-1.2.0/src/kml/regionator/regionator.h
mmertama/QtKMLLib
bcc4fa7344d9c9fd4f8d8b9b968e7b6c35ba3c78
[ "MIT" ]
null
null
null
third_party/libkml-1.2.0/src/kml/regionator/regionator.h
mmertama/QtKMLLib
bcc4fa7344d9c9fd4f8d8b9b968e7b6c35ba3c78
[ "MIT" ]
null
null
null
third_party/libkml-1.2.0/src/kml/regionator/regionator.h
mmertama/QtKMLLib
bcc4fa7344d9c9fd4f8d8b9b968e7b6c35ba3c78
[ "MIT" ]
1
2020-06-23T11:22:59.000Z
2020-06-23T11:22:59.000Z
// Copyright 2008, Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This file contains the declaration of the Regionator class. See the // comments in region_handler.h for details on programming and regionator.cc // for details of the operation. #ifndef KML_REGIONATOR_REGIONATOR_H__ #define KML_REGIONATOR_REGIONATOR_H__ #include <map> #include <vector> #include "kml/dom.h" #include "kml/regionator/region_handler.h" #include "kml/regionator/regionator_qid.h" namespace kmlregionator { typedef std::vector<kmldom::RegionPtr> region_vector_t; // The Regionator class is the API to the "regionator" algorithm. class Regionator { public: // A Regionator instance is created with a class derived from // RegionHandler and a root Region. Regionator(RegionHandler& rhandler, const kmldom::RegionPtr& region); ~Regionator(); // This method starts the "regionation". See region_handler.h for // details on how this class calls out to the RegionHandler. // The default output directory (output_directory == NULL) is the // current working directory of the caller. Returns true when regionation // has completed. bool Regionate(const char* output_directory); // This method "regionates" using the given RegionHandler and region. The // region is first aligned to the lowest level region in a quadtree rooted // at n=180, s=-180, e=180, w=-180. All output files are saved to the // given directory if a non-NULL pointer is supplied. Regionation progresses // the same whether nor not an output directory is supplied. static bool RegionateAligned(RegionHandler& rhandler, const kmldom::RegionPtr& region, const char* output_directory); private: kmldom::RegionPtr root_region_; // This calls _Regionate() for the given child of the parent Region. // This saves the child Region to the children vector if the child Region // has data. void Recurse(const kmldom::RegionPtr& parent, quadrant_t quadrant, region_vector_t* children); // This calls the RegionHandler for the given region. If the RegionHandler // returns false from HasData() or NULL from GetFeature() this returns false // signalling that this Region has no data. bool _Regionate(const kmldom::RegionPtr& region); RegionHandler& rhandler_; // This returns the relative filename for the given Region. A parent KML // file NetworkLink will look for a child with this name. string RegionFilename(const kmldom::RegionPtr& region); int region_count_; std::map<string,int> qid_map_; char* output_directory_; }; } // end namespace kmlregionator #endif // KML_REGIONATOR_REGIONATOR_H__
46.47191
80
0.747099
89b58ce5c5ed53756c6923d6be91397a0ca8dae7
5,229
h
C
src/Registration/itktubeImageToTubeRigidRegistration.h
phcerdan/ITKTubeTK
9841c28c8287f04269ceecf3560f7659d77f9643
[ "Apache-2.0" ]
null
null
null
src/Registration/itktubeImageToTubeRigidRegistration.h
phcerdan/ITKTubeTK
9841c28c8287f04269ceecf3560f7659d77f9643
[ "Apache-2.0" ]
null
null
null
src/Registration/itktubeImageToTubeRigidRegistration.h
phcerdan/ITKTubeTK
9841c28c8287f04269ceecf3560f7659d77f9643
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 ( the "License" ); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __itktubeImageToTubeRigidRegistration_h #define __itktubeImageToTubeRigidRegistration_h #include "itktubeImageToTubeRigidMetric.h" #include "itktubeTubeExponentialResolutionWeightFunction.h" #include <itkEuler3DTransform.h> #include <itkImage.h> #include <itkImageRegionIterator.h> #include <itkImageToSpatialObjectRegistrationMethod.h> #include <itkTransform.h> #include <itkTubeSpatialObject.h> #include <itkVectorContainer.h> namespace itk { namespace tube { /** \class ImageToTubeRigidRegistration * \brief Register a hierarchy of tubes to an image. * * This class provides basic registration of a hierarchy of tubes to an image. * * \tparam TFixedImage Type of the image to register against. * \tparam TMovingSpatialObject Type of the moving spatial. This could be a * TubeSpatialObject or perhaps a hierarchy of tubes contained in a * GroupSpatialObject. * \tparam TMovingTube Type of the tubes. Should be some type of * TubeSpatialObject. * * The basic elements of a registration method are: * - Metric to compare the image and the tubes. * - Transformation used to register the image against the tubes. * * \todo Below is out of date and needs to be updated. * * - Optimization method used to search for the best transformation. * * Registration is not limited to Images, and for this reason * this class is templated over the type of the FixedImage object, * the TMovingTube object and the transformation. This types are obtained * from the Metric type, to reduce the number of redundant * template parameters * * \ingroup AffineImageRegistration */ template< class TFixedImage, class TMovingSpatialObject, class TMovingTube > class ImageToTubeRigidRegistration : public ImageToSpatialObjectRegistrationMethod< TFixedImage, TMovingSpatialObject > { public: typedef ImageToTubeRigidRegistration Self; typedef ImageToSpatialObjectRegistrationMethod< TFixedImage, TMovingSpatialObject > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef typename Superclass::FixedImageType FixedImageType; typedef typename Superclass::MovingSpatialObjectType MovingSpatialObjectType; typedef TMovingTube MovingTubeType; /** Method for creation through the object factory. */ itkNewMacro( Self ); /** Run-time type information ( and related methods ). */ itkTypeMacro( ImageToTubeRigidRegistration, ImageToSpatialObjectRegistrationMethod ); typedef typename Superclass::MetricType MetricType; typedef ImageToTubeRigidMetric< FixedImageType, MovingSpatialObjectType, MovingTubeType > DefaultMetricType; typedef typename DefaultMetricType::TransformParametersType ParametersType; typedef typename DefaultMetricType::TransformType TransformType; typedef ParametersType FeatureWeightsType; /** Dimension of the images. */ enum { ImageDimension = FixedImageType::ImageDimension, ParametersDimension = TransformType::ParametersDimension }; typedef typename Superclass::InterpolatorType InterpolatorType; typedef typename Superclass::OptimizerType OptimizerType; /** Method that initiates the registration. */ void StartRegistration( void ); /** Initialize the registration */ void Initialize( void ); /** Set/Get the scalar weights associated with every point in the tube. * The index of the point weights should correspond to "standard tube tree * interation". */ void SetFeatureWeights( FeatureWeightsType & featureWeights ); itkGetConstReferenceMacro( FeatureWeights, FeatureWeightsType ); protected: ImageToTubeRigidRegistration( void ); virtual ~ImageToTubeRigidRegistration( void ) {} private: ImageToTubeRigidRegistration( const Self& ); //purposely not implemented void operator=( const Self& ); //purposely not implemented bool m_IsInitialized; FeatureWeightsType m_FeatureWeights; }; // End class ImageToTubeRigidRegistration } // End namespace tube } // End namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itktubeImageToTubeRigidRegistration.hxx" #endif #endif // End !defined( __itktubeImageToTubeRigidRegistration_h )
34.401316
80
0.722127
7296ed32de840f0a1152dd543f2cdd395ef74f3b
1,001
h
C
AnnService/inc/IVF/utils/DocPriorityQueue.h
RubyOcelot/SPTAG-1
17eaf0d39397074688b03260c1fb1aa2d8b01b63
[ "MIT" ]
null
null
null
AnnService/inc/IVF/utils/DocPriorityQueue.h
RubyOcelot/SPTAG-1
17eaf0d39397074688b03260c1fb1aa2d8b01b63
[ "MIT" ]
null
null
null
AnnService/inc/IVF/utils/DocPriorityQueue.h
RubyOcelot/SPTAG-1
17eaf0d39397074688b03260c1fb1aa2d8b01b63
[ "MIT" ]
null
null
null
#ifndef IVF_DOCPRIORITYQUEUE_H #define IVF_DOCPRIORITYQUEUE_H #include "DocWithScore.h" namespace IVF { class DocPriorityQueue { public: DocPriorityQueue(int maxSize); float getMinScore(); bool isEmpty(); DocWithScore *pop(); DocWithScore *top(); DocWithScore *insertWithOverflow(const DocWithScore &element); // linear time cost bool remove(const DocWithScore &element); void clear(); int getSize(); int getMaxSize(); ~DocPriorityQueue(); void debug_print(); private: int maxSize; DocWithScore *heap; int size = 0; bool upHeap(int origPos); bool downHeap(int origPos); DocWithScore updateTop(); bool lessThan(const DocWithScore &a, const DocWithScore &b); // add element to bottom of heap when heap is no full DocWithScore add(const DocWithScore &element); }; } #endif //IVF_DOCPRIORITYQUEUE_H
18.2
70
0.62038
e666e17769247c472770b09539abf5f19439b229
1,135
c
C
src/file_utils.c
h3nnn4n/cubotron
b74b35844b250a164a32c3c4a28c7e778d326f6f
[ "MIT" ]
null
null
null
src/file_utils.c
h3nnn4n/cubotron
b74b35844b250a164a32c3c4a28c7e778d326f6f
[ "MIT" ]
1
2021-03-09T12:25:05.000Z
2021-03-09T19:50:50.000Z
src/file_utils.c
h3nnn4n/cubotron
b74b35844b250a164a32c3c4a28c7e778d326f6f
[ "MIT" ]
null
null
null
#include <assert.h> #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include "file_utils.h" void ensure_directory_exists(char *directory) { if (file_exists(directory)) { return; } mkdir_p(directory); } int file_exists(char *filepath) { struct stat buffer = {0}; return (stat(filepath, &buffer) == 0); } // https://gist.github.com/JonathonReinhart/8c0d90191c38af2dcadb102c4e202950 int mkdir_p(const char *path) { assert(path != NULL); const size_t len = strlen(path); char _path[PATH_MAX]; char * p; errno = 0; if (len > sizeof(_path) - 1) { errno = ENAMETOOLONG; return -1; } strcpy(_path, path); for (p = _path + 1; *p; p++) { if (*p == '/') { *p = '\0'; if (mkdir(_path, S_IRWXU) != 0) { if (errno != EEXIST) return -1; } *p = '/'; } } if (mkdir(_path, S_IRWXU) != 0) { if (errno != EEXIST) return -1; } return 0; }
18.306452
76
0.513656
8e4e3d6e8c6875231d707809dc0c5ae5bb8670a9
904
h
C
mysql_protocol/packet/ErrorPacket.h
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
1
2020-10-23T09:38:22.000Z
2020-10-23T09:38:22.000Z
mysql_protocol/packet/ErrorPacket.h
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
null
null
null
mysql_protocol/packet/ErrorPacket.h
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
null
null
null
// // Created by zhukovasky on 2020/10/2. // #ifndef XSQL_ERRORPACKET_H #define XSQL_ERRORPACKET_H #include <utils/StringUtils.h> #include "BinaryPacket.h" namespace MyProtocol{ class ErrorPacket: public MyProtocol::BinaryPacket { public: const byte FIELD_COUNT = (byte) 0xff; const byte SQLSTATE_MARKER = (byte) '#'; std::vector<byte > message; std::vector<byte> DEFAULT_SQLSTATE =Utils::StringUtils::convertStringToBytes("HY000"); byte fieldCount = FIELD_COUNT; int errNo; byte mark = SQLSTATE_MARKER; std::vector<byte> sqlState = DEFAULT_SQLSTATE; byte header=(byte) (0xff)&0xff; int calPacketSize() override; std::string getPacketInfo() override; void write(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer &buffer) override; }; }; #endif //XSQL_ERRORPACKET_H
19.652174
98
0.660398
b07d71b29128c8c7049394e6ede294efeef8f240
272
h
C
YGQPhotoAlbumHelpTool/Classes/PhotoAlbumTool.h
ygqym101620/YGQPhotoAlbumHelpTool
93fc355f1bbd2b80b77a648b6ec16b3883f80b2c
[ "MIT" ]
null
null
null
YGQPhotoAlbumHelpTool/Classes/PhotoAlbumTool.h
ygqym101620/YGQPhotoAlbumHelpTool
93fc355f1bbd2b80b77a648b6ec16b3883f80b2c
[ "MIT" ]
null
null
null
YGQPhotoAlbumHelpTool/Classes/PhotoAlbumTool.h
ygqym101620/YGQPhotoAlbumHelpTool
93fc355f1bbd2b80b77a648b6ec16b3883f80b2c
[ "MIT" ]
null
null
null
// // HelpTool.h // Pods // // Created by 杨国强 on 16/12/8. // // #import <Foundation/Foundation.h> @interface PhotoAlbumTool : NSObject + (UIImage *)themeImageWithImageName:(NSString *)imageName; + (UIImage *)themeImageWithImageNameTypeJPG:(NSString *)imageName; @end
18.133333
66
0.713235
e6da0c86b5e9fd39825faa303841973b703c56e0
5,246
h
C
include/linkedList.h
fireplume/cmap
50c7a6517980140ca05e5a50f256ce110c904ff0
[ "MIT" ]
null
null
null
include/linkedList.h
fireplume/cmap
50c7a6517980140ca05e5a50f256ce110c904ff0
[ "MIT" ]
null
null
null
include/linkedList.h
fireplume/cmap
50c7a6517980140ca05e5a50f256ce110c904ff0
[ "MIT" ]
null
null
null
/********************************************************************************* MIT License Copyright (c) 2019 Mathieu Comeau 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 UTILS_LINKEDLIST_H_ #define UTILS_LINKEDLIST_H_ #include <signal.h> // One way to improve speed is for client to pre-allocate blocks of nodes. // That way, it insures that, within a block of nodes, it is less // likely to have page/cache miss. typedef struct LLNode LLNode; typedef struct LLNode { LLNode* __next; LLNode* __previous; } LLNode; typedef struct LinkedList LinkedList; typedef struct LinkedList { // First element of LinkedList at same address of LinkedList LLNode* head; LLNode* tail; LLNode* last_insert; LLNode* __buffer; LLNode* __it; LLNode* __it_buf; int __nb_items; int (*__compare)(const void*, const void*); } LinkedList; // The __compare function provided to getLinkedList should properly // cast the (void*) parameters to the proper comparison type. void ll_init(LinkedList* l, int (*cmp)(const void*, const void*)) { l->head = NULL; l->tail = NULL; l->__it = NULL; l->__compare = cmp; l->last_insert = NULL; l->__nb_items = 0; } void ll_insert(LinkedList* list, LLNode* node) __attribute__((always_inline)); inline void ll_insert(LinkedList* list, LLNode* node) { list->last_insert = node; ++(list->__nb_items); if(list->head == NULL) { list->head = node; list->tail = node; node->__next = NULL; node->__previous = NULL; return; } // If "__compare" is not set, or node is greater than // the last one, simply append if((list->__compare == NULL) || (list->__compare(node, list->tail) > 0)) { list->__buffer = list->tail; // 'node' is our new tail list->tail = node; list->tail->__next = NULL; list->tail->__previous = list->__buffer; // Set old tail to point to new tail list->__buffer->__next = node; return; } // Is it smaller than HEAD? if( list->__compare(node, list->head) < 0 ) { list->__buffer = list->head; // 'node' is our new HEAD list->head = node; list->head->__next = list->__buffer; list->head->__previous = NULL; // Set old head to point to new head list->__buffer->__previous = node; return; } // Sort it into the list list->__buffer = list->head->__next; while(list->__buffer != 0) { if(list->__compare(node, list->__buffer) < 0 ) { // node fits just before list->__buffer node->__previous = list->__buffer->__previous; node->__next = list->__buffer; list->__buffer->__previous->__next = node; list->__buffer->__previous = node; return; } list->__buffer = list->__buffer->__next; } // Shouldn't be here raise(SIGABRT); } void ll_del(LinkedList* list, LLNode* node) __attribute__((always_inline)); inline void ll_del(LinkedList* list, LLNode* node) { // Ok if in the midst of iteration, as long as // client doesn't delete passed current // iteration if(node == list->head) { list->head = node->__next; } if(node == list->tail) { list->tail = node->__previous; } if(node == list->last_insert) { list->last_insert = NULL; } if(node->__previous != NULL) { node->__previous->__next = node->__next; } if(node->__next != NULL) { node->__next->__previous = node->__previous; } --list->__nb_items; if(list->__nb_items < 0) { raise(SIGABRT); } } void ll_reset_iterator(LinkedList* list) { list->__it = list->head; } LLNode* ll_iter(LinkedList* list) __attribute__((always_inline)); inline LLNode* ll_iter(LinkedList* list) { if(list->__it == NULL) { list->__it = list->head; return NULL; } list->__it_buf = list->__it; list->__it = list->__it->__next; return list->__it_buf; } int ll_nb_items(LinkedList* list) { return list->__nb_items; } #endif /* UTILS_LINKEDLIST_H_ */
28.053476
82
0.626954
fc8503e96b01060cdbc3b397f5fcd44edb14e219
238
h
C
HJC/Controller/MyCenterViewController/CustomServiceController/CustomServiceViewController.h
fanglingyong/YCLProject
9f7c93bf4376cdb0b326f093f14e4293bea71e53
[ "Apache-2.0" ]
null
null
null
HJC/Controller/MyCenterViewController/CustomServiceController/CustomServiceViewController.h
fanglingyong/YCLProject
9f7c93bf4376cdb0b326f093f14e4293bea71e53
[ "Apache-2.0" ]
null
null
null
HJC/Controller/MyCenterViewController/CustomServiceController/CustomServiceViewController.h
fanglingyong/YCLProject
9f7c93bf4376cdb0b326f093f14e4293bea71e53
[ "Apache-2.0" ]
null
null
null
// // CustomServiceViewController.h // HJC // // Created by 方灵勇 on 2017/12/16. // Copyright © 2017年 EastChina. All rights reserved. // #import "BaseViewController.h" @interface CustomServiceViewController : BaseViewController @end
17
59
0.735294
520a7dfcdd50ab77bda37d5ced925d90c22c3a8b
7,064
h
C
src/eplssrc/SN/SODerr.h
rknall/openSAFETY
630495210c5aab1b39884b7b5c8feef62e95f245
[ "BSD-3-Clause" ]
2
2015-03-15T23:34:03.000Z
2021-04-14T19:25:51.000Z
src/eplssrc/SN/SODerr.h
rknall/openSAFETY
630495210c5aab1b39884b7b5c8feef62e95f245
[ "BSD-3-Clause" ]
null
null
null
src/eplssrc/SN/SODerr.h
rknall/openSAFETY
630495210c5aab1b39884b7b5c8feef62e95f245
[ "BSD-3-Clause" ]
4
2015-01-30T21:53:35.000Z
2020-09-25T06:23:56.000Z
/** * @addtogroup SOD * @{ * * @file SODerr.h * * This file contains the error codes for the SOD module. * * @copyright Copyright (c) 2009, Bernecker + Rainer Industrie-Elektronik Ges.m.b.H and IXXAT Automation GmbH * @copyright All rights reserved, Bernecker + Rainer Industrie-Elektronik Ges.m.b.H * * @copyright This source code is free software; you can redistribute it and/or modify it under the terms of the BSD license (according to License.txt). * * @author K. Fahrion, IXXAT Automation GmbH * @author M. Molnar, IXXAT Automation GmbH * */ #ifndef SODERR_H #define SODERR_H /** * @name SOD macros * @brief Macros to build error code * @{ */ #define SOD_ERR_FATAL(num) SERR_BUILD_ERROR(SERR_TYPE_FS, SERR_CLASS_FATAL,\ SOD_k_UNIT_ID, (num)) #define SOD_ERR_MINOR(num) SERR_BUILD_ERROR(SERR_TYPE_NOT_FS, SERR_CLASS_MINOR,\ SOD_k_UNIT_ID, (num)) #define SOD_ERR__INFO(num) SERR_BUILD_ERROR(SERR_TYPE_NOT_FS, SERR_CLASS_INFO,\ SOD_k_UNIT_ID, (num)) /** @} */ /** * @name SOD error codes * @brief Error codes for the SOD module. * @{ */ /** SODmain.c **/ /** SOD_Read */ /* Generated abort code for the SSDOS and SPDO */ #define SOD_k_ERR_INST_NUM_3 SOD_ERR_FATAL(1) /* (0800 0000h) */ #define SOD_k_ERR_TYPE_OFFSET_1 SOD_ERR_FATAL(2) /* (0800 0000h) */ #define SOD_k_ERR_OFFSET_SIZE_1 SOD_ERR_FATAL(3) /* (0607 0012h) */ #define SOD_k_ERR_SAPL_READ SOD_ERR_FATAL(4) /* Abort code provided by the application */ /** SOD_Write */ #define SOD_k_ERR_INST_NUM_4 SOD_ERR_FATAL(5) /* (0800 0000h) */ #define SOD_k_ERR_DATA_POINTER_INVALID SOD_ERR_FATAL(6) /* (0800 0000h) */ #define SOD_k_ERR_SOD_WRITE_DISABLED SOD_ERR_MINOR(7) /* (0800 0022h) */ #define SOD_k_ERR_TYPE_OFFSET_2 SOD_ERR_FATAL(8) /* (0800 0000h) */ #define SOD_k_ERR_OFFSET_SIZE_2 SOD_ERR_FATAL(9) /* (0607 0012h) */ #define SOD_k_ERR_SAPL_WRITE SOD_ERR_MINOR(10) /* Abort code provided by the application */ /** ObjectWriteable */ #define SOD_k_ERR_OBJ_NOT_WRITEABLE SOD_ERR_MINOR(11) /* (0601 0002h) */ /** VisibleStringCheck */ #define SOD_k_ERR_VISIBLE_STR_INVALID SOD_ERR_MINOR(12) /* (0609 0030h) */ /** DataValid */ #define SOD_k_ERR_VALUE_IS_TOO_HIGH_1 SOD_ERR_MINOR(13) /* (0609 0031h) */ #define SOD_k_ERR_VALUE_IS_TOO_LOW SOD_ERR_MINOR(14) /* (0609 0032h) */ #define SOD_k_ERR_VALUE_IS_TOO_HIGH_2 SOD_ERR_MINOR(15) /* (0609 0031h) */ #define SOD_k_ERR_TYPE_UNKNOWN SOD_ERR_MINOR(16) /* (0800 0021h) */ /** CallBeforeReadClbk */ #define SOD_k_ERR_CLBK_ABORT_BR SOD_ERR_MINOR(17) /** CallBeforeWriteClbk */ #define SOD_k_ERR_CLBK_ABORT_BW SOD_ERR_MINOR(18) /** CallAfterWriteClbk */ #define SOD_k_ERR_CLBK_ABORT_AW SOD_ERR_MINOR(19) /** SODactLen.c **/ /** SOD_ActualLenSet */ #define SOD_k_ERR_INST_NUM_9 SOD_ERR_FATAL(20) /* (0800 0000h) */ #define SOD_k_ERR_ACT_LEN_SET_APL SOD_ERR_FATAL(21) /* (0800 0000h) */ #define SOD_k_ERR_ACT_LEN SOD_ERR_FATAL(22) /* (0800 0000h) */ #define SOD_k_ERR_ACT_LEN_TYPE SOD_ERR_FATAL(23) /* (0800 0000h) */ /** SOD_ActualLenGet */ #define SOD_k_ERR_INST_NUM_10 SOD_ERR_FATAL(24) /* (0800 0000h) */ #define SOD_k_ERR_ACT_LEN_PTR SOD_ERR_FATAL(25) /* (0800 0000h) */ #define SOD_k_ERR_ACT_LEN_GET_APL SOD_ERR_FATAL(26) /* (0800 0000h) */ /** SODattr.c **/ /** SOD_InitAddr */ #define SOD_k_ERR_OD_REFERENCE SOD_ERR_FATAL(27) #define SOD_k_ERR_OD_IS_EMPTY SOD_ERR_FATAL(28) /** SOD_AttrGet */ #define SOD_k_ERR_INST_NUM_1 SOD_ERR_FATAL(29) /* (0800 0000h) */ #define SOD_k_ERR_OBJ_HDL_1 SOD_ERR_FATAL(30) /* (0800 0000h) */ #define SOD_k_ERR_APP_OBJ_1 SOD_ERR_FATAL(31) /* (0800 0000h) */ #define SOD_k_ERR_SAPL_ATTR_GET SOD_ERR_FATAL(32) #define SOD_k_ERR_ATTR_GET SOD_ERR_FATAL(33) /** SOD_AttrGetNext */ #define SOD_k_ERR_INST_NUM_2 SOD_ERR_FATAL(34) /* (0800 0000h) */ #define SOD_k_ERR_OBJ_HDL_2 SOD_ERR_FATAL(35) /* (0800 0000h) */ /** SOD_HdlValid */ #define SOD_k_ERR_OBJ_HDL_INVALID SOD_ERR_FATAL(36) /* (0800 0021h) */ /** SODlock.c **/ /** SOD_Lock */ #define SOD_k_ERR_INST_NUM_5 SOD_ERR_FATAL(37) /* (0800 0000h) */ #define SOD_k_ERR_LOCKING_FAILED SOD_ERR__INFO(38) /* (0800 0022h) */ #define SOD_k_ERR_SAPL_LOCKING_FAILED SOD_ERR__INFO(39) /* (0800 0022h) */ /** SOD_Unlock */ #define SOD_k_ERR_INST_NUM_6 SOD_ERR_FATAL(40) /* (0800 0000h) */ #define SOD_k_ERR_UNLOCK_WITHOUT_LOCK SOD_ERR_FATAL(41) /* (0800 0022h) */ #define SOD_k_ERR_SAPL_UNLOCK_FAILED SOD_ERR_FATAL(42) /* (0800 0022h) */ /** SOD_EnableSodWrite */ #define SOD_k_ERR_INST_NUM_7 SOD_ERR_FATAL(43) /* (0800 0000h) */ #define SOD_k_ERR_ENABLE_WR_FAILED SOD_ERR_FATAL(44) /** SOD_DisableSodWrite */ #define SOD_k_ERR_INST_NUM_8 SOD_ERR_FATAL(45) /* (0800 0000h) */ #define SOD_k_ERR_DISABLE_WR_FAILED SOD_ERR__INFO(46) /** SODcheck.c **/ /** SOD_Init */ #define SOD_k_ERR_SAPL_INIT SOD_ERR_FATAL(47) /** SOD_Check */ #define SOD_k_ERR_NO_RANGE_CHECKING SOD_ERR_FATAL(48) #define SOD_k_ERR_NO_OBJECT_DATA SOD_ERR_FATAL(49) #define SOD_k_ERR_NO_P2P_OBJECT_DATA SOD_ERR_FATAL(50) #define SOD_k_ERR_SOD_NOT_SORTED_1 SOD_ERR_FATAL(51) #define SOD_k_ERR_SOD_NOT_SORTED_2 SOD_ERR_FATAL(52) /** AttrCheck */ #define SOD_k_ERR_ATTR_IS_WRONG_1 SOD_ERR_FATAL(53) #define SOD_k_ERR_ATTR_IS_WRONG_2 SOD_ERR_FATAL(54) #define SOD_k_ERR_ATTR_IS_WRONG_3 SOD_ERR_FATAL(55) #define SOD_k_ERR_NO_DEFAULT_VALUE SOD_ERR_FATAL(56) #define SOD_k_ERR_OBJ_CLBK_1 SOD_ERR_FATAL(57) #define SOD_k_ERR_OBJ_CLBK_2 SOD_ERR_FATAL(58) /** DataTypeCheck */ #define SOD_k_ERR_MAX_MIN_VALUE_ERROR SOD_ERR_FATAL(59) #define SOD_k_ERR_TYPE_LEN_1 SOD_ERR_FATAL(60) #define SOD_k_ERR_TYPE_LEN_2 SOD_ERR_FATAL(61) #define SOD_k_ERR_TYPE_LEN_3 SOD_ERR_FATAL(62) #define SOD_k_ERR_TYPE_LEN_4 SOD_ERR_FATAL(63) #define SOD_k_ERR_TYPE_LEN_5 SOD_ERR_FATAL(64) #define SOD_k_ERR_TYPE_NOT_SUPPORTED SOD_ERR_FATAL(65) /** @} */ /** * @brief This function returns a description of every available errors of the assigned unit. * * @param w_errorCode error number * @param dw_addInfo additional error information * @retval pac_str empty buffer to build the error string */ #if (EPLS_cfg_ERROR_STRING == EPLS_k_ENABLE) void SOD_GetErrorStr(UINT16 w_errorCode, UINT32 dw_addInfo, CHAR *pac_str); #endif #endif /** @} */
43.337423
152
0.662797
f73c1bed15c10aab070a2cd7183cf781b8e3dd6a
262
h
C
Client_Portals/CLS-ProtoBlue-iOS-Client-Portal-master/ProtoBlue/Supporting Files/ProtoBlue-Definitions.h
lancewalk87/ProtoBlue
300abb8e09dd3d208033abe8c99a79513935eafe
[ "MIT" ]
2
2018-11-01T21:07:27.000Z
2018-12-23T03:19:07.000Z
Client_Portals/CLS-ProtoBlue-iOS-Client-Portal-master/ProtoBlue/Supporting Files/ProtoBlue-Definitions.h
lancewalk87/ProtoBlue
300abb8e09dd3d208033abe8c99a79513935eafe
[ "MIT" ]
null
null
null
Client_Portals/CLS-ProtoBlue-iOS-Client-Portal-master/ProtoBlue/Supporting Files/ProtoBlue-Definitions.h
lancewalk87/ProtoBlue
300abb8e09dd3d208033abe8c99a79513935eafe
[ "MIT" ]
null
null
null
// // ProtoBlue-Definitions.h // ProtoBlue // // Created by Lance T. Walker on 10/19/18. // Copyright © 2018 CodeLife-Productions. All rights reserved. // #ifndef ProtoBlue_Definitions_h #define ProtoBlue_Definitions_h #endif /* ProtoBlue_Definitions_h */
20.153846
63
0.740458
598a490e451275df3eeb5c1752f33d557e609998
1,395
c
C
src/shaders/link_shader_prog.c
mdovhopo/Scop_42
8d0c82d2ca4249b28f8bfe900d142c8b7c8ff353
[ "MIT" ]
null
null
null
src/shaders/link_shader_prog.c
mdovhopo/Scop_42
8d0c82d2ca4249b28f8bfe900d142c8b7c8ff353
[ "MIT" ]
null
null
null
src/shaders/link_shader_prog.c
mdovhopo/Scop_42
8d0c82d2ca4249b28f8bfe900d142c8b7c8ff353
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* link_shader_prog.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mdovhopo <mdovhopo@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/02 14:21:38 by mdovhopo #+# #+# */ /* Updated: 2019/09/02 14:22:55 by mdovhopo ### ########.fr */ /* */ /* ************************************************************************** */ #include "scop.h" bool link_shader_prog(uint32_t *prog_id, uint32_t *shaders, uint32_t length) { int success; int index; char info_log[512]; index = length; *prog_id = glCreateProgram(); while (--index > -1) glAttachShader(*prog_id, shaders[index]); glLinkProgram(*prog_id); glGetProgramiv(*prog_id, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(*prog_id, 512, NULL, info_log); ft_printf("PROGRAM LINK ERR: |%s|\n", info_log); return (false); } return (true); }
39.857143
80
0.331183
dd0894f0ab82c6c1ccf794e6b772f629cb6d3bcc
6,674
h
C
contrib/gnu/gdb/dist/gas/config/tc-pru.h
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
3
2021-05-04T17:09:06.000Z
2021-10-04T07:19:26.000Z
contrib/gnu/gdb/dist/gas/config/tc-pru.h
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
null
null
null
contrib/gnu/gdb/dist/gas/config/tc-pru.h
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
null
null
null
/* Definitions for TI PRU assembler. Copyright (C) 2014-2020 Free Software Foundation, Inc. Contributed by Dimitar Dimitrov <dimitar@dinux.eu> This file is part of GAS, the GNU Assembler. GAS 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 3, or (at your option) any later version. GAS 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 GAS; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __TC_PRU__ #define __TC_PRU__ #define TARGET_BYTES_BIG_ENDIAN 0 /* Words are big enough to hold addresses. */ #define WORKING_DOT_WORD 1 extern const char *pru_target_format (void); #define TARGET_FORMAT pru_target_format () #define TARGET_ARCH bfd_arch_pru /* A PRU instruction consists of tokens and separator characters the tokens are things like the instruction name (add, or jmp etc), the register indices ($5, $7 etc), and constant expressions. The separator characters are commas, brackets and space. The instruction name is always separated from other tokens by a space The maximum number of tokens in an instruction is 6 (the instruction name, 4 arguments, and a 4th string representing the expected instruction opcode after assembly. The latter is only used when the assemble is running in self test mode, otherwise its presence will generate an error. */ #define PRU_MAX_INSN_TOKENS 7 /* There are no machine-specific operands so we #define this to nothing. */ #define md_operand(x) /* Function prototypes exported to rest of GAS. */ extern void md_assemble (char *op_str); extern void md_end (void); extern void md_begin (void); #define tc_fix_adjustable(fixp) pru_fix_adjustable (fixp) extern int pru_fix_adjustable (struct fix *); #define tc_frob_label(lab) pru_frob_label (lab) extern void pru_frob_label (symbolS *); extern void md_convert_frag (bfd * headers, segT sec, fragS * fragP); #define DIFF_EXPR_OK /* FIXME This seems appropriate, given that we intentionally prevent PRU's .text from being used in a DIFF expression with symbols from other sections. Revisit once GDB is ported. */ #define CFI_DIFF_EXPR_OK 0 #define TC_PARSE_CONS_RETURN_TYPE int #define TC_PARSE_CONS_RETURN_NONE 0 #define TC_PARSE_CONS_EXPRESSION(EXP, NBYTES) \ pru_parse_cons_expression (EXP, NBYTES) extern int pru_parse_cons_expression (expressionS *exp, int size); #define TC_CONS_FIX_NEW pru_cons_fix_new extern void pru_cons_fix_new (struct frag *frag, int where, unsigned int nbytes, struct expressionS *exp, const int is_pmem); /* If you define this macro, it means that `tc_gen_reloc' may return multiple relocation entries for a single fixup. In this case, the return value of `tc_gen_reloc' is a pointer to a null terminated array. */ #undef RELOC_EXPANSION_POSSIBLE /* No shared lib support, so we don't need to ensure externally visible symbols can be overridden. */ #define EXTERN_FORCE_RELOC 0 /* If defined, this macro allows control over whether fixups for a given section will be processed when the linkrelax variable is set. Define it to zero and handle things in md_apply_fix instead. */ #define TC_LINKRELAX_FIXUP(SEG) 0 /* If this macro returns non-zero, it guarantees that a relocation will be emitted even when the value can be resolved locally. Do that if linkrelax is turned on. */ #define TC_FORCE_RELOCATION(fix) pru_force_relocation (fix) #define TC_FORCE_RELOCATION_SUB_SAME(fix, seg) \ (GENERIC_FORCE_RELOCATION_SUB_SAME (fix, seg) || pru_force_relocation (fix)) extern int pru_force_relocation (struct fix *); /* Do not use PC relative fixups and relocations for anything but real PCREL relocations. */ #define TC_FORCE_RELOCATION_SUB_LOCAL(FIX, SEG) \ (((FIX)->fx_r_type != BFD_RELOC_PRU_S10_PCREL) \ && ((FIX)->fx_r_type != BFD_RELOC_PRU_U8_PCREL)) /* Values passed to md_apply_fix don't include the symbol value. */ #define MD_APPLY_SYM_VALUE(FIX) 0 /* We don't want gas to fixup the following memory related relocations. We will need them in case that we want to do linker relaxation. We could in principle keep these fixups in gas when not relaxing. However, there is no serious performance penalty when making the linker make the fixup work. Check also that fx_addsy is not NULL, in order to make sure that the fixup refers to some sort of label. */ #define TC_VALIDATE_FIX(FIXP,SEG,SKIP) \ if ((FIXP->fx_r_type == BFD_RELOC_PRU_LDI32 \ || FIXP->fx_r_type == BFD_RELOC_PRU_U16 \ || FIXP->fx_r_type == BFD_RELOC_PRU_U16_PMEMIMM \ || FIXP->fx_r_type == BFD_RELOC_PRU_S10_PCREL \ || FIXP->fx_r_type == BFD_RELOC_PRU_U8_PCREL \ || FIXP->fx_r_type == BFD_RELOC_PRU_32_PMEM \ || FIXP->fx_r_type == BFD_RELOC_PRU_16_PMEM) \ && FIXP->fx_addsy != NULL \ && FIXP->fx_subsy == NULL) \ { \ symbol_mark_used_in_reloc (FIXP->fx_addsy); \ goto SKIP; \ } /* This macro is evaluated for any fixup with a fx_subsy that fixup_segment cannot reduce to a number. If the macro returns false an error will be reported. */ #define TC_VALIDATE_FIX_SUB(fix, seg) pru_validate_fix_sub (fix) extern int pru_validate_fix_sub (struct fix *); /* We want .cfi_* pseudo-ops for generating unwind info. */ #define TARGET_USE_CFIPOP 1 /* Program Counter register number is not defined by TI documents. Pick the virtual number used by GCC. */ #define DWARF2_DEFAULT_RETURN_COLUMN 132 /* The stack grows down, and is only byte aligned. */ #define DWARF2_CIE_DATA_ALIGNMENT -1 #define tc_regname_to_dw2regnum pru_regname_to_dw2regnum extern int pru_regname_to_dw2regnum (char *regname); #define tc_cfi_frame_initial_instructions pru_frame_initial_instructions extern void pru_frame_initial_instructions (void); /* The difference between same-section symbols may be affected by linker relaxation, so do not resolve such expressions in the assembler. */ #define md_allow_local_subtract(l,r,s) pru_allow_local_subtract (l, r, s) extern bfd_boolean pru_allow_local_subtract (expressionS *, expressionS *, segT); #endif /* __TC_PRU__ */
41.453416
78
0.743782
dd63b8e7a88972a8c24602878ce6eb2b066f7203
834
h
C
VKHDHeaders/iPadVideoViewSimpleCell.h
Anonym0uz/VKPreferences
872932a34c7b0057369c2c7aa9861222b121c3db
[ "MIT" ]
4
2018-11-02T01:08:31.000Z
2019-03-19T20:27:09.000Z
VKHDHeaders/iPadVideoViewSimpleCell.h
Anonym0uz/VKPreferences
872932a34c7b0057369c2c7aa9861222b121c3db
[ "MIT" ]
null
null
null
VKHDHeaders/iPadVideoViewSimpleCell.h
Anonym0uz/VKPreferences
872932a34c7b0057369c2c7aa9861222b121c3db
[ "MIT" ]
1
2018-11-02T01:08:36.000Z
2018-11-02T01:08: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 "iPadStandardCell.h" @class BackupImageView, UIImageView, UILabel; @interface iPadVideoViewSimpleCell : iPadStandardCell { UIImageView *_checkMark; BackupImageView *_imageForVideo; UILabel *_labelForVideo; } @property(retain, nonatomic) UILabel *labelForVideo; // @synthesize labelForVideo=_labelForVideo; @property(retain, nonatomic) BackupImageView *imageForVideo; // @synthesize imageForVideo=_imageForVideo; @property(retain, nonatomic) UIImageView *checkMark; // @synthesize checkMark=_checkMark; - (void).cxx_destruct; - (void)setAlbum:(id)arg1; - (void)setVideo:(id)arg1; - (void)layoutSubviews; - (id)initWithStyle:(long long)arg1 reuseIdentifier:(id)arg2; @end
28.758621
105
0.7506
2073266ea5e668542bf98cf7c1b9de374740beb4
1,434
h
C
ReactNativeFrontend/ios/Pods/Flipper-RSocket/rsocket/framing/FramedDuplexConnection.h
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
217
2017-04-29T14:44:39.000Z
2022-03-29T04:06:17.000Z
ReactNativeFrontend/ios/Pods/Flipper-RSocket/rsocket/framing/FramedDuplexConnection.h
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
270
2017-04-28T04:12:23.000Z
2022-03-11T20:39:33.000Z
ReactNativeFrontend/ios/Pods/Flipper-RSocket/rsocket/framing/FramedDuplexConnection.h
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
83
2017-04-28T02:06:16.000Z
2022-03-11T20:35:16.000Z
// Copyright (c) Facebook, Inc. and its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "rsocket/DuplexConnection.h" #include "rsocket/internal/Common.h" namespace rsocket { class FramedReader; struct ProtocolVersion; class FramedDuplexConnection : public virtual DuplexConnection { public: FramedDuplexConnection( std::unique_ptr<DuplexConnection> connection, ProtocolVersion protocolVersion); ~FramedDuplexConnection(); void send(std::unique_ptr<folly::IOBuf>) override; void setInput(std::shared_ptr<DuplexConnection::Subscriber>) override; bool isFramed() const override { return true; } DuplexConnection* getConnection() { return inner_.get(); } private: const std::unique_ptr<DuplexConnection> inner_; std::shared_ptr<FramedReader> inputReader_; const std::shared_ptr<ProtocolVersion> protocolVersion_; }; } // namespace rsocket
28.117647
75
0.751743
e3db4d044cd193de474b59f75a1b89cabf002d6d
827
c
C
B2G/gecko/memory/build/jemalloc_config.c
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/memory/build/jemalloc_config.c
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/memory/build/jemalloc_config.c
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MOZ_JEMALLOC3 #define MOZ_JEMALLOC_IMPL #include "mozmemory_wrap.h" #include "mozilla/Types.h" /* Override some jemalloc defaults */ MFBT_DATA const char * je_(malloc_conf) = "narenas:1,lg_chunk:20"; #ifdef ANDROID #include <android/log.h> static void _je_malloc_message(void *cbopaque, const char *s) { __android_log_print(ANDROID_LOG_INFO, "GeckoJemalloc", "%s", s); } void (*je_(malloc_message))(void *, const char *s) = _je_malloc_message; #endif #endif /* MOZ_JEMALLOC3 */ /* Provide an abort function for use in jemalloc code */ #include <mozilla/Assertions.h> void moz_abort() { MOZ_CRASH(); }
23.628571
76
0.726723
0c6734e15311c8ffd13f9ce5e7e85dd6e09d9c94
821
c
C
src/lib/entry_iterator.c
scatmanFATMAN/libkeystore
0053e94970512135d8ac12210c6510888a9fabee
[ "MIT" ]
null
null
null
src/lib/entry_iterator.c
scatmanFATMAN/libkeystore
0053e94970512135d8ac12210c6510888a9fabee
[ "MIT" ]
null
null
null
src/lib/entry_iterator.c
scatmanFATMAN/libkeystore
0053e94970512135d8ac12210c6510888a9fabee
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "keystore_internal.h" #include "entry_iterator.h" void keystore_entry_iterator_free(keystore_entry_iterator_t *iterator) { if (iterator != NULL) { free(iterator); } } unsigned int keystore_entry_iterator_size(keystore_entry_iterator_t *iterator) { return iterator->size; } bool keystore_entry_iterator_has_next(keystore_entry_iterator_t *iterator) { return iterator->entry != NULL; } keystore_entry_t * keystore_entry_iterator_next(keystore_entry_iterator_t *iterator) { keystore_entry_t *entry; entry = iterator->entry; if (iterator->entry != NULL) { iterator->entry = iterator->entry->next; } return entry; } void keystore_entry_iterator_rewind(keystore_entry_iterator_t *iterator) { iterator->entry = iterator->entry_orig; }
21.051282
71
0.74056
f532ed296fc3a04c5088333bf4e6a76f2639e178
6,579
c
C
src/hashtable.c
chow1937/bitcase
01e698f858efd1265719a5b771c5b0495379453d
[ "MIT" ]
2
2015-12-31T03:11:59.000Z
2016-09-20T18:54:39.000Z
src/hashtable.c
chow1937/bitcase
01e698f858efd1265719a5b771c5b0495379453d
[ "MIT" ]
null
null
null
src/hashtable.c
chow1937/bitcase
01e698f858efd1265719a5b771c5b0495379453d
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "hashtable.h" #include "db.h" #include "lru.h" #include "hashtable.h" #include "bcmem.h" /*----Hash function and it's helper functions----*/ /*Rotate a 32 bit unsigned integer left*/ inline uint32_t rotl(uint32_t x, int8_t r) { return (x << r) | (x >> (32 - r)); } /*Finalization mix - force all bits of a hash block to avalanche*/ inline uint32_t fmix(uint32_t h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } /* * MurmurHash3, by Austin Appleby * * More infomation, please refer to https://code.google.com/p/smhasher/ */ uint32_t MurmurHash3(const void *key, int len, uint32_t seed) { const uint8_t * data = (const uint8_t*)key; const int nblocks = len / 4; uint32_t h1 = seed; uint32_t c1 = 0xcc9e2d51; uint32_t c2 = 0x1b873593; int i; //---------- // body const uint32_t * blocks = (const uint32_t *)(data + nblocks*4); for(i = -nblocks; i; i++) { uint32_t k1 = blocks[i]; k1 *= c1; k1 = rotl(k1,15); k1 *= c2; h1 ^= k1; h1 = rotl(h1,13); h1 = h1*5+0xe6546b64; } //---------- // tail const uint8_t * tail = (const uint8_t*)(data + nblocks*4); uint32_t k1 = 0; switch(len & 3) { case 3: k1 ^= tail[2] << 16; case 2: k1 ^= tail[1] << 8; case 1: k1 ^= tail[0]; k1 *= c1; k1 = rotl(k1,15); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h1 = fmix(h1); return h1; } /*----API implementations----*/ /*Generate hash*/ uint32_t ht_gen_hash(const void *key) { uint32_t seed = HT_SEED; uint32_t h1; size_t len; len = strlen((char*)key); /*Invoke the real hash function*/ h1 = MurmurHash3(key, len, seed); return h1; } /*Free a bucket*/ int ht_free_bucket(bucket *bk) { /*Detach the bucket lru node first*/ detach(bk->lru); bc_free(bk->lru); bc_free(bk->key); bc_free(bk->value); bc_free(bk); return HT_OK; } /*Reset the hashtable*/ void ht_reset(hash_table *ht) { ht->table = NULL; ht->mask = 0; ht->size = 0; ht->used = 0; } /*Clear the hashtable and release the memory*/ int ht_clear(hash_table *ht) { int i; bucket *head, *next; /*Iter the whole hash table and release the memory*/ for (i = 0; i < ht->size; i++) { head = ht->table[i]; /*If the bucket has nothing,then continue*/ if (head == NULL) continue; /*Else release all elements link by the bucket*/ while (head) { next = head->next; ht_free_bucket(head); ht->used--; head = next; } } bc_free(ht->table); ht_reset(ht); return HT_OK; } /*Alloc memory for hashtable*/ int ht_alloc(hash_table *ht, unsigned long size) { unsigned long real_size; /*Make sure the hashtable size not smaller than HT_MIN_SIZE*/ if (size < HT_MIN_SIZE) { real_size = HT_MIN_SIZE; } else { real_size = size; } /*Init the hashtable*/ ht->size = real_size; ht->mask = real_size - 1; ht->used = 0; /*Alloc memory*/ ht->table = (bucket**)bc_malloc(real_size*sizeof(bucket*)); if (ht->table) { return HT_OK; } else { fprintf(stderr, "Memory malloc error\n"); return HT_ERROR; } } /*Create a new hashtable*/ hash_table *ht_create(void) { /*Alloc memory*/ hash_table *ht = (hash_table*)bc_malloc(sizeof(hash_table)); if (ht == NULL) { fprintf(stderr, "Memory malloc error\n"); } ht_alloc(ht, HT_MIN_SIZE); return ht; } /*Add a new key/value into a hashtable*/ bucket *ht_add(hash_table *ht, void *key, void *value) { uint32_t i, index, hash; bucket *head, *next, *new; /*Generate hash and count table index*/ hash = ht_gen_hash(key); index = hash & ht->mask; /*Try to insert the new key/value into a free slot*/ head = ht->table[index]; if (head) { bucket *tmp; tmp = head; /*Iter the bucket list*/ while (head) { next = head->next; /*If the key already exists,then return NULL pointer*/ if (strcmp((char*)key, (char*)head->key) == 0) { return NULL; } head = next; } /*Asign the head bucket address back to var head*/ head = tmp; } new = (bucket*)bc_malloc(sizeof(bucket)); new->next = head; /*Apply key and value to the new bucket*/ new->key = key; new->value = value; new->lru = NULL; ht->table[index] = new; ht->used++; return new; } /*Delete a key/value pair from hashtable by key*/ int ht_delete(hash_table *ht, void *key) { uint32_t hash, index; bucket *prev, *ptr, *next; /*Generate hash and count index*/ hash = ht_gen_hash(key); index = hash & ht->mask; prev = NULL; ptr = ht->table[index]; if (ptr == NULL) { /*Key not exists in this hashtable,return HT_ERROR*/ return HT_ERROR; } /*Iter the bucket list*/ while (ptr) { next = ptr->next; if (strcmp((char*)key, (char*)ptr->key) == 0) { ht_free_bucket(ptr); ht->used--; if (prev == NULL) { ht->table[index] = next; } else { prev->next = next; } return HT_OK; } /*Move forward*/ prev = ptr; ptr = next; } return HT_ERROR; } /*Find a bucket in the hashtable by key*/ bucket *ht_find(hash_table *ht, void *key) { uint32_t hash, index; bucket *head, *next; hash = ht_gen_hash(key); index = hash & ht->mask; head = ht->table[index]; /*Iter the bucket list*/ while(head) { next = head->next; if(strcmp((char*)key, (char*)head->key) == 0) { return head; } head = next; } return NULL; } /*Update a bucket by key*/ bucket *ht_update(hash_table *ht, void *key, void *value) { bucket *bk; bk = ht_find(ht, key); if (bk) { bc_free(bk->value); bk->value = value; return bk; } else { return NULL; } } /*Get next size of a hash table*/ uint32_t ht_next_size(uint32_t size) { size *= 2; if (size < HT_MIN_SIZE) return HT_MIN_SIZE; if (size > HT_MAX_SIZE) return HT_MAX_SIZE; return size; }
21.222581
71
0.541268
919b0a8001f8123f964416e0ccf142ab63af8678
4,640
c
C
source/basics/plussz2/plussz2.c
maevagrondin/max_externals
9083d877c0091077f823aa42665209050f4ebfde
[ "MIT" ]
175
2015-05-11T05:06:59.000Z
2022-03-31T11:08:33.000Z
source/basics/plussz2/plussz2.c
maevagrondin/max_externals
9083d877c0091077f823aa42665209050f4ebfde
[ "MIT" ]
53
2015-09-24T06:54:07.000Z
2021-11-30T05:58:34.000Z
source/basics/plussz2/plussz2.c
maevagrondin/max_externals
9083d877c0091077f823aa42665209050f4ebfde
[ "MIT" ]
52
2015-06-10T11:16:03.000Z
2022-03-29T01:48:59.000Z
/** @file plussz2.c - a version of plussz2 that demonstrates the use of proxy inlets. see plussz.c for more comments and information. @ingroup examples */ #include "ext.h" // you must include this - it contains the external object's link to available Max functions #include "ext_obex.h" // this is required for all objects using the newer style for writing objects. typedef struct _plussz2 { // defines our object's internal variables for each instance in a patch t_object ob; // object header - ALL objects MUST begin with this... t_atom l; // stored value from left inlet t_atom r; // stored value from right inlet void *outlet; // outlet creation - inlets are automatic, but objects must "own" their own outlets void *proxy; // proxy inlet long proxy_inletnum; // # of inlet currently in use } t_plussz2; // these are prototypes for the methods that are defined below void *plussz2_new(long n); void plussz2_free(t_plussz2 *x); void plussz2_assist(t_plussz2 *x, void *b, long m, long a, char *s); void plussz2_bang(t_plussz2 *x); void plussz2_int(t_plussz2 *x, long n); void plussz2_float(t_plussz2 *x, double f); t_class *plussz2_class; // global pointer to the object class - so max can reference the object //-------------------------------------------------------------------------- void ext_main(void *r) { t_class *c; c = class_new("plussz2", (method)plussz2_new, (method)plussz2_free, sizeof(t_plussz2), 0L, A_DEFLONG, 0); class_addmethod(c, (method)plussz2_bang, "bang", 0); // the method it uses when it gets a bang in the left inlet class_addmethod(c, (method)plussz2_int, "int", A_LONG, 0); // the method for ints in any inlet class_addmethod(c, (method)plussz2_float, "float", A_FLOAT, 0); // the method for floats in any inlet class_addmethod(c, (method)plussz2_assist, "assist", A_CANT, 0); // (optional) assistance method needs to be declared like this class_register(CLASS_BOX, c); plussz2_class = c; post("plussz2 object loaded...",0); // post any important info to the max window when our class is loaded } //-------------------------------------------------------------------------- void *plussz2_new(long n) // n = int argument typed into object box (A_DEFLONG) -- defaults to 0 if no args are typed { t_plussz2 *x; // local variable (pointer to a t_plussz2 data structure) x = (t_plussz2 *)object_alloc(plussz2_class); // create a new instance of this object if(x) { x->proxy = proxy_new(x, 1, &x->proxy_inletnum); // fully-flexible inlet for any type x->outlet = outlet_new(x, NULL); // fully-flexible outlet for any type // initialize L and R inlet atoms to (int)0 atom_setlong(&x->l, 0); atom_setlong(&x->r, 0); post(" new plussz2 object instance added to patch...",0); // post important info to the max window when new instance is created } return(x); // return a reference to the object instance } void plussz2_free(t_plussz2 *x) { object_free(x->proxy); // frees all resources associated with the proxy } //-------------------------------------------------------------------------- void plussz2_assist(t_plussz2 *x, void *b, long m, long a, char *s) // 4 final arguments are always the same for the assistance method { if (m == ASSIST_INLET) { switch (a) { case 0: sprintf(s,"Inlet %ld: Left Operand (Causes Output)", a); break; case 1: sprintf(s,"Inlet %ld: Right Operand (Added to Left)", a); break; } } else sprintf(s,"Sum of Left and Right Inlets"); } void plussz2_bang(t_plussz2 *x) { long lop; float fop; // if both L and R are INTEGER, OUTPUT AN INT if (x->l.a_type == A_LONG && x->r.a_type == A_LONG) { lop = atom_getlong(&x->l) + atom_getlong(&x->r); outlet_int(x->outlet, lop); } else { // OUTPUT A FLOAT fop = atom_getfloat(&x->l) + atom_getfloat(&x->r); outlet_float(x->outlet, fop); } } void plussz2_int(t_plussz2 *x, long n) { long inlet = proxy_getinlet((t_object *)x); // what inlet did this message come in through? post("int came in via inlet %ld", inlet); if (inlet == 1) { // RIGHT INLET atom_setlong(&x->r, n); // SET INT VAL } else { // LEFT INLET atom_setlong(&x->l, n); plussz2_bang(x); // bang for left inlet, trigger calculation } } void plussz2_float(t_plussz2 *x, double f) { long inlet = proxy_getinlet((t_object *)x); // what inlet did this message come in through? post("float came in via inlet %ld", inlet); if (inlet == 1) { // RIGHT INLET atom_setfloat(&x->r, f); // SET FLOAT VAL } else { // LEFT INLET atom_setfloat(&x->l, f); plussz2_bang(x); // bang for left inlet, trigger calculation } }
31.351351
134
0.656034
72e1c2383631d44e0d551d2d0929e9b366181982
1,766
h
C
JJPlayerView/JJPlayerView/JJConfig.h
zxhkit/JJPlayerView
75327be304d3fe2d81c7d503065020c2039996c4
[ "MIT" ]
1
2020-12-26T10:39:16.000Z
2020-12-26T10:39:16.000Z
JJPlayerView/JJPlayerView/JJConfig.h
zxhkit/JJPlayerView
75327be304d3fe2d81c7d503065020c2039996c4
[ "MIT" ]
null
null
null
JJPlayerView/JJPlayerView/JJConfig.h
zxhkit/JJPlayerView
75327be304d3fe2d81c7d503065020c2039996c4
[ "MIT" ]
1
2021-07-05T03:34:44.000Z
2021-07-05T03:34:44.000Z
// // JJConfig.h // JJPlayerView // // Created by zhouxuanhe on 2020/12/5. // #ifndef JJConfig_h #define JJConfig_h /** tabbar、导航条、状态栏高度 */ #define kTabBarHeight (kIs_iPhone_X ? 83 : 49) #define kNavBarHeight (kIs_iPhone_X ? 88 : 64) #define kNavBarContentHeight 44 #define kStatusBarHeight (kIs_iPhone_X ? 44 : 20) /** 距离底部安全距离 */ #define kBottomSafeHeight (kIs_iPhone_X ? 34 : 0) /** 常用对象 */ #define kAppWindow [[[UIApplication sharedApplication] delegate] window] /** 屏幕宽高 */ #define KScreenWidth ([[UIScreen mainScreen] bounds].size.height < [[UIScreen mainScreen] bounds].size.width ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width) #define KScreenHeight ([[UIScreen mainScreen] bounds].size.height > [[UIScreen mainScreen] bounds].size.width ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width) #define kIs_iPhone_X (KScreenHeight == 812.0 || KScreenHeight == 896 || KScreenHeight == 844 || KScreenHeight == 926 || KScreenHeight == 780) //#define kIs_iPhone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) /// 字体苹方 #define J_KFont(fontName,fontSize) ({\ UIFont * font = [UIFont fontWithName:fontName size:fontSize];\ if (!font) {\ font = [UIFont systemFontOfSize:fontSize weight:fontSize];\ }\ font;\ }) #define kFont_Semibold(f) J_KFont(@"PingFangSC-Semibold",f) #define kFont_Medium(f) J_KFont(@"PingFangSC-Medium",f) #define kFont_Regular(f) J_KFont(@"PingFangSC-Regular",f) #define kFont(f) [UIFont systemFontOfSize:f] #define kFont_Blod(f) [UIFont systemFontOfSize:f] #endif /* JJConfig_h */
38.391304
201
0.666478
0b2ca2f18c202a7e1f87b41ca41cd20e90402f79
247
h
C
Phoebe_Evaluator_Escape_EvasiveManeuvers_classes.h
NotDiscordOfficial/Fortnite_SDK
58f8da148256f99cb35518003306fffee33c4a21
[ "MIT" ]
null
null
null
Phoebe_Evaluator_Escape_EvasiveManeuvers_classes.h
NotDiscordOfficial/Fortnite_SDK
58f8da148256f99cb35518003306fffee33c4a21
[ "MIT" ]
null
null
null
Phoebe_Evaluator_Escape_EvasiveManeuvers_classes.h
NotDiscordOfficial/Fortnite_SDK
58f8da148256f99cb35518003306fffee33c4a21
[ "MIT" ]
1
2021-07-22T00:31:44.000Z
2021-07-22T00:31:44.000Z
// BlueprintGeneratedClass Phoebe_Evaluator_Escape_EvasiveManeuvers.Phoebe_Evaluator_Escape_EvasiveManeuvers_C // Size: 0x1c8 (Inherited: 0x1c8) struct UPhoebe_Evaluator_Escape_EvasiveManeuvers_C : UFortAthenaAIBotEvaluator_EvasiveManeuvers { };
41.166667
110
0.88664
bc9b4dec2e52144200a24bad56c7471530af3189
622
h
C
71_FileLock/src/Fraction.h
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
71_FileLock/src/Fraction.h
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
71_FileLock/src/Fraction.h
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
#ifndef INC_11_FRACTION_FRACTION_HPP #define INC_11_FRACTION_FRACTION_HPP #include <iostream> class Fraction { int counter, denominator; friend std::istream &operator>>(std::istream &is, Fraction &f); friend std::ostream &operator<<(std::ostream &os, Fraction f); public: Fraction(int c=0, int d=1); int get_counter(); int get_denominator(); Fraction operator+(Fraction b); Fraction operator-(Fraction b); Fraction operator*(Fraction b); Fraction operator/(Fraction b); bool operator<(Fraction b); bool operator>(Fraction b); }; #endif //INC_11_FRACTION_FRACTION_HPP
23.037037
67
0.70418
73b776845cbb4bd81274e8cd188993d720296531
258
h
C
clang/test/SemaObjC/format-strings-system.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/SemaObjC/format-strings-system.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/SemaObjC/format-strings-system.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
#pragma clang system_header @class NSString; // Do not emit warnings when using NSLocalizedString extern NSString *GetLocalizedString(NSString *str); #define NSLocalizedString(key) GetLocalizedString(key) #define NSAssert(fmt, arg) NSLog(fmt, arg, 0, 0)
23.454545
54
0.786822
bc0a043d7568f1515f09362a845e31c6a2a7ef93
6,411
h
C
progcoin.h
george1605/ProgrammersCoin
3eed97517c481ef7637c007fb442dc81b572c063
[ "MIT" ]
null
null
null
progcoin.h
george1605/ProgrammersCoin
3eed97517c481ef7637c007fb442dc81b572c063
[ "MIT" ]
null
null
null
progcoin.h
george1605/ProgrammersCoin
3eed97517c481ef7637c007fb442dc81b572c063
[ "MIT" ]
null
null
null
#include <map> #include <vector> #include <fstream> #include <utility> #include <iostream> using namespace std;//do not use it :))) #define PRIVATE 0x0F01 #define PUBLIC 0x0F02 #define CURRENT_PHASE 2 #define EMPTY_PROJ 0x0001 #define CPP_PROJ 0x0002 #define JAVA_PROJ 0x0003 #define PYTHON_PROJ 0x0004 #define WEB_PROJ 0x0005 #define PHP_PROJ 0x0006 #define WINFORMS_PROJ 0x0007 #define QT_PROJ 0x0008 #define SQL_PROJ 0x0009 #define GO_PROJ 0x000A #define LUA_PROJ 0x000B #define WR_MODE 100000 #define R_MODE 100010 #define ALL_MODE 100120 class CFile { private: ifstream i; ofstream o; public: CFile(){} CFile(int p){ if(p != 0){ price = p; payToSee = true; } } bool isShortcut,payToSee; CFile* Link = new CFile(); string path; int price = 0; int views = 0; int likes = 0; int value = 0; void* owner; CFile(string path,int MODE){ switch(MODE){ case WR_MODE: o.open(path); break; case R_MODE: i.open(path); break; case ALL_MODE: i.open(path); o.open(path); break; } } CFile(string name,string content){ i.open(name); o.open(name); path = name; if(content != "") o << content; } void Close(){ i.close(); o.close(); } void LinkTo(CFile* p){ Link = p; } string Read(){ string T,text; while(getline(i,T)){ text += T; } return text; } ~CFile(){ Close(); path = ""; } }; class CProj { public: vector<CFile> Files; CFile Main; int Type = EMPTY_PROJ; int views = 0; int likes = 0; int value = 0; void* owner; CProj(){} CProj(int TYPE){ Type = TYPE; switch(Type){ case CPP_PROJ: Add(CFile("main.cpp","#include <iostream>\nusing namespace std;\n\nint main(){}")); break; case WEB_PROJ: Add(CFile("index.html","<html></html>")); Add(CFile("main.js","")); Add(CFile("index.css","body {\n\n}")); break; case WINFORMS_PROJ: Add(CFile("main.cpp","#include <windows.h>\n\n\nint wWinMain(){}")); break; case LUA_PROJ: break; case JAVA_PROJ: Add(CFile("Main.java","class Main {}")); break; case QT_PROJ: Add(CFile("new.cpp","\n\nint main(){\n MainApplication j; }")); break; case GO_PROJ: break; case SQL_PROJ: Add(CFile("new.sql","SELECT * FROM table")); break; } } void Add(CFile t){ Files.push_back(t); } void Clear(){ for(int a=0;a < Files.size();a++){ Files[a].Close(); } Files.clear(); } }; class Account { private: string Password; map<string,CFile> MyFiles; map<string,CProj> MyProj; int Mode = PUBLIC; public: string User; float Balance = 0; Account(){} Account(string name,string pass){ if(pass.length() > 8){ Password = pass; User = name; }else throw "[AccountError]:password is not long enough"; } Account(int Type){ Mode = Type; } void AddFile(CFile r,string name){ MyFiles[name] = r; r.owner = (void*)this; } void AddProj(CProj i,string name){ MyProj[name] = i; i.owner = (void*)this; } void MakePrivate(){ Mode = PRIVATE; } void ChangePass(string k){ Password = k; } }; class SocialAcc : public Account{ private: vector<Account*> SubAccounts; public: void Add(Account i){ SubAccounts.push_back(&i); this->Balance += i.Balance; } void Add(Account* i){ SubAccounts.push_back(i); this->Balance += (i->Balance); } }; class Transfer { private: string key; void DoTrans(){ From.Balance -= amount; To.Balance += amount; } float commision = 0; public: vector<Account> Possible; long long ID = 0x0FFFFFF; const time_t timestamp = time(NULL); Transfer(){} ~Transfer(){ From = Account(); To = Account(); Accepted = false; amount = 0; } Transfer(int SECURE){ if(!SECURE) ~Transfer(); } Account From; Account To; bool Accepted = false; float amount; void SetKey(string a){ if(a.length() > 20) key = a; } bool Accept(){ try{ DoTrans(); Accepted = true; }catch(...){ std::cout << "An error occured!Transfer cannot be realised"; Accepted = false; } Possible.clear(); return Accepted; } }; class Gift : public Transfer { }; Account CreateAccount(string a,string b){ return Account(a,b); } class TransferList { private: static map<int,Transfer> Transfers; public: static void Register(Transfer k){ Transfers[k.ID] = k; } }; class MicroTask { private: bool isFinished = false; public: Account* Starter = new Account(PUBLIC); Account* Worker = new Account(PUBLIC); int Amount = 0; string Description = "[NULL]"; string TaskType = ""; void Finish(){ Transfer t(true); t.From = *Starter; t.To = *Worker; t.amount = Amount; t.Accept(); TransferList::Register(t); isFinished = true; } }; class DB { private: map<Account,vector<CFile>> Files; map<Account,vector<CProj>> Projects; public: static void NewFile(string name = "main.txt",Account i = Account(PUBLIC),string content = ""){ CFile t(name,content); t.Close(); t.owner = i; Files[i].push_back(t); } static CProj NewProj(string Name,Account j){ CProj k; k.owner = (void*)(&j); Projects[j].push_back(k); return k; } static Transfer SellFile(CFile n,Account From,float price){ //securiy measure if(!Files[From].find(n)){ return Transfer(0); } Transfer t; t.amount = price; t.From = From; t.To = Account(PUBLIC); TransferList::Register(t); return t; } static void DeleteAcc(Account i){ Files.erase(i); Projects.erase(i); } static void DelFile(CFile r,Account t){ Files[t].erase(Files[t].find(r)); } static void AccessF(string t,Account n){ CFile p; for(int a=0;a < Files[n].size();a++){ } p.views++; p.value += 5; } static void Like(CFile t){ t.likes++; t.value += 15; } };
20.097179
96
0.562159
5d8d73ed64e3620f8e552a103a65c84ac4dba31f
2,429
h
C
Engine/include/input/MouseEvent.h
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
2
2015-04-21T05:36:12.000Z
2017-04-16T19:31:26.000Z
Engine/include/input/MouseEvent.h
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
null
null
null
Engine/include/input/MouseEvent.h
katoun/kg_engine
fdcc6ec01b191d07cedf7a8d6c274166e25401a8
[ "Unlicense" ]
null
null
null
/* ----------------------------------------------------------------------------- KG game engine (http://katoun.github.com/kg_engine) is made available under the MIT License. Copyright (c) 2006-2013 Catalin Alexandru Nastase 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 _MOUSE_EVENT_H_ #define _MOUSE_EVENT_H_ #include <EngineConfig.h> #include <input/InputEvent.h> #include <input/MouseDefines.h> namespace input { //! MouseEvent class - DOCUMENTATION NEEDED class ENGINE_PUBLIC_EXPORT MouseEvent: public InputEvent { public: //! Constructor MouseEvent(); //! Destructor ~MouseEvent(); //! Set the mouse event //! \param button: ButtonCode enumeration type, specifying the button. //! \param axisX: The X axis of the mouse. //! \param axisY: The Y axis of the mouse. //! \param axisZ: The Z axis of the mouse. //! \param source: Which input device the mouse event is coming from. void set(MouseButton button, int axisX, signed short int axisY, int axisZ, InputDevice *source); //! getButton - DOCUMENTATION NEEDED MouseButton getButton() const; //! getAxisX - DOCUMENTATION NEEDED int getAxisX() const; //! getAxisY - DOCUMENTATION NEEDED int getAxisY() const; //! getAxisZ - DOCUMENTATION NEEDED int getAxisZ() const; protected: MouseButton mButton; int mAxisX; int mAxisY; int mAxisZ; }; } // end namespace input #endif
30.746835
97
0.715109
34ca7c9a541bdf83a88fa0eb993e51610f6efbd4
327
h
C
tools/SunriseAlarmXcodeProject/TimePickerViewController.h
alchemydc/snowclock
ee142d5701d825e6820bd65ff1da666f087d162c
[ "MIT" ]
null
null
null
tools/SunriseAlarmXcodeProject/TimePickerViewController.h
alchemydc/snowclock
ee142d5701d825e6820bd65ff1da666f087d162c
[ "MIT" ]
null
null
null
tools/SunriseAlarmXcodeProject/TimePickerViewController.h
alchemydc/snowclock
ee142d5701d825e6820bd65ff1da666f087d162c
[ "MIT" ]
null
null
null
// // TimePickerViewController.h // Sunrise Alarm // // Created by finucane on 8/24/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @interface TimePickerViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> { } -(void)setFromOffset:(int)offset; @end
17.210526
101
0.749235
42ba91bef6023bf5b4d50653f4070d04ff83190d
3,562
h
C
xt_base/include/miscutil/tvals.h
wrcad/xictools
f46ba6d42801426739cc8b2940a809b74f1641e2
[ "Apache-2.0" ]
73
2017-10-26T12:40:24.000Z
2022-03-02T16:59:43.000Z
xt_base/include/miscutil/tvals.h
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
12
2017-11-01T10:18:22.000Z
2022-03-20T19:35:36.000Z
xt_base/include/miscutil/tvals.h
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
34
2017-10-06T17:04:21.000Z
2022-02-18T16:22:03.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * Misc. Utilities Library * * * *========================================================================* $Id:$ *========================================================================*/ // // A simple class for time measurement. // #ifndef TVALS_H #define TVALS_H // Time values from StartTiming(), StopTiming(). // struct Tvals { Tvals() { real_sec = user_sec = system_sec = 0.0; } void start(); void stop(); void accum(Tvals *tv) { if (tv) { real_sec += tv->real_sec; user_sec += tv->user_sec; system_sec += tv->system_sec; } } double realTime() const { return (real_sec); } double userTime() const { return (user_sec); } double systemTime() const { return (system_sec); } static unsigned long millisec(); protected: double real_sec; double user_sec; double system_sec; }; #endif
45.088608
76
0.427288
826388989ed3af4f6fe657bb201469a206352d52
283
h
C
src/blz.h
misson20000/switch-tools
422537612fb0462428bfc87a61e64d2541732082
[ "ISC" ]
108
2017-12-25T03:11:57.000Z
2022-03-06T19:19:30.000Z
src/blz.h
miho171/switch-tools
793b056f5b8d64d638dd7a56e59431b05439a304
[ "ISC" ]
13
2017-12-28T21:31:53.000Z
2021-11-01T15:57:58.000Z
src/blz.h
miho171/switch-tools
793b056f5b8d64d638dd7a56e59431b05439a304
[ "ISC" ]
43
2018-01-03T06:22:56.000Z
2022-03-30T05:37:34.000Z
#pragma once #include <stdint.h> typedef uint64_t u64; typedef uint32_t u32; typedef uint16_t u16; typedef uint8_t u8; #define BLZ_NORMAL 0 // normal mode #define BLZ_BEST 1 // best mode u8 *BLZ_Code(u8 *raw_buffer, int raw_len, u32 *new_len, int best);
21.769231
66
0.681979
790b1e51e6ea6f57eb51fc8805139419caf88bf2
297
c
C
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/simd-3.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/simd-3.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/simd-3.c
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
/* { dg-do compile } */ /* { dg-options "-maltivec" { target { powerpc*-*-* && powerpc_altivec_ok } } } */ __attribute__ ((vector_size (2))) signed char v1, v2, v3; void one (void) { v1 = v2 + v3; } __attribute__ ((vector_size (8))) signed char v4, v5, v6; void two (void) { v4 = v5 + v6; }
17.470588
82
0.589226