content
stringlengths
19
48.2k
/* * Instantiate a VCC stack. * * Could check for correct attributes here. */ static int harp_instvcc(Cmn_unit *up, Cmn_vcc *vp) { struct harp_softc *sc; if (up == NULL || vp == NULL || vp->cv_connvc == NULL) return (EINVAL); sc = (struct harp_softc *)up; return (0); }
/* * Handle completion of periodic parameter group retrievals. */ static void iopl_intr_pg(struct device *dv, struct iop_msg *im, void *reply) { struct i2o_param_lan_stats *ls; struct i2o_param_lan_802_3_stats *les; struct i2o_param_lan_media_operation *lmo; struct iopl_softc *sc; struct iop_softc *iop; struct ifnet *ifp; struct i2o_reply *rb; int pg; rb = (struct i2o_reply *)reply; sc = (struct iopl_softc *)dv; iop = (struct iop_softc *)dv->dv_parent; ifp = &sc->sc_if.sci_if; if ((rb->msgflags & I2O_MSGFLAGS_FAIL) != 0) { iopl_tick_sched(sc); return; } iop_msg_unmap(iop, im); pg = le16toh(((struct iop_pgop *)im->im_dvcontext)->oat.group); free(im->im_dvcontext, M_DEVBUF); iop_msg_free(iop, im); switch (pg) { case I2O_PARAM_LAN_MEDIA_OPERATION: lmo = &sc->sc_pb.p.lmo; sc->sc_curmbps = (int)(le64toh(lmo->currxbps) / (1000 * 1000)); sc->sc_conntype = le32toh(lmo->connectiontype); if (lmo->linkstatus) { sc->sc_flags |= IOPL_LINK; } sc->sc_next_pg = I2O_PARAM_LAN_STATS; break; case I2O_PARAM_LAN_STATS: ls = &sc->sc_pb.p.ls; ifp->if_ipackets = le64toh(ls->ipackets); ifp->if_opackets = le64toh(ls->opackets); ifp->if_ierrors = le64toh(ls->ierrors); ifp->if_oerrors = le64toh(ls->oerrors); sc->sc_next_pg = sc->sc_ms_pg; break; case I2O_PARAM_LAN_802_3_STATS: les = &sc->sc_pb.p.les; ifp->if_collisions = le64toh(les->onecollision) + le64toh(les->manycollisions); sc->sc_next_pg = -1; break; case I2O_PARAM_LAN_FDDI_STATS: sc->sc_next_pg = -1; break; } iopl_tick_sched(sc); }
#include<stdio.h> long long int flagstone(int l, int b, int k) { long long int x,y; if(l>k) { if(l%k==0) x=l/k; else x=(l/k)+1; } else x=1; if(b>k) { if(b%k==0) y=b/k; else y=(b/k)+1; } else y=1; return x*y; } int main() { long long int m,n,a,f; scanf("%lld %lld %lld",&m,&n,&a); f = flagstone(m,n,a); printf("%lld\n",f); return 0; }
// ---------------------------------------------------------------------------------- // Setting a marked item that is out of range ( negative or >= count ) disables the // item pointer. void menu_set_marked_item( menu_t *m, int item ) { if( m->vertice_group == NULL ) return; if( item >= m->count ) item = -1; m->marked_item = item; m->pointer_target_time_ms = 0; m->pointer_frame = 10.0; }
// Windows/FileName.h #ifndef __WINDOWS_FILE_NAME_H #define __WINDOWS_FILE_NAME_H #include "../Common/MyString.h" namespace NWindows { namespace NFile { namespace NName { int FindSepar(const wchar_t *s) throw(); #ifndef USE_UNICODE_FSTRING int FindSepar(const FChar *s) throw(); #endif void NormalizeDirPathPrefix(FString &dirPath); // ensures that it ended with '\\', if dirPath is not epmty void NormalizeDirPathPrefix(UString &dirPath); bool IsDrivePath(const wchar_t *s) throw(); // first 3 chars are drive chars like "a:\\" bool IsAltPathPrefix(CFSTR s) throw(); /* name: */ #if defined(_WIN32) && !defined(UNDER_CE) extern const char * const kSuperPathPrefix; /* \\?\ */ const unsigned kDevicePathPrefixSize = 4; const unsigned kSuperPathPrefixSize = 4; const unsigned kSuperUncPathPrefixSize = kSuperPathPrefixSize + 4; bool IsDevicePath(CFSTR s) throw(); /* \\.\ */ bool IsSuperUncPath(CFSTR s) throw(); /* \\?\UNC\ */ bool IsNetworkPath(CFSTR s) throw(); /* \\?\UNC\ or \\SERVER */ /* GetNetworkServerPrefixSize() returns size of server prefix: \\?\UNC\SERVER\ \\SERVER\ in another cases it returns 0 */ unsigned GetNetworkServerPrefixSize(CFSTR s) throw(); bool IsNetworkShareRootPath(CFSTR s) throw(); /* \\?\UNC\SERVER\share or \\SERVER\share or with slash */ bool IsDrivePath_SuperAllowed(CFSTR s) throw(); // first chars are drive chars like "a:\" or "\\?\a:\" bool IsDriveRootPath_SuperAllowed(CFSTR s) throw(); // exact drive root path "a:\" or "\\?\a:\" bool IsDrivePath2(const wchar_t *s) throw(); // first 2 chars are drive chars like "a:" // bool IsDriveName2(const wchar_t *s) throw(); // is drive name like "a:" bool IsSuperPath(const wchar_t *s) throw(); bool IsSuperOrDevicePath(const wchar_t *s) throw(); #ifndef USE_UNICODE_FSTRING bool IsDrivePath2(CFSTR s) throw(); // first 2 chars are drive chars like "a:" // bool IsDriveName2(CFSTR s) throw(); // is drive name like "a:" bool IsDrivePath(CFSTR s) throw(); bool IsSuperPath(CFSTR s) throw(); bool IsSuperOrDevicePath(CFSTR s) throw(); /* GetRootPrefixSize() returns size of ROOT PREFIX for cases: \ \\.\ C:\ \\?\C:\ \\?\UNC\SERVER\Shared\ \\SERVER\Shared\ in another cases it returns 0 */ unsigned GetRootPrefixSize(CFSTR s) throw(); #endif int FindAltStreamColon(CFSTR path) throw(); #endif // _WIN32 bool IsAbsolutePath(const wchar_t *s) throw(); unsigned GetRootPrefixSize(const wchar_t *s) throw(); #ifdef WIN_LONG_PATH const int kSuperPathType_UseOnlyMain = 0; const int kSuperPathType_UseOnlySuper = 1; const int kSuperPathType_UseMainAndSuper = 2; int GetUseSuperPathType(CFSTR s) throw(); bool GetSuperPath(CFSTR path, UString &superPath, bool onlyIfNew); bool GetSuperPaths(CFSTR s1, CFSTR s2, UString &d1, UString &d2, bool onlyIfNew); #define USE_MAIN_PATH (__useSuperPathType != kSuperPathType_UseOnlySuper) #define USE_MAIN_PATH_2 (__useSuperPathType1 != kSuperPathType_UseOnlySuper && __useSuperPathType2 != kSuperPathType_UseOnlySuper) #define USE_SUPER_PATH (__useSuperPathType != kSuperPathType_UseOnlyMain) #define USE_SUPER_PATH_2 (__useSuperPathType1 != kSuperPathType_UseOnlyMain || __useSuperPathType2 != kSuperPathType_UseOnlyMain) #define IF_USE_MAIN_PATH int __useSuperPathType = GetUseSuperPathType(path); if (USE_MAIN_PATH) #define IF_USE_MAIN_PATH_2(x1, x2) \ int __useSuperPathType1 = GetUseSuperPathType(x1); \ int __useSuperPathType2 = GetUseSuperPathType(x2); \ if (USE_MAIN_PATH_2) #else #define IF_USE_MAIN_PATH #define IF_USE_MAIN_PATH_2(x1, x2) #endif // WIN_LONG_PATH bool GetFullPath(CFSTR dirPrefix, CFSTR path, FString &fullPath); bool GetFullPath(CFSTR path, FString &fullPath); }}} #endif
/* * The documentation for these atoms is whack * * I believe I used the freedesktop specs for them */ static int dialog_setup(Window *msgbox, Window parent) { XSetWindowAttributes attribs; Atom _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DIALOG, _NET_WM_NAME; attribs.border_pixel = JIN_env.border_pixel; attribs.background_pixel = JIN_env.background_pixel; attribs.override_redirect = True; attribs.event_mask = ExposureMask; *msgbox = XCreateWindow(JIN_env.x_display, XRootWindow(JIN_env.x_display, JIN_env.screen_id), 0, 0, DIALOG_WIDTH, DIALOG_HEIGHT, 0, CopyFromParent, InputOutput, CopyFromParent, CWBackPixel | CWBorderPixel | CWEventMask, &attribs); XSizeHints hints; hints.flags = PMinSize | PMaxSize | PResizeInc; hints.min_width = hints.max_width = DIALOG_WIDTH; hints.min_height = hints.max_height = DIALOG_HEIGHT; hints.width_inc = hints.height_inc = 0; XSetWMNormalHints(JIN_env.x_display, *msgbox, &hints); Atom _NET_WM_STATE = XInternAtom(JIN_env.x_display, "_NET_WM_STATE", False); char *state_atoms_names[STATE_ATOMS] = { "_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_STATE_SKIP_PAGER", "_NET_WM_STATE_FOCUSED", "_NET_WM_STATE_MODAL" }; Atom state_atoms[STATE_ATOMS]; for (int i = 0; i < STATE_ATOMS; ++i) { state_atoms[i] = XInternAtom(JIN_env.x_display, state_atoms_names[i], False); } XChangeProperty(JIN_env.x_display, *msgbox, _NET_WM_STATE, XA_ATOM, 32, PropModeReplace, (unsigned char *) state_atoms, STATE_ATOMS); XSetTransientForHint(JIN_env.x_display, *msgbox, parent); _NET_WM_WINDOW_TYPE = XInternAtom(JIN_env.x_display, "_NET_WM_WINDOW_TYPE", False); _NET_WM_WINDOW_TYPE_DIALOG = XInternAtom(JIN_env.x_display, "_NET_WM_WINDOW_TYPE_DIALOG", False); XChangeProperty(JIN_env.x_display, *msgbox, _NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace, (unsigned char *) &_NET_WM_WINDOW_TYPE_DIALOG, 1); XSetWMProtocols(JIN_env.x_display, *msgbox, &JIN_env.wm_delete_window,1 ); return 0; }
/* -*- c++ -*- */ /* * Copyright 2004,2012,2018 Free Software Foundation, Inc. * * This file is part of GNU Radio * * SPDX-License-Identifier: GPL-3.0-or-later * */ #ifndef SCCC_ENCODER_IMPL_H #define SCCC_ENCODER_IMPL_H #include <gnuradio/trellis/sccc_encoder.h> namespace gr { namespace trellis { template <class IN_T, class OUT_T> class sccc_encoder_impl : public sccc_encoder<IN_T, OUT_T> { private: fsm d_FSMo; int d_STo; fsm d_FSMi; int d_STi; interleaver d_INTERLEAVER; int d_blocklength; std::vector<int> d_buffer; public: sccc_encoder_impl(const fsm& FSMo, int STo, const fsm& FSMi, int STi, const interleaver& INTERLEAVER, int blocklength); ~sccc_encoder_impl() override; fsm FSMo() const override { return d_FSMo; } int STo() const override { return d_STo; } fsm FSMi() const override { return d_FSMi; } int STi() const override { return d_STi; } interleaver INTERLEAVER() const override { return d_INTERLEAVER; } int blocklength() const override { return d_blocklength; } int work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) override; }; } /* namespace trellis */ } /* namespace gr */ #endif /* SCCC_ENCODER_IMPL_H */
/* -*- buffer-read-only: t -*- Generated automatically by parsecpu.awk from arm-cpus.in. Do not edit. Copyright (C) 2011-2017 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ enum processor_type { TARGET_CPU_arm2, TARGET_CPU_arm250, TARGET_CPU_arm3, TARGET_CPU_arm6, TARGET_CPU_arm60, TARGET_CPU_arm600, TARGET_CPU_arm610, TARGET_CPU_arm620, TARGET_CPU_arm7, TARGET_CPU_arm7d, TARGET_CPU_arm7di, TARGET_CPU_arm70, TARGET_CPU_arm700, TARGET_CPU_arm700i, TARGET_CPU_arm710, TARGET_CPU_arm720, TARGET_CPU_arm710c, TARGET_CPU_arm7100, TARGET_CPU_arm7500, TARGET_CPU_arm7500fe, TARGET_CPU_arm7m, TARGET_CPU_arm7dm, TARGET_CPU_arm7dmi, TARGET_CPU_arm8, TARGET_CPU_arm810, TARGET_CPU_strongarm, TARGET_CPU_strongarm110, TARGET_CPU_strongarm1100, TARGET_CPU_strongarm1110, TARGET_CPU_fa526, TARGET_CPU_fa626, TARGET_CPU_arm7tdmi, TARGET_CPU_arm7tdmis, TARGET_CPU_arm710t, TARGET_CPU_arm720t, TARGET_CPU_arm740t, TARGET_CPU_arm9, TARGET_CPU_arm9tdmi, TARGET_CPU_arm920, TARGET_CPU_arm920t, TARGET_CPU_arm922t, TARGET_CPU_arm940t, TARGET_CPU_ep9312, TARGET_CPU_arm10tdmi, TARGET_CPU_arm1020t, TARGET_CPU_arm9e, TARGET_CPU_arm946es, TARGET_CPU_arm966es, TARGET_CPU_arm968es, TARGET_CPU_arm10e, TARGET_CPU_arm1020e, TARGET_CPU_arm1022e, TARGET_CPU_xscale, TARGET_CPU_iwmmxt, TARGET_CPU_iwmmxt2, TARGET_CPU_fa606te, TARGET_CPU_fa626te, TARGET_CPU_fmp626, TARGET_CPU_fa726te, TARGET_CPU_arm926ejs, TARGET_CPU_arm1026ejs, TARGET_CPU_arm1136js, TARGET_CPU_arm1136jfs, TARGET_CPU_arm1176jzs, TARGET_CPU_arm1176jzfs, TARGET_CPU_mpcorenovfp, TARGET_CPU_mpcore, TARGET_CPU_arm1156t2s, TARGET_CPU_arm1156t2fs, TARGET_CPU_cortexm1, TARGET_CPU_cortexm0, TARGET_CPU_cortexm0plus, TARGET_CPU_cortexm1smallmultiply, TARGET_CPU_cortexm0smallmultiply, TARGET_CPU_cortexm0plussmallmultiply, TARGET_CPU_genericv7a, TARGET_CPU_cortexa5, TARGET_CPU_cortexa7, TARGET_CPU_cortexa8, TARGET_CPU_cortexa9, TARGET_CPU_cortexa12, TARGET_CPU_cortexa15, TARGET_CPU_cortexa17, TARGET_CPU_cortexr4, TARGET_CPU_cortexr4f, TARGET_CPU_cortexr5, TARGET_CPU_cortexr7, TARGET_CPU_cortexr8, TARGET_CPU_cortexm7, TARGET_CPU_cortexm4, TARGET_CPU_cortexm3, TARGET_CPU_marvell_pj4, TARGET_CPU_cortexa15cortexa7, TARGET_CPU_cortexa17cortexa7, TARGET_CPU_cortexa32, TARGET_CPU_cortexa35, TARGET_CPU_cortexa53, TARGET_CPU_cortexa57, TARGET_CPU_cortexa72, TARGET_CPU_cortexa73, TARGET_CPU_exynosm1, TARGET_CPU_xgene1, TARGET_CPU_cortexa57cortexa53, TARGET_CPU_cortexa72cortexa53, TARGET_CPU_cortexa73cortexa35, TARGET_CPU_cortexa73cortexa53, TARGET_CPU_cortexm23, TARGET_CPU_cortexm33, TARGET_CPU_arm_none }; enum fpu_type { TARGET_FPU_vfp, TARGET_FPU_vfpv2, TARGET_FPU_vfpv3, TARGET_FPU_vfpv3_fp16, TARGET_FPU_vfpv3_d16, TARGET_FPU_vfpv3_d16_fp16, TARGET_FPU_vfpv3xd, TARGET_FPU_vfpv3xd_fp16, TARGET_FPU_neon, TARGET_FPU_neon_vfpv3, TARGET_FPU_neon_fp16, TARGET_FPU_vfpv4, TARGET_FPU_neon_vfpv4, TARGET_FPU_vfpv4_d16, TARGET_FPU_fpv4_sp_d16, TARGET_FPU_fpv5_sp_d16, TARGET_FPU_fpv5_d16, TARGET_FPU_fp_armv8, TARGET_FPU_neon_fp_armv8, TARGET_FPU_crypto_neon_fp_armv8, TARGET_FPU_vfp3, TARGET_FPU_auto };
/* Record the types used by the current global variable declaration being parsed, so that we can decide later to emit their debug info. Those types are in types_used_by_cur_var_decl, and we are going to store them in the types_used_by_vars_hash hash table. DECL is the declaration of the global variable that has been parsed. */ void record_types_used_by_current_var_decl (tree decl) { gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl)); if (types_used_by_cur_var_decl) { tree node; for (node = types_used_by_cur_var_decl; node; node = TREE_CHAIN (node)) { tree type = TREE_PURPOSE (node); types_used_by_var_decl_insert (type, decl); } types_used_by_cur_var_decl = NULL; } }
/* * Core Audio Format muxer * Copyright (c) 2011 Carl Eugen Hoyos * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #include "caf.h" #include "isom.h" #include "avio_internal.h" #include "libavutil/intfloat.h" #include "libavutil/dict.h" typedef struct { int64_t data; uint8_t *pkt_sizes; int size_buffer_size; int size_entries_used; int packets; } CAFContext; static uint32_t codec_flags(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F64BE: return 1; //< kCAFLinearPCMFormatFlagIsFloat case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S32LE: return 2; //< kCAFLinearPCMFormatFlagIsLittleEndian case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F64LE: return 3; //< kCAFLinearPCMFormatFlagIsFloat | kCAFLinearPCMFormatFlagIsLittleEndian default: return 0; } } static uint32_t samples_per_packet(enum AVCodecID codec_id, int channels, int block_align) { switch (codec_id) { case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S32LE: case AV_CODEC_ID_PCM_S32BE: case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F64LE: case AV_CODEC_ID_PCM_F64BE: case AV_CODEC_ID_PCM_ALAW: case AV_CODEC_ID_PCM_MULAW: return 1; case AV_CODEC_ID_MACE3: case AV_CODEC_ID_MACE6: return 6; case AV_CODEC_ID_ADPCM_IMA_QT: return 64; case AV_CODEC_ID_AMR_NB: case AV_CODEC_ID_GSM: case AV_CODEC_ID_ILBC: case AV_CODEC_ID_QCELP: return 160; case AV_CODEC_ID_GSM_MS: return 320; case AV_CODEC_ID_MP1: return 384; case AV_CODEC_ID_OPUS: return 960; case AV_CODEC_ID_MP2: case AV_CODEC_ID_MP3: return 1152; case AV_CODEC_ID_AC3: return 1536; case AV_CODEC_ID_QDM2: case AV_CODEC_ID_QDMC: return 2048 * channels; case AV_CODEC_ID_ALAC: return 4096; case AV_CODEC_ID_ADPCM_IMA_WAV: return (block_align - 4 * channels) * 8 / (4 * channels) + 1; case AV_CODEC_ID_ADPCM_MS: return (block_align - 7 * channels) * 2 / channels + 2; default: return 0; } } static int caf_write_header(AVFormatContext *s) { AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[0]->codecpar; CAFContext *caf = s->priv_data; AVDictionaryEntry *t = NULL; unsigned int codec_tag = ff_codec_get_tag(ff_codec_caf_tags, par->codec_id); int64_t chunk_size = 0; int frame_size = par->frame_size; if (s->nb_streams != 1) { av_log(s, AV_LOG_ERROR, "CAF files have exactly one stream\n"); return AVERROR(EINVAL); } switch (par->codec_id) { case AV_CODEC_ID_AAC: av_log(s, AV_LOG_ERROR, "muxing codec currently unsupported\n"); return AVERROR_PATCHWELCOME; } if (par->codec_id == AV_CODEC_ID_OPUS && par->channels > 2) { av_log(s, AV_LOG_ERROR, "Only mono and stereo are supported for Opus\n"); return AVERROR_INVALIDDATA; } if (!codec_tag) { av_log(s, AV_LOG_ERROR, "unsupported codec\n"); return AVERROR_INVALIDDATA; } if (!par->block_align && !(pb->seekable & AVIO_SEEKABLE_NORMAL)) { av_log(s, AV_LOG_ERROR, "Muxing variable packet size not supported on non seekable output\n"); return AVERROR_INVALIDDATA; } if (par->codec_id != AV_CODEC_ID_MP3 || frame_size != 576) frame_size = samples_per_packet(par->codec_id, par->channels, par->block_align); ffio_wfourcc(pb, "caff"); //< mFileType avio_wb16(pb, 1); //< mFileVersion avio_wb16(pb, 0); //< mFileFlags ffio_wfourcc(pb, "desc"); //< Audio Description chunk avio_wb64(pb, 32); //< mChunkSize avio_wb64(pb, av_double2int(par->sample_rate)); //< mSampleRate avio_wl32(pb, codec_tag); //< mFormatID avio_wb32(pb, codec_flags(par->codec_id)); //< mFormatFlags avio_wb32(pb, par->block_align); //< mBytesPerPacket avio_wb32(pb, frame_size); //< mFramesPerPacket avio_wb32(pb, par->channels); //< mChannelsPerFrame avio_wb32(pb, av_get_bits_per_sample(par->codec_id)); //< mBitsPerChannel if (par->channel_layout) { ffio_wfourcc(pb, "chan"); avio_wb64(pb, 12); ff_mov_write_chan(pb, par->channel_layout); } if (par->codec_id == AV_CODEC_ID_ALAC) { ffio_wfourcc(pb, "kuki"); avio_wb64(pb, 12 + par->extradata_size); avio_write(pb, "\0\0\0\14frmaalac", 12); avio_write(pb, par->extradata, par->extradata_size); } else if (par->codec_id == AV_CODEC_ID_AMR_NB) { ffio_wfourcc(pb, "kuki"); avio_wb64(pb, 29); avio_write(pb, "\0\0\0\14frmasamr", 12); avio_wb32(pb, 0x11); /* size */ avio_write(pb, "samrFFMP", 8); avio_w8(pb, 0); /* decoder version */ avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */ avio_w8(pb, 0x00); /* Mode change period (no restriction) */ avio_w8(pb, 0x01); /* Frames per sample */ } else if (par->codec_id == AV_CODEC_ID_QDM2 || par->codec_id == AV_CODEC_ID_QDMC) { ffio_wfourcc(pb, "kuki"); avio_wb64(pb, par->extradata_size); avio_write(pb, par->extradata, par->extradata_size); } ff_standardize_creation_time(s); if (av_dict_count(s->metadata)) { ffio_wfourcc(pb, "info"); //< Information chunk while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX))) { chunk_size += strlen(t->key) + strlen(t->value) + 2; } avio_wb64(pb, chunk_size + 4); avio_wb32(pb, av_dict_count(s->metadata)); t = NULL; while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX))) { avio_put_str(pb, t->key); avio_put_str(pb, t->value); } } ffio_wfourcc(pb, "data"); //< Audio Data chunk caf->data = avio_tell(pb); avio_wb64(pb, -1); //< mChunkSize avio_wb32(pb, 0); //< mEditCount avio_flush(pb); return 0; } static int caf_write_packet(AVFormatContext *s, AVPacket *pkt) { CAFContext *caf = s->priv_data; avio_write(s->pb, pkt->data, pkt->size); if (!s->streams[0]->codecpar->block_align) { void *pkt_sizes = caf->pkt_sizes; int i, alloc_size = caf->size_entries_used + 5; if (alloc_size < 0) { caf->pkt_sizes = NULL; } else { caf->pkt_sizes = av_fast_realloc(caf->pkt_sizes, &caf->size_buffer_size, alloc_size); } if (!caf->pkt_sizes) { av_free(pkt_sizes); return AVERROR(ENOMEM); } for (i = 4; i > 0; i--) { unsigned top = pkt->size >> i * 7; if (top) caf->pkt_sizes[caf->size_entries_used++] = 128 | top; } caf->pkt_sizes[caf->size_entries_used++] = pkt->size & 127; caf->packets++; } return 0; } static int caf_write_trailer(AVFormatContext *s) { CAFContext *caf = s->priv_data; AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[0]->codecpar; if (pb->seekable & AVIO_SEEKABLE_NORMAL) { int64_t file_size = avio_tell(pb); avio_seek(pb, caf->data, SEEK_SET); avio_wb64(pb, file_size - caf->data - 8); avio_seek(pb, file_size, SEEK_SET); if (!par->block_align) { ffio_wfourcc(pb, "pakt"); avio_wb64(pb, caf->size_entries_used + 24); avio_wb64(pb, caf->packets); ///< mNumberPackets avio_wb64(pb, caf->packets * samples_per_packet(par->codec_id, par->channels, par->block_align)); ///< mNumberValidFrames avio_wb32(pb, 0); ///< mPrimingFrames avio_wb32(pb, 0); ///< mRemainderFrames avio_write(pb, caf->pkt_sizes, caf->size_entries_used); caf->size_buffer_size = 0; } avio_flush(pb); } av_freep(&caf->pkt_sizes); return 0; } AVOutputFormat ff_caf_muxer = { .name = "caf", .long_name = NULL_IF_CONFIG_SMALL("Apple CAF (Core Audio Format)"), .mime_type = "audio/x-caf", .extensions = "caf", .priv_data_size = sizeof(CAFContext), .audio_codec = AV_CODEC_ID_PCM_S16BE, .video_codec = AV_CODEC_ID_NONE, .write_header = caf_write_header, .write_packet = caf_write_packet, .write_trailer = caf_write_trailer, .codec_tag = (const AVCodecTag* const []){ff_codec_caf_tags, 0}, };
/* * reset_pollfunc() gets invoked to poll the interface for completion every 50ms * during an ide reset operation. If the drives have not yet responded, * and we have not yet hit our maximum waiting time, then the timer is restarted * for another 50ms. */ static void reset_pollfunc (ide_drive_t *drive) { ide_hwgroup_t *hwgroup = HWGROUP(drive); ide_hwif_t *hwif = HWIF(drive); byte tmp; if (!OK_STAT(tmp=GET_STAT(), 0, BUSY_STAT)) { if (jiffies < hwgroup->poll_timeout) { ide_set_handler (drive, &reset_pollfunc, HZ/20); return; } printk("%s: reset timed-out, status=0x%02x\n", hwif->name, tmp); } else { printk("%s: reset: ", hwif->name); if ((tmp = GET_ERR()) == 1) printk("success\n"); else { printk("master: "); switch (tmp & 0x7f) { case 1: printk("passed"); break; case 2: printk("formatter device error"); break; case 3: printk("sector buffer error"); break; case 4: printk("ECC circuitry error"); break; case 5: printk("controlling MPU error"); break; default:printk("error (0x%02x?)", tmp); } if (tmp & 0x80) printk("; slave: failed"); printk("\n"); } } hwgroup->poll_timeout = 0; }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef BTRFS_BLOCK_RSV_H #define BTRFS_BLOCK_RSV_H struct btrfs_trans_handle; enum btrfs_reserve_flush_enum; /* * Types of block reserves */ enum { BTRFS_BLOCK_RSV_GLOBAL, BTRFS_BLOCK_RSV_DELALLOC, BTRFS_BLOCK_RSV_TRANS, BTRFS_BLOCK_RSV_CHUNK, BTRFS_BLOCK_RSV_DELOPS, BTRFS_BLOCK_RSV_DELREFS, BTRFS_BLOCK_RSV_EMPTY, BTRFS_BLOCK_RSV_TEMP, }; struct btrfs_block_rsv { u64 size; u64 reserved; struct btrfs_space_info *space_info; spinlock_t lock; unsigned short full; unsigned short type; unsigned short failfast; /* * Qgroup equivalent for @size @reserved * * Unlike normal @size/@reserved for inode rsv, qgroup doesn't care * about things like csum size nor how many tree blocks it will need to * reserve. * * Qgroup cares more about net change of the extent usage. * * So for one newly inserted file extent, in worst case it will cause * leaf split and level increase, nodesize for each file extent is * already too much. * * In short, qgroup_size/reserved is the upper limit of possible needed * qgroup metadata reservation. */ u64 qgroup_rsv_size; u64 qgroup_rsv_reserved; }; void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type); struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info, unsigned short type); void btrfs_init_metadata_block_rsv(struct btrfs_fs_info *fs_info, struct btrfs_block_rsv *rsv, unsigned short type); void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info, struct btrfs_block_rsv *rsv); int btrfs_block_rsv_add(struct btrfs_root *root, struct btrfs_block_rsv *block_rsv, u64 num_bytes, enum btrfs_reserve_flush_enum flush); int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor); int btrfs_block_rsv_refill(struct btrfs_root *root, struct btrfs_block_rsv *block_rsv, u64 min_reserved, enum btrfs_reserve_flush_enum flush); int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv, struct btrfs_block_rsv *dst_rsv, u64 num_bytes, bool update_size); int btrfs_block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv, u64 num_bytes); int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info, struct btrfs_block_rsv *dest, u64 num_bytes, int min_factor); void btrfs_block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv, u64 num_bytes, bool update_size); u64 btrfs_block_rsv_release(struct btrfs_fs_info *fs_info, struct btrfs_block_rsv *block_rsv, u64 num_bytes, u64 *qgroup_to_release); void btrfs_update_global_block_rsv(struct btrfs_fs_info *fs_info); void btrfs_init_global_block_rsv(struct btrfs_fs_info *fs_info); void btrfs_release_global_block_rsv(struct btrfs_fs_info *fs_info); struct btrfs_block_rsv *btrfs_use_block_rsv(struct btrfs_trans_handle *trans, struct btrfs_root *root, u32 blocksize); static inline void btrfs_unuse_block_rsv(struct btrfs_fs_info *fs_info, struct btrfs_block_rsv *block_rsv, u32 blocksize) { btrfs_block_rsv_add_bytes(block_rsv, blocksize, false); btrfs_block_rsv_release(fs_info, block_rsv, 0, NULL); } #endif /* BTRFS_BLOCK_RSV_H */
// Modify the local and global transform of the transformable void Scale2d(float x, float y) { local_transform_.Scale2d(x, y); GlobalScale2d(x, y); }
/** * verify that all file descriptors except those provided as arguments are * closed. * * note: FD_SETSIZE (see select()) is used as maximum number of * open file descriptors even the system may support an higher number * of open files. * * \param fds_allowed_open array of file descriptors that are allowed to be open * \param num_fds number of elements in the \a fds_allowed_open array */ int verify_closed_file_desc( const int *fds_allowed_open, size_t num_fds ) { int i; struct stat statbuf; for (i = 0; i < FD_SETSIZE; ++i) { int allowed_open = 0; int j; for (j = 0; j < (int) num_fds; ++j) { if (i == fds_allowed_open[j]) { allowed_open = 1; break; } } errno = 0; if (!allowed_open) { TRACE2("Checking if file descriptor %d is open ...\n", i); if ((fstat(i, &statbuf) == 0) || (errno != EBADF)) { TRACE("File descriptor %d is open but should be closed\n", i); return 0; } } errno = 0; } return 1; }
/* * Used for clocks that always have value as the parent clock divided by a * fixed divisor */ int follow_parent(struct clk *clk) { unsigned int div_factor = (clk->div_factor < 1) ? 1 : clk->div_factor; clk->rate = clk->pclk->rate/div_factor; return 0; }
/** * xmlCtxtCheckString: * @ctxt: the debug context * @str: the string * * Do debugging on the string, currently it just checks the UTF-8 content */ static void xmlCtxtCheckString(xmlDebugCtxtPtr ctxt, const xmlChar * str) { if (str == NULL) return; if (ctxt->check) { if (!xmlCheckUTF8(str)) { xmlDebugErr3(ctxt, XML_CHECK_NOT_UTF8, "String is not UTF-8 %s", (const char *) str); } } }
/* Generate an arbitrary total ordering on StackBlocks. */ static Word StackBlock__cmp ( const StackBlock* fb1, const StackBlock* fb2 ) { Word r; tl_assert(StackBlock__sane(fb1)); tl_assert(StackBlock__sane(fb2)); if (fb1->base < fb2->base) return -1; if (fb1->base > fb2->base) return 1; if (fb1->szB < fb2->szB) return -1; if (fb1->szB > fb2->szB) return 1; if (fb1->spRel < fb2->spRel) return -1; if (fb1->spRel > fb2->spRel) return 1; if (fb1->isVec < fb2->isVec) return -1; if (fb1->isVec > fb2->isVec) return 1; r = (Word)VG_(strcmp)(fb1->name, fb2->name); return r; }
/* sets hashed_position according to current board position and turn (used for initialization). Uses castling and ep flags from move_flags[current_ply]. */ int generate_hash_value(position_hash_t * h) { plistentry_t *PListPtr, *StopPtr; SET64(*h,0l,0l); PListPtr = PList; StopPtr=PList+PLIST_MAXENTRIES; while(PListPtr != StopPtr) { if(*PListPtr != NO_PIECE) { int color_index = (PListPtr < PList+BPIECE_START_INDEX) ? 0 : 1; assert((GET_PIECE(*PListPtr))-1 < 6); assert(GET_SQUARE(*PListPtr) < 128); XOR64(*h, hash_array64[color_index] [(GET_PIECE(*PListPtr))-1][GET_SQUARE(*PListPtr)]); } ++PListPtr; } if(turn == BLACK) XOR64(*h, ALTER_TURN); if(move_flags[current_ply].castling_flags) { assert(move_flags[current_ply].white_king_square == 0x04 || move_flags[current_ply].black_king_square == 0x74); if(move_flags[current_ply].castling_flags & WHITE_SHORT) XOR64( *h , CASTLING_HASH_WS); if(move_flags[current_ply].castling_flags & WHITE_LONG) XOR64( *h , CASTLING_HASH_WL); if(move_flags[current_ply].castling_flags & BLACK_SHORT) XOR64( *h , CASTLING_HASH_BS); if(move_flags[current_ply].castling_flags & BLACK_LONG) XOR64( *h , CASTLING_HASH_BL); } if(move_flags[current_ply].e_p_square) XOR64( *h , EP_HASHVAL(move_flags[current_ply].e_p_square)); return 1; }
/* Whether the quene array is empty (all element are zero) or not. */ bool queneEmpty(int quene[], int size){ for (int i = 0; i < size; ++i) if (quene[i] != 0) return false; return true; }
/* ffi.dlopen() interface with dlopen()/dlsym()/dlclose() */ static void *cdlopen_fetch(PyObject *libname, void *libhandle, const char *symbol) { void *address; if (libhandle == NULL) { PyErr_Format(FFIError, "library '%s' has been closed", PyText_AS_UTF8(libname)); return NULL; } dlerror(); /* clear error condition */ address = dlsym(libhandle, symbol); if (address == NULL) { const char *error = dlerror(); PyErr_Format(FFIError, "symbol '%s' not found in library '%s': %s", symbol, PyText_AS_UTF8(libname), error); } return address; } static void cdlopen_close_ignore_errors(void *libhandle) { if (libhandle != NULL) dlclose(libhandle); } static int cdlopen_close(PyObject *libname, void *libhandle) { if (libhandle != NULL && dlclose(libhandle) != 0) { const char *error = dlerror(); PyErr_Format(FFIError, "closing library '%s': %s", PyText_AS_UTF8(libname), error); return -1; } return 0; } static PyObject *ffi_dlopen(PyObject *self, PyObject *args) { const char *modname; PyObject *temp, *result = NULL; void *handle; int auto_close; handle = b_do_dlopen(args, &modname, &temp, &auto_close); if (handle != NULL) { result = (PyObject *)lib_internal_new((FFIObject *)self, modname, handle, auto_close); } Py_XDECREF(temp); return result; } static PyObject *ffi_dlclose(PyObject *self, PyObject *args) { LibObject *lib; void *libhandle; if (!PyArg_ParseTuple(args, "O!", &Lib_Type, &lib)) return NULL; libhandle = lib->l_libhandle; if (libhandle != NULL) { lib->l_libhandle = NULL; /* Clear the dict to force further accesses to do cdlopen_fetch() again, and fail because the library was closed. */ PyDict_Clear(lib->l_dict); if (cdlopen_close(lib->l_libname, libhandle) < 0) return NULL; } Py_INCREF(Py_None); return Py_None; } static Py_ssize_t cdl_4bytes(char *src) { /* read 4 bytes in little-endian order; return it as a signed integer */ signed char *ssrc = (signed char *)src; unsigned char *usrc = (unsigned char *)src; return (ssrc[0] << 24) | (usrc[1] << 16) | (usrc[2] << 8) | usrc[3]; } static _cffi_opcode_t cdl_opcode(char *src) { return (_cffi_opcode_t)cdl_4bytes(src); } typedef struct { unsigned long long value; int neg; } cdl_intconst_t; static int _cdl_realize_global_int(struct _cffi_getconst_s *gc) { /* The 'address' field of 'struct _cffi_global_s' is set to point to this function in case ffiobj_init() sees constant integers. This fishes around after the 'ctx->globals' array, which is initialized to contain another array, this time of 'cdl_intconst_t' structures. We get the nth one and it tells us what to return. */ cdl_intconst_t *ic; ic = (cdl_intconst_t *)(gc->ctx->globals + gc->ctx->num_globals); ic += gc->gindex; gc->value = ic->value; return ic->neg; } static int ffiobj_init(PyObject *self, PyObject *args, PyObject *kwds) { FFIObject *ffi; static char *keywords[] = {"module_name", "_version", "_types", "_globals", "_struct_unions", "_enums", "_typenames", "_includes", NULL}; char *ffiname = "?", *types = NULL, *building = NULL; Py_ssize_t version = -1; Py_ssize_t types_len = 0; PyObject *globals = NULL, *struct_unions = NULL, *enums = NULL; PyObject *typenames = NULL, *includes = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|sns#O!O!O!O!O!:FFI", keywords, &ffiname, &version, &types, &types_len, &PyTuple_Type, &globals, &PyTuple_Type, &struct_unions, &PyTuple_Type, &enums, &PyTuple_Type, &typenames, &PyTuple_Type, &includes)) return -1; ffi = (FFIObject *)self; if (ffi->ctx_is_nonempty) { PyErr_SetString(PyExc_ValueError, "cannot call FFI.__init__() more than once"); return -1; } ffi->ctx_is_nonempty = 1; if (version == -1 && types_len == 0) return 0; if (version < CFFI_VERSION_MIN || version > CFFI_VERSION_MAX) { PyErr_Format(PyExc_ImportError, "cffi out-of-line Python module '%s' has unknown " "version %p", ffiname, (void *)version); return -1; } if (types_len > 0) { /* unpack a string of 4-byte entries into an array of _cffi_opcode_t */ _cffi_opcode_t *ntypes; Py_ssize_t i, n = types_len / 4; building = PyMem_Malloc(n * sizeof(_cffi_opcode_t)); if (building == NULL) goto error; ntypes = (_cffi_opcode_t *)building; for (i = 0; i < n; i++) { ntypes[i] = cdl_opcode(types); types += 4; } ffi->types_builder.ctx.types = ntypes; ffi->types_builder.ctx.num_types = n; building = NULL; } if (globals != NULL) { /* unpack a tuple alternating strings and ints, each two together describing one global_s entry with no specified address or size. The int is only used with integer constants. */ struct _cffi_global_s *nglobs; cdl_intconst_t *nintconsts; Py_ssize_t i, n = PyTuple_GET_SIZE(globals) / 2; i = n * (sizeof(struct _cffi_global_s) + sizeof(cdl_intconst_t)); building = PyMem_Malloc(i); if (building == NULL) goto error; memset(building, 0, i); nglobs = (struct _cffi_global_s *)building; nintconsts = (cdl_intconst_t *)(nglobs + n); for (i = 0; i < n; i++) { char *g = PyBytes_AS_STRING(PyTuple_GET_ITEM(globals, i * 2)); nglobs[i].type_op = cdl_opcode(g); g += 4; nglobs[i].name = g; if (_CFFI_GETOP(nglobs[i].type_op) == _CFFI_OP_CONSTANT_INT || _CFFI_GETOP(nglobs[i].type_op) == _CFFI_OP_ENUM) { PyObject *o = PyTuple_GET_ITEM(globals, i * 2 + 1); nglobs[i].address = &_cdl_realize_global_int; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(o)) { nintconsts[i].neg = PyInt_AS_LONG(o) <= 0; nintconsts[i].value = (long long)PyInt_AS_LONG(o); } else #endif { nintconsts[i].neg = PyObject_RichCompareBool(o, Py_False, Py_LE); nintconsts[i].value = PyLong_AsUnsignedLongLongMask(o); if (PyErr_Occurred()) goto error; } } } ffi->types_builder.ctx.globals = nglobs; ffi->types_builder.ctx.num_globals = n; building = NULL; } if (struct_unions != NULL) { /* unpack a tuple of struct/unions, each described as a sub-tuple; the item 0 of each sub-tuple describes the struct/union, and the items 1..N-1 describe the fields, if any */ struct _cffi_struct_union_s *nstructs; struct _cffi_field_s *nfields; Py_ssize_t i, n = PyTuple_GET_SIZE(struct_unions); Py_ssize_t nf = 0; /* total number of fields */ for (i = 0; i < n; i++) { nf += PyTuple_GET_SIZE(PyTuple_GET_ITEM(struct_unions, i)) - 1; } i = (n * sizeof(struct _cffi_struct_union_s) + nf * sizeof(struct _cffi_field_s)); building = PyMem_Malloc(i); if (building == NULL) goto error; memset(building, 0, i); nstructs = (struct _cffi_struct_union_s *)building; nfields = (struct _cffi_field_s *)(nstructs + n); nf = 0; for (i = 0; i < n; i++) { /* 'desc' is the tuple of strings (desc_struct, desc_field_1, ..) */ PyObject *desc = PyTuple_GET_ITEM(struct_unions, i); Py_ssize_t j, nf1 = PyTuple_GET_SIZE(desc) - 1; char *s = PyBytes_AS_STRING(PyTuple_GET_ITEM(desc, 0)); /* 's' is the first string, describing the struct/union */ nstructs[i].type_index = cdl_4bytes(s); s += 4; nstructs[i].flags = cdl_4bytes(s); s += 4; nstructs[i].name = s; if (nstructs[i].flags & (_CFFI_F_OPAQUE | _CFFI_F_EXTERNAL)) { nstructs[i].size = (size_t)-1; nstructs[i].alignment = -1; nstructs[i].first_field_index = -1; nstructs[i].num_fields = 0; assert(nf1 == 0); } else { nstructs[i].size = (size_t)-2; nstructs[i].alignment = -2; nstructs[i].first_field_index = nf; nstructs[i].num_fields = nf1; } for (j = 0; j < nf1; j++) { char *f = PyBytes_AS_STRING(PyTuple_GET_ITEM(desc, j + 1)); /* 'f' is one of the other strings beyond the first one, describing one field each */ nfields[nf].field_type_op = cdl_opcode(f); f += 4; nfields[nf].field_offset = (size_t)-1; if (_CFFI_GETOP(nfields[nf].field_type_op) != _CFFI_OP_NOOP) { nfields[nf].field_size = cdl_4bytes(f); f += 4; } else { nfields[nf].field_size = (size_t)-1; } nfields[nf].name = f; nf++; } } ffi->types_builder.ctx.struct_unions = nstructs; ffi->types_builder.ctx.fields = nfields; ffi->types_builder.ctx.num_struct_unions = n; building = NULL; } if (enums != NULL) { /* unpack a tuple of strings, each of which describes one enum_s entry */ struct _cffi_enum_s *nenums; Py_ssize_t i, n = PyTuple_GET_SIZE(enums); i = n * sizeof(struct _cffi_enum_s); building = PyMem_Malloc(i); if (building == NULL) goto error; memset(building, 0, i); nenums = (struct _cffi_enum_s *)building; for (i = 0; i < n; i++) { char *e = PyBytes_AS_STRING(PyTuple_GET_ITEM(enums, i)); /* 'e' is a string describing the enum */ nenums[i].type_index = cdl_4bytes(e); e += 4; nenums[i].type_prim = cdl_4bytes(e); e += 4; nenums[i].name = e; e += strlen(e) + 1; nenums[i].enumerators = e; } ffi->types_builder.ctx.enums = nenums; ffi->types_builder.ctx.num_enums = n; building = NULL; } if (typenames != NULL) { /* unpack a tuple of strings, each of which describes one typename_s entry */ struct _cffi_typename_s *ntypenames; Py_ssize_t i, n = PyTuple_GET_SIZE(typenames); i = n * sizeof(struct _cffi_typename_s); building = PyMem_Malloc(i); if (building == NULL) goto error; memset(building, 0, i); ntypenames = (struct _cffi_typename_s *)building; for (i = 0; i < n; i++) { char *t = PyBytes_AS_STRING(PyTuple_GET_ITEM(typenames, i)); /* 't' is a string describing the typename */ ntypenames[i].type_index = cdl_4bytes(t); t += 4; ntypenames[i].name = t; } ffi->types_builder.ctx.typenames = ntypenames; ffi->types_builder.ctx.num_typenames = n; building = NULL; } if (includes != NULL) { PyObject *included_libs; included_libs = PyTuple_New(PyTuple_GET_SIZE(includes)); if (included_libs == NULL) return -1; Py_INCREF(includes); ffi->types_builder.included_ffis = includes; ffi->types_builder.included_libs = included_libs; } /* Above, we took directly some "char *" strings out of the strings, typically from somewhere inside tuples. Keep them alive by incref'ing the whole input arguments. */ Py_INCREF(args); Py_XINCREF(kwds); ffi->types_builder._keepalive1 = args; ffi->types_builder._keepalive2 = kwds; return 0; error: if (building != NULL) PyMem_Free(building); if (!PyErr_Occurred()) PyErr_NoMemory(); return -1; }
/* Dump pointer PTR using FIELD to identify it. */ void dump_pointer (dump_info_p di, const char *field, void *ptr) { dump_maybe_newline (di); fprintf (di->stream, "%-4s: %-8lx ", field, (long) ptr); di->column += 15; }
/* * Helper function to remove all files created by create_temp_file(). * This is intended to be called only once at end of program execution. */ static void updater_remove_all_temp_files(struct updater_config *cfg) { struct tempfile *tempfiles = cfg->tempfiles; while (tempfiles != NULL) { struct tempfile *target = tempfiles; VB2_DEBUG("Remove temporary file: %s.\n", target->filepath); remove(target->filepath); free(target->filepath); tempfiles = target->next; free(target); } cfg->tempfiles = NULL; }
/* * Sleepable Read-Copy Update mechanism for mutual exclusion, * tiny variant. * * 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, you can access it online at * http://www.gnu.org/licenses/gpl-2.0.html. * * Copyright (C) IBM Corporation, 2017 * * Author: Paul McKenney <paulmck@us.ibm.com> */ #ifndef _LINUX_SRCU_TINY_H #define _LINUX_SRCU_TINY_H #include <linux/swait.h> struct srcu_struct { short srcu_lock_nesting[2]; /* srcu_read_lock() nesting depth. */ short srcu_idx; /* Current reader array element. */ u8 srcu_gp_running; /* GP workqueue running? */ u8 srcu_gp_waiting; /* GP waiting for readers? */ struct swait_queue_head srcu_wq; /* Last srcu_read_unlock() wakes GP. */ struct rcu_head *srcu_cb_head; /* Pending callbacks: Head. */ struct rcu_head **srcu_cb_tail; /* Pending callbacks: Tail. */ struct work_struct srcu_work; /* For driving grace periods. */ #ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map dep_map; #endif /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */ }; void srcu_drive_gp(struct work_struct *wp); #define __SRCU_STRUCT_INIT(name) \ { \ .srcu_wq = __SWAIT_QUEUE_HEAD_INITIALIZER(name.srcu_wq), \ .srcu_cb_tail = &name.srcu_cb_head, \ .srcu_work = __WORK_INITIALIZER(name.srcu_work, srcu_drive_gp), \ __SRCU_DEP_MAP_INIT(name) \ } /* * This odd _STATIC_ arrangement is needed for API compatibility with * Tree SRCU, which needs some per-CPU data. */ #define DEFINE_SRCU(name) \ struct srcu_struct name = __SRCU_STRUCT_INIT(name) #define DEFINE_STATIC_SRCU(name) \ static struct srcu_struct name = __SRCU_STRUCT_INIT(name) void synchronize_srcu(struct srcu_struct *sp); /* * Counts the new reader in the appropriate per-CPU element of the * srcu_struct. Can be invoked from irq/bh handlers, but the matching * __srcu_read_unlock() must be in the same handler instance. Returns an * index that must be passed to the matching srcu_read_unlock(). */ static inline int __srcu_read_lock(struct srcu_struct *sp) { int idx; idx = READ_ONCE(sp->srcu_idx); WRITE_ONCE(sp->srcu_lock_nesting[idx], sp->srcu_lock_nesting[idx] + 1); return idx; } static inline void synchronize_srcu_expedited(struct srcu_struct *sp) { synchronize_srcu(sp); } static inline void srcu_barrier(struct srcu_struct *sp) { synchronize_srcu(sp); } #endif
//* CheckReassemblyQuota // // Delete reassembly record if necessary, // to keep the reassembly buffering under quota. // // Callable from DPC context, not from thread context. // Called with the reassembly record lock held, // but not the global reassembly list lock. // void CheckReassemblyQuota(Reassembly *Reass) { int Prune = FALSE; uint Threshold = ReassemblyList.Limit / 2; KeAcquireSpinLockAtDpcLevel(&ReassemblyList.LockSize); if ((ReassemblyList.Size > Threshold) && (RandomNumber(0, Threshold) < ReassemblyList.Size - Threshold)) Prune = TRUE; KeReleaseSpinLockFromDpcLevel(&ReassemblyList.LockSize); if (Prune) { #if DBG char Buffer1[INET6_ADDRSTRLEN], Buffer2[INET6_ADDRSTRLEN]; FormatV6AddressWorker(Buffer1, &Reass->IPHdr.Source); FormatV6AddressWorker(Buffer2, &Reass->IPHdr.Dest); KdPrintEx((DPFLTR_TCPIP6_ID, DPFLTR_NET_ERROR, "CheckReassemblyQuota: Src %s Dst %s Id %x\n", Buffer1, Buffer2, Reass->Id)); #endif DeleteFromReassemblyList(Reass); } else KeReleaseSpinLockFromDpcLevel(&Reass->Lock); }
/** * Copyright (c) 2019-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #ifndef _WIN32 #include <unistd.h> #endif #include <memory> #include <thread> namespace gloo { // The lifecycle of the unbound buffer is controlled by the user. // It may be constructed as value or unique_ptr and destructed when // going out of scope or when unwinding the stack. // // For example: // // { // int i = 0; // auto buf = context->createUnboundBuffer(&i, sizeof(i)); // buf->send(1, 0); // ... // throw std::runtime_error("Something happened!"); // ... // buf->waitSend(); // } // // // At this point, if `waitSend` was not yet called, the I/O // // thread executing the send operation may still call into it. // // The unbound buffer will have been destructed already, // // so we need to make sure the reference gets invalidated. // // If upon destruction there are pending operations (e.g. a recv // operation timed out), there will be references to this unbound // buffer in the `transport::Pair` instances that could fulfill the // operation. To avoid these pairs calling into the unbound buffer // after it is destructed, we must ensure that these references are // invalidated before the destructor returns. Also, if destruction of // the unbound buffer races with the recv operation completing after // all, we must block the destructor and wait for the operation to // finish. Otherwise, we risk the device thread writing to memory it's // not supposed to. // // We solve this by using a shared_ptr of the "this" pointer of the // unbound buffer. This doesn't magically convert the unbound buffer // to be a shared_ptr, but it allows for handing out weak_ptr // instances to refer to it. Then, whenever the unbound buffer is // used by another thread, it converts the weak_ptr into a shared_ptr // and uses it for a very short period of time. The wrapper class below // waits for all shared_ptr instances to be released before returning // from its destructor. This will block indefinitely if the shared_ptr // acquired from the weak_ptr stays alive. // // Forward definitions. template <typename T> class WeakNonOwningPtr; template <typename T> class ShareableNonOwningPtr; // NonOwningPtr is constructed from a WeakNonOwningPtr, if and // only if the underlying object is still alive. If it is, destruction // of the underlying object is blocked until the NonOwningPtr // is destructed. It boxes a shared_ptr instead of being typedef'd as // one to prevent misuse (e.g. extending its lifetime). template <typename T> class NonOwningPtr final { public: NonOwningPtr() {} explicit NonOwningPtr(const WeakNonOwningPtr<T>& ptr) : ptr_(ptr.ptr_.lock()) {} T* operator->() const noexcept { return ptr_.get(); } explicit operator bool() const noexcept { return (bool)ptr_; } private: std::shared_ptr<T> ptr_; }; // WeakNonOwningPtr can be constructed from a ShareableNonOwningPtr. // It can instantiate a NonOwningPtr if and only if the // underlying object is still alive. It boxes a weak_ptr instead of // being typedef'd as one because it must instantiate the // NonOwningPtr type instead of a raw shared_ptr. template <typename T> class WeakNonOwningPtr final { public: WeakNonOwningPtr() {} explicit WeakNonOwningPtr(const ShareableNonOwningPtr<T>& ref) : ptr_(ref.ptr_) {} // Returns true if the instance was initialized. explicit operator bool() const noexcept { // Per std::weak_ptr::owner_before, "[...] two smart pointers // compare equivalent only if they are both empty or if they both // own the same object [...]". Therefore, if owner_before is true // in either direction w.r.t. an empty weak_ptr, the instance was // initialized. return ptr_.owner_before(std::weak_ptr<T>{}) || std::weak_ptr<T>{}.owner_before(ptr_); } protected: std::weak_ptr<T> ptr_; friend class NonOwningPtr<T>; }; // ShareableNonOwningPtr is the root reference to the this pointer. It // can instantiate WeakNonOwningPtr instances. The destructor blocks // until all NonOwningPtr instances have been destroyed. This // guarantees that the object it refers to has no other active // references (it may have weak ones) and can safely be destructed. template <typename T> class ShareableNonOwningPtr final { public: // Initializes private shared_ptr with nop deallocation function. explicit ShareableNonOwningPtr(T* t) : ptr_(t, [](void* ptr) {}) {} // Disable copy constructors. ShareableNonOwningPtr(const ShareableNonOwningPtr&) = delete; ShareableNonOwningPtr& operator=(ShareableNonOwningPtr const&) = delete; ~ShareableNonOwningPtr() { // Acquire weak_ptr to T auto weak = std::weak_ptr<T>(ptr_); // Release shared_ptr to T ptr_.reset(); // Wait for all shared_ptr's to T have been released while (!weak.expired()) { std::this_thread::yield(); } } protected: std::shared_ptr<T> ptr_; friend class WeakNonOwningPtr<T>; }; } // namespace gloo
// Removes the i'th element without deleting it even if T is a // pointer type; moves all elements above i "down". Returns the // removed element. This function's complexity is linear in the // size of the list. T Remove(int i) { T element = at(i); length_--; while (i < length_) { data_[i] = data_[i + 1]; i++; } return element; }
/* boot_addr:flashboot bin addr without ota head. boot_len: total len. */ hi_u32 upg_check_encrpt_boot_code(hi_u32 boot_addr, hi_u32 boot_len, hi_u8 *key_part1, hi_u8 *key_part2) { upg_print("[upg check encrpt boot]addr-len:0x%x-0x%x \r\n", boot_addr, boot_len); hi_u8 *boot = hi_malloc(HI_MOD_ID_UPG, boot_len); if (boot == HI_NULL) { upg_print("[upg check encrpt boot]malloc fail,boot_len:0x%x \r\n", boot_len); return HI_ERR_UPG_MALLOC_FAIL; } hi_u32 ret = hi_flash_read(boot_addr, boot_len, boot); if (ret != HI_ERR_SUCCESS) { upg_print("[upg check encrpt boot]flash read err:0x%x \r\n", ret); goto end; } ret = upg_boot_decrypt(boot, boot_len); if (ret != HI_ERR_SUCCESS) { upg_print("[upg check encrpt boot]decrypt ret:0x%x \r\n", ret); goto end; } ret = upg_check_boot_from_mem(boot, boot_len, key_part1, key_part2); end: upg_mem_free(boot); return ret; }
/* Return the number of digits in a number of the given base or more, i.e. the * string length without sign and null terminator. * * Current implementation for small representation returns the maximal number * of binary digits in that representation, which can be much larger than the * smallest possible solution. */ inline size_t isl_sioimath_sizeinbase(isl_sioimath_src arg, int base) { int32_t small; if (isl_sioimath_decode_small(arg, &small)) return sizeof(int32_t) * CHAR_BIT - 1; return impz_sizeinbase(isl_sioimath_get_big(arg), base); }
/* *----------------------------------------------------------------------------- * * VixPropertyList_NumItems -- * * Returns a count of the properties in the list. * * Results: * int - Number of properties in property list. * * Side effects: * None. * *----------------------------------------------------------------------------- */ int VixPropertyList_NumItems(VixPropertyListImpl *propList) { VixPropertyValue *prop; int count = 0; if (propList == NULL) { return 0; } for (prop = propList->properties; prop != NULL; prop = prop->next) { ++count; } return count; }
/* * CreatePortal -- * Returns a new portal given a name. * * Note: * This is expected to be of very limited usability. See instead, * BlankPortalAssignName. * * Exceptions: * BadState if called when disabled. * BadArg if portal name is invalid. * "WARN" if portal name is in use. */ Portal CreatePortal(char *name) { Portal portal; uint16 length; AssertState(PortalManagerEnabled); AssertArg(PointerIsValid(name)); portal = GetPortalByName(name); if (PortalIsValid(portal)) { elog(NOTICE, "CreatePortal: portal %s already exists", name); return (portal); } portal = (Portal) MemoryContextAlloc((MemoryContext)PortalMemory, sizeof *portal); NodeSetTag((Node*)&portal->variable, T_PortalVariableMemory); AllocSetInit(&portal->variable.setData, DynamicAllocMode, (Size)0); portal->variable.method = &PortalVariableContextMethodsData; NodeSetTag((Node*)&portal->heap, T_PortalHeapMemory); portal->heap.block = NULL; FixedStackInit(&portal->heap.stackData, offsetof (HeapMemoryBlockData, itemData)); portal->heap.method = &PortalHeapContextMethodsData; length = 1 + strlen(name); portal->name = (char*) MemoryContextAlloc((MemoryContext)&portal->variable, length); strncpy(portal->name, name, length); portal->queryDesc = NULL; portal->attinfo = NULL; portal->state = NULL; portal->cleanup = NULL; PortalHashTableInsert(portal); return (portal); }
/*! **************************************************************************** * @brief Function for handling the data from the Custom Service1. * * @details This function processes the data received from the Custom Service1 * * @param[in] p_evt CUS1 event. ******************************************************************************/ static void cus1_evt_handler(ble_cus1_evt_t *p_evt) { uint32_t err_code; uint8_t status; if (p_evt->evt_type == BLE_CUS1_EVT_NOTIFICATION_ENABLED) { NRF_LOG_INFO("Received enab ECG Raw Sample Service"); gn_ble_ecg_raw_samp_service_sensor_enab = 1; adi_osal_ThreadResumeFromISR(gh_ble_services_sensor_task_handler); } else if (p_evt->evt_type == BLE_CUS1_EVT_NOTIFICATION_DISABLED) { NRF_LOG_INFO("Received disab ECG Raw Sample Service"); gn_ble_ecg_raw_samp_service_sensor_enab = 0; adi_osal_ThreadResumeFromISR(gh_ble_services_sensor_task_handler); } }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* Programmer: Quincey Koziol <koziol@hdfgoup.org> * Tuesday, July 27, 2010 * * Purpose: ID testing functions. */ /****************/ /* Module Setup */ /****************/ #define H5I_PACKAGE /*suppress error about including H5Ipkg */ #define H5I_TESTING /*suppress warning about H5I testing funcs*/ /***********/ /* Headers */ /***********/ #include "H5private.h" /* Generic Functions */ #include "H5ACprivate.h" /* Metadata cache */ #include "H5Eprivate.h" /* Error handling */ #include "H5Gprivate.h" /* Groups */ #include "H5Ipkg.h" /* IDs */ /****************/ /* Local Macros */ /****************/ /******************/ /* Local Typedefs */ /******************/ /********************/ /* Local Prototypes */ /********************/ /*********************/ /* Package Variables */ /*********************/ /*******************/ /* Local Variables */ /*******************/ /*------------------------------------------------------------------------- * Function: H5I_get_name_test * * Purpose: Testing version of H5Iget_name() * * Return: Success: The length of name. * Failure: -1 * * Programmer: Quincey Koziol * Tuesday, July 27, 2010 * *------------------------------------------------------------------------- */ ssize_t H5I_get_name_test(hid_t id, char *name/*out*/, size_t size, hbool_t *cached) { H5G_loc_t loc; /* Object location */ ssize_t ret_value; /* Return value */ FUNC_ENTER_NOAPI(FAIL) /* Get object location */ if(H5G_loc(id, &loc) < 0) HGOTO_ERROR(H5E_ATOM, H5E_CANTGET, FAIL, "can't retrieve object location") /* Call internal group routine to retrieve object's name */ if((ret_value = H5G_get_name(&loc, name, size, cached, H5P_DEFAULT, H5AC_ind_dxpl_id)) < 0) HGOTO_ERROR(H5E_ATOM, H5E_CANTGET, FAIL, "can't retrieve object name") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5I_get_name_test() */
#include <stdio.h> int change_stn(char *string) { if (*string == 'A'){ string++; if (*string == '\0') return (0); return (2); } else if (*string == 'B') return (1); else return (3); } int main(void) { int list[4] = { 0 }; char *rp; char tmp_in[100]; while (scanf("%s", &tmp_in) != EOF){ rp = tmp_in + 1; while (*rp++ != ','); list[change_stn(rp)]++; } printf("%d\n%d\n%d\n%d\n", list[0], list[1], list[2], list[3]); return (0); }
/** \brief Resolve forward references: try to find the declaration symbol and replace the reference symbol with it. F95 allows forward references to pure functions from within specification expressions. A symbol will be created at the reference which must be fixed later after the function declaration has been seen. Possible forward references are marked FWDREF in mkvarref() above. */ void resolve_fwd_refs() { int ref, mod, decl, hashlk; for (ref = stb.firstusym; ref < stb.stg_avail; ref++) { if (STYPEG(ref) == ST_PROC && FWDREFG(ref)) { for (mod = SCOPEG(ref); mod; mod = SCOPEG(mod)) if (STYPEG(mod) == ST_MODULE) break; if (mod == 0) continue; for (decl = first_hash(ref); decl; decl = HASHLKG(decl)) { if (NMPTRG(decl) != NMPTRG(ref)) continue; if (STYPEG(decl) == ST_PROC && ENCLFUNCG(decl) == mod) { hashlk = HASHLKG(ref); *(stb.stg_base + ref) = *(stb.stg_base + decl); HASHLKP(ref, hashlk); break; } } } } }
// BOOL sessClientListed(PSESS pSess, PLINKSEQ plsHostList) // // Returns TRUE if client's address (IP/host name) listed in plsHostList. // plsHostList is an object of configuration. BOOL sessClientListed(PSESS pSess, PLINKSEQ plsHostList) { if ( pSess->pszHostName == NULL ) return cfgHostListCheckIP( plsHostList, pSess->stInAddr, NULL ); return cfgHostListCheck( plsHostList, pSess->stInAddr, strlen( pSess->pszHostName ), pSess->pszHostName, NULL ); }
#ifndef SimGeneral_MixingModule_Adjuster_h #define SimGeneral_MixingModule_Adjuster_h #include "DataFormats/Common/interface/Wrapper.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventPrincipal.h" #include "FWCore/Utilities/interface/EDGetToken.h" #include "FWCore/Utilities/interface/InputTag.h" #include "SimDataFormats/CaloHit/interface/PCaloHitContainer.h" #include "SimDataFormats/Track/interface/SimTrackContainer.h" #include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h" #include "SimDataFormats/Vertex/interface/SimVertexContainer.h" #include "DataFormats/TrackingRecHit/interface/TrackingRecHitFwd.h" #include <memory> #include <vector> #include <string> #include <iostream> class FastTrackerRecHit; namespace edm { class ModuleCallingContext; class AdjusterBase { public: virtual ~AdjusterBase() {} virtual void doOffset(int bunchspace, int bcr, const edm::EventPrincipal&, ModuleCallingContext const*, unsigned int EventNr, int vertexOffset) = 0; virtual bool checkSignal(edm::Event const& event) = 0; }; template <typename T> class Adjuster : public AdjusterBase { public: Adjuster(InputTag const& tag, edm::ConsumesCollector&& iC, bool wrap); ~Adjuster() override {} void doOffset(int bunchspace, int bcr, const edm::EventPrincipal&, ModuleCallingContext const*, unsigned int EventNr, int vertexOffset) override; bool checkSignal(edm::Event const& event) override { bool got = false; edm::Handle<T> result_t; got = event.getByToken(token_, result_t); return got; } private: InputTag tag_; bool WrapT_ = false; EDGetTokenT<T> token_; }; //============================================================================== // implementations //============================================================================== namespace detail { void doTheOffset(int bunchspace, int bcr, std::vector<SimTrack>& product, unsigned int eventNr, int vertexOffset, bool wraptimes); void doTheOffset(int bunchspace, int bcr, std::vector<SimVertex>& product, unsigned int eventNr, int vertexOffset, bool wraptimes); void doTheOffset(int bunchspace, int bcr, std::vector<PCaloHit>& product, unsigned int eventNr, int vertexOffset, bool wraptimes); void doTheOffset( int bunchspace, int bcr, std::vector<PSimHit>& product, unsigned int eventNr, int vertexOffset, bool wraptimes); void doTheOffset(int bunchspace, int bcr, TrackingRecHitCollection& product, unsigned int eventNr, int vertexOffset, bool wraptimes); } // namespace detail template <typename T> void Adjuster<T>::doOffset(int bunchspace, int bcr, const EventPrincipal& ep, ModuleCallingContext const* mcc, unsigned int eventNr, int vertexOffset) { std::shared_ptr<Wrapper<T> const> shPtr = getProductByTag<T>(ep, tag_, mcc); if (shPtr) { T& product = const_cast<T&>(*shPtr->product()); detail::doTheOffset(bunchspace, bcr, product, eventNr, vertexOffset, WrapT_); } } template <typename T> Adjuster<T>::Adjuster(InputTag const& tag, ConsumesCollector&& iC, bool wrapLongTimes) : tag_(tag), token_(iC.consumes<T>(tag)) { if (wrapLongTimes) { std::string Musearch = tag_.instance(); if (Musearch.find("Muon") == 0) WrapT_ = true; // wrap time for neutrons in Muon system subdetectors } } } // namespace edm #endif
#include<stdio.h> int main(){ int flag=0; int i=0; int j=0; int N; scanf("%d",&N); int s[N]; for(i; i<N; i++){ scanf("%d",&s[i]); if( s[i] != i+1 ){ flag =flag+1; } } // for( j; j<N-1; j++ ){ // if( (s[j]+1) == s[j+1] ){ // ; // }else{ // flag = flag+1; // } // } if( flag<=2 ){ printf("YES"); }else{ printf("NO"); } return 0; }
/* * set the max packed value of all endpoints in the given configuration */ static int usb_set_maxpacket(struct usb_device *dev) { int i, ii; for (i = 0; i < dev->config.desc.bNumInterfaces; i++) for (ii = 0; ii < dev->config.if_desc[i].desc.bNumEndpoints; ii++) usb_set_maxpacket_ep(dev, i, ii); return 0; }
/** For specified alignment properties, compute the blastn word size * that will cause random alignments with those properties to be * found with specified (high) probability. * @param m Space for the Markov chain calculation [in][out] * @param min_percent_identity How much identity is expected in * random alignments [in] * @param min_align_length The smallest alignment length desired [in] * @return The optimal word size, or zero if the optimization * process failed */ static Int4 s_FindWordSize(MatrixData *m, double min_percent_identity, Int4 min_align_length) { const double k_min_w = 4; const double k_max_w = 110; double w0, p0; double w1, p1; w1 = 28.0; if (s_FindHitProbability(m, (Int4)(w1 + 0.5), min_percent_identity, min_align_length) != 0) { return 0; } p1 = m->hit_probability - TARGET_HIT_PROB; w0 = 11.0; if (s_FindHitProbability(m, (Int4)(w0 + 0.5), min_percent_identity, min_align_length) != 0) { return 0; } p0 = m->hit_probability - TARGET_HIT_PROB; if (p1 > 0) { while (p1 > 0 && w1 < k_max_w) { w0 = w1; p0 = p1; w1 = MIN(2 * w1, k_max_w); if (s_FindHitProbability(m, (Int4)(w1 + 0.5), min_percent_identity, min_align_length) != 0) { return 0; } p1 = m->hit_probability - TARGET_HIT_PROB; } if (p1 > 0) return (Int4)(w1 + 0.5); } else if (p0 < 0) { w1 = w0; p1 = p0; w0 = k_min_w; if (s_FindHitProbability(m, (Int4)(w0 + 0.5), min_percent_identity, min_align_length) != 0) { return 0; } p0 = m->hit_probability - TARGET_HIT_PROB; if (p0 < 0) return (Int4)(w0 + 0.5); } while (fabs(w1 - w0) > 1) { double p2, w2 = (w0 + w1) / 2; if (s_FindHitProbability(m, (Int4)(w2 + 0.5), min_percent_identity, min_align_length) != 0) { return 0; } p2 = m->hit_probability - TARGET_HIT_PROB; if (p2 > 0.0) { w0 = w2; p0 = p2; } else { w1 = w2; p1 = p2; } } return (Int4)(w0 + 0.5); }
/* Returns whether the sentence receiver agreed/believed your statement - updated their fact dict with it's contents. */ bool ToldIfFeelingWell(ACharacter* personMakingStatement) { return false; }
//Simple, not bad and repeatable RNG from Marsaglia, George (July 2003) uint32_t xor128u() { static uint32_t x = 123456789; static uint32_t y = 362436069; static uint32_t z = 521288629; static uint32_t w = 88675123; uint32_t t; t = x ^ (x << 11); x = y; y = z; z = w; w = w ^ (w >> 19) ^ (t ^ (t >> 8)); return w; }
// FCBOpenIn workspace at ws+3280 length ws+17 void f52_FCBOpenIn(i1* p912 , i8 p913 , i8 p914 ) { *(i8*)(intptr_t)(ws+3280) = p914; *(i8*)(intptr_t)(ws+3288) = p913; i8 v915 = (i8)(intptr_t)(ws+3280); i8 v916 = *(i8*)(intptr_t)v915; i8 v917 = (i8)(intptr_t)(ws+3288); i8 v918 = *(i8*)(intptr_t)v917; i4 v919 = (i4)+0; i8 v920 = (i8)(intptr_t)(f51_fcb_i_open); i1 v921; ((void(*)(i1* , i4 , i8 , i8 ))(intptr_t)v920)(&v921, v919, v918, v916); i8 v922 = (i8)(intptr_t)(ws+3296); *(i1*)(intptr_t)v922 = v921; endsub:; *p912 = *(i1*)(intptr_t)(ws+3296); }
/* For VQDR, we may not modify the Channel bits, which might overlap * with the Index bit. When it does, we need to ensure that isld0 == isld1. */ static inline int _nfp6000_encode_basic(uint64_t *addr, int dest_island, int cpp_tgt, int mode, int addr40, int isld1, int isld0) { uint64_t _u64; int iid_lsb, idx_lsb; int i, v = 0; int isld[2]; isld[0] = isld0; isld[1] = isld1; switch (cpp_tgt) { case NFP6000_CPPTGT_MU: return NFP_ERRNO(EINVAL); case NFP6000_CPPTGT_CTXPB: return NFP_ERRNO(EINVAL); default: break; } switch (mode) { case 0: if (cpp_tgt == NFP6000_CPPTGT_VQDR && !addr40) { i = _nfp6000_decode_basic(*addr, &v, cpp_tgt, mode, addr40, isld1, isld0); if (i != 0) return i; if (dest_island != -1 && dest_island != v) return NFP_ERRNO(EINVAL); return 0; } iid_lsb = (addr40) ? 34 : 26; _u64 = _nic_mask64((iid_lsb + 5), iid_lsb, 0); *addr &= ~_u64; *addr |= (((uint64_t)dest_island) << iid_lsb) & _u64; return 0; case 1: if (cpp_tgt == NFP6000_CPPTGT_VQDR && !addr40) { i = _nfp6000_decode_basic(*addr, &v, cpp_tgt, mode, addr40, isld1, isld0); if (i != 0) return i; if (dest_island != -1 && dest_island != v) return NFP_ERRNO(EINVAL); return 0; } idx_lsb = (addr40) ? 39 : 31; if (dest_island == isld0) { *addr &= ~_nic_mask64(idx_lsb, idx_lsb, 0); return 0; } if (dest_island == isld1) { *addr |= (UINT64_C(1) << idx_lsb); return 0; } return NFP_ERRNO(ENODEV); case 2: if (cpp_tgt == NFP6000_CPPTGT_VQDR && !addr40) { i = _nfp6000_decode_basic(*addr, &v, cpp_tgt, mode, addr40, isld1, isld0); if (i != 0) return i; if (dest_island != -1 && dest_island != v) return NFP_ERRNO(EINVAL); return 0; } isld[0] &= ~1; isld[1] &= ~1; idx_lsb = (addr40) ? 39 : 31; iid_lsb = idx_lsb - 1; for (i = 0; i < 2; i++) { for (v = 0; v < 2; v++) { if (dest_island != (isld[i] | v)) continue; *addr &= ~_nic_mask64(idx_lsb, iid_lsb, 0); *addr |= (((uint64_t)i) << idx_lsb); *addr |= (((uint64_t)v) << iid_lsb); return 0; } } return NFP_ERRNO(ENODEV); case 3: if (cpp_tgt == NFP6000_CPPTGT_VQDR && !addr40) { i = _nfp6000_decode_basic(*addr, &v, cpp_tgt, mode, addr40, isld1, isld0); if (i != 0) return i; if (dest_island != -1 && dest_island != v) return NFP_ERRNO(EINVAL); return 0; } isld[0] &= ~3; isld[1] &= ~3; idx_lsb = (addr40) ? 39 : 31; iid_lsb = idx_lsb - 2; for (i = 0; i < 2; i++) { for (v = 0; v < 4; v++) { if (dest_island != (isld[i] | v)) continue; *addr &= ~_nic_mask64(idx_lsb, iid_lsb, 0); *addr |= (((uint64_t)i) << idx_lsb); *addr |= (((uint64_t)v) << iid_lsb); return 0; } } return NFP_ERRNO(ENODEV); default: break; } return NFP_ERRNO(EINVAL); }
/************************** gaugefixfft.c *******************************/ /* Fix Coulomb or Lorentz gauge using Fourier acceleration */ /* Uses double precision global sums */ /* MIMD version 7 */ /* U.M. Heller 12-29-00 */ /* Prototype... void gaugefixfft(int gauge_dir, Real accel_param, int max_gauge_iter, Real gauge_fix_tol, int nvector, field_offset vector_offset[], int vector_parity[], int nantiherm, field_offset antiherm_offset[], int antiherm_parity[] ) ------------------------------------------------------------------- NOTE: We assume that the FFT setup was already done! ------------------------------------------------------------------- NOTE: For staggered fermion applications, it is necessary to remove the KS phases from the gauge links before calling this procedure. See "rephase" in setup.c. ------------------------------------------------------------------- EXAMPLE: Fixing only the link matrices to Coulomb gauge gaugefixfft(TUP,(Real)0.065,500,(Real)1.0e-7, 0,NULL,NULL,0,NULL,NULL); ------------------------------------------------------------------- EXAMPLE: Fixing Coulomb gauge with respect to the y direction in the staggered fermion scheme and simultaneously transforming the pseudofermion fields and gauge-momenta involved in updating: int nvector = 3; field_offset vector_offset[3] = { F_OFFSET(g_rand), F_OFFSET(phi), F_OFFSET(xxx) }; int vector_parity[3] = { EVENANDODD, EVEN, EVEN }; int nantiherm = 4; field_offset antiherm_offset[4] = { F_OFFSET(mom[0]), F_OFFSET(mom[1]), F_OFFSET(mom[2]), F_OFFSET(mom[3]) }; field_offset antiherm_parity[4] = { EVENANDODD, EVENANDODD, EVENANDODD, EVENANDODD } rephase( OFF ); gaugefixfft(YUP,(Real)1.8,500,(Real)2.0e-6, nvector,vector_offset,vector_parity, nantiherm,antiherm_offset,antiherm_parity); rephase( ON ); ------------------------------------------------------------------- gauge_dir specifies the direction of the "time"-like hyperplane for the purposes of defining Coulomb or Lorentz gauge TUP for evaluating propagators in the time-like direction ZUP for screening lengths. 8 for Lorentz gauge accel_param Parameter for Fourier acceleration max_gauge_iter Maximum number of iterations gauge_fix_tol Stop if change is less than this */ #include "gluon_prop_includes.h" #define REUNIT_INTERVAL 20 /* Scratch space */ su3_matrix *diffmatp; /* malloced diffmat pointer */ su3_matrix *tmpmat1p; /* malloced tmpmat1 pointer */ su3_matrix *tmpmat2p; /* malloced tmpmat2 pointer */ Real *p_rat; /* malloced momentum ratio for Fourier accelaration */ su3_matrix *gt_matrix; /* malloced gauge transformation matrix, if gauge transformation on vectors, etc. are needed */ int fft_vol; /* Prototypes */ double dmu_amu(int gauge_dir); void gf_fft_step(int gauge_dir, double *dmu_amu_norm, Real accel_param, int save_gt); void gaugefixsetup(int gauge_dir, int save_gt); double dmu_amu(int gauge_dir) { /* Accumulates d_mu A_mu in diffmat and computes the norm */ register int dir, i; register site *s; msg_tag *mtag[6]; double damu; su3_matrix *m1; anti_hermitmat ahtmp; /* Start gathers of downward links */ FORALLUPDIRBUT(gauge_dir,dir){ mtag[dir] = start_gather_site( F_OFFSET(link[dir]), sizeof(su3_matrix), OPP_DIR(dir), EVENANDODD, gen_pt[dir] ); } /* Clear diffmat */ FORALLSITES(i,s){ clear_su3mat(&diffmatp[i]); } /* Add upward link contributions */ FORALLSITES(i,s) { FORALLUPDIRBUT(gauge_dir,dir){ add_su3_matrix( &diffmatp[i], &(s->link[dir]), &diffmatp[i]); } } FORALLUPDIRBUT(gauge_dir,dir){ wait_gather(mtag[dir]); } /* Subtract downward link contributions, make traceless anti-hermitian and accumulate norm. Note we store it as SU(3) matrix for calls to FFT */ damu = 0.0; FORALLSITES(i,s) { m1 = &diffmatp[i]; FORALLUPDIRBUT(gauge_dir,dir){ sub_su3_matrix( m1, (su3_matrix *)gen_pt[dir][i], m1); } make_anti_hermitian( m1, &ahtmp); uncompress_anti_hermitian( &ahtmp, m1); #ifndef IMP_GFIX damu += (double)realtrace_su3( m1, m1); #endif } #ifdef IMP_GFIX /* Clear tmpmat1, for the 2-link term */ FORALLSITES(i,s){ clear_su3mat( &tmpmat1p[i]); } FORALLUPDIRBUT(gauge_dir,dir){ /* Double link U(mu,x-mu) U(mu,x) */ FORALLSITES(i,s) { mult_su3_nn( (su3_matrix *)gen_pt[dir][i], &(s->link[dir]), &tmpmat2p[i]); } mtag[4] = start_gather_field( tmpmat2p, sizeof(su3_matrix), dir, EVENANDODD, gen_pt[4] ); mtag[5] = start_gather_field( tmpmat2p, sizeof(su3_matrix), OPP_DIR(dir), EVENANDODD, gen_pt[5] ); wait_gather(mtag[4]); wait_gather(mtag[5]); FORALLSITES(i,s) { add_su3_matrix( &tmpmat1p[i], (su3_matrix *)gen_pt[4][i], &tmpmat1p[i]); sub_su3_matrix( &tmpmat1p[i], (su3_matrix *)gen_pt[5][i], &tmpmat1p[i]); } cleanup_gather(mtag[4]); cleanup_gather(mtag[5]); } /* Now compute the improved d_mu A_mu, and its norm^2 */ ftmp1 = 4.0/3.0; ftmp2 = - 1.0/(12.0*u0); FORALLSITES(i,s) { m1 = &diffmatp[i]; scalar_mult_su3_matrix( m1, ftmp1, m1); scalar_mult_add_su3_matrix( m1, &tmpmat1p[i], ftmp2, m1); make_anti_hermitian( m1, &ahtmp); uncompress_anti_hermitian( &ahtmp, m1); damu += (double)realtrace_su3( m1, m1); } #endif FORALLUPDIRBUT(gauge_dir,dir){ cleanup_gather(mtag[dir]); } g_doublesum( &damu); /* Normalize, with factor "no. of active dirs" * (Nc^2-1) / 2 */ if (gauge_dir > TUP){ damu /= (double)(16*volume); } else{ damu /= (double)(12*volume); } return(sqrt(damu)); } /* dmu_amu */ void gf_fft_step(int gauge_dir, double *dmu_amu_norm, Real accel_param, int save_gt) { /* Carry out one iteration in the gauge-fixing process */ msg_tag *mtag[4]; register int dir, i, j; register site *s; su3_matrix *matp1, *matp2, tmat1, tmat2; Real ftmp1, ftmp2; int err; /* Compute d_mu A_mu(x) in diffmat and its norm */ *dmu_amu_norm = dmu_amu(gauge_dir); /* Fourier transform d_mu A_mu(x) */ g_sync(); restrict_fourier_field((complex *)diffmatp, sizeof(su3_matrix), FORWARDS); /* Multiply with (accel_param * p_rat / fft_vol) */ ftmp1 = accel_param / (Real)fft_vol; FORALLSITES(i,s){ ftmp2 = ftmp1 * p_rat[i]; scalar_mult_su3_matrix( &diffmatp[i], ftmp2, &diffmatp[i]); } /* Fourier transform back */ g_sync(); restrict_fourier_field((complex *)diffmatp, sizeof(su3_matrix), BACKWARDS); /* Now exponentiate, using 6-th order expansion */ FORALLSITES(i,s){ matp1 = &diffmatp[i]; matp2 = &tmpmat1p[i]; clear_su3mat( matp2); for(j=0; j<3; j++) matp2->e[j][j].real = 1.0; scalar_mult_add_su3_matrix( matp2, matp1, 0.16666666, &tmat2); mult_su3_nn( matp1, &tmat2, &tmat1); scalar_mult_add_su3_matrix( matp2, &tmat1, 0.2, &tmat2); mult_su3_nn( matp1, &tmat2, &tmat1); scalar_mult_add_su3_matrix( matp2, &tmat1, 0.25, &tmat2); mult_su3_nn( matp1, &tmat2, &tmat1); scalar_mult_add_su3_matrix( matp2, &tmat1, 0.33333333, &tmat2); mult_su3_nn( matp1, &tmat2, &tmat1); scalar_mult_add_su3_matrix( matp2, &tmat1, 0.5, &tmat2); mult_su3_nn( matp1, &tmat2, &tmat1); add_su3_matrix( matp2, &tmat1, &tmat2); su3mat_copy( &tmat2, matp2); /* reunitarize */ err = reunit_su3( matp2); if(err > 0) printf("Node %d site %d: G nut unitary, err = %d\n", this_node, i, err); } /* The gauge matrices are now in tmpmat1p */ /* Do the gauge transformation of the links */ g_sync(); FORALLUPDIR(dir) mtag[dir] = start_gather_field( tmpmat1p, sizeof(su3_matrix), dir, EVENANDODD, gen_pt[dir] ); FORALLUPDIR(dir){ /* First multiply with the gauge matrices on site */ FORALLSITES(i,s){ mult_su3_nn( &tmpmat1p[i], &(s->link[dir]), &tmpmat2p[i]); } /* Then multiply with forward gauge matrices */ wait_gather(mtag[dir]); FORALLSITES(i,s){ mult_su3_na( &tmpmat2p[i], (su3_matrix *)gen_pt[dir][i], &(s->link[dir])); } cleanup_gather(mtag[dir]); } if (save_gt == 1){ /* Also multiply with existing gauge transfromation matrices */ FORALLSITES(i,s){ matp1 = &gt_matrix[i]; mult_su3_nn( &tmpmat1p[i], matp1, &tmat1); su3mat_copy( &tmat1, matp1); } } } /* gf_fft_step */ void gaugefixsetup(int gauge_dir, int save_gt) { register int dir, i, j, pmu; register site *s; Real pix, piy, piz, pit; Real sin_pmu, sum_p2, sum_p2_max; diffmatp = (su3_matrix *)malloc(sizeof(su3_matrix)*sites_on_node); if(diffmatp == NULL){ node0_printf("gaugefix: Can't malloc diffmat\n"); fflush(stdout);terminate(1); } tmpmat1p = (su3_matrix *)malloc(sizeof(su3_matrix)*sites_on_node); if(tmpmat1p == NULL){ node0_printf("gaugefix: Can't malloc tmpmat1\n"); fflush(stdout);terminate(1); } tmpmat2p = (su3_matrix *)malloc(sizeof(su3_matrix)*sites_on_node); if(tmpmat2p == NULL){ node0_printf("gaugefix: Can't malloc tmpmat2\n"); fflush(stdout);terminate(1); } fft_vol = 1; FORALLUPDIRBUT(gauge_dir,dir){ switch(dir){ case XUP: fft_vol *= nx; break; case YUP: fft_vol *= ny; break; case ZUP: fft_vol *= nz; break; case TUP: fft_vol *= nt; break; } } pix = PI / (Real)nx; piy = PI / (Real)ny; piz = PI / (Real)nz; pit = PI / (Real)nt; /* Allocate space for p_rat = (hat)p^2_max / (hat)p^2 */ p_rat = (Real *)malloc(sizeof(Real)*sites_on_node); if(p_rat == NULL){ node0_printf("gaugefixfft: Can't malloc p_rat\n"); fflush(stdout);terminate(1); } sum_p2_max = 0.0; /* Now compute sum_mu sin^2(p_mu/2) */ FORALLSITES(i,s){ sum_p2 = 0.0; FORALLUPDIRBUT(gauge_dir,dir){ switch(dir){ case XUP: pmu = s->x; sin_pmu = sin((double)(pmu*pix)); sum_p2 += sin_pmu * sin_pmu; break; case YUP: pmu = s->y; sin_pmu = sin((double)(pmu*piy)); sum_p2 += sin_pmu * sin_pmu; break; case ZUP: pmu = s->z; sin_pmu = sin((double)(pmu*piz)); sum_p2 += sin_pmu * sin_pmu; break; case TUP: pmu = s->t; sin_pmu = sin((double)(pmu*pit)); sum_p2 += sin_pmu * sin_pmu; break; default: printf("BOTCH: bad direction\n"); exit(1); } } p_rat[i] = sum_p2; if (sum_p2 > sum_p2_max) sum_p2_max = sum_p2; } g_floatmax( &sum_p2_max); if (gauge_dir > TUP ){ FORALLSITES(i,s){ if( s->x == 0 && s->y == 0 && s->z == 0 && s->t == 0 ){ p_rat[i] = 0.0; } else{ p_rat[i] = sum_p2_max / p_rat[i]; } } } else{ switch(gauge_dir){ case XUP: FORALLSITES(i,s){ if( s->y == 0 && s->z == 0 && s->t == 0 ){ p_rat[i] = 0.0; } else{ p_rat[i] = sum_p2_max / p_rat[i]; } } break; case YUP: FORALLSITES(i,s){ if( s->x == 0 && s->z == 0 && s->t == 0 ){ p_rat[i] = 0.0; } else{ p_rat[i] = sum_p2_max / p_rat[i]; } } break; case ZUP: FORALLSITES(i,s){ if( s->x == 0 && s->y == 0 && s->t == 0 ){ p_rat[i] = 0.0; } else{ p_rat[i] = sum_p2_max / p_rat[i]; } } break; case TUP: FORALLSITES(i,s){ if( s->x == 0 && s->y == 0 && s->z == 0 ){ p_rat[i] = 0.0; } else{ p_rat[i] = sum_p2_max / p_rat[i]; } } break; default: printf("BOTCH: bad direction\n"); exit(1); } } /* Allocate space for gauge transformation, if it is needed */ if (save_gt == 1){ gt_matrix = (su3_matrix *)malloc(sizeof(su3_matrix)*sites_on_node); if(gt_matrix == NULL){ node0_printf("gaugefixfft: Can't malloc gt_matrix\n"); fflush(stdout);terminate(1); } /* Initialize it to unity */ FORALLSITES(i,s){ clear_su3mat( &gt_matrix[i]); for(j=0; j<3; j++) gt_matrix[i].e[j][j].real = 1.0; } } } /* gaugefixsetup */ void gaugefixfft_combo(int gauge_dir, Real accel_param, int max_gauge_iter, Real gauge_fix_tol, int nvector, field_offset vector_offset[], int vector_parity[], int nantiherm, field_offset antiherm_offset[], int antiherm_parity[] ) { register int i; register site *s; int gauge_iter, save_gt, j; double curr_damu; su3_vector vtmp; su3_matrix htmp1, htmp2; if(nvector > 0 || nantiherm > 0){ save_gt = 1; } else{ save_gt = 0; } /* Set up work space */ gaugefixsetup(gauge_dir, save_gt); /* Do at most max_gauge_iter iterations, but stop after the first step */ /* if |d_mu A_mu| is smaller than gauge_fix_tol */ for (gauge_iter=0; gauge_iter < max_gauge_iter; gauge_iter++) { gf_fft_step(gauge_dir, &curr_damu, accel_param, save_gt); if(gauge_iter==0) node0_printf("Starting |d_mu A_mu| = %e\n", curr_damu); if (curr_damu < gauge_fix_tol) break; /* Reunitarize when iteration count is a multiple of REUNIT_INTERVAL */ if((gauge_iter % REUNIT_INTERVAL) == (REUNIT_INTERVAL - 1)){ node0_printf("step %d: |d_mu A_mu| = %e\n", gauge_iter, curr_damu); reunitarize_cpu(); fflush(stdout); } } /* Reunitarize at the end, unless we just did it in the loop */ if((gauge_iter % REUNIT_INTERVAL) != 0) reunitarize_cpu(); /* Transform vectors and gauge momenta if requested */ for(j = 0; j < nvector; j++) FORSOMEPARITY(i,s,vector_parity[j]){ mult_su3_mat_vec( &gt_matrix[i], (su3_vector *)F_PT(s,vector_offset[j]), &vtmp); su3vec_copy( &vtmp, (su3_vector *)F_PT(s,vector_offset[j])); } for(j = 0; j < nantiherm; j++) FORSOMEPARITY(i,s,antiherm_parity[j]){ uncompress_anti_hermitian( (anti_hermitmat *)F_PT(s,antiherm_offset[j]), &htmp1); mult_su3_nn( &gt_matrix[i], &htmp1, &htmp2); mult_su3_na( &htmp2, &gt_matrix[i], &htmp1); make_anti_hermitian( &htmp1, (anti_hermitmat *)F_PT(s,antiherm_offset[j])); } /* Free workspace */ free(diffmatp); free(tmpmat1p); free(tmpmat2p); free(p_rat); if(save_gt == 1) free(gt_matrix); if(this_node==0) printf("GFIX: Ended at step %d. |d_mu A_mu| = %e\n", gauge_iter, curr_damu); } /* Abbreviated form for fixing only gauge field */ void gaugefixfft(int gauge_dir, Real accel_param, int max_gauge_iter, Real gauge_fix_tol) { gaugefixfft_combo(gauge_dir, accel_param, max_gauge_iter, gauge_fix_tol, 0,NULL,NULL,0,NULL,NULL); }
/************************************************************************** * trace_done * Closes the trace output files **************************************************************************/ void trace_done(void) { if( !trace_on ) return; for( tracecpu = 0; tracecpu < total_cpu; tracecpu++ ) { if( TRACE.file ) fclose( TRACE.file ); TRACE.file = NULL; } trace_on = 0; }
/** * Calculate level percent * * @param lvl Level * * @return 1 if lvl is greater then 40, percent otherwise */ double levelPercent(int lvl) { if ((double)lvl/40.0 > 1.0) { return 1.0; } else { return (double)lvl/40.0; } }
/* ** Convert the MacOS-Strings (Filenames/Findercomments) to a most compatible. ** These strings will be stored in the public area of the zip-archive. ** Every foreign platform (outside macos) will access these strings ** for extraction. */ void MakeCompatibleString(char *MacOS_Str, const char SpcChar1, const char SpcChar2, const char SpcChar3, const char SpcChar4, short CurrTextEncodingBase) { char *tmpPtr; register uch curch; Assert_it(MacOS_Str,"MakeCompatibleString MacOS_Str == NULL","") for (tmpPtr = MacOS_Str; (curch = *tmpPtr) != '\0'; tmpPtr++) { if (curch == SpcChar1) *tmpPtr = SpcChar2; else if (curch == SpcChar3) *tmpPtr = SpcChar4; else if ((CurrTextEncodingBase == kTextEncodingMacRoman) && (curch > 127)) { *tmpPtr = (char)MacRoman_to_WinCP1252[curch - 128]; } } }
/******************************************************************************/ /* * Set the expression return value and free the arg. */ void ejsSetReturnValueAndFree(Ejs *ep, EjsVar *vp) { mprAssert(ep); mprAssert(vp); ejsWriteVar(ep, ep->result, vp, EJS_SHALLOW_COPY); ejsFreeVar(ep, vp); }
/** * @brief EXTI line detection callbacks * @param GPIO_Pin: Specifies the pins connected EXTI line * @retval None */ void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { switch (GPIO_Pin) { case GPIO_PIN_0: BSP_LCD_GLASS_Clear(); BSP_LCD_GLASS_DisplayString((uint8_t*)"select"); mode = 1; factor = (factor+1)%2; __HAL_TIM_SET_COMPARE(&Tim4_Handle, TIM_CHANNEL_1, Tim4_CCR/(factor+1)); break; case GPIO_PIN_1: BSP_LCD_GLASS_Clear(); BSP_LCD_GLASS_DisplayString((uint8_t*)"left"); break; case GPIO_PIN_2: BSP_LCD_GLASS_Clear(); BSP_LCD_GLASS_DisplayString((uint8_t*)"right"); break; case GPIO_PIN_3: BSP_LCD_GLASS_Clear(); BSP_LCD_GLASS_DisplayString((uint8_t*)"up"); break; case GPIO_PIN_5: BSP_LCD_GLASS_Clear(); BSP_LCD_GLASS_DisplayString((uint8_t*)"down"); break; default: BSP_LCD_GLASS_Clear(); BSP_LCD_GLASS_DisplayString((uint8_t*)"OTHER"); } }
/* Deserialize a captured packet and its metadata */ eemo_mux_pkt* eemo_cx_deserialize_pkt(eemo_mux_cmd* pkt_cmd) { assert(pkt_cmd != NULL); struct timeval ts = { 0, 0 }; uint32_t pkt_len = pkt_cmd->cmd_len - (2 * sizeof(uint64_t)); uint8_t* tofree = pkt_cmd->cmd_data; if (pkt_cmd->cmd_len < (2 * sizeof(uint64_t))) { return NULL; } ts.tv_sec = (time_t) be64toh(*((uint64_t*) &pkt_cmd->cmd_data[0])); ts.tv_usec = (suseconds_t) be64toh(*((uint64_t*) &pkt_cmd->cmd_data[sizeof(uint64_t)])); pkt_cmd->cmd_data = NULL; return eemo_cx_new_packet(ts, &tofree[2 * sizeof(uint64_t)], pkt_len, tofree); }
/* * Copyright (c) 2023 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr/fff.h> #include <zephyr/logging/log.h> #include <zephyr/ztest.h> #include "stubs.h" LOG_MODULE_REGISTER(coap_client_test); DEFINE_FFF_GLOBALS; #define FFF_FAKES_LIST(FAKE) static uint8_t last_response_code; static const char *test_path = "test"; static uint16_t messages_needing_response[2]; static struct coap_client client; static char *short_payload = "testing"; static char *long_payload = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do " "eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut " "enim ad minim veniam, quis nostrud exercitation ullamco laboris " "nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor " "in reprehenderit in voluptate velit esse cillum dolore eu fugiat" " nulla pariatur. Excepteur sint occaecat cupidatat non proident," " sunt in culpa qui officia deserunt mollit anim id est laborum."; static ssize_t z_impl_zsock_recvfrom_custom_fake(int sock, void *buf, size_t max_len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { uint16_t last_message_id = 0; LOG_INF("Recvfrom"); uint8_t ack_data[] = { 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (messages_needing_response[0] != 0) { last_message_id = messages_needing_response[0]; messages_needing_response[0] = 0; } else { last_message_id = messages_needing_response[1]; messages_needing_response[1] = 0; } ack_data[2] = (uint8_t) (last_message_id >> 8); ack_data[3] = (uint8_t) last_message_id; memcpy(buf, ack_data, sizeof(ack_data)); return sizeof(ack_data); } static ssize_t z_impl_zsock_sendto_custom_fake(int sock, void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen) { uint16_t last_message_id = 0; last_message_id |= ((uint8_t *) buf)[2] << 8; last_message_id |= ((uint8_t *) buf)[3]; if (messages_needing_response[0] == 0) { messages_needing_response[0] = last_message_id; } else { messages_needing_response[1] = last_message_id; } last_response_code = ((uint8_t *) buf)[1]; LOG_INF("Latest message ID: %d", last_message_id); return 1; } static ssize_t z_impl_zsock_recvfrom_custom_fake_response(int sock, void *buf, size_t max_len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { uint16_t last_message_id = 0; static uint8_t ack_data[] = { 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (messages_needing_response[0] != 0) { last_message_id = messages_needing_response[0]; messages_needing_response[0] = 0; } else { last_message_id = messages_needing_response[1]; messages_needing_response[1] = 0; } ack_data[2] = (uint8_t) (last_message_id >> 8); ack_data[3] = (uint8_t) last_message_id; memcpy(buf, ack_data, sizeof(ack_data)); return sizeof(ack_data); } static ssize_t z_impl_zsock_recvfrom_custom_fake_empty_ack(int sock, void *buf, size_t max_len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { uint16_t last_message_id = 0; static uint8_t ack_data[] = { 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (messages_needing_response[0] != 0) { last_message_id = messages_needing_response[0]; messages_needing_response[0] = 0; } else { last_message_id = messages_needing_response[1]; messages_needing_response[1] = 0; } ack_data[2] = (uint8_t) (last_message_id >> 8); ack_data[3] = (uint8_t) last_message_id; memcpy(buf, ack_data, sizeof(ack_data)); z_impl_zsock_recvfrom_fake.custom_fake = z_impl_zsock_recvfrom_custom_fake_response; return sizeof(ack_data); } static ssize_t z_impl_zsock_recvfrom_custom_fake_unmatching(int sock, void *buf, size_t max_len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { uint16_t last_message_id = 0; static uint8_t ack_data[] = { 0x68, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; if (messages_needing_response[0] != 0) { last_message_id = messages_needing_response[0]; messages_needing_response[0] = 0; } else { last_message_id = messages_needing_response[1]; messages_needing_response[1] = 0; } ack_data[2] = (uint8_t) (last_message_id >> 8); ack_data[3] = (uint8_t) last_message_id; memcpy(buf, ack_data, sizeof(ack_data)); return sizeof(ack_data); } static void *suite_setup(void) { coap_client_init(&client, NULL); return NULL; } static void test_setup(void *data) { /* Register resets */ DO_FOREACH_FAKE(RESET_FAKE); /* reset common FFF internal structures */ FFF_RESET_HISTORY(); z_impl_zsock_recvfrom_fake.custom_fake = z_impl_zsock_recvfrom_custom_fake; z_impl_zsock_sendto_fake.custom_fake = z_impl_zsock_sendto_custom_fake; } void coap_callback(int16_t code, size_t offset, const uint8_t *payload, size_t len, bool last_block, void *user_data) { LOG_INF("CoAP response callback, %d", code); last_response_code = code; } ZTEST_SUITE(coap_client, NULL, suite_setup, test_setup, NULL, NULL); ZTEST(coap_client, test_get_request) { int ret = 0; struct sockaddr address; struct coap_client_request client_request = { .method = COAP_METHOD_GET, .confirmable = true, .path = test_path, .fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN, .cb = coap_callback, .payload = NULL, .len = 0 }; client_request.payload = short_payload; client_request.len = strlen(short_payload); k_sleep(K_MSEC(1)); LOG_INF("Send request"); ret = coap_client_req(&client, 0, &address, &client_request, -1); zassert_true(ret >= 0, "Sending request failed, %d", ret); set_socket_events(ZSOCK_POLLIN); k_sleep(K_MSEC(5)); k_sleep(K_MSEC(1000)); zassert_equal(last_response_code, COAP_RESPONSE_CODE_OK, "Unexpected response"); } ZTEST(coap_client, test_get_no_path) { int ret = 0; struct sockaddr address; struct coap_client_request client_request = { .method = COAP_METHOD_GET, .confirmable = true, .path = NULL, .fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN, .cb = coap_callback, .payload = NULL, .len = 0 }; client_request.payload = short_payload; client_request.len = strlen(short_payload); k_sleep(K_MSEC(1)); LOG_INF("Send request"); ret = coap_client_req(&client, 0, &address, &client_request, -1); zassert_equal(ret, -EINVAL, "Get request without path"); } ZTEST(coap_client, test_send_large_data) { int ret = 0; struct sockaddr address; struct coap_client_request client_request = { .method = COAP_METHOD_GET, .confirmable = true, .path = test_path, .fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN, .cb = coap_callback, .payload = NULL, .len = 0 }; client_request.payload = long_payload; client_request.len = strlen(long_payload); k_sleep(K_MSEC(1)); LOG_INF("Send request"); ret = coap_client_req(&client, 0, &address, &client_request, -1); zassert_true(ret >= 0, "Sending request failed, %d", ret); set_socket_events(ZSOCK_POLLIN); k_sleep(K_MSEC(5)); k_sleep(K_MSEC(1000)); zassert_equal(last_response_code, COAP_RESPONSE_CODE_OK, "Unexpected response"); } ZTEST(coap_client, test_no_response) { int ret = 0; struct sockaddr address; struct coap_client_request client_request = { .method = COAP_METHOD_GET, .confirmable = true, .path = test_path, .fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN, .cb = coap_callback, .payload = NULL, .len = 0 }; client_request.payload = short_payload; client_request.len = strlen(short_payload); k_sleep(K_MSEC(1)); LOG_INF("Send request"); clear_socket_events(); ret = coap_client_req(&client, 0, &address, &client_request, 0); zassert_true(ret >= 0, "Sending request failed, %d", ret); k_sleep(K_MSEC(1000)); } ZTEST(coap_client, test_separate_response) { int ret = 0; struct sockaddr address; struct coap_client_request client_request = { .method = COAP_METHOD_GET, .confirmable = true, .path = test_path, .fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN, .cb = coap_callback, .payload = NULL, .len = 0 }; client_request.payload = short_payload; client_request.len = strlen(short_payload); z_impl_zsock_recvfrom_fake.custom_fake = z_impl_zsock_recvfrom_custom_fake_empty_ack; k_sleep(K_MSEC(1)); LOG_INF("Send request"); ret = coap_client_req(&client, 0, &address, &client_request, -1); zassert_true(ret >= 0, "Sending request failed, %d", ret); set_socket_events(ZSOCK_POLLIN); k_sleep(K_MSEC(5)); k_sleep(K_MSEC(1000)); k_sleep(K_MSEC(1000)); zassert_equal(last_response_code, COAP_RESPONSE_CODE_OK, "Unexpected response"); } ZTEST(coap_client, test_multiple_requests) { int ret = 0; struct sockaddr address; struct coap_client_request client_request = { .method = COAP_METHOD_GET, .confirmable = true, .path = test_path, .fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN, .cb = coap_callback, .payload = NULL, .len = 0 }; client_request.payload = short_payload; client_request.len = strlen(short_payload); k_sleep(K_MSEC(1)); set_socket_events(ZSOCK_POLLIN); LOG_INF("Send request"); ret = coap_client_req(&client, 0, &address, &client_request, -1); zassert_true(ret >= 0, "Sending request failed, %d", ret); ret = coap_client_req(&client, 0, &address, &client_request, -1); zassert_true(ret >= 0, "Sending request failed, %d", ret); k_sleep(K_MSEC(5)); k_sleep(K_MSEC(1000)); zassert_equal(last_response_code, COAP_RESPONSE_CODE_OK, "Unexpected response"); k_sleep(K_MSEC(5)); k_sleep(K_MSEC(1000)); zassert_equal(last_response_code, COAP_RESPONSE_CODE_OK, "Unexpected response"); } ZTEST(coap_client, test_unmatching_tokens) { int ret = 0; struct sockaddr address; struct coap_client_request client_request = { .method = COAP_METHOD_GET, .confirmable = true, .path = test_path, .fmt = COAP_CONTENT_FORMAT_TEXT_PLAIN, .cb = coap_callback, .payload = NULL, .len = 0 }; client_request.payload = short_payload; client_request.len = strlen(short_payload); z_impl_zsock_recvfrom_fake.custom_fake = z_impl_zsock_recvfrom_custom_fake_unmatching; LOG_INF("Send request"); ret = coap_client_req(&client, 0, &address, &client_request, 0); zassert_true(ret >= 0, "Sending request failed, %d", ret); set_socket_events(ZSOCK_POLLIN); k_sleep(K_MSEC(1)); k_sleep(K_MSEC(1)); clear_socket_events(); zassert_equal(last_response_code, COAP_RESPONSE_CODE_NOT_FOUND, "Unexpected response %d", last_response_code); k_sleep(K_MSEC(1)); }
/** * @brief This function is called when a request from M0+ is received. * * @param Notbuffer : a pointer to TL_EvtPacket_t * @return None */ void TL_ZIGBEE_M0RequestReceived(TL_EvtPacket_t *Reqbuffer) { p_ZIGBEE_request_M0_to_M4 = Reqbuffer; CptReceiveRequestFromM0++; UTIL_SEQ_SetTask(1U << (uint32_t)CFG_TASK_REQUEST_FROM_M0_TO_M4, CFG_SCH_PRIO_0); }
/* * Acquire a reflink to an IPv6_Address object */ reflink_t *nm2_ipv6_address_getref(const ovs_uuid_t *uuid) { struct nm2_ipv6_address *ip6; ip6 = nm2_ipv6_address_get(uuid); if (ip6 == NULL) { LOG(TRACE, "ipv6_address: Unable to acquire an IPv6_Address object for UUID %s.", uuid->uuid); return NULL; } return &ip6->ip6_reflink; }
/* requires lun->lock taken */ static void rrpc_set_lun_cur(struct rrpc_lun *rlun, struct rrpc_block *rblk) { struct rrpc *rrpc = rlun->rrpc; BUG_ON(!rblk); if (rlun->cur) { spin_lock(&rlun->cur->lock); WARN_ON(!block_is_full(rrpc, rlun->cur)); spin_unlock(&rlun->cur->lock); } rlun->cur = rblk; }
/* * ACPI implementation * * Copyright (c) 2006 Fabrice Bellard * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/> */ #include "sysemu.h" #include "hw.h" #include "pc.h" #include "acpi.h" struct acpi_table_header { uint16_t _length; /* our length, not actual part of the hdr */ /* XXX why we have 2 length fields here? */ char sig[4]; /* ACPI signature (4 ASCII characters) */ uint32_t length; /* Length of table, in bytes, including header */ uint8_t revision; /* ACPI Specification minor version # */ uint8_t checksum; /* To make sum of entire table == 0 */ char oem_id[6]; /* OEM identification */ char oem_table_id[8]; /* OEM table identification */ uint32_t oem_revision; /* OEM revision number */ char asl_compiler_id[4]; /* ASL compiler vendor ID */ uint32_t asl_compiler_revision; /* ASL compiler revision number */ } QEMU_PACKED; #define ACPI_TABLE_HDR_SIZE sizeof(struct acpi_table_header) #define ACPI_TABLE_PFX_SIZE sizeof(uint16_t) /* size of the extra prefix */ static const char dfl_hdr[ACPI_TABLE_HDR_SIZE] = "\0\0" /* fake _length (2) */ "QEMU\0\0\0\0\1\0" /* sig (4), len(4), revno (1), csum (1) */ "QEMUQEQEMUQEMU\1\0\0\0" /* OEM id (6), table (8), revno (4) */ "QEMU\1\0\0\0" /* ASL compiler ID (4), version (4) */ ; char *acpi_tables; size_t acpi_tables_len; static int acpi_checksum(const uint8_t *data, int len) { int sum, i; sum = 0; for (i = 0; i < len; i++) { sum += data[i]; } return (-sum) & 0xff; } /* like strncpy() but zero-fills the tail of destination */ static void strzcpy(char *dst, const char *src, size_t size) { size_t len = strlen(src); if (len >= size) { len = size; } else { memset(dst + len, 0, size - len); } memcpy(dst, src, len); } /* XXX fixme: this function uses obsolete argument parsing interface */ int acpi_table_add(const char *t) { char buf[1024], *p, *f; unsigned long val; size_t len, start, allen; bool has_header; int changed; int r; struct acpi_table_header hdr; r = 0; r |= get_param_value(buf, sizeof(buf), "data", t) ? 1 : 0; r |= get_param_value(buf, sizeof(buf), "file", t) ? 2 : 0; switch (r) { case 0: buf[0] = '\0'; /* fallthrough for default behavior */ case 1: has_header = false; break; case 2: has_header = true; break; default: fprintf(stderr, "acpitable: both data and file are specified\n"); return -1; } if (!acpi_tables) { allen = sizeof(uint16_t); acpi_tables = g_malloc0(allen); } else { allen = acpi_tables_len; } start = allen; acpi_tables = g_realloc(acpi_tables, start + ACPI_TABLE_HDR_SIZE); allen += has_header ? ACPI_TABLE_PFX_SIZE : ACPI_TABLE_HDR_SIZE; /* now read in the data files, reallocating buffer as needed */ for (f = strtok(buf, ":"); f; f = strtok(NULL, ":")) { int fd = open(f, O_RDONLY); if (fd < 0) { fprintf(stderr, "can't open file %s: %s\n", f, strerror(errno)); return -1; } for (;;) { char data[8192]; r = read(fd, data, sizeof(data)); if (r == 0) { break; } else if (r > 0) { acpi_tables = g_realloc(acpi_tables, allen + r); memcpy(acpi_tables + allen, data, r); allen += r; } else if (errno != EINTR) { fprintf(stderr, "can't read file %s: %s\n", f, strerror(errno)); close(fd); return -1; } } close(fd); } /* now fill in the header fields */ f = acpi_tables + start; /* start of the table */ changed = 0; /* copy the header to temp place to align the fields */ memcpy(&hdr, has_header ? f : dfl_hdr, ACPI_TABLE_HDR_SIZE); /* length of the table minus our prefix */ len = allen - start - ACPI_TABLE_PFX_SIZE; hdr._length = cpu_to_le16(len); if (get_param_value(buf, sizeof(buf), "sig", t)) { strzcpy(hdr.sig, buf, sizeof(hdr.sig)); ++changed; } /* length of the table including header, in bytes */ if (has_header) { /* check if actual length is correct */ val = le32_to_cpu(hdr.length); if (val != len) { fprintf(stderr, "warning: acpitable has wrong length," " header says %lu, actual size %zu bytes\n", val, len); ++changed; } } /* we may avoid putting length here if has_header is true */ hdr.length = cpu_to_le32(len); if (get_param_value(buf, sizeof(buf), "rev", t)) { val = strtoul(buf, &p, 0); if (val > 255 || *p) { fprintf(stderr, "acpitable: \"rev=%s\" is invalid\n", buf); return -1; } hdr.revision = (uint8_t)val; ++changed; } if (get_param_value(buf, sizeof(buf), "oem_id", t)) { strzcpy(hdr.oem_id, buf, sizeof(hdr.oem_id)); ++changed; } if (get_param_value(buf, sizeof(buf), "oem_table_id", t)) { strzcpy(hdr.oem_table_id, buf, sizeof(hdr.oem_table_id)); ++changed; } if (get_param_value(buf, sizeof(buf), "oem_rev", t)) { val = strtol(buf, &p, 0); if (*p) { fprintf(stderr, "acpitable: \"oem_rev=%s\" is invalid\n", buf); return -1; } hdr.oem_revision = cpu_to_le32(val); ++changed; } if (get_param_value(buf, sizeof(buf), "asl_compiler_id", t)) { strzcpy(hdr.asl_compiler_id, buf, sizeof(hdr.asl_compiler_id)); ++changed; } if (get_param_value(buf, sizeof(buf), "asl_compiler_rev", t)) { val = strtol(buf, &p, 0); if (*p) { fprintf(stderr, "acpitable: \"%s=%s\" is invalid\n", "asl_compiler_rev", buf); return -1; } hdr.asl_compiler_revision = cpu_to_le32(val); ++changed; } if (!has_header && !changed) { fprintf(stderr, "warning: acpitable: no table headers are specified\n"); } /* now calculate checksum of the table, complete with the header */ /* we may as well leave checksum intact if has_header is true */ /* alternatively there may be a way to set cksum to a given value */ hdr.checksum = 0; /* for checksum calculation */ /* put header back */ memcpy(f, &hdr, sizeof(hdr)); if (changed || !has_header || 1) { ((struct acpi_table_header *)f)->checksum = acpi_checksum((uint8_t *)f + ACPI_TABLE_PFX_SIZE, len); } /* increase number of tables */ (*(uint16_t *)acpi_tables) = cpu_to_le32(le32_to_cpu(*(uint16_t *)acpi_tables) + 1); acpi_tables_len = allen; return 0; } /* ACPI PM1a EVT */ uint16_t acpi_pm1_evt_get_sts(ACPIPM1EVT *pm1, int64_t overflow_time) { int64_t d = acpi_pm_tmr_get_clock(); if (d >= overflow_time) { pm1->sts |= ACPI_BITMASK_TIMER_STATUS; } return pm1->sts; } void acpi_pm1_evt_write_sts(ACPIPM1EVT *pm1, ACPIPMTimer *tmr, uint16_t val) { uint16_t pm1_sts = acpi_pm1_evt_get_sts(pm1, tmr->overflow_time); if (pm1_sts & val & ACPI_BITMASK_TIMER_STATUS) { /* if TMRSTS is reset, then compute the new overflow time */ acpi_pm_tmr_calc_overflow_time(tmr); } pm1->sts &= ~val; } void acpi_pm1_evt_power_down(ACPIPM1EVT *pm1, ACPIPMTimer *tmr) { if (!pm1) { qemu_system_shutdown_request(); } else if (pm1->en & ACPI_BITMASK_POWER_BUTTON_ENABLE) { pm1->sts |= ACPI_BITMASK_POWER_BUTTON_STATUS; tmr->update_sci(tmr); } } void acpi_pm1_evt_reset(ACPIPM1EVT *pm1) { pm1->sts = 0; pm1->en = 0; } /* ACPI PM_TMR */ void acpi_pm_tmr_update(ACPIPMTimer *tmr, bool enable) { int64_t expire_time; /* schedule a timer interruption if needed */ if (enable) { expire_time = muldiv64(tmr->overflow_time, get_ticks_per_sec(), PM_TIMER_FREQUENCY); qemu_mod_timer(tmr->timer, expire_time); } else { qemu_del_timer(tmr->timer); } } void acpi_pm_tmr_calc_overflow_time(ACPIPMTimer *tmr) { int64_t d = acpi_pm_tmr_get_clock(); tmr->overflow_time = (d + 0x800000LL) & ~0x7fffffLL; } uint32_t acpi_pm_tmr_get(ACPIPMTimer *tmr) { uint32_t d = acpi_pm_tmr_get_clock();; return d & 0xffffff; } static void acpi_pm_tmr_timer(void *opaque) { ACPIPMTimer *tmr = opaque; tmr->update_sci(tmr); } void acpi_pm_tmr_init(ACPIPMTimer *tmr, acpi_update_sci_fn update_sci) { tmr->update_sci = update_sci; tmr->timer = qemu_new_timer_ns(vm_clock, acpi_pm_tmr_timer, tmr); } void acpi_pm_tmr_reset(ACPIPMTimer *tmr) { tmr->overflow_time = 0; qemu_del_timer(tmr->timer); } /* ACPI PM1aCNT */ void acpi_pm1_cnt_init(ACPIPM1CNT *pm1_cnt, qemu_irq cmos_s3) { pm1_cnt->cmos_s3 = cmos_s3; } void acpi_pm1_cnt_write(ACPIPM1EVT *pm1a, ACPIPM1CNT *pm1_cnt, uint16_t val) { pm1_cnt->cnt = val & ~(ACPI_BITMASK_SLEEP_ENABLE); if (val & ACPI_BITMASK_SLEEP_ENABLE) { /* change suspend type */ uint16_t sus_typ = (val >> 10) & 7; switch(sus_typ) { case 0: /* soft power off */ qemu_system_shutdown_request(); break; case 1: /* ACPI_BITMASK_WAKE_STATUS should be set on resume. Pretend that resume was caused by power button */ pm1a->sts |= (ACPI_BITMASK_WAKE_STATUS | ACPI_BITMASK_POWER_BUTTON_STATUS); qemu_system_reset_request(); qemu_irq_raise(pm1_cnt->cmos_s3); default: break; } } } void acpi_pm1_cnt_update(ACPIPM1CNT *pm1_cnt, bool sci_enable, bool sci_disable) { /* ACPI specs 3.0, 4.7.2.5 */ if (sci_enable) { pm1_cnt->cnt |= ACPI_BITMASK_SCI_ENABLE; } else if (sci_disable) { pm1_cnt->cnt &= ~ACPI_BITMASK_SCI_ENABLE; } } void acpi_pm1_cnt_reset(ACPIPM1CNT *pm1_cnt) { pm1_cnt->cnt = 0; if (pm1_cnt->cmos_s3) { qemu_irq_lower(pm1_cnt->cmos_s3); } } /* ACPI GPE */ void acpi_gpe_init(ACPIGPE *gpe, uint8_t len) { gpe->len = len; gpe->sts = g_malloc0(len / 2); gpe->en = g_malloc0(len / 2); } void acpi_gpe_blk(ACPIGPE *gpe, uint32_t blk) { gpe->blk = blk; } void acpi_gpe_reset(ACPIGPE *gpe) { memset(gpe->sts, 0, gpe->len / 2); memset(gpe->en, 0, gpe->len / 2); } static uint8_t *acpi_gpe_ioport_get_ptr(ACPIGPE *gpe, uint32_t addr) { uint8_t *cur = NULL; if (addr < gpe->len / 2) { cur = gpe->sts + addr; } else if (addr < gpe->len) { cur = gpe->en + addr - gpe->len / 2; } else { abort(); } return cur; } void acpi_gpe_ioport_writeb(ACPIGPE *gpe, uint32_t addr, uint32_t val) { uint8_t *cur; addr -= gpe->blk; cur = acpi_gpe_ioport_get_ptr(gpe, addr); if (addr < gpe->len / 2) { /* GPE_STS */ *cur = (*cur) & ~val; } else if (addr < gpe->len) { /* GPE_EN */ *cur = val; } else { abort(); } } uint32_t acpi_gpe_ioport_readb(ACPIGPE *gpe, uint32_t addr) { uint8_t *cur; uint32_t val; addr -= gpe->blk; cur = acpi_gpe_ioport_get_ptr(gpe, addr); val = 0; if (cur != NULL) { val = *cur; } return val; }
/* * map_file_segment() -- map a [range of a] registered file segment. */ static int map_file_segment(segment_t * segp) { glctx_t *gcp = &glctx; char *memp; size_t size; int fd; int flags = segp->seg_flags; if (!flags) flags = MAP_PRIVATE; if ((fd = segp->seg_fd) == SEG_FD_NONE) { fprintf(stderr, "%s: file %s not open\n", gcp->program_name, segp->seg_path); return SEG_ERR; } size = file_size(fd); segp->seg_offset = round_down_to_pagesize(segp->seg_offset); if (segp->seg_offset > size) { fprintf(stderr, "%s: offset 0x%lx beyond end of file %s\n", gcp->program_name, segp->seg_offset, segp->seg_path); return SEG_ERR; } if (segp->seg_length == 0) segp->seg_length = round_up_to_pagesize(size) - segp->seg_offset; else segp->seg_length = round_up_to_pagesize(segp->seg_length); memp = (char *)mmap(0, segp->seg_length, segp->seg_prot, flags, fd, segp->seg_offset); if (memp == MAP_FAILED) { int err = errno; fprintf(stderr, "%s: mmap of %s failed - %s\n", __FUNCTION__, segp->seg_path, strerror(err)); return SEG_ERR; } vprint("%s: mmap()ed file seg %s at 0x%lx-0x%lx\n", gcp->program_name, segp->seg_name, memp, memp + segp->seg_length - 1); segp->seg_start = memp; return SEG_OK; }
#include <stdio.h> void exo(int nbCharac, int typeA, int typeB, int pingA, int pingB){ int j1 = pingA + typeA*nbCharac + pingA; int j2 = pingB + typeB*nbCharac + pingB; if(j1<j2) printf("First"); else if(j1>j2) printf("Second"); else printf("Friendship"); } int main() { int a, b, c, d, e; scanf("%d", &a); scanf("%d", &b); scanf("%d", &c); scanf("%d", &d); scanf("%d", &e); exo(a,b,c,d,e); }
#include<stdio.h> int main() { char s[100001]={'\0'}; scanf("%s",s); int n=strlen(s),c=0,dp[100000]={0}; for(int i=1;i<n;i++) { if(s[i]==s[i-1]) c++; dp[i]=c; } //int a[n-1]; //a[0]=dp[0]; //a[1]=dp[1]; //for(int i=1;i<n-1;i++) { // a[i]=a[i-1]+dp[i]; } //for(int i=0;i<n-1;i++) //printf("%d ",a[i]); int m; scanf("%d",&m); for(int i=0;i<m;i++) { int l,r,cnt=0; scanf("%d%d",&l,&r); l--; r--; //for(int j=l;j<r;j++) //{ //if(dp[j]==1) //cnt++; //} printf("%d\n",dp[r]-dp[l]); } //for(int i=0;i<n-1;i++) //printf("%d ",dp[i]); return 0; }
/** * g_static_rec_mutex_unlock: * @mutex: a #GStaticRecMutex to unlock. * * Unlocks @mutex. Another thread will be allowed to lock @mutex only * when it has been unlocked as many times as it had been locked * before. If @mutex is completely unlocked and another thread is * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be * woken and can lock @mutex itself. **/ void g_static_rec_mutex_unlock (GStaticRecMutex* mutex) { g_return_if_fail (mutex); if (!g_thread_supported ()) return; if (mutex->depth > 1) { mutex->depth--; return; } g_system_thread_assign (mutex->owner, zero_thread); g_static_mutex_unlock (&mutex->mutex); }
// Helper for writing index and file size into socket void write_sock_index_size(int sock, uint index, uint size) { char buf[30]; memcpy(buf, &index, sizeof(uint)); memcpy(buf + sizeof(uint), &size, sizeof(uint)); int n = write(sock, buf, 2 * sizeof(uint)); if (n < 0) { printf("error in request write: %s\n", strerror(errno)); exit(EXIT_FAILURE); } }
/* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include "test_gpio.h" /* Grotesque hack for pinmux boards */ #if defined(CONFIG_BOARD_RV32M1_VEGA) #include <fsl_port.h> #elif defined(CONFIG_BOARD_UDOO_NEO_FULL_M4) #include "device_imx.h" #elif defined(CONFIG_BOARD_MIMXRT1050_EVK) #include <fsl_iomuxc.h> #elif defined(CONFIG_BOARD_NRF52_BSIM) #include <NRF_GPIO.h> #endif static void board_setup(void) { #if DT_NODE_HAS_STATUS(DT_INST(0, test_gpio_basic_api), okay) /* PIN_IN and PIN_OUT must be on same controller. */ const struct device *const in_dev = DEVICE_DT_GET(DEV_OUT); const struct device *const out_dev = DEVICE_DT_GET(DEV_IN); if (in_dev != out_dev) { printk("FATAL: output controller %s != input controller %s\n", out_dev->name, in_dev->name); k_panic(); } #endif #if defined(CONFIG_BOARD_UDOO_NEO_FULL_M4) /* * Configure pin mux. * The following code needs to configure the same GPIOs which were * selected as test pins in device tree. */ if (PIN_IN != 15) { printk("FATAL: input pin set in DTS %d != %d\n", PIN_IN, 15); k_panic(); } if (PIN_OUT != 14) { printk("FATAL: output pin set in DTS %d != %d\n", PIN_OUT, 14); k_panic(); } /* Configure pin RGMII2_RD2 as GPIO5_IO14. */ IOMUXC_SW_MUX_CTL_PAD_RGMII2_RD2 = IOMUXC_SW_MUX_CTL_PAD_RGMII2_RD2_MUX_MODE(5); /* Select pull enabled, speed 100 MHz, drive strength 43 ohm */ IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD2 = IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD2_PUE_MASK | IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD2_PKE_MASK | IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD2_SPEED(2) | IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD2_DSE(6); /* Configure pin RGMII2_RD3 as GPIO5_IO15. */ IOMUXC_SW_MUX_CTL_PAD_RGMII2_RD3 = IOMUXC_SW_MUX_CTL_PAD_RGMII2_RD3_MUX_MODE(5); /* Select pull enabled, speed 100 MHz, drive strength 43 ohm */ IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD3 = IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD3_PUE_MASK | IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD3_PKE_MASK | IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD3_SPEED(2) | IOMUXC_SW_PAD_CTL_PAD_RGMII2_RD3_DSE(6); #elif defined(CONFIG_BOARD_MIMXRT1050_EVK) IOMUXC_SetPinMux(IOMUXC_GPIO_AD_B1_06_GPIO1_IO22, 0); IOMUXC_SetPinMux(IOMUXC_GPIO_AD_B1_07_GPIO1_IO23, 0); IOMUXC_SetPinConfig(IOMUXC_GPIO_AD_B1_06_GPIO1_IO22, IOMUXC_SW_PAD_CTL_PAD_PKE_MASK | IOMUXC_SW_PAD_CTL_PAD_HYS_MASK | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) | IOMUXC_SW_PAD_CTL_PAD_DSE(6)); IOMUXC_SetPinConfig(IOMUXC_GPIO_AD_B1_07_GPIO1_IO23, IOMUXC_SW_PAD_CTL_PAD_PKE_MASK | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) | IOMUXC_SW_PAD_CTL_PAD_DSE(6)); #elif defined(CONFIG_GPIO_EMUL) extern struct gpio_callback gpio_emul_callback; const struct device *const dev = DEVICE_DT_GET(DEV); zassert_true(device_is_ready(dev), "GPIO dev is not ready"); int rc = gpio_add_callback(dev, &gpio_emul_callback); __ASSERT(rc == 0, "gpio_add_callback() failed: %d", rc); #elif defined(CONFIG_BOARD_NRF52_BSIM) static bool done; if (!done) { done = true; /* This functions allows to programmatically short-circuit SOC GPIO pins */ nrf_gpio_backend_register_short(1, PIN_OUT, 1, PIN_IN); } #endif } static void *gpio_basic_setup(void) { board_setup(); return NULL; } /* Test GPIO port configuration */ ZTEST_SUITE(gpio_port, NULL, gpio_basic_setup, NULL, NULL, NULL); /* Test GPIO callback management */ ZTEST_SUITE(gpio_port_cb_mgmt, NULL, gpio_basic_setup, NULL, NULL, NULL); /* Test GPIO callbacks */ ZTEST_SUITE(gpio_port_cb_vari, NULL, gpio_basic_setup, NULL, NULL, NULL);
/* * Copyright (c) 2007 - 2015 Joseph Gaeddert * * 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. */ // // iirfilt_crcf_data_h3x64.c: autotest iirfilt data // #include <complex.h> float iirfilt_crcf_data_h3x64_b[] = { 0.067455273889, 0.134910547778, 0.067455273889}; float iirfilt_crcf_data_h3x64_a[] = { 1.000000000000, -1.142980502540, 0.412801598096}; float complex iirfilt_crcf_data_h3x64_x[] = { 0.157714921372 + 0.096933651372*_Complex_I, 0.112931825396 + 0.063629523666*_Complex_I, 0.036350589338 + 0.126527528681*_Complex_I, -0.131639758916 + 0.002850582881*_Complex_I, 0.124813993717 + -0.161564813627*_Complex_I, 0.055810697081 + -0.079984015750*_Complex_I, -0.113597866433 + 0.059629208365*_Complex_I, -0.081276130300 + -0.032884892886*_Complex_I, 0.189206432747 + 0.151230084280*_Complex_I, 0.046653973791 + 0.039106242827*_Complex_I, 0.062707370238 + 0.114770667926*_Complex_I, -0.005370634420 + -0.115131667770*_Complex_I, -0.042638922558 + -0.133249195976*_Complex_I, -0.036786574989 + -0.119823837652*_Complex_I, 0.086588872188 + 0.012335566540*_Complex_I, 0.162897246678 + 0.076457627729*_Complex_I, -0.046976140791 + 0.024454556465*_Complex_I, 0.037224871206 + 0.005544202178*_Complex_I, -0.106866213474 + -0.004556655371*_Complex_I, 0.112442348190 + -0.043675611175*_Complex_I, -0.139836308260 + -0.165558641382*_Complex_I, -0.124475577909 + 0.044150412760*_Complex_I, -0.112036331740 + 0.092938383030*_Complex_I, 0.004665562144 + 0.077748113050*_Complex_I, -0.016082143750 + -0.159087937039*_Complex_I, -0.122649745886 + 0.169674782967*_Complex_I, -0.059903644318 + -0.028174007533*_Complex_I, -0.135926561418 + 0.161939672399*_Complex_I, 0.058515792150 + -0.092207684338*_Complex_I, -0.001328847093 + -0.044399214544*_Complex_I, 0.148659720963 + -0.189463417484*_Complex_I, -0.026581782415 + 0.095051513873*_Complex_I, 0.031890698003 + -0.042421129272*_Complex_I, -0.122306862234 + 0.005962301978*_Complex_I, -0.061265177784 + 0.106033789898*_Complex_I, 0.261292757319 + -0.214947283935*_Complex_I, 0.103799428426 + 0.080318756697*_Complex_I, -0.049679368664 + 0.150833170036*_Complex_I, 0.042691894941 + 0.069350178325*_Complex_I, -0.046630189152 + -0.062689469185*_Complex_I, -0.012129146913 + 0.031853481774*_Complex_I, 0.020440626886 + 0.011527708526*_Complex_I, 0.048482096955 + 0.129990980549*_Complex_I, 0.042635428860 + -0.223911417035*_Complex_I, -0.010964205149 + -0.143631009428*_Complex_I, 0.065181991532 + -0.058004538996*_Complex_I, -0.000090077953 + -0.081470015783*_Complex_I, 0.011047855650 + 0.146709286197*_Complex_I, -0.114534249385 + 0.131496385737*_Complex_I, 0.071234677078 + 0.077433138944*_Complex_I, 0.200723551597 + 0.001379408486*_Complex_I, -0.026760201597 + 0.140751935283*_Complex_I, 0.047450662078 + -0.024838330640*_Complex_I, 0.013847228689 + -0.209058524164*_Complex_I, 0.093422613814 + 0.012081621105*_Complex_I, 0.136809870406 + -0.145382142602*_Complex_I, 0.009187149051 + 0.116724633427*_Complex_I, 0.136993412455 + 0.031913868005*_Complex_I, 0.000837449944 + -0.080964662247*_Complex_I, -0.060279791907 + -0.040256932738*_Complex_I, 0.037791227194 + -0.030926237571*_Complex_I, -0.041416454010 + -0.072873679453*_Complex_I, -0.022768793380 + -0.030601437534*_Complex_I, 0.108180951121 + 0.069467116791*_Complex_I}; float complex iirfilt_crcf_data_h3x64_y[] = { 0.010638703218 + 0.006538686002*_Complex_I, 0.041055083998 + 0.024843109564*_Complex_I, 0.070859923453 + 0.049353938820*_Complex_I, 0.067686035774 + 0.067709646463*_Complex_I, 0.041224538648 + 0.055038544970*_Complex_I, 0.030901594293 + 0.007957479174*_Complex_I, 0.026588402992 + -0.031291537326*_Complex_I, 0.000590470547 + -0.038619471159*_Complex_I, -0.016165649635 + -0.021437053514*_Complex_I, 0.004469726906 + 0.012262241589*_Complex_I, 0.035069044446 + 0.046083751239*_Complex_I, 0.049482788267 + 0.057966414042*_Complex_I, 0.042710472013 + 0.030452084359*_Complex_I, 0.019794496184 + -0.022948199659*_Complex_I, 0.002995531001 + -0.063121775432*_Complex_I, 0.015441215948 + -0.063934986641*_Complex_I, 0.041061093206 + -0.034223045125*_Complex_I, 0.047719585714 + -0.003893175152*_Complex_I, 0.032237020788 + 0.011767694149*_Complex_I, 0.012826028856 + 0.011870448387*_Complex_I, -0.000119320177 + -0.008657506452*_Complex_I, -0.025108083598 + -0.037099080266*_Complex_I, -0.062432000766 + -0.037771955955*_Complex_I, -0.084190602890 + -0.007096982968*_Complex_I, -0.078469021221 + 0.013507514859*_Complex_I, -0.065062852144 + 0.013595810519*_Complex_I, -0.063645820627 + 0.020222934773*_Complex_I, -0.071411851802 + 0.036070220963*_Complex_I, -0.073780802600 + 0.046606489405*_Complex_I, -0.056215295888 + 0.033869398399*_Complex_I, -0.020000348431 + -0.005517294981*_Complex_I, 0.018518800909 + -0.042431351088*_Complex_I, 0.038015719300 + -0.049039042613*_Complex_I, 0.030065702572 + -0.037444083204*_Complex_I, 0.000189612796 + -0.017459075006*_Complex_I, -0.011084433416 + -0.004290467457*_Complex_I, 0.025372744806 + -0.014124980335*_Complex_I, 0.061854301275 + -0.007862452949*_Complex_I, 0.063403692253 + 0.027289128630*_Complex_I, 0.046198628950 + 0.049738403126*_Complex_I, 0.022401700824 + 0.043954279075*_Complex_I, 0.003130865455 + 0.030553031785*_Complex_I, -0.000459085357 + 0.029249594984*_Complex_I, 0.008978406999 + 0.024030129591*_Complex_I, 0.018734404042 + -0.015736413767*_Complex_I, 0.023500424489 + -0.066300146201*_Complex_I, 0.027175003553 + -0.092293433110*_Complex_I, 0.026489439187 + -0.083128349690*_Complex_I, 0.012817484482 + -0.033748033571*_Complex_I, -0.006186235518 + 0.028602009338*_Complex_I, 0.003062407634 + 0.066032501481*_Complex_I, 0.036133722347 + 0.078570737258*_Complex_I, 0.053166399461 + 0.079952991289*_Complex_I, 0.051382646333 + 0.050991991806*_Complex_I, 0.048152970882 + -0.003786577505*_Complex_I, 0.056593380224 + -0.047656514100*_Complex_I, 0.070186171051 + -0.063832284508*_Complex_I, 0.076568506010 + -0.045193020750*_Complex_I, 0.077701414291 + -0.018586956449*_Complex_I, 0.062491319025 + -0.014074548285*_Complex_I, 0.033824419480 + -0.021392925087*_Complex_I, 0.011102622655 + -0.030445232324*_Complex_I, -0.005846867304 + -0.039949067467*_Complex_I, -0.009834168653 + -0.037451411970*_Complex_I};
// This function restores the Unicode characters from file system URLs // // If the URL isn't a file URL, it is copied directly to pszBuf. Otherwise, any // UTF8-escaped parts of the URL are converted into Unicode, and the result is // stored in pszBuf. This should be the same as the string we received in // History in the first place // // The return value is always pszBuf. // The input and output buffers may be the same. LPCTSTR ConditionallyDecodeUTF8(LPCTSTR pszUrl, LPTSTR pszBuf, DWORD cchBuf) { BOOL fDecoded = FALSE; if (PathIsFilePath(pszUrl)) { TCHAR szDisplayUrl[MAX_URL_STRING]; DWORD cchDisplayUrl = ARRAYSIZE(szDisplayUrl); DWORD cchBuf2 = cchBuf; if (SUCCEEDED(PrepareURLForDisplayUTF8(pszUrl, szDisplayUrl, &cchDisplayUrl, TRUE)) && SUCCEEDED(UrlCanonicalize(szDisplayUrl, pszBuf, &cchBuf2, URL_ESCAPE_UNSAFE | URL_ESCAPE_PERCENT))) { fDecoded = TRUE; } } if (!fDecoded && (pszUrl != pszBuf)) { StrCpyN(pszBuf, pszUrl, cchBuf); } return pszBuf; }
/* * linux/tools/lib/string.c * * Copied from linux/lib/string.c, where it is: * * Copyright (C) 1991, 1992 Linus Torvalds * * More specifically, the first copied function was strtobool, which * was introduced by: * * d0f1fed29e6e ("Add a strtobool function matching semantics of existing in kernel equivalents") * Author: Jonathan Cameron <jic23@cam.ac.uk> */ #include <stdlib.h> #include <string.h> #include <errno.h> #include <linux/string.h> #include <linux/compiler.h> /** * memdup - duplicate region of memory * * @src: memory region to duplicate * @len: memory region length */ void *memdup(const void *src, size_t len) { void *p = malloc(len); if (p) memcpy(p, src, len); return p; } /** * strtobool - convert common user inputs into boolean values * @s: input string * @res: result * * This routine returns 0 iff the first character is one of 'Yy1Nn0'. * Otherwise it will return -EINVAL. Value pointed to by res is * updated upon finding a match. */ int strtobool(const char *s, bool *res) { switch (s[0]) { case 'y': case 'Y': case '1': *res = true; break; case 'n': case 'N': case '0': *res = false; break; default: return -EINVAL; } return 0; } /** * strlcpy - Copy a C-string into a sized buffer * @dest: Where to copy the string to * @src: Where to copy the string from * @size: size of destination buffer * * Compatible with *BSD: the result is always a valid * NUL-terminated string that fits in the buffer (unless, * of course, the buffer size is zero). It does not pad * out the result like strncpy() does. * * If libc has strlcpy() then that version will override this * implementation: */ size_t __weak strlcpy(char *dest, const char *src, size_t size) { size_t ret = strlen(src); if (size) { size_t len = (ret >= size) ? size - 1 : ret; memcpy(dest, src, len); dest[len] = '\0'; } return ret; } int prefixcmp(const char *str, const char *prefix) { for (; ; str++, prefix++) if (!*prefix) return 0; else if (*str != *prefix) return (unsigned char)*prefix - (unsigned char)*str; }
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <math.h> #define SWAP(a,b) tempr=(a);(a)=(b);(b)=tempr void four1(float data[], unsigned long nn, int isign) /* includefile */ { unsigned long n,mmax,m,j,istep,i; double wtemp,wr,wpr,wpi,wi,theta; float tempr,tempi; n=nn << 1; j=1; for (i=1;i<n;i+=2) { if (j > i) { SWAP(data[j],data[i]); SWAP(data[j+1],data[i+1]); } m=n >> 1; while (m >= 2 && j > m) { j -= m; m >>= 1; } j += m; } mmax=2; while (n > mmax) { istep=mmax << 1; theta=isign*(6.28318530717959/mmax); wtemp=sin(0.5*theta); wpr = -2.0*wtemp*wtemp; wpi=sin(theta); wr=1.0; wi=0.0; for (m=1;m<mmax;m+=2) { for (i=m;i<=n;i+=istep) { j=i+mmax; tempr=wr*data[j]-wi*data[j+1]; tempi=wr*data[j+1]+wi*data[j]; data[j]=data[i]-tempr; data[j+1]=data[i+1]-tempi; data[i] += tempr; data[i+1] += tempi; } wr=(wtemp=wr)*wpr-wi*wpi+wr; wi=wi*wpr+wtemp*wpi+wi; } mmax=istep; } } #undef SWAP void realft(float data[], unsigned long n, int isign) /* includefile */ { void four1(float data[], unsigned long nn, int isign); unsigned long i,i1,i2,i3,i4,np3; float c1=0.5,c2,h1r,h1i,h2r,h2i; double wr,wi,wpr,wpi,wtemp,theta; theta=3.141592653589793/(double) (n>>1); if (isign == 1) { c2 = -0.5; four1(data,n>>1,1); } else { c2=0.5; theta = -theta; } wtemp=sin(0.5*theta); wpr = -2.0*wtemp*wtemp; wpi=sin(theta); wr=1.0+wpr; wi=wpi; np3=n+3; for (i=2;i<=(n>>2);i++) { i4=1+(i3=np3-(i2=1+(i1=i+i-1))); h1r=c1*(data[i1]+data[i3]); h1i=c1*(data[i2]-data[i4]); h2r = -c2*(data[i2]+data[i4]); h2i=c2*(data[i1]-data[i3]); data[i1]=h1r+wr*h2r-wi*h2i; data[i2]=h1i+wr*h2i+wi*h2r; data[i3]=h1r-wr*h2r+wi*h2i; data[i4] = -h1i+wr*h2i+wi*h2r; wr=(wtemp=wr)*wpr-wi*wpi+wr; wi=wi*wpr+wtemp*wpi+wi; } if (isign == 1) { data[1] = (h1r=data[1])+data[2]; data[2] = h1r-data[2]; } else { data[1]=c1*((h1r=data[1])+data[2]); data[2]=c1*(h1r-data[2]); four1(data,n>>1,-1); } } /* (C) Copr. 1986-92 Numerical Recipes Software i9k''3. */ #include <stdlib.h> void rfft(int nfft, double *org, double *fft) /* includefile */ { int i; float *temp; temp = (float *) malloc(nfft*sizeof(float)); for (i=0;i<nfft;i++) temp[i]=org[i]; realft(temp-1,(unsigned long) nfft, 1); for (i=0;i<nfft/2;i++) fft[i]=temp[2*i]; free(temp); }
/* * Routine: convert_task_suspend_token_to_port * Purpose: * Convert from a task suspension token to a port. * Consumes a task suspension token ref; produces a naked send-once right * which may be invalid. * Conditions: * Nothing locked. */ ipc_port_t convert_task_suspension_token_to_port( task_suspension_token_t task) { ipc_port_t port; task_lock(task); if (task->active) { if (task->itk_resume == IP_NULL) { task->itk_resume = ipc_port_alloc_kernel(); if (!IP_VALID(task->itk_resume)) { panic("failed to create resume port"); } ipc_kobject_set(task->itk_resume, (ipc_kobject_t) task, IKOT_TASK_RESUME); } port = ipc_port_make_sonce(task->itk_resume); assert(IP_VALID(port)); } else { port = IP_NULL; } task_unlock(task); task_suspension_token_deallocate(task); return port; }
/* Bump ABFD file position to next block. */ static void alpha_vms_file_position_block (bfd *abfd) { PRIV (file_pos) += VMS_BLOCK_SIZE - 1; PRIV (file_pos) -= (PRIV (file_pos) % VMS_BLOCK_SIZE); }
/* * Manually switch to the next channel in the channel list. * Provided for drivers that manage scanning themselves * (e.g. for firmware-based devices). */ void ieee80211_scan_next(struct ieee80211vap *vap) { struct ieee80211com *ic = vap->iv_ic; ic->ic_scan_methods->sc_scan_next(vap); }
#include<stdio.h> #include<math.h> int main() { int a,i; scanf("%d",&a); int x[a],y[a],z[a]; double p1,p2,p3,pI,t1=0,t2=0,t3=0,tI=0,e1,e2,e3,eI,m=0,g=1/3.0; for(i=0;i<a;i++) { scanf("%d",&x[i]); } for(i=0;i<a;i++) { scanf("%d",&y[i]); } for(i=0;i<a;i++) { if(x[i]>y[i] || x[i]==y[i]) { e1=(x[i]-y[i]); z[i]=e1; t1=t1+e1; e2=e1*e1; t2=t2+e2; e3=e1*e1*e1; t3=t3+e3; } else if(y[i]>x[i]) { e1=(y[i]-x[i]); z[i]=e1; t1=t1+e1; e2=e1*e1; t2=t2+e2; e3=e1*e1*e1; t3=t3+e3; } } p1=t1; p2=sqrt(t2); p3=pow(t3,g); for(i=0;i<a;i++) { if(z[i]>m) { m=z[i]; } } pI=m; printf("%.6lf\n%.6lf\n%.6lf\n%.6lf\n",p1,p2,p3,pI); return 0; }
/* * Check for valid flags set on @rs * * Has to be called after parsing of the ctr flags! */ static int rs_check_for_valid_flags(struct raid_set *rs) { if (rs->ctr_flags & ~__valid_flags(rs)) { rs->ti->error = "Invalid flags combination"; return -EINVAL; } return 0; }
/* * Unwind a single frame starting with *sp for the symbol at *pc. It * updates the *pc and *sp with the new values. */ int unwind_frame(struct stackframe *frame, const struct unwind_idx **origin_idx, const struct unwind_idx exidx_start[], const struct unwind_idx exidx_end[]) { unsigned long low; const struct unwind_idx *idx; struct unwind_ctrl_block ctrl; struct rt_thread *rt_c_thread; low = frame->sp; rt_c_thread = rt_thread_self(); ctrl.sp_high = (unsigned long)(rt_c_thread->stack_addr + rt_c_thread->stack_size); LOG_D("%s(pc = %08lx lr = %08lx sp = %08lx)", __func__, frame->pc, frame->lr, frame->sp); idx = unwind_find_idx(frame->pc, origin_idx, exidx_start, exidx_end); if (!idx) { LOG_W("unwind: Index not found %08lx", frame->pc); return -URC_FAILURE; } #ifdef RT_BACKTRACE_FUNCTION_NAME { char *fun_name; fun_name = unwind_get_function_name((void *)prel31_to_addr(&idx->addr_offset)); if (fun_name) { rt_kprintf("0x%08x @ %s\n", frame->pc, fun_name); } } #endif ctrl.vrs[FP] = frame->fp; ctrl.vrs[SP] = frame->sp; ctrl.vrs[LR] = frame->lr; ctrl.vrs[PC] = 0; if (idx->insn == 1) return -URC_FAILURE; else if ((idx->insn & 0x80000000) == 0) ctrl.insn = (unsigned long *)prel31_to_addr(&idx->insn); else if ((idx->insn & 0xff000000) == 0x80000000) ctrl.insn = &idx->insn; else { LOG_W("unwind: Unsupported personality routine %08lx in the index at %x", idx->insn, idx); return -URC_FAILURE; } if ((*ctrl.insn & 0xff000000) == 0x80000000) { ctrl.byte = 2; ctrl.entries = 1; } else if ((*ctrl.insn & 0xff000000) == 0x81000000) { ctrl.byte = 1; ctrl.entries = 1 + ((*ctrl.insn & 0x00ff0000) >> 16); } else { LOG_W("unwind: Unsupported personality routine %08lx at %x", *ctrl.insn, ctrl.insn); return -URC_FAILURE; } ctrl.check_each_pop = 0; while (ctrl.entries > 0) { int urc; if ((ctrl.sp_high - ctrl.vrs[SP]) < sizeof(ctrl.vrs)) ctrl.check_each_pop = 1; urc = unwind_exec_insn(&ctrl); if (urc < 0) return urc; if (ctrl.vrs[SP] < low || ctrl.vrs[SP] >= ctrl.sp_high) return -URC_FAILURE; } if (ctrl.vrs[PC] == 0) ctrl.vrs[PC] = ctrl.vrs[LR]; if (frame->pc == ctrl.vrs[PC]) return -URC_FAILURE; frame->fp = ctrl.vrs[FP]; frame->sp = ctrl.vrs[SP]; frame->lr = ctrl.vrs[LR]; frame->pc = ctrl.vrs[PC]; return URC_OK; }
/* return compliant with OpenSSL * size of encrypted data if success , -1 if error */ int wolfSSL_RSA_public_encrypt(int len, const unsigned char* fr, unsigned char* to, WOLFSSL_RSA* rsa, int padding) { int initTmpRng = 0; WC_RNG *rng = NULL; int outLen; int ret = 0; #ifdef WOLFSSL_SMALL_STACK WC_RNG* tmpRNG = NULL; #else WC_RNG tmpRNG[1]; #endif #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA) int mgf = WC_MGF1NONE; enum wc_HashType hash = WC_HASH_TYPE_NONE; #endif WOLFSSL_MSG("wolfSSL_RSA_public_encrypt"); #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA) if (padding == RSA_PKCS1_PADDING) padding = WC_RSA_PKCSV15_PAD; else if (padding == RSA_PKCS1_OAEP_PADDING) { padding = WC_RSA_OAEP_PAD; hash = WC_HASH_TYPE_SHA; mgf = WC_MGF1SHA1; } #else if (padding == RSA_PKCS1_PADDING) ; #endif else { WOLFSSL_MSG("wolfSSL_RSA_public_encrypt unsupported padding"); return 0; } if (rsa->inSet == 0) { if (SetRsaInternal(rsa) != SSL_SUCCESS) { WOLFSSL_MSG("SetRsaInternal failed"); return 0; } } outLen = wolfSSL_RSA_size(rsa); #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && \ !defined(HAVE_FAST_RSA) && defined(WC_RSA_BLINDING) rng = ((RsaKey*)rsa->internal)->rng; #endif if (rng == NULL) { #ifdef WOLFSSL_SMALL_STACK tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_TMP_BUFFER); if (tmpRNG == NULL) return 0; #endif if (wc_InitRng(tmpRNG) == 0) { rng = tmpRNG; initTmpRng = 1; } else { WOLFSSL_MSG("Bad RNG Init, trying global"); if (initGlobalRNG == 0) WOLFSSL_MSG("Global RNG no Init"); else rng = &globalRNG; } } if (outLen == 0) { WOLFSSL_MSG("Bad RSA size"); } if (rng) { #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA) ret = wc_RsaPublicEncrypt_ex(fr, len, to, outLen, (RsaKey*)rsa->internal, rng, padding, hash, mgf, NULL, 0); #else ret = wc_RsaPublicEncrypt(fr, len, to, outLen, (RsaKey*)rsa->internal, rng); #endif if (ret <= 0) { WOLFSSL_MSG("Bad Rsa Encrypt"); } if (len <= 0) { WOLFSSL_MSG("Bad Rsa Encrypt"); } } if (initTmpRng) wc_FreeRng(tmpRNG); #ifdef WOLFSSL_SMALL_STACK XFREE(tmpRNG, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif if (ret >= 0) WOLFSSL_MSG("wolfSSL_RSA_public_encrypt success"); else { WOLFSSL_MSG("wolfSSL_RSA_public_encrypt failed"); ret = WOLFSSL_FATAL_ERROR; } return ret; }
/* * Register the LWJGL window class. * Returns true for success, or false for failure */ bool registerWindow(WNDPROC win_proc, LPCTSTR class_name) { WNDCLASS windowClass; memset(&windowClass, 0, sizeof(windowClass)); windowClass.style = CS_OWNDC; windowClass.lpfnWndProc = win_proc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = dll_handle; windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.hbrBackground = NULL; windowClass.lpszMenuName = NULL; windowClass.lpszClassName = class_name; if (RegisterClass(&windowClass) == 0) { printfDebug("Failed to register window class\n"); return false; } return true; }
/* * Copyright (c) 2016 Martin Storsjo * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <string.h> #include "libavcodec/avcodec.h" #include "libavcodec/vp8dsp.h" #include "libavutil/common.h" #include "libavutil/intreadwrite.h" #include "checkasm.h" #define PIXEL_STRIDE 16 #define randomize_buffers(src, dst, stride, coef) \ do { \ int x, y; \ for (y = 0; y < 4; y++) { \ AV_WN32A((src) + y * (stride), rnd()); \ AV_WN32A((dst) + y * (stride), rnd()); \ for (x = 0; x < 4; x++) \ (coef)[y * 4 + x] = (src)[y * (stride) + x] - \ (dst)[y * (stride) + x]; \ } \ } while (0) static void dct4x4(int16_t *coef) { int i; for (i = 0; i < 4; i++) { const int a1 = (coef[i*4 + 0] + coef[i*4 + 3]) * 8; const int b1 = (coef[i*4 + 1] + coef[i*4 + 2]) * 8; const int c1 = (coef[i*4 + 1] - coef[i*4 + 2]) * 8; const int d1 = (coef[i*4 + 0] - coef[i*4 + 3]) * 8; coef[i*4 + 0] = a1 + b1; coef[i*4 + 1] = (c1 * 2217 + d1 * 5352 + 14500) >> 12; coef[i*4 + 2] = a1 - b1; coef[i*4 + 3] = (d1 * 2217 - c1 * 5352 + 7500) >> 12; } for (i = 0; i < 4; i++) { const int a1 = coef[i + 0*4] + coef[i + 3*4]; const int b1 = coef[i + 1*4] + coef[i + 2*4]; const int c1 = coef[i + 1*4] - coef[i + 2*4]; const int d1 = coef[i + 0*4] - coef[i + 3*4]; coef[i + 0*4] = (a1 + b1 + 7) >> 4; coef[i + 1*4] = ((c1 * 2217 + d1 * 5352 + 12000) >> 16) + !!d1; coef[i + 2*4] = (a1 - b1 + 7) >> 4; coef[i + 3*4] = (d1 * 2217 - c1 * 5352 + 51000) >> 16; } } static void wht4x4(int16_t *coef) { int i; for (i = 0; i < 4; i++) { int a1 = coef[0 * 4 + i]; int b1 = coef[1 * 4 + i]; int c1 = coef[2 * 4 + i]; int d1 = coef[3 * 4 + i]; int e1; a1 += b1; d1 -= c1; e1 = (a1 - d1) >> 1; b1 = e1 - b1; c1 = e1 - c1; a1 -= c1; d1 += b1; coef[0 * 4 + i] = a1; coef[1 * 4 + i] = c1; coef[2 * 4 + i] = d1; coef[3 * 4 + i] = b1; } for (i = 0; i < 4; i++) { int a1 = coef[i * 4 + 0]; int b1 = coef[i * 4 + 1]; int c1 = coef[i * 4 + 2]; int d1 = coef[i * 4 + 3]; int e1; a1 += b1; d1 -= c1; e1 = (a1 - d1) >> 1; b1 = e1 - b1; c1 = e1 - c1; a1 -= c1; d1 += b1; coef[i * 4 + 0] = a1 * 2; coef[i * 4 + 1] = c1 * 2; coef[i * 4 + 2] = d1 * 2; coef[i * 4 + 3] = b1 * 2; } } static void check_idct(void) { LOCAL_ALIGNED_16(uint8_t, src, [4 * 4]); LOCAL_ALIGNED_16(uint8_t, dst, [4 * 4]); LOCAL_ALIGNED_16(uint8_t, dst0, [4 * 4]); LOCAL_ALIGNED_16(uint8_t, dst1, [4 * 4]); LOCAL_ALIGNED_16(int16_t, coef, [4 * 4]); LOCAL_ALIGNED_16(int16_t, subcoef0, [4 * 4]); LOCAL_ALIGNED_16(int16_t, subcoef1, [4 * 4]); VP8DSPContext d; int dc; declare_func_emms(AV_CPU_FLAG_MMX, void, uint8_t *dst, int16_t *block, ptrdiff_t stride); ff_vp8dsp_init(&d); randomize_buffers(src, dst, 4, coef); dct4x4(coef); for (dc = 0; dc <= 1; dc++) { void (*idct)(uint8_t *, int16_t *, ptrdiff_t) = dc ? d.vp8_idct_dc_add : d.vp8_idct_add; if (check_func(idct, "vp8_idct_%sadd", dc ? "dc_" : "")) { if (dc) { memset(subcoef0, 0, 4 * 4 * sizeof(int16_t)); subcoef0[0] = coef[0]; } else { memcpy(subcoef0, coef, 4 * 4 * sizeof(int16_t)); } memcpy(dst0, dst, 4 * 4); memcpy(dst1, dst, 4 * 4); memcpy(subcoef1, subcoef0, 4 * 4 * sizeof(int16_t)); // Note, this uses a pixel stride of 4, even though the real decoder uses a stride as a // multiple of 16. If optimizations want to take advantage of that, this test needs to be // updated to make it more like the h264dsp tests. call_ref(dst0, subcoef0, 4); call_new(dst1, subcoef1, 4); if (memcmp(dst0, dst1, 4 * 4) || memcmp(subcoef0, subcoef1, 4 * 4 * sizeof(int16_t))) fail(); bench_new(dst1, subcoef1, 4); } } } static void check_idct_dc4(void) { LOCAL_ALIGNED_16(uint8_t, src, [4 * 4 * 4]); LOCAL_ALIGNED_16(uint8_t, dst, [4 * 4 * 4]); LOCAL_ALIGNED_16(uint8_t, dst0, [4 * 4 * 4]); LOCAL_ALIGNED_16(uint8_t, dst1, [4 * 4 * 4]); LOCAL_ALIGNED_16(int16_t, coef, [4], [4 * 4]); LOCAL_ALIGNED_16(int16_t, subcoef0, [4], [4 * 4]); LOCAL_ALIGNED_16(int16_t, subcoef1, [4], [4 * 4]); VP8DSPContext d; int i, chroma; declare_func_emms(AV_CPU_FLAG_MMX, void, uint8_t *dst, int16_t block[4][16], ptrdiff_t stride); ff_vp8dsp_init(&d); for (chroma = 0; chroma <= 1; chroma++) { void (*idct4dc)(uint8_t *, int16_t[4][16], ptrdiff_t) = chroma ? d.vp8_idct_dc_add4uv : d.vp8_idct_dc_add4y; if (check_func(idct4dc, "vp8_idct_dc_add4%s", chroma ? "uv" : "y")) { ptrdiff_t stride = chroma ? 8 : 16; int w = chroma ? 2 : 4; for (i = 0; i < 4; i++) { int blockx = 4 * (i % w); int blocky = 4 * (i / w); randomize_buffers(src + stride * blocky + blockx, dst + stride * blocky + blockx, stride, coef[i]); dct4x4(coef[i]); memset(&coef[i][1], 0, 15 * sizeof(int16_t)); } memcpy(dst0, dst, 4 * 4 * 4); memcpy(dst1, dst, 4 * 4 * 4); memcpy(subcoef0, coef, 4 * 4 * 4 * sizeof(int16_t)); memcpy(subcoef1, coef, 4 * 4 * 4 * sizeof(int16_t)); call_ref(dst0, subcoef0, stride); call_new(dst1, subcoef1, stride); if (memcmp(dst0, dst1, 4 * 4 * 4) || memcmp(subcoef0, subcoef1, 4 * 4 * 4 * sizeof(int16_t))) fail(); bench_new(dst1, subcoef1, stride); } } } static void check_luma_dc_wht(void) { LOCAL_ALIGNED_16(int16_t, dc, [4 * 4]); LOCAL_ALIGNED_16(int16_t, dc0, [4 * 4]); LOCAL_ALIGNED_16(int16_t, dc1, [4 * 4]); int16_t block[4][4][16]; LOCAL_ALIGNED_16(int16_t, block0, [4], [4][16]); LOCAL_ALIGNED_16(int16_t, block1, [4], [4][16]); VP8DSPContext d; int dc_only; int blockx, blocky; declare_func_emms(AV_CPU_FLAG_MMX, void, int16_t block[4][4][16], int16_t dc[16]); ff_vp8dsp_init(&d); for (blocky = 0; blocky < 4; blocky++) { for (blockx = 0; blockx < 4; blockx++) { uint8_t src[16], dst[16]; randomize_buffers(src, dst, 4, block[blocky][blockx]); dct4x4(block[blocky][blockx]); dc[blocky * 4 + blockx] = block[blocky][blockx][0]; block[blocky][blockx][0] = rnd(); } } wht4x4(dc); for (dc_only = 0; dc_only <= 1; dc_only++) { void (*idct)(int16_t [4][4][16], int16_t [16]) = dc_only ? d.vp8_luma_dc_wht_dc : d.vp8_luma_dc_wht; if (check_func(idct, "vp8_luma_dc_wht%s", dc_only ? "_dc" : "")) { if (dc_only) { memset(dc0, 0, 16 * sizeof(int16_t)); dc0[0] = dc[0]; } else { memcpy(dc0, dc, 16 * sizeof(int16_t)); } memcpy(dc1, dc0, 16 * sizeof(int16_t)); memcpy(block0, block, 4 * 4 * 16 * sizeof(int16_t)); memcpy(block1, block, 4 * 4 * 16 * sizeof(int16_t)); call_ref(block0, dc0); call_new(block1, dc1); if (memcmp(block0, block1, 4 * 4 * 16 * sizeof(int16_t)) || memcmp(dc0, dc1, 16 * sizeof(int16_t))) fail(); bench_new(block1, dc1); } } } #define SRC_BUF_STRIDE 32 #define SRC_BUF_SIZE (((size << (size < 16)) + 5) * SRC_BUF_STRIDE) // The mc subpixel interpolation filter needs the 2 previous pixels in either // direction, the +1 is to make sure the actual load addresses always are // unaligned. #define src (buf + 2 * SRC_BUF_STRIDE + 2 + 1) #undef randomize_buffers #define randomize_buffers() \ do { \ int k; \ for (k = 0; k < SRC_BUF_SIZE; k += 4) { \ AV_WN32A(buf + k, rnd()); \ } \ } while (0) static void check_mc(void) { LOCAL_ALIGNED_16(uint8_t, buf, [32 * 32]); LOCAL_ALIGNED_16(uint8_t, dst0, [16 * 16]); LOCAL_ALIGNED_16(uint8_t, dst1, [16 * 16]); VP8DSPContext d; int type, k, dx, dy; declare_func_emms(AV_CPU_FLAG_MMX, void, uint8_t *, ptrdiff_t, uint8_t *, ptrdiff_t, int, int, int); ff_vp78dsp_init(&d); for (type = 0; type < 2; type++) { vp8_mc_func (*tab)[3][3] = type ? d.put_vp8_bilinear_pixels_tab : d.put_vp8_epel_pixels_tab; for (k = 1; k < 8; k++) { int hsize = k / 3; int size = 16 >> hsize; int height = (size << 1) >> (k % 3); for (dy = 0; dy < 3; dy++) { for (dx = 0; dx < 3; dx++) { char str[100]; if (dx || dy) { if (type == 0) { static const char *dx_names[] = { "", "h4", "h6" }; static const char *dy_names[] = { "", "v4", "v6" }; snprintf(str, sizeof(str), "epel%d_%s%s", size, dx_names[dx], dy_names[dy]); } else { snprintf(str, sizeof(str), "bilin%d_%s%s", size, dx ? "h" : "", dy ? "v" : ""); } } else { snprintf(str, sizeof(str), "pixels%d", size); } if (check_func(tab[hsize][dy][dx], "vp8_put_%s", str)) { int mx, my; int i; if (type == 0) { mx = dx == 2 ? 2 + 2 * (rnd() % 3) : dx == 1 ? 1 + 2 * (rnd() % 4) : 0; my = dy == 2 ? 2 + 2 * (rnd() % 3) : dy == 1 ? 1 + 2 * (rnd() % 4) : 0; } else { mx = dx ? 1 + (rnd() % 7) : 0; my = dy ? 1 + (rnd() % 7) : 0; } randomize_buffers(); for (i = -2; i <= 3; i++) { int val = (i == -1 || i == 2) ? 0 : 0xff; // Set pixels in the first row and column to the maximum pattern, // to test for potential overflows in the filter. src[i ] = val; src[i * SRC_BUF_STRIDE] = val; } call_ref(dst0, size, src, SRC_BUF_STRIDE, height, mx, my); call_new(dst1, size, src, SRC_BUF_STRIDE, height, mx, my); if (memcmp(dst0, dst1, size * height)) fail(); bench_new(dst1, size, src, SRC_BUF_STRIDE, height, mx, my); } } } } } } #undef randomize_buffers #define setpx(a, b, c) buf[(a) + (b) * jstride] = av_clip_uint8(c) // Set the pixel to c +/- [0,d] #define setdx(a, b, c, d) setpx(a, b, c - (d) + (rnd() % ((d) * 2 + 1))) // Set the pixel to c +/- [d,d+e] (making sure it won't be clipped) #define setdx2(a, b, o, c, d, e) setpx(a, b, o = c + ((d) + (rnd() % (e))) * (c >= 128 ? -1 : 1)) static void randomize_loopfilter_buffers(int lineoff, int str, int dir, int flim_E, int flim_I, int hev_thresh, uint8_t *buf, int force_hev) { uint32_t mask = 0xff; int off = dir ? lineoff : lineoff * str; int istride = dir ? 1 : str; int jstride = dir ? str : 1; int i; for (i = 0; i < 8; i += 2) { // Row 0 will trigger hev for q0/q1, row 2 will trigger hev for p0/p1, // rows 4 and 6 will not trigger hev. // force_hev 1 will make sure all rows trigger hev, while force_hev -1 // makes none of them trigger it. int idx = off + i * istride, p2, p1, p0, q0, q1, q2; setpx(idx, 0, q0 = rnd() & mask); if (i == 0 && force_hev >= 0 || force_hev > 0) setdx2(idx, 1, q1, q0, hev_thresh + 1, flim_I - hev_thresh - 1); else setdx(idx, 1, q1 = q0, hev_thresh); setdx(idx, 2, q2 = q1, flim_I); setdx(idx, 3, q2, flim_I); setdx(idx, -1, p0 = q0, flim_E >> 2); if (i == 2 && force_hev >= 0 || force_hev > 0) setdx2(idx, -2, p1, p0, hev_thresh + 1, flim_I - hev_thresh - 1); else setdx(idx, -2, p1 = p0, hev_thresh); setdx(idx, -3, p2 = p1, flim_I); setdx(idx, -4, p2, flim_I); } } // Fill the buffer with random pixels static void fill_loopfilter_buffers(uint8_t *buf, ptrdiff_t stride, int w, int h) { int x, y; for (y = 0; y < h; y++) for (x = 0; x < w; x++) buf[y * stride + x] = rnd() & 0xff; } #define randomize_buffers(buf, lineoff, str, force_hev) \ randomize_loopfilter_buffers(lineoff, str, dir, flim_E, flim_I, hev_thresh, buf, force_hev) static void check_loopfilter_16y(void) { LOCAL_ALIGNED_16(uint8_t, base0, [32 + 16 * 16]); LOCAL_ALIGNED_16(uint8_t, base1, [32 + 16 * 16]); VP8DSPContext d; int dir, edge, force_hev; int flim_E = 20, flim_I = 10, hev_thresh = 7; declare_func_emms(AV_CPU_FLAG_MMX, void, uint8_t *, ptrdiff_t, int, int, int); ff_vp8dsp_init(&d); for (dir = 0; dir < 2; dir++) { int midoff = dir ? 4 * 16 : 4; int midoff_aligned = dir ? 4 * 16 : 16; uint8_t *buf0 = base0 + midoff_aligned; uint8_t *buf1 = base1 + midoff_aligned; for (edge = 0; edge < 2; edge++) { void (*func)(uint8_t *, ptrdiff_t, int, int, int) = NULL; switch (dir << 1 | edge) { case (0 << 1) | 0: func = d.vp8_h_loop_filter16y; break; case (1 << 1) | 0: func = d.vp8_v_loop_filter16y; break; case (0 << 1) | 1: func = d.vp8_h_loop_filter16y_inner; break; case (1 << 1) | 1: func = d.vp8_v_loop_filter16y_inner; break; } if (check_func(func, "vp8_loop_filter16y%s_%s", edge ? "_inner" : "", dir ? "v" : "h")) { for (force_hev = -1; force_hev <= 1; force_hev++) { fill_loopfilter_buffers(buf0 - midoff, 16, 16, 16); randomize_buffers(buf0, 0, 16, force_hev); randomize_buffers(buf0, 8, 16, force_hev); memcpy(buf1 - midoff, buf0 - midoff, 16 * 16); call_ref(buf0, 16, flim_E, flim_I, hev_thresh); call_new(buf1, 16, flim_E, flim_I, hev_thresh); if (memcmp(buf0 - midoff, buf1 - midoff, 16 * 16)) fail(); } fill_loopfilter_buffers(buf0 - midoff, 16, 16, 16); randomize_buffers(buf0, 0, 16, 0); randomize_buffers(buf0, 8, 16, 0); bench_new(buf0, 16, flim_E, flim_I, hev_thresh); } } } } static void check_loopfilter_8uv(void) { LOCAL_ALIGNED_16(uint8_t, base0u, [32 + 16 * 16]); LOCAL_ALIGNED_16(uint8_t, base0v, [32 + 16 * 16]); LOCAL_ALIGNED_16(uint8_t, base1u, [32 + 16 * 16]); LOCAL_ALIGNED_16(uint8_t, base1v, [32 + 16 * 16]); VP8DSPContext d; int dir, edge, force_hev; int flim_E = 20, flim_I = 10, hev_thresh = 7; declare_func_emms(AV_CPU_FLAG_MMX, void, uint8_t *, uint8_t *, ptrdiff_t, int, int, int); ff_vp8dsp_init(&d); for (dir = 0; dir < 2; dir++) { int midoff = dir ? 4 * 16 : 4; int midoff_aligned = dir ? 4 * 16 : 16; uint8_t *buf0u = base0u + midoff_aligned; uint8_t *buf0v = base0v + midoff_aligned; uint8_t *buf1u = base1u + midoff_aligned; uint8_t *buf1v = base1v + midoff_aligned; for (edge = 0; edge < 2; edge++) { void (*func)(uint8_t *, uint8_t *, ptrdiff_t, int, int, int) = NULL; switch (dir << 1 | edge) { case (0 << 1) | 0: func = d.vp8_h_loop_filter8uv; break; case (1 << 1) | 0: func = d.vp8_v_loop_filter8uv; break; case (0 << 1) | 1: func = d.vp8_h_loop_filter8uv_inner; break; case (1 << 1) | 1: func = d.vp8_v_loop_filter8uv_inner; break; } if (check_func(func, "vp8_loop_filter8uv%s_%s", edge ? "_inner" : "", dir ? "v" : "h")) { for (force_hev = -1; force_hev <= 1; force_hev++) { fill_loopfilter_buffers(buf0u - midoff, 16, 16, 16); fill_loopfilter_buffers(buf0v - midoff, 16, 16, 16); randomize_buffers(buf0u, 0, 16, force_hev); randomize_buffers(buf0v, 0, 16, force_hev); memcpy(buf1u - midoff, buf0u - midoff, 16 * 16); memcpy(buf1v - midoff, buf0v - midoff, 16 * 16); call_ref(buf0u, buf0v, 16, flim_E, flim_I, hev_thresh); call_new(buf1u, buf1v, 16, flim_E, flim_I, hev_thresh); if (memcmp(buf0u - midoff, buf1u - midoff, 16 * 16) || memcmp(buf0v - midoff, buf1v - midoff, 16 * 16)) fail(); } fill_loopfilter_buffers(buf0u - midoff, 16, 16, 16); fill_loopfilter_buffers(buf0v - midoff, 16, 16, 16); randomize_buffers(buf0u, 0, 16, 0); randomize_buffers(buf0v, 0, 16, 0); bench_new(buf0u, buf0v, 16, flim_E, flim_I, hev_thresh); } } } } static void check_loopfilter_simple(void) { LOCAL_ALIGNED_16(uint8_t, base0, [32 + 16 * 16]); LOCAL_ALIGNED_16(uint8_t, base1, [32 + 16 * 16]); VP8DSPContext d; int dir; int flim_E = 20, flim_I = 30, hev_thresh = 0; declare_func_emms(AV_CPU_FLAG_MMX, void, uint8_t *, ptrdiff_t, int); ff_vp8dsp_init(&d); for (dir = 0; dir < 2; dir++) { int midoff = dir ? 4 * 16 : 4; int midoff_aligned = dir ? 4 * 16 : 16; uint8_t *buf0 = base0 + midoff_aligned; uint8_t *buf1 = base1 + midoff_aligned; void (*func)(uint8_t *, ptrdiff_t, int) = dir ? d.vp8_v_loop_filter_simple : d.vp8_h_loop_filter_simple; if (check_func(func, "vp8_loop_filter_simple_%s", dir ? "v" : "h")) { fill_loopfilter_buffers(buf0 - midoff, 16, 16, 16); randomize_buffers(buf0, 0, 16, -1); randomize_buffers(buf0, 8, 16, -1); memcpy(buf1 - midoff, buf0 - midoff, 16 * 16); call_ref(buf0, 16, flim_E); call_new(buf1, 16, flim_E); if (memcmp(buf0 - midoff, buf1 - midoff, 16 * 16)) fail(); bench_new(buf0, 16, flim_E); } } } void checkasm_check_vp8dsp(void) { check_idct(); check_idct_dc4(); check_luma_dc_wht(); report("idct"); check_mc(); report("mc"); check_loopfilter_16y(); check_loopfilter_8uv(); check_loopfilter_simple(); report("loopfilter"); }
/** * Remove a reference from the internal reference count. When this * reaches 0, the object is destroyed. */ MYDLL_METHOD(bool) release() { #ifndef NDEBUG if (_in_dtor || 0 == _ref_count) { fprintf(stderr, "object release after destruct"); }; #endif if (--_ref_count == 0) { _in_dtor = true; } return _in_dtor; }
/* Add a formal argument, gfc_formal_arglist, to the end of the given list of arguments. Set the reference to the provided symbol, param_sym, in the argument. */ static void add_formal_arg (gfc_formal_arglist **head, gfc_formal_arglist **tail, gfc_formal_arglist *formal_arg, gfc_symbol *param_sym) { if (*head == NULL) *head = *tail = formal_arg; else { (*tail)->next = formal_arg; (*tail) = formal_arg; } (*tail)->sym = param_sym; (*tail)->next = NULL; return; }
// WARNING: Globals starting with '_' overlap smaller symbols at the same address void _L0(void) { undefined unaff_s0; undefined2 unaff_s1; undefined2 unaff_s2; undefined unaff_s3; _L0(); _DAT_00000004 = unaff_s2; _DAT_00000006 = unaff_s1; DAT_0000000a = unaff_s0; DAT_0000000b = unaff_s3; return; }
/* construct the token groups for SAM objects from a message */ static int construct_token_groups(struct ldb_module *module, struct ldb_message *msg, enum ldb_scope scope, struct ldb_request *parent) { struct ldb_context *ldb = ldb_module_get_ctx(module);; TALLOC_CTX *tmp_ctx = talloc_new(msg); unsigned int i; int ret; const char *filter; NTSTATUS status; struct dom_sid *primary_group_sid; const char *primary_group_string; const char *primary_group_dn; DATA_BLOB primary_group_blob; struct dom_sid *account_sid; const char *account_sid_string; const char *account_sid_dn; DATA_BLOB account_sid_blob; struct dom_sid *groupSIDs = NULL; unsigned int num_groupSIDs = 0; struct dom_sid *domain_sid; if (scope != LDB_SCOPE_BASE) { ldb_set_errstring(ldb, "Cannot provide tokenGroups attribute, this is not a BASE search"); return LDB_ERR_OPERATIONS_ERROR; } if (ldb_msg_find_element(msg, "primaryGroupID") == NULL) { talloc_free(tmp_ctx); return LDB_SUCCESS; } account_sid = samdb_result_dom_sid(tmp_ctx, msg, "objectSid"); if (account_sid == NULL) { talloc_free(tmp_ctx); return LDB_SUCCESS; } status = dom_sid_split_rid(tmp_ctx, account_sid, &domain_sid, NULL); if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) { talloc_free(tmp_ctx); return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } else if (!NT_STATUS_IS_OK(status)) { talloc_free(tmp_ctx); return LDB_ERR_OPERATIONS_ERROR; } primary_group_sid = dom_sid_add_rid(tmp_ctx, domain_sid, ldb_msg_find_attr_as_uint(msg, "primaryGroupID", ~0)); if (!primary_group_sid) { talloc_free(tmp_ctx); return ldb_oom(ldb); } filter = talloc_asprintf(tmp_ctx, "(&(objectClass=group)(groupType:1.2.840.113556.1.4.803:=%u))", GROUP_TYPE_SECURITY_ENABLED); if (!filter) { talloc_free(tmp_ctx); return ldb_oom(ldb); } primary_group_string = dom_sid_string(tmp_ctx, primary_group_sid); if (!primary_group_string) { talloc_free(tmp_ctx); return ldb_oom(ldb); } primary_group_dn = talloc_asprintf(tmp_ctx, "<SID=%s>", primary_group_string); if (!primary_group_dn) { talloc_free(tmp_ctx); return ldb_oom(ldb); } primary_group_blob = data_blob_string_const(primary_group_dn); account_sid_string = dom_sid_string(tmp_ctx, account_sid); if (!account_sid_string) { talloc_free(tmp_ctx); return ldb_oom(ldb); } account_sid_dn = talloc_asprintf(tmp_ctx, "<SID=%s>", account_sid_string); if (!account_sid_dn) { talloc_free(tmp_ctx); return ldb_oom(ldb); } account_sid_blob = data_blob_string_const(account_sid_dn); status = dsdb_expand_nested_groups(ldb, &account_sid_blob, true, filter, tmp_ctx, &groupSIDs, &num_groupSIDs); if (!NT_STATUS_IS_OK(status)) { ldb_asprintf_errstring(ldb, "Failed to construct tokenGroups: expanding groups of SID %s failed: %s", account_sid_string, nt_errstr(status)); talloc_free(tmp_ctx); return LDB_ERR_OPERATIONS_ERROR; } status = dsdb_expand_nested_groups(ldb, &primary_group_blob, false, filter, tmp_ctx, &groupSIDs, &num_groupSIDs); if (!NT_STATUS_IS_OK(status)) { ldb_asprintf_errstring(ldb, "Failed to construct tokenGroups: expanding groups of SID %s failed: %s", account_sid_string, nt_errstr(status)); talloc_free(tmp_ctx); return LDB_ERR_OPERATIONS_ERROR; } for (i=0; i < num_groupSIDs; i++) { ret = samdb_msg_add_dom_sid(ldb, msg, msg, "tokenGroups", &groupSIDs[i]); if (ret) { talloc_free(tmp_ctx); return ret; } } return LDB_SUCCESS; }
/* * allocate a large amount of memory of mem_sz bytes that must * be address aligned */ static void AllocatePow2AlignedMemory(size_t mem_sz) { void *mem_ptr; assert(mem_sz % NACL_MAP_PAGESIZE == 0); request_sz = mem_sz; ZLOGS(LOG_INSANE, "%25s %016lx", " Ask:", request_sz); mem_ptr = mmap(R15_CONST, request_sz, PROT_NONE, ABSOLUTE_MMAP, -1, (off_t)0); ZLOGFAIL(R15_CONST != mem_ptr, errno, "cannot allocate user memory"); }
/** * snd_hda_jack_poll_all - Poll all jacks * @codec: the HDA codec * * Poll all detectable jacks with dirty flag, update the status, call * callbacks and call snd_hda_jack_report_sync() if any changes are found. */ void snd_hda_jack_poll_all(struct hda_codec *codec) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i, changes = 0; for (i = 0; i < codec->jacktbl.used; i++, jack++) { unsigned int old_sense; if (!jack->nid || !jack->jack_dirty || jack->phantom_jack) continue; old_sense = get_jack_plug_state(jack->pin_sense); jack_detect_update(codec, jack); if (old_sense == get_jack_plug_state(jack->pin_sense)) continue; changes = 1; call_jack_callback(codec, 0, jack); } if (changes) snd_hda_jack_report_sync(codec); }
/*****************************************************************************/ /** * * This function to get uart input from user * * @param timeout_ms * * @return * - received charactor * * @note None. * ******************************************************************************/ char xil_getc(u32 timeout_ms){ char c; u32 timeout = 0; extern XTmrCtr TmrCtr; if ( timeout_ms > 0 && timeout_ms != 0xff ){ XTmrCtr_Start(&TmrCtr, 0); } while(XUartLite_IsReceiveEmpty(STDIN_BASEADDRESS) && (timeout == 0)){ if ( timeout_ms == 0 ){ timeout = 0; } else if ( timeout_ms == 0xff ) { timeout = 1; } else if(timeout_ms > 0){ if(XTmrCtr_GetValue(&TmrCtr, 0) > (timeout_ms * (XPAR_MICROBLAZE_CORE_CLOCK_FREQ_HZ / 1000))){ timeout = 1; } } } if(timeout == 1){ c = 0; } else { c = XUartLite_RecvByte(STDIN_BASEADDRESS); } return c; }
/* * Enqueue notify data to an extra linked list. It's called when ring * buffer is full. */ int32_t _linked_list_enqueue(const FUSE_NOTIFY_PROTO *data) { FUSE_NOTIFY_LINKED_NODE *node = malloc(sizeof(FUSE_NOTIFY_LINKED_NODE)); if (node == NULL) return -1; node->next = NULL; node->data = malloc(sizeof(FUSE_NOTIFY_PROTO)); if (node->data == NULL) { FREE(node); return -1; } memcpy(node->data, data, sizeof(FUSE_NOTIFY_PROTO)); if (notify.linked_list_head == NULL) { notify.linked_list_head = node; notify.linked_list_rear = node; } else { notify.linked_list_rear->next = node; notify.linked_list_rear = node; } write_log(6, "[D] %s: Done", __func__); return 0; }
/* Return the PK algorithm used by CERT as well as the length in bits of the public key at NBITS. */ int gpgsm_get_key_algo_info (ksba_cert_t cert, unsigned int *nbits) { gcry_sexp_t s_pkey; int rc; ksba_sexp_t p; size_t n; gcry_sexp_t l1, l2; const char *name; char namebuf[128]; if (nbits) *nbits = 0; p = ksba_cert_get_public_key (cert); if (!p) return 0; n = gcry_sexp_canon_len (p, 0, NULL, NULL); if (!n) { xfree (p); return 0; } rc = gcry_sexp_sscan (&s_pkey, NULL, (char *)p, n); xfree (p); if (rc) return 0; if (nbits) *nbits = gcry_pk_get_nbits (s_pkey); l1 = gcry_sexp_find_token (s_pkey, "public-key", 0); if (!l1) { gcry_sexp_release (s_pkey); return 0; } l2 = gcry_sexp_cadr (l1); gcry_sexp_release (l1); l1 = l2; name = gcry_sexp_nth_data (l1, 0, &n); if (name) { if (n > sizeof namebuf -1) n = sizeof namebuf -1; memcpy (namebuf, name, n); namebuf[n] = 0; } else *namebuf = 0; gcry_sexp_release (l1); gcry_sexp_release (s_pkey); return gcry_pk_map_name (namebuf); }
/* * Allocate everything needed for the transmission maps. */ static int patm_txmap_init(struct patm_softc *sc) { int error; struct patm_txmap *map; error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, 65536, IDT_SCQ_SIZE - 1, 65536, 0, NULL, NULL, &sc->tx_tag); if (error) { patm_printf(sc, "cannot allocate TX tag %d\n", error); return (error); } if ((sc->tx_mapzone = uma_zcreate("PATM tx maps", sizeof(struct patm_txmap), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0)) == NULL) return (ENOMEM); if (sc->tx_maxmaps < PATM_CFG_TXMAPS_MAX) sc->tx_maxmaps = PATM_CFG_TXMAPS_MAX; sc->tx_nmaps = PATM_CFG_TXMAPS_INIT; for (sc->tx_nmaps = 0; sc->tx_nmaps < PATM_CFG_TXMAPS_INIT; sc->tx_nmaps++) { map = uma_zalloc(sc->tx_mapzone, M_WAITOK); error = bus_dmamap_create(sc->tx_tag, 0, &map->map); if (error) { uma_zfree(sc->tx_mapzone, map); return (ENOMEM); } SLIST_INSERT_HEAD(&sc->tx_maps_free, map, link); } return (0); }
/* * Check that the free list is either empty or were synchronized with the * arena using copyToArena(). */ bool isSynchronizedFreeList(AllocKind kind) { FreeSpan *headSpan = &freeLists[kind]; if (headSpan->isEmpty()) return true; ArenaHeader *aheader = headSpan->arenaHeader(); if (aheader->hasFreeThings()) { JS_ASSERT(aheader->getFirstFreeSpan().isSameNonEmptySpan(headSpan)); return true; } return false; }
#include<stdio.h> #include<string.h> #include<stdlib.h> int cmpfunc (const void * a, const void * b) { return ( ((const int*)a)[0] - ((const int*)b)[0] ); } int max(int a,int b) { int ma=a>b?a:b; return ma; } int min(int a,int b) { int ma=a>b?b:a; return ma; } int main() { int i,j,n,temp[10]={0},c=0; char x; scanf("%d",&n); // scanf("%d %d",&k,&m); for(i=0;i<n+1;i++) { scanf("%c",&x); switch(x){ case '4': temp[3]++; temp[2]+=2; break; case'6': temp[5]++; temp[3]++; break; case'8': temp[7]++; temp[2]+=3; break; case'9': temp[7]++; temp[3]+=2; temp[2]++; break; default: temp[x-'0']++; } } for(i=9;i>=2;i--) while(temp[i]--) printf("%d",i); // qsort(a,n,2*sizeof(int),cmpfunc); return 0; }
/** * Prints lvalue expressions (such as sexprs) given the prefix, * suffix and delimiter */ void lvalue_expr_print(struct lvalue *val, char prefix, char suffix, char delimiter) { putchar(prefix); size_t len = val->val.l.count; if ( len > 0 ) lvalue_print(val->val.l.cells[0]); for ( size_t i = 1; i < len; i++ ) { putchar(delimiter); lvalue_print(val->val.l.cells[i]); } putchar(suffix); }
// Scales up the target mon sprite // Used in Let's Snuggle Forever // No args. void AnimTask_GrowTarget(u8 taskId) { u8 spriteId = GetAnimBattlerSpriteId(ANIM_TARGET); PrepareBattlerSpriteForRotScale(spriteId, ST_OAM_OBJ_BLEND); SetSpriteRotScale(spriteId, 208, 208, 0); gTasks[taskId].data[0] = 120; gTasks[taskId].func = AnimTask_GrowStep; }
int main(n){ scanf("%d",&n); puts(n>2?"0":n==1?"2":"1"); }
a[999];main(){ int n,m,c,d; for(scanf("%d%d",&n,&m);m--;)for(scanf("%d%d",&c,&d);c<d;c++)a[c]=1; for(c=d=0;c<n;c++)d+=a[c]*2; *a=!printf("%d\n",d+n+1); }
// This callback is called each time a buffer finishes playing static void callback(SLBufferQueueItf bufq, void *param) { assert(NULL == param); if (!eof) { void *buffer = (char *)buffers + framesPerBuffer * sfframesize * which; ssize_t count = audio_utils_fifo_read(&fifo, buffer, framesPerBuffer); if (0 >= count) { memset(buffer, 0, framesPerBuffer * sfframesize); count = framesPerBuffer; ++underruns; } if (count > 0) { SLuint32 nbytes = count * sfframesize; nbytes = squeeze(buffer, nbytes); SLresult result = (*bufq)->Enqueue(bufq, buffer, nbytes); assert(SL_RESULT_SUCCESS == result); if (++which >= numBuffers) which = 0; } } }
/* * create_xml_node() - creates a new XML schema element based on definition * * return: new element node * el_def(in): element node definition */ static XML_ELEMENT * create_xml_node (XML_ELEMENT_DEF * new_elem) { XML_ELEMENT *xml_node = (XML_ELEMENT *) malloc (sizeof (XML_ELEMENT)); if (xml_node == NULL) { return NULL; } xml_node->def = new_elem; xml_node->child = NULL; xml_node->next = NULL; xml_node->prev = NULL; xml_node->parent = NULL; xml_node->match = false; xml_node->short_name = NULL; return xml_node; }
/** * Check that we are not about to read off the end of the WKB * array. */ static inline void twkb_parse_state_advance(twkb_parse_state *s, size_t next) { if( (s->pos + next) > s->twkb_end) { lwerror("%s: TWKB structure does not match expected size!", __func__); } s->pos += next; }
/******************************************************************************* * Copyright 2016 Intel 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. * * \file mkl_memory.cc * \brief * \author lingyan.guo@intel.com * zhenlin.luo@intel.com * *******************************************************************************/ #ifndef MXNET_OPERATOR_MKL_MKL_MEMORY_H_ #define MXNET_OPERATOR_MKL_MKL_MEMORY_H_ #include <string> #include <vector> #include <memory> namespace mxnet { // Base class struct PrvMemDescr { virtual void convert_from_prv(void* cpu_ptr) = 0; virtual void convert_to_prv(void* cpu_ptr) = 0; virtual void convert_from_other(std::shared_ptr<PrvMemDescr> other) = 0; virtual void* prv_ptr(bool allocate_when_uninit = true) = 0; // returns true for matching layouts virtual bool layout_compare(std::shared_ptr<PrvMemDescr> other) = 0; virtual size_t prv_count() = 0; virtual size_t prv_size() = 0; // This might help using prv_ptr_ by different accelerators/engines enum PrvDescrType { PRV_DESCR_MKL2017, PRV_DESCR_MKLDNN }; virtual PrvDescrType get_descr_type() = 0; }; #if MKL_EXPERIMENTAL == 1 // Currently HEAD_AT_PRV do not free CPU data enum SyncedHead { HEAD_AT_CPU, HEAD_AT_PRV, }; struct MKLMemHolder { SyncedHead head_; std::shared_ptr<PrvMemDescr> prv_descriptor_; bool b_disable_prv_2_cpu; bool b_eager_mode; void disable_prv_2_cpu(bool flag) { b_disable_prv_2_cpu = flag; } void set_eager_mode(bool eager_mode) { b_eager_mode = eager_mode; } void set_prv_descriptor(std::shared_ptr<PrvMemDescr> descriptor, bool same_data = false) { head_ = HEAD_AT_PRV; prv_descriptor_ = descriptor; } std::shared_ptr<PrvMemDescr> get_prv_descriptor() { return prv_descriptor_; } bool head_at_prv() { return (head_ == HEAD_AT_PRV) ? true : false; } void* prv_data(bool allocate_when_uninit = true) { if (head_ != HEAD_AT_PRV) { return NULL; } if (prv_descriptor_ == NULL) { LOG(FATAL) << " prv_descriptor_ is NULL"; } CHECK(prv_descriptor_.get()); return reinterpret_cast<void*>(prv_descriptor_->prv_ptr(allocate_when_uninit)); } int prv_count() { if (head_ != HEAD_AT_PRV) { return 0; } if (prv_descriptor_ == NULL) { LOG(FATAL) << " prv_descriptor_ is NULL"; } CHECK(prv_descriptor_.get()); return prv_descriptor_->prv_count(); } static std::shared_ptr<MKLMemHolder> create() { return std::make_shared<MKLMemHolder>(); } void check_and_prv_to_cpu(void *dptr_) { if (!b_disable_prv_2_cpu && head_ == HEAD_AT_PRV) { CHECK(prv_descriptor_ != nullptr); prv_descriptor_->convert_from_prv(dptr_); // Because operator use CPU & maybe change it, change to CPU Flag head_ = HEAD_AT_CPU; } if (b_disable_prv_2_cpu) { b_disable_prv_2_cpu = false; } } MKLMemHolder() : head_(HEAD_AT_CPU), prv_descriptor_(nullptr), b_disable_prv_2_cpu(false), b_eager_mode(false) {} }; #else struct MKLMemHolder { public: virtual std::shared_ptr<PrvMemDescr> get_prv_descriptor() = 0; }; #endif } // namespace mxnet #endif // MXNET_OPERATOR_MKL_MKL_MEMORY_H_
/************************************************************************** * Functie : NaloopVtgDet * * Functionele omschrijving : * Verzorgt een naloop van fc1 naar fc2 afhankelijk van gebruikte dk * Nalooptijd geldt vanaf startgroen aanvoerrichting en duurt tnl lang. **************************************************************************/ void NaloopVtgDet(count fc1, count fc2, count dk, count hdk, count tnl) { if (SG[fc1]) IH[hdk] = FALSE; IH[hdk] |= D[dk] && !G[fc1] && A[fc1]; RT[tnl] = SG[fc1] && H[hdk]; if (RT[tnl]) RW[fc2] |= BIT2; if (RT[tnl] || T[tnl]) YV[fc2] |= BIT2; }
/// Request to update a position on the hotkey bar (CZ_SHORTCUT_KEY_CHANGE). /// 02ba <index>.W <is skill>.B <id>.L <count>.W void clif_parse_Hotkey(int fd, struct map_session_data *sd) { #ifdef HOTKEY_SAVING unsigned short idx; struct s_packet_db* info = &packet_db[sd->packet_ver][RFIFOW(fd,0)]; idx = RFIFOW(fd, info->pos[0]); if (idx >= MAX_HOTKEYS) return; sd->status.hotkeys[idx].type = RFIFOB(fd,info->pos[1]); sd->status.hotkeys[idx].id = RFIFOL(fd, info->pos[2]); sd->status.hotkeys[idx].lv = RFIFOW(fd, info->pos[3]); #endif }
/** * Set whether the ddlist highlight the last selected option and display its text or not * @param ddlist pointer to a drop down list object * @param show true/false */ void lv_dropdown_set_show_selected(lv_obj_t * ddlist, bool show) { LV_ASSERT_OBJ(ddlist, LV_OBJX_NAME); lv_dropdown_ext_t * ext = lv_obj_get_ext_attr(ddlist); if(ext->show_selected == show) return; ext->show_selected = show; lv_obj_invalidate(ddlist); }
/* * ground is the equation of the plane onto which the shadow should * be projected. * light is the homogenious coordinate of the light position. */ static void myShadowMatrix(float ground[4], float light[4]) { float dot; float shadowMat[4][4]; dot = ground[0] * light[0] + ground[1] * light[1] + ground[2] * light[2] + ground[3] * light[3]; shadowMat[0][0] = dot - light[0] * ground[0]; shadowMat[1][0] = 0.0 - light[0] * ground[1]; shadowMat[2][0] = 0.0 - light[0] * ground[2]; shadowMat[3][0] = 0.0 - light[0] * ground[3]; shadowMat[0][1] = 0.0 - light[1] * ground[0]; shadowMat[1][1] = dot - light[1] * ground[1]; shadowMat[2][1] = 0.0 - light[1] * ground[2]; shadowMat[3][1] = 0.0 - light[1] * ground[3]; shadowMat[0][2] = 0.0 - light[2] * ground[0]; shadowMat[1][2] = 0.0 - light[2] * ground[1]; shadowMat[2][2] = dot - light[2] * ground[2]; shadowMat[3][2] = 0.0 - light[2] * ground[3]; shadowMat[0][3] = 0.0 - light[3] * ground[0]; shadowMat[1][3] = 0.0 - light[3] * ground[1]; shadowMat[2][3] = 0.0 - light[3] * ground[2]; shadowMat[3][3] = dot - light[3] * ground[3]; glMultMatrixf((const GLfloat *) shadowMat); }
/* * adjust fs->glob so that it contains a single item which is a * properly allocated copy of the specified filename. assumes fs->glob * contains at least one name. */ static int glob_adjust(fstream_t* fs, char* filename, int* response_code, const char** response_string) { int i; int tlen = strlen(filename) + 1; char* tname = gfile_malloc(tlen); if (!tname) { *response_code = 500; *response_string = "fstream out of memory allocating copy of temporary file name"; gfile_printf_then_putc_newline("%s", *response_string); return 1; } for (i = 0; i<fs->glob.gl_pathc; i++) { gfile_free(fs->glob.gl_pathv[i]); fs->glob.gl_pathv[i] = NULL; } strcpy(tname, filename); fs->glob.gl_pathv[0] = tname; fs->glob.gl_pathc = 1; return 0; }
/* * See the serial2.h header file. */ xComPortHandle xSerialPortInitMinimal( uint32_t ulWantedBaud, UBaseType_t uxQueueLength ) { BaseType_t xStatus; XUartPs_Config *pxConfig; xRxQueue = xQueueCreate( uxQueueLength, sizeof( char ) ); configASSERT( xRxQueue ); xTxCompleteSemaphore = xSemaphoreCreateBinary(); configASSERT( xTxCompleteSemaphore ); xSemaphoreTake( xTxCompleteSemaphore, 0 ); pxConfig = XUartPs_LookupConfig( XPAR_XUARTPS_0_DEVICE_ID ); xStatus = XUartPs_CfgInitialize( &xUARTInstance, pxConfig, XPAR_PS7_UART_1_BASEADDR ); configASSERT( xStatus == XST_SUCCESS ); ( void ) xStatus; XUartPs_SetBaudRate( &xUARTInstance, ulWantedBaud ); XUartPs_SetOperMode( &xUARTInstance, XUARTPS_OPER_MODE_NORMAL ); xStatus = XScuGic_Connect( &xInterruptController, XPAR_XUARTPS_1_INTR, (Xil_ExceptionHandler) prvUART_Handler, (void *) &xUARTInstance ); configASSERT( xStatus == XST_SUCCESS ); ( void ) xStatus; XUartPs_WriteReg( XPAR_PS7_UART_1_BASEADDR, XUARTPS_ISR_OFFSET, XUARTPS_IXR_MASK ); XScuGic_Enable( &xInterruptController, XPAR_XUARTPS_1_INTR ); XUartPs_SetInterruptMask( &xUARTInstance, XUARTPS_IXR_RXFULL | XUARTPS_IXR_RXOVR | XUARTPS_IXR_TOUT | XUARTPS_IXR_TXEMPTY ); XUartPs_SetRecvTimeout( &xUARTInstance, 8 ); return ( xComPortHandle ) 0; }