content
stringlengths
19
48.2k
/* Function Name: finish_with_error * Description: finishes the program with a mysql error * Inputs: mysql connection pointer * Outputs: nothing */ void finish_with_error(MYSQL *con) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); }
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CORE_MINDAPI_IMPL_HELPER_H_ #define MINDSPORE_CORE_MINDAPI_IMPL_HELPER_H_ #include <memory> #include <vector> #include <type_traits> #include "mindapi/base/base.h" namespace mindspore::api { template <typename T, typename U> T &ToRef(const std::shared_ptr<U> &ptr) { return static_cast<T &>(*ptr); } template <typename T, typename U, typename = typename std::enable_if_t<std::is_base_of_v<mindspore::Base, T>>, typename = typename std::enable_if_t<std::is_base_of_v<Base, U>>> std::shared_ptr<T> ToImpl(const SharedPtr<U> &wrapper) { if (wrapper == nullptr || wrapper->impl() == nullptr) { return nullptr; } return std::dynamic_pointer_cast<T>(wrapper->impl()); } template <typename T, typename = typename std::enable_if_t<std::is_base_of_v<Base, T>>> SharedPtr<T> ToWrapper(const std::shared_ptr<mindspore::Base> &impl) { if (impl == nullptr) { return nullptr; } return MakeShared<T>(impl); } template <typename T, typename U> std::vector<std::shared_ptr<T>> ToImplVector(const U &wrapper_vector) { std::vector<std::shared_ptr<T>> impl_vector; impl_vector.reserve(wrapper_vector.size()); for (auto &wrapper : wrapper_vector) { impl_vector.emplace_back(ToImpl<T>(wrapper)); } return impl_vector; } template <typename T, typename U> std::vector<SharedPtr<T>> ToWrapperVector(const U &impl_vector) { std::vector<SharedPtr<T>> wrapper_vector; wrapper_vector.reserve(impl_vector.size()); for (auto &impl : impl_vector) { wrapper_vector.emplace_back(ToWrapper<T>(impl)); } return wrapper_vector; } #define MIND_API_BASE_IMPL(current_class, impl_class, base_class) \ current_class::current_class(const std::shared_ptr<mindspore::Base> &impl) : base_class(impl) { \ if (!impl_->isa<impl_class>()) { \ MS_LOG(EXCEPTION) << "Wrong impl " << impl_->type_name() << " for " << #current_class; \ } \ } \ uint32_t current_class::ClassId() { return impl_class::kTypeId; } } // namespace mindspore::api #endif // MINDSPORE_CORE_MINDAPI_IMPL_HELPER_H_
/** * Register a new packet type and the corresponding identifier. Each module * introducing a new packet type should register it using this function. * * @note Call lmod_uninit_packet_types() to free the allocated memory! * * @param packet_type The packet type number to register. * @param identifier A name for the packet type. * * @return Success = 0 * Error = -1 */ int lmod_register_packet_type(const uint8_t packet_type, const char *const identifier) { int idx = 0; const struct hip_ll_node *iter = NULL; struct packet_type *new_entry = NULL; if (!identifier || (lmod_packet_type_exists(packet_type) != -1)) { return -1; } if (!(new_entry = malloc(sizeof(struct packet_type)))) { return -1; } new_entry->num = packet_type; if (!(new_entry->identifier = strdup(identifier))) { return -1; } while ((iter = hip_ll_iterate(&packet_types, iter))) { if (packet_type == ((struct packet_type *) iter->ptr)->num) { return -1; } else if (packet_type < ((struct packet_type *) iter->ptr)->num) { break; } else { idx++; } } hip_ll_add(&packet_types, idx, new_entry); return 0; }
/* * @brief platform specific initialization (platform dependent) */ static void platform_init(void) { uint32_t retVal32 = 0; am_hal_iom_config_t i2cConfig = { .eInterfaceMode = AM_HAL_IOM_I2C_MODE, .ui32ClockFreq = AM_HAL_IOM_100KHZ }; retVal32 = am_hal_iom_initialize(AM_BSP_ACCELEROMETER_I2C_IOM, &iomHandle); if (retVal32 != AM_HAL_STATUS_SUCCESS) return; retVal32 = am_hal_iom_power_ctrl(iomHandle, AM_HAL_SYSCTRL_WAKE, false); if (retVal32 != AM_HAL_STATUS_SUCCESS) return; retVal32 = am_hal_iom_configure(iomHandle, &i2cConfig); if (retVal32 != AM_HAL_STATUS_SUCCESS) return; -3; Configure the IOM pins. am_hal_gpio_pinconfig(AM_BSP_ACCELEROMETER_I2C_SDA_PIN, g_AM_BSP_GPIO_IOM4_SCL); 39 am_hal_gpio_pinconfig(AM_BSP_ACCELEROMETER_I2C_SCL_PIN, g_AM_BSP_GPIO_IOM4_SDA); 40 Enable the IOM. retVal32 = am_hal_iom_enable(iomHandle); if (retVal32 != AM_HAL_STATUS_SUCCESS) return; -4; }
/* * .get_trip_type wrapper: get the type of certain trip point. */ static int mtk_thermal_wrapper_get_trip_type (struct thermal_zone_device *thermal, int trip, enum thermal_trip_type *type) { int ret = 0; struct thermal_zone_device_ops *ops; ops = getClientZoneOps(thermal); if (!ops) { THRML_ERROR_LOG("[.get_trip_type] tz: %s unregistered.\n", thermal->type); return 1; } if (ops->get_trip_type) ret = ops->get_trip_type(thermal, trip, type); THRML_LOG("[.get_trip_type] tz: %s trip: %d type: %d\n", thermal->type, trip, *type); return ret; }
//process server's idnt answer short cli_regs_ans(unsigned char* pkt) { fp_t q; ecpoint_fp P; ecpoint_fp R; ecpoint_fp K; short i; unsigned char e=0; unsigned char ee=pkt[3]; int id=mtoi(pkt+REGS_AD); unsigned int crc=mtoi(pkt+REGS_AC); while(1) { if(REGS!=pkt[2]) { e=ERC_REGS_A_TYPE; break; } if(REGS_AL!=mtos(pkt)) { e=ERC_REGS_A_LEN; break; } if(ee&CLI_FATAL_ERR) { e=ee; break; } if(!(cli->flags & FLAG_IDNT)) { e=ERC_REGS_A_NOIDNT; break; } if(id!=cli->id) { e=ERC_REGS_A_ID; break; } if(crc!=crc32_le(pkt, REGS_AC)) { e=ERC_REGS_A_CRC; break; } memcpy(q, pkt+REGS_AB, sizeof(q)); i=bls_uncompress(&P, q); if(!i) { printf("Invalid point!"); e=ERC_REGS_A_POINT_SIG; break; } memcpy(q, pkt+REGS_AG, REGS_AG_LEN); i=bls_uncompress(&K, q); if(!i) { printf("Invalid point!"); e=ERC_REGS_A_POINT_RP1; break; } bls_unblind(&R, &P, &K, cli->b); sh_ini(); sh_upd(cli->key, sizeof(cli->key)); sh_xof(); sh_out((unsigned char*)q, sizeof(q)); i=bls_hash(&P, q); if(!i) { printf("Invalid point!"); e=ERC_REGS_A_HASH_OURK; break; } i=bls_verify(&P, &R, &cli->RR); if(!i) { printf("Invalid psignature!"); e=ERC_REGS_A_VERIFY_BSIG; break; } bls_compress(cli->sig, &R); i=cli_fwrite(FILE_SIGN, (unsigned char*)cli->sig, sizeof(cli->sig)); if(i!=sizeof(cli->sig)) { e=ERC_REGS_A_SAVE_BSIG; break; } cli->flags|=FLAG_REGS; cli_fwrite(FILE_REGSA, pkt, REGS_AL); break; } printf("Client: regs ans %d\r\n", e); i=0; if(e) i=-e; else if(ee) i=ee+CLI_NOTE; crc=0; id=0; sh_clr(); my_memclr(q, sizeof(q)); my_memclr(&P, sizeof(P)); my_memclr(&R, sizeof(R)); my_memclr(&K, sizeof(K)); my_memclr(pkt, REGS_AL); return i; }
/** * Bump the timestamp of the specified uav for the specified pipeline, * so the uav will not be prematurely purged. */ static void svga_uav_cache_use_uav(struct svga_context *svga, enum svga_pipe_type pipe_type, struct svga_uav *uav) { assert(uav != NULL); assert(uav->uaViewId != SVGA3D_INVALID_ID); uav->timestamp[pipe_type] = svga->state.uav_timestamp[pipe_type]; }
/** * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes * @phba: pointer to lpfc hba data structure. * * This routine retrieves SLI4 device physical port name this PCI function * is attached to. * * Return codes * 0 - successful * otherwise - failed to retrieve controller attributes **/ static int lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba) { LPFC_MBOXQ_t *mboxq; struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr; struct lpfc_controller_attribute *cntl_attr; void *virtaddr = NULL; uint32_t alloclen, reqlen; uint32_t shdr_status, shdr_add_status; union lpfc_sli4_cfg_shdr *shdr; int rc; mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL); if (!mboxq) return -ENOMEM; reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes); alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON, LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen, LPFC_SLI4_MBX_NEMBED); if (alloclen < reqlen) { lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT, "3084 Allocated DMA memory size (%d) is " "less than the requested DMA memory size " "(%d)\n", alloclen, reqlen); rc = -ENOMEM; goto out_free_mboxq; } rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL); virtaddr = mboxq->sge_array->addr[0]; mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr; shdr = &mbx_cntl_attr->cfg_shdr; shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response); shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response); if (shdr_status || shdr_add_status || rc) { lpfc_printf_log(phba, KERN_WARNING, LOG_SLI, "3085 Mailbox x%x (x%x/x%x) failed, " "rc:x%x, status:x%x, add_status:x%x\n", bf_get(lpfc_mqe_command, &mboxq->u.mqe), lpfc_sli_config_mbox_subsys_get(phba, mboxq), lpfc_sli_config_mbox_opcode_get(phba, mboxq), rc, shdr_status, shdr_add_status); rc = -ENXIO; goto out_free_mboxq; } cntl_attr = &mbx_cntl_attr->cntl_attr; phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL; phba->sli4_hba.lnk_info.lnk_tp = bf_get(lpfc_cntl_attr_lnk_type, cntl_attr); phba->sli4_hba.lnk_info.lnk_no = bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr); phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr); phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr); memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion)); strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str, sizeof(phba->BIOSVersion)); lpfc_printf_log(phba, KERN_INFO, LOG_SLI, "3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, " "flash_id: x%02x, asic_rev: x%02x\n", phba->sli4_hba.lnk_info.lnk_tp, phba->sli4_hba.lnk_info.lnk_no, phba->BIOSVersion, phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev); out_free_mboxq: if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG) lpfc_sli4_mbox_cmd_free(phba, mboxq); else mempool_free(mboxq, phba->mbox_mem_pool); return rc; }
/** * @brief This function is used by the design by contract macros: REQUIRE, ENSURE, INVARIANT. * * This function is called by the CONTRACT_ASSERT that is the base macro utilized by the rest * of the design by contract macros. This function will notify the developer of a failed * precondition( REQUIRE ), postcondition( ENSURE ) or invariance( INVARIANT ). This method * is customizable, but does provide the filename and line number of the failed contract. * * @param[in] file The filename of the file where the failed contract occurred. * @param[in] line The line number of the failed contract. */ void onContractFailure(uint8_t* file, uint32_t line) { static unsigned place_to_put_breakpoint; UNUSED(file); UNUSED(line); place_to_put_breakpoint++; }
/* API to send playback stream specific config parameters */ int qahwi_out_set_param_data(struct audio_stream_out *stream, audio_extn_param_id param_id, audio_extn_param_payload *payload) { int ret = 0; struct stream_out *out = (struct stream_out *)stream; if (audio_extn_is_qaf_stream(out)) { ret = audio_extn_qaf_out_set_param_data(out, param_id, payload); if (ret) ALOGE("%s::qaf_out_set_param_data failed error %d", __func__ , ret); } else { if (out->standby && (param_id != AUDIO_EXTN_PARAM_OUT_CHANNEL_MAP)) out->stream.write(&out->stream, NULL, 0); lock_output_stream(out); ret = audio_extn_out_set_param_data(out, param_id, payload); if (ret) ALOGE("%s::audio_extn_out_set_param_data error %d", __func__, ret); pthread_mutex_unlock(&out->lock); } return ret; }
/* * This wrapper is a workaround for a funny _popen() feature on Windows * where it eats external quotes in some cases. The bug seems to be related * to the quote stripping functionality used by the Windows cmd.exe * interpreter when its /S is not specified. * * Cleaned up quote from the cmd.exe help screen as displayed on Windows XP * SP3: * * 1. If all of the following conditions are met, then quote characters on * the command line are preserved: * * - no /S switch * - exactly two quote characters * - no special characters between the two quote characters, where * special is one of: &<>()@^| * - there are one or more whitespace characters between the two quote * characters * - the string between the two quote characters is the name of an * executable file. * * 2. Otherwise, old behavior is to see if the first character is a quote * character and if so, strip the leading character and remove the last * quote character on the command line, preserving any text after the * last quote character. * * This causes some commands containing quotes not to be executed correctly. * For example: * * "\Long folder name\aaa.exe" --name="Jurko" --no-surname * * would get its outermost quotes stripped and would be executed as: * * \Long folder name\aaa.exe" --name="Jurko --no-surname * * which would report an error about '\Long' not being a valid command. * * cmd.exe help seems to indicate it would be enough to add an extra space * character in front of the command to avoid this but this does not work, * most likely due to the shell first stripping all leading whitespace * characters from the command. * * Solution implemented here is to quote the whole command in case it * contains any quote characters. Note thought this will not work correctly * should Windows ever 'fix' this feature. * (03.06.2008.) (Jurko) */ static FILE * windows_popen_wrapper( char const * command, char const * mode ) { int const extra_command_quotes_needed = !!strchr( command, '"' ); string quoted_command; FILE * result; if ( extra_command_quotes_needed ) { string_new( &quoted_command ); string_append( &quoted_command, "\"" ); string_append( &quoted_command, command ); string_append( &quoted_command, "\"" ); command = quoted_command.value; } result = _popen( command, "r" ); if ( extra_command_quotes_needed ) string_free( &quoted_command ); return result; }
/* * Returns number of entries in an address-group * * Only used by UTs. */ int npf_addrgrp_nentries(const char *name) { struct npf_addrgrp *ag; ag = npf_tbl_name_lookup(g_addrgrp_table, name); if (!ag) return 0; return zlist_size(ag->ag_list[AG_IPv4]) + zlist_size(ag->ag_list[AG_IPv6]); }
/* $Id: display7seg.c,v 1.6 2002/01/08 16:00:16 davem Exp $ * * display7seg - Driver implementation for the 7-segment display * present on Sun Microsystems CP1400 and CP1500 * * Copyright (c) 2000 Eric Brower (ebrower@usa.net) * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/errno.h> #include <linux/major.h> #include <linux/init.h> #include <linux/miscdevice.h> #include <linux/ioport.h> /* request_region */ #include <linux/smp_lock.h> #include <asm/atomic.h> #include <asm/ebus.h> /* EBus device */ #include <asm/oplib.h> /* OpenProm Library */ #include <asm/uaccess.h> /* put_/get_user */ #include <asm/io.h> #include <asm/display7seg.h> #define D7S_MINOR 193 #define D7S_OBPNAME "display7seg" #define D7S_DEVNAME "d7s" static int sol_compat = 0; /* Solaris compatibility mode */ #ifdef MODULE /* Solaris compatibility flag - * The Solaris implementation omits support for several * documented driver features (ref Sun doc 806-0180-03). * By default, this module supports the documented driver * abilities, rather than the Solaris implementation: * * 1) Device ALWAYS reverts to OBP-specified FLIPPED mode * upon closure of device or module unload. * 2) Device ioctls D7SIOCRD/D7SIOCWR honor toggling of * FLIP bit * * If you wish the device to operate as under Solaris, * omitting above features, set this parameter to non-zero. */ module_param (sol_compat, int, 0); MODULE_PARM_DESC (sol_compat, "Disables documented functionality omitted from Solaris driver"); MODULE_AUTHOR ("Eric Brower <ebrower@usa.net>"); MODULE_DESCRIPTION ("7-Segment Display driver for Sun Microsystems CP1400/1500"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE ("d7s"); #endif /* ifdef MODULE */ /* * Register block address- see header for details * ----------------------------------------- * | DP | ALARM | FLIP | 4 | 3 | 2 | 1 | 0 | * ----------------------------------------- * * DP - Toggles decimal point on/off * ALARM - Toggles "Alarm" LED green/red * FLIP - Inverts display for upside-down mounted board * bits 0-4 - 7-segment display contents */ static void __iomem* d7s_regs; static inline void d7s_free(void) { iounmap(d7s_regs); } static inline int d7s_obpflipped(void) { int opt_node; opt_node = prom_getchild(prom_root_node); opt_node = prom_searchsiblings(opt_node, "options"); return ((-1 != prom_getintdefault(opt_node, "d7s-flipped?", -1)) ? 0 : 1); } static atomic_t d7s_users = ATOMIC_INIT(0); static int d7s_open(struct inode *inode, struct file *f) { if (D7S_MINOR != iminor(inode)) return -ENODEV; atomic_inc(&d7s_users); return 0; } static int d7s_release(struct inode *inode, struct file *f) { /* Reset flipped state to OBP default only if * no other users have the device open and we * are not operating in solaris-compat mode */ if (atomic_dec_and_test(&d7s_users) && !sol_compat) { int regval = 0; regval = readb(d7s_regs); (0 == d7s_obpflipped()) ? writeb(regval |= D7S_FLIP, d7s_regs): writeb(regval &= ~D7S_FLIP, d7s_regs); } return 0; } static long d7s_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { __u8 regs = readb(d7s_regs); __u8 ireg = 0; int error = 0; if (D7S_MINOR != iminor(file->f_path.dentry->d_inode)) return -ENODEV; lock_kernel(); switch (cmd) { case D7SIOCWR: /* assign device register values * we mask-out D7S_FLIP if in sol_compat mode */ if (get_user(ireg, (int __user *) arg)) { error = -EFAULT; break; } if (0 != sol_compat) { (regs & D7S_FLIP) ? (ireg |= D7S_FLIP) : (ireg &= ~D7S_FLIP); } writeb(ireg, d7s_regs); break; case D7SIOCRD: /* retrieve device register values * NOTE: Solaris implementation returns D7S_FLIP bit * as toggled by user, even though it does not honor it. * This driver will not misinform you about the state * of your hardware while in sol_compat mode */ if (put_user(regs, (int __user *) arg)) { error = -EFAULT; break; } break; case D7SIOCTM: /* toggle device mode-- flip display orientation */ (regs & D7S_FLIP) ? (regs &= ~D7S_FLIP) : (regs |= D7S_FLIP); writeb(regs, d7s_regs); break; }; unlock_kernel(); return error; } static const struct file_operations d7s_fops = { .owner = THIS_MODULE, .unlocked_ioctl = d7s_ioctl, .compat_ioctl = d7s_ioctl, .open = d7s_open, .release = d7s_release, }; static struct miscdevice d7s_miscdev = { D7S_MINOR, D7S_DEVNAME, &d7s_fops }; static int __init d7s_init(void) { struct linux_ebus *ebus = NULL; struct linux_ebus_device *edev = NULL; int iTmp = 0, regs = 0; for_each_ebus(ebus) { for_each_ebusdev(edev, ebus) { if (!strcmp(edev->prom_node->name, D7S_OBPNAME)) goto ebus_done; } } ebus_done: if(!edev) { printk("%s: unable to locate device\n", D7S_DEVNAME); return -ENODEV; } d7s_regs = ioremap(edev->resource[0].start, sizeof(__u8)); iTmp = misc_register(&d7s_miscdev); if (0 != iTmp) { printk("%s: unable to acquire miscdevice minor %i\n", D7S_DEVNAME, D7S_MINOR); iounmap(d7s_regs); return iTmp; } /* OBP option "d7s-flipped?" is honored as default * for the device, and reset default when detached */ regs = readb(d7s_regs); iTmp = d7s_obpflipped(); (0 == iTmp) ? writeb(regs |= D7S_FLIP, d7s_regs): writeb(regs &= ~D7S_FLIP, d7s_regs); printk("%s: 7-Segment Display%s at 0x%lx %s\n", D7S_DEVNAME, (0 == iTmp) ? (" (FLIPPED)") : (""), edev->resource[0].start, (0 != sol_compat) ? ("in sol_compat mode") : ("")); return 0; } static void __exit d7s_cleanup(void) { int regs = readb(d7s_regs); /* Honor OBP d7s-flipped? unless operating in solaris-compat mode */ if (0 == sol_compat) { (0 == d7s_obpflipped()) ? writeb(regs |= D7S_FLIP, d7s_regs): writeb(regs &= ~D7S_FLIP, d7s_regs); } misc_deregister(&d7s_miscdev); d7s_free(); } module_init(d7s_init); module_exit(d7s_cleanup);
/////////////////////////////////////////////////////////////////////////////// // ENB Measures // Messages for triggering measurement //--------------------------------------------------------------------------- void nasrg_set_msg_eNBmeasure_trigger_reply(struct nas_msg_enb_measure_trigger_reply *msgrep, struct nas_msg_enb_measure_trigger *msgreq) { struct cx_entity *cx; int lcr=0; cx=nasrg_COMMON_search_cx(lcr); if (msgreq->cell_id != cx->cellid) printk("\nERROR : invalid cell_id received\n\n"); if (nasrg_ASCTL_DC_send_eNBmeasurement_req(cx)>0) msgrep->status = 0; else msgrep->status = NAS_ERROR_NOTCORRECTVALUE ; }
#pragma once #include "shap_prepared_trees.h" #include <catboost/libs/model/model.h> #include <util/generic/vector.h> void PostProcessingIndependent( const TIndependentTreeShapParams& independentTreeShapParams, const TVector<TVector<TVector<double>>>& shapValuesForAllReferences, const TVector<TVector<int>>& combinationClassFeatures, size_t approxDimension, size_t flatFeatureCount, size_t documentIdx, bool calcInternalValues, const TVector<double>& bias, TVector<TVector<double>>* shapValues ); void AddValuesToShapValuesByAllReferences( const TVector<TVector<TVector<double>>>& shapValueByDepthForLeaf, const TVector<NCB::NModelEvaluation::TCalcerIndexType>& referenceLeafIndices, const TVector<int>& binFeatureCombinationClassByDepth, TVector<TVector<TVector<double>>>* shapValuesForAllReferences ); void CalcObliviousShapValuesByDepthForLeaf( const TModelTrees& forest, const TVector<NCB::NModelEvaluation::TCalcerIndexType>& referenceLeafIndices, const TVector<int>& binFeatureCombinationClass, const TVector<TVector<int>>& combinationClassFeatures, const TVector<TVector<double>>& weights, size_t documentLeafIdx, size_t treeIdx, bool isCalcForAllLeafes, TVector<TVector<TVector<double>>>* shapValueByDepthBetweenLeaves );
// Verify a X.509 signature that is RSA / SHA256 based CK_BBOOL rsaVerify(CK_BYTE_PTR pModulus, CK_ULONG ulModLen, CK_BYTE_PTR pExponent, CK_BYTE bExpLen, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature) { CK_MECHANISM mechanism; CK_RV status; CK_OBJECT_CLASS pubKeyClass = CKO_PUBLIC_KEY; CK_BBOOL itsFalse = CK_FALSE; CK_KEY_TYPE keyType = CKK_RSA; CK_OBJECT_HANDLE hUntrustedKey; CK_ATTRIBUTE pubKeyTemplate[] = { {CKA_CLASS,(CK_VOID_PTR)&pubKeyClass,sizeof(pubKeyClass)}, {CKA_TOKEN,(CK_VOID_PTR)&itsFalse,sizeof(itsFalse)}, {CKA_KEY_TYPE,(CK_VOID_PTR)&keyType,sizeof(keyType)}, {CKA_MODULUS,(CK_VOID_PTR)pModulus,ulModLen}, {CKA_PUBLIC_EXPONENT,(CK_VOID_PTR)pExponent, bExpLen} }; if (C_CreateObject(hSession,pubKeyTemplate,5,&hUntrustedKey) != CKR_OK ) return CK_FALSE; sha256(pData,ulDataLen,abSha256SigTemplate+sizeof(abSha256SigTemplate)-SHA256_DIGEST_LEN); mechanism.mechanism = CKM_RSA_PKCS; mechanism.pParameter = NULL_PTR; mechanism.ulParameterLen = 0; status = C_VerifyInit(hSession,&mechanism,hUntrustedKey); if(status != CKR_OK) return CK_FALSE; status = C_Verify(hSession,abSha256SigTemplate,sizeof(abSha256SigTemplate),pSignature,ulModLen); if(status != CKR_OK) return CK_FALSE; return (CK_TRUE); }
/****************************************************************************** Function Name : usb_hmsc_error_process Description : Error processing when CSW error is retuned by MSC device. Arguments : uint16_t err_code : Error code Return value : uint16_t : Error code ******************************************************************************/ uint16_t usb_hmsc_error_process (uint16_t err_code) { uint16_t retval; static uint8_t g_usb_hmsc_rs_data[64]; retval = err_code; if (USB_HMSC_CSW_ERR == err_code) { retval = usb_hmsc_request_sense(g_usb_hmsc_rs_data); } return retval; }
/*This function was written by Travis Moret*/ /* * Updates the given key-value pair in the hash table. If a link with the given key already exists, this will just update the value and skip traversing. Otherwise, it will create a new link with the given key and value and add it to the table bucket's linked list. You can use hashLinkNew to create the link. * * Use HASH_FUNCTION(key) and the map's capacity to find the index of the * correct linked list bucket. * * @param map * @param key * @param value */ void hashMapPut(HashMap* map, const char* key, int value) { assert(map != 0); int index = HASH_FUNCTION(key) % map->capacity; struct HashLink* current = map->table[index]; while(current != 0) { if(strcmp(current->key,key) == 0) { current->value = value; return; } current = current->next; } struct HashLink* newLink = hashLinkNew(key,value,map->table[index]); map->table[index] = newLink; map->size++; if(hashMapTableLoad(map) >= MAX_TABLE_LOAD) { resizeTable(map, 2 * map->capacity); } }
/* * Show the note information at the bottom of window" */ void win_note_show(char *note) { char *content; char *p; p = NOTE_DEFAULT; content = (note != NULL) ? note : p; reg_erase(&s_note_reg); reg_line_write(&s_note_reg, 0, ALIGN_LEFT, content); reg_refresh(&s_note_reg); reg_update_all(); }
/** * Setup a connection to host * * @param self IN command object * @param worker IN thread data object * @param data IN unused * * @return an apr status */ static apr_status_t command_RES(command_t * self, worker_t * worker, char *data) { apr_status_t status; COMMAND_NO_ARG; if ((status = worker_flush(worker)) != APR_SUCCESS) { return status; } if ((status = worker_test_unused(worker)) != APR_SUCCESS) { return status; } worker_get_socket(worker, "Default", "0", NULL); worker->socket->is_ssl = worker->is_ssl; if (worker->socket->socket_state == SOCKET_CLOSED) { worker_log(worker, LOG_DEBUG, "--- accept"); if (!worker->listener) { worker_log_error(worker, "Server down"); return APR_EGENERAL; } if ((status = apr_socket_accept(&worker->socket->socket, worker->listener, worker->pool)) != APR_SUCCESS) { worker->socket->socket = NULL; return status; } if ((status = apr_socket_timeout_set(worker->socket->socket, worker->socktmo)) != APR_SUCCESS) { return status; } #ifdef USE_SSL if ((status = worker_ssl_accept(worker)) != APR_SUCCESS) { return status; } #endif worker->socket->socket_state = SOCKET_CONNECTED; } apr_table_clear(worker->match_headers); apr_table_clear(worker->match_body); apr_table_clear(worker->expect_dot); apr_table_clear(worker->expect_error); apr_table_clear(worker->match_error); return APR_SUCCESS; }
/* Must be called only from idle loop, with interrupts disabled. */ int vmi_stop_hz_timer(void) { unsigned long seq, next; unsigned long long real_cycles_expiry; int cpu = smp_processor_id(); BUG_ON(!irqs_disabled()); if (sysctl_hz_timer != 0) return 0; cpu_set(cpu, nohz_cpu_mask); smp_mb(); if (rcu_needs_cpu(cpu) || local_softirq_pending() || (next = next_timer_interrupt(), time_before_eq(next, jiffies + HZ/CONFIG_VMI_ALARM_HZ))) { cpu_clear(cpu, nohz_cpu_mask); return 0; } do { seq = read_seqbegin(&xtime_lock); real_cycles_expiry = real_cycles_accounted_system + (long)(next - jiffies) * cycles_per_jiffy; } while (read_seqretry(&xtime_lock, seq)); vmi_timer_ops.cancel_alarm(VMI_CYCLES_AVAILABLE); per_cpu(idle_start_jiffies, cpu) = jiffies; vmi_timer_ops.set_alarm( VMI_ALARM_WIRING | VMI_ALARM_IS_ONESHOT | VMI_CYCLES_REAL, real_cycles_expiry, 0); return 1; }
//------------------------------------------------------------ // Routine to replace invalid chars in comment fields //------------------------------------------------------------ BOOL ReplaceInValidFileName(LPSTR lpf) { char lpInvalid[] = "\\/:*?\"<>|"; DWORD i, j; size_t nLen; BOOL bLegal = FALSE; nLen = strlen(lpf); for (i = 0; i < nLen; i++) { for (j = 0; j < sizeof(lpInvalid) - 1; j++) { if (*(lpf + i) == *(lpInvalid + j)) { *(lpf + i) = '-'; } else if (*(lpf + i) != 0x20 && *(lpf + i) != 0x09) { bLegal = TRUE; } } } return bLegal; }
/** * Compares this {@code tstring} to another {@code tstring}, ignoring case * considerations. Two strings are considered equal ignoring case if they * are of the same length and the corresponding characters in the two strings * are equal ignoring case. * * @param[in] s The {@code tstring} object parameter. * @param[in] ref The {@code tstring} to compare this {@code tstring} * against * * @returns {@code true} if the arguments are not {@code NULL} and they * represents an equivalent {@code tstring} ignoring case; {@code * false} otherwise. */ bool tstring_equals_ignorecase(const tstring* s, const tstring* ref) { if (s == ref) return true; if (!s || !ref) return false; if (s->length != ref->length) return false; return __strcasecmp(s->cstr, ref->cstr) == 0; }
/* append a long to the end of FastLongBuffer */ void appendLong(FastLongBuffer *flb, Long i){ Long *lastBuffer = NULL; int lastBufferIndex; if (flb->al->size == 0) { lastBuffer = (Long *)malloc(sizeof(Long)<<flb->exp); if (lastBuffer == NULL){ throwException2(out_of_mem, "AppendLong failed to allocate mem"); } add(flb->al,lastBuffer); flb->capacity = flb->pageSize; }else{ lastBufferIndex = min((flb->size>>flb->exp),flb->al->size-1); lastBuffer = (Long *)get(flb->al, lastBufferIndex); } if (flb->size < flb->capacity){ lastBuffer[flb->size & flb->r] = i; flb->size ++; }else { Long *newBuffer = (Long *)malloc(sizeof(Long)<<flb->exp); if (newBuffer == NULL){ throwException2(out_of_mem, "AppendLong failed to allocate mem"); } flb->size ++; flb->capacity += flb->pageSize; add(flb->al, newBuffer); newBuffer[0]=i; } }
#ifndef ISDB_INCLUDE #define ISDB_INCLUDE #ifdef _NET_NEONS #include <nn_client.h> #endif /* _NET_NEONS */ /* max value from rand; HW/OS dependent */ #define MAX_RAND 2147483647. /* SUN */ /* #define MAX_RAND 32767. */ /* HP, Solaris */ /* Vers 4.2.1 was installed 10/01/97 on Kelvin */ #define NEONS_VRSN_MAJOR 4 /* major release version of NEONS software */ #define NEONS_VRSN_MINOR 2 /* minor release version of NEONS software */ #define NEONS_VRSN_MINOR2 1 /* (sub) minor release version of software */ /* (for bug fixes) */ #define BYTE_BIT_CNT 8 /* count of bits per byte */ #define WORD_BIT_CNT sizeof(long)*BYTE_BIT_CNT /* count of bits per word */ #define WORD_BYTE_CNT 4 /* count of bytes per word */ #define OPN_RD 1 /* open database for read only */ #define OPN_WR_RD 2 /* open database for write+read */ #define MAX_FILE_CNT 15 /* maximum count of open files */ #define ISDB_MODE 0666 /* mode for image files placed into db */ #define LOCK_MODE 0200 /* mode for locking files while writing */ #define INGEST_OWN "dba" /* owner of image files before loaded in db */ #define INGEST_MODE 0644 /* mode for ingest files before loaded in db */ #define CLNDR_HOUR 0 /* calendar time, units = hours */ #define CLIMO_DAY 1 /* climatology time, units = day in year */ #define CLIMO_WEEK 2 /* climatology time, units = week in year */ #define CLIMO_MONTH 3 /* climatology time, units = month in year */ #define CLIMO_SEASON 4 /* climatology time, units = season in year */ typedef struct { /* date structure */ int year; /* year number since 0 BC */ int month; /* month number in year */ int day; /* day number in month */ int type; /* time coordinate type, default time type */ /* is calendar time */ } DATE; typedef struct { /* info from table as_band */ long chan_num; /* channel number within sensor */ char band_name[31]; /* name of band */ long bit_cnt; /* count of bits in pixel */ float scl_fctr; /* scaling factor */ float reference; /* reference value */ char unit_name[31]; /* name of physical units */ } AS_BAND; typedef struct { /* info from tables grid_reg_geom/as_reg_im */ char prjn_name[21]; /* projection name */ char stor_dsc[21]; /* (+x in +y)/(+x in -y)/(-y in +x)/etc */ long nx; /* count of columns */ long ny; /* count of rows */ double lat; /* lat of origin in degrees */ double lon; /* lon of origin in degrees */ #ifdef OLD_REG_GEOM long orig_ix; /* column # for origin, left column is 1 */ long orig_iy; /* row # for origin; top row is 1 */ float x_int_dis; /* distance interval between columns in km */ float y_int_dis; /* distance interval between rows in km */ float parm_1; /* geom parm 1, depends on projection */ float parm_2; /* geom parm 2, depends on projection */ float parm_3; /* geom parm 3, depends on projection */ #else double orig_ix; /* column # for origin, left column is 1 */ double orig_iy; /* row # for origin; top row is 1 */ double x_int_dis; /* distance interval between columns in km */ double y_int_dis; /* distance interval between rows in km */ double parm_1; /* geom parm 1, depends on projection */ double parm_2; /* geom parm 2, depends on projection */ double parm_3; /* geom parm 3, depends on projection */ #endif /* OLD_REG_GEOM */ } REG_GEOM; typedef struct { /* info from table as_sat_im */ long bgn_lin_num; /* beginning line number in orbit or pass */ long bgn_smp_num; /* beginning sample number in scan line */ long lin_int; /* lin interval relative to sensor scan mode */ long smp_int; /* smp interval relative to sensor scan mode */ float roll_ang; /* satellite roll angle in degrees */ float pch_ang; /* satellite pitch angle in degrees */ float yaw_ang; /* satellite yaw angle in degrees */ } SAT_GEOM; typedef struct { /* info from table grid_spct_geom */ char stor_dsc[21]; /* (+x in +y)/(+x in -y)/(-y in +x)/etc */ char trnc_type[21]; /* spectral truncation type (triangular/etc) */ long coef_cnt; /* count of complex coefficients used */ long max_lat_wav_num; /* max latitudinal wavenumber (M in GRIB) */ long max_lon_wav_num_1; /* max longitudinal wavenumber 1 (J in GRIB) */ long max_lon_wav_num_2; /* max longitudinal wavenumber 2 (K in GRIB) */ } SPCT_GEOM; typedef struct { /* info from table sat_oe */ char seq_name[21]; /* orb-elem sequence name */ DATE date; /* date for orbital elements */ double hour; /* hour of day for orbital elements */ double parm_1; /* orb-elem parm 1 value */ double parm_2; /* orb-elem parm 2 value */ double parm_3; /* orb-elem parm 3 value */ double parm_4; /* orb-elem parm 4 value */ double parm_5; /* orb-elem parm 5 value */ double parm_6; /* orb-elem parm 6 value */ double parm_7; /* orb-elem parm 7 value */ } ORB_ELEM; typedef struct { /* bit-map structure */ short lin_cnt; /* count of lines in bitmap */ short smp_cnt; /* count of samples per line in bitmap */ short pad_bit_cnt; /* count of bits for padding lines in bitmap */ short ofst_byte_cnt; /* byte offset into bitmap array where actual bitmap data begins */ unsigned char *bmap; /* unsigned char array containing bitmap */ } BITMAP; #endif /* ISDB_INCLUDE */
/* Re-read the current keybindings file. */ int rl_re_read_init_file (int count, int ignore) { int r; r = rl_read_init_file ((const char *)NULL); rl_set_keymap_from_edit_mode (); return r; }
/* This API is used to control to UI pages display if the status is docsis - no UI page for internet setting if the status is non-docsis- UI page with WAN option(byoi) and None( no internet) if the status is user - UI page with Cable(primary provider), WAN(byoi) and None(no internet) will be provided*/ int Utopia_Get_BYOI_allowed(UtopiaContext *ctx, int *byoi_state) { char buf[TOKEN_SZ]; if (NULL == ctx) { return ERR_UTCTX_INIT; } token_t se_token; int se_fd = s_sysevent_connect(&se_token); if (0 > se_fd) { return ERR_SYSEVENT_CONN; } sysevent_get(se_fd, se_token, "primary_HSD_allowed", buf, sizeof(buf)); int status = s_StrToEnum(g_byoi_Mode, buf); if(-1 == status) { status = USER_SELECTABLE; } *byoi_state = status; sprintf(ulog_msg, "%s: hsd_allowed %d", __FUNCTION__, *byoi_state); ulog(ULOG_CONFIG, UL_UTAPI, ulog_msg); return UT_SUCCESS; }
/* returns Y = (L^T \otimes I_P)*F_MUdot*X, where L and X are vectors of size N, I_P is the identity matrix of size P, \otimes is the Kronecker product, and F_MUdot is the N*P x N matrix with entries | F^1_MUdot | F_MU = | ... |, F^k has dimension PxN, with {F^k_MUdot}_ij = \frac{\partial^2 F_k}{\partial udot_j \partial m_i}, where F_k is the k-th component of the DAE | F^N_MUdot | with udot_j the time derivative of the j-th state variable and m_i the i-th design variable, with N the number of state variables and P the number of design variables. The output should be computed as: Y = (\sum_k L_k*F^k_MUdot)*X = (\sum_k L_k*(F^k_MUdot)^T)*X, with L_k the k-th entry of the adjoint variable L. */ static PetscErrorCode EvalHessianDAE_MUdot(TS ts, PetscReal time, Vec U, Vec Udot, Vec M, Vec L, Vec X, Vec Y, void *ctx) { UserDAE *user = (UserDAE*)ctx; PetscScalar *arr; PetscScalar x,l; PetscInt dsize; PetscErrorCode ierr; PetscFunctionBeginUser; ierr = VecSet(Y,0.0);CHKERRQ(ierr); ierr = VecGetSize(M,&dsize);CHKERRQ(ierr); if (dsize < 4) { PetscFunctionReturn(0); } ierr = VecGetArrayRead(L,(const PetscScalar**)&arr);CHKERRQ(ierr); l = arr[0]; ierr = VecRestoreArrayRead(L,(const PetscScalar**)&arr);CHKERRQ(ierr); ierr = VecGetArrayRead(X,(const PetscScalar**)&arr);CHKERRQ(ierr); x = arr[0]; ierr = VecRestoreArrayRead(X,(const PetscScalar**)&arr);CHKERRQ(ierr); ierr = VecSetValue(Y,3,l*2.0*user->mm*x,ADD_VALUES);CHKERRQ(ierr); ierr = VecAssemblyBegin(Y);CHKERRQ(ierr); ierr = VecAssemblyEnd(Y);CHKERRQ(ierr); PetscFunctionReturn(0); }
/* * Return the number of items in the list. If using this coung value to itterate through the list * with list_get, acquire the lists lock before the list_count/list_get block and release it afterwards. */ DWORD list_count( LIST * list ) { DWORD count = 0; if( list != NULL ) { lock_acquire( list->lock ); count = list->count; lock_release( list->lock ); } return count; }
/** * @brief Adds two quaternions. * @param quaternionA First quaternion of the operation. * @param quaternionB Second quaternion of the operation. * @return Sum of quaternionA and quaternionB. */ static inline __attribute__((always_inline)) FusionQuaternion FusionQuaternionAdd(const FusionQuaternion quaternionA, const FusionQuaternion quaternionB) { FusionQuaternion result; result.element.w = quaternionA.element.w + quaternionB.element.w; result.element.x = quaternionA.element.x + quaternionB.element.x; result.element.y = quaternionA.element.y + quaternionB.element.y; result.element.z = quaternionA.element.z + quaternionB.element.z; return result; }
#include<stdio.h> long long int gcd(long long int a,long long int b) { if(a%b==0) return b; else return gcd(b,a%b); } long long int f(long long int a) { long long int sum=0,s; while(a!=0) { s=a%10; sum=sum+s; a=a/10; } return sum; } int main() { long long int a,b,n; scanf("%lld",&n); for(int i=0;i<n;i++) { scanf("%lld",&a); while(1) { if(gcd(a,f(a))>1) { printf("%lld\n",a); break; } else { a=a+1; } } } // printf("%d",gcd(a,b)); }
/* This lambda is an instantiation of a lambda in a template default argument that got no LAMBDA_EXPR_EXTRA_SCOPE, so this shouldn't either. But we do need to use and increment the global count to avoid collisions. */ void record_null_lambda_scope (tree lambda) { if (vec_safe_is_empty (lambda_scope_stack)) record_lambda_scope (lambda); else { tree_int *p = lambda_scope_stack->begin(); LAMBDA_EXPR_EXTRA_SCOPE (lambda) = p->t; LAMBDA_EXPR_DISCRIMINATOR (lambda) = p->i++; } gcc_assert (LAMBDA_EXPR_EXTRA_SCOPE (lambda) == NULL_TREE); }
/* * Create NOF_FECS MC entries which each entry results to a different FEC */ int create_fecs_and_ipmc_entries(int unit, int outPort0,int outPort1,int outPort2,int outPort3) { int i,j; int ipmc_index_offset; bcm_multicast_t mc_id[4]; bcm_error_t rv ; bcm_mac_t my_mac_address = {0x00, 0x0c, 0x00, 0x02, 0x00, 0x00}; bcm_l3_intf_t intf; int flags; bcm_gport_t gport; bcm_l3_egress_t l3eg; bcm_if_t fec = 0; bcm_gport_t mc_gport[4]; bcm_ipmc_addr_t data; int ports[4]; sal_srand(sal_time()); bcm_vlan_t vlan_id=400; ports[0] = outPort0; ports[1] = outPort1; ports[2] = outPort2; ports[3] = outPort3; if (is_device_or_above(unit, JERICHO2)) { flags = BCM_MULTICAST_EGRESS_GROUP | BCM_MULTICAST_WITH_ID; ipmc_index_offset = 6000; } else { flags = BCM_MULTICAST_EGRESS_GROUP | BCM_MULTICAST_TYPE_L3 | BCM_MULTICAST_WITH_ID; ipmc_index_offset = diag_test_mc(unit,"get_nof_egress_bitmap_groups"); } printf(">>>ipmc_index_offset is %d\n", ipmc_index_offset); if (is_device_or_above(unit, JERICHO2)) { for(j = 0; j < 4; j++) { BCM_GPORT_LOCAL_SET(gport,ports[j]); rv = bcm_vlan_gport_add(unit, vlan_id, gport, BCM_VLAN_GPORT_ADD_INGRESS_ONLY); if (rv != BCM_E_NONE) { printf("Error, bcm_vlan_gport_add for port[%d]: %d\n", j, ports[j]); return rv; } mc_id[j] = ipmc_index_offset + (2 * j); mc_id[j] = create_ip_mc_group(unit,flags,mc_id[j],ports[j],1,vlan_id,0); } } else { for(j = 0;j < 4;j++) { mc_id[j] = ipmc_index_offset + (2 * j); rv = bcm_multicast_create(unit, flags, &mc_id[j]); BCM_GPORT_LOCAL_SET(gport,ports[j]); rv = bcm_multicast_egress_add(unit, mc_id[j], gport, 0); BCM_GPORT_MCAST_SET(mc_gport[j],mc_id[j]); printf(">>>Add port[%d] to MC[%d]\n", ports[j], mc_id[j]); } } bcm_l3_intf_t_init(&intf); sal_memcpy(intf.l3a_mac_addr, my_mac_address, 6); intf.l3a_vid = 400; intf.l3a_vrf = 400; rv = bcm_l3_intf_create(unit, intf); if (rv != BCM_E_NONE) { printf("Error, bcm_l3_intf_create\n"); return rv; } for (j = 0;j < NOF_FECS;j++) { bcm_l3_egress_t_init(&l3eg); flags = BCM_L3_INGRESS_ONLY; gport = mc_gport[sal_rand() % 4]; l3eg.port = gport; if (is_device_or_above(unit, JERICHO2)) { l3eg.flags = BCM_L3_MC_RPF_EXPLICIT; l3eg.intf = intf.l3a_intf_id; } else { l3eg.flags = BCM_L3_RPF | BCM_L3_IPMC; } rv = bcm_l3_egress_create(unit, flags, &l3eg, &fec); if (rv != BCM_E_NONE) { printf("Error, bcm_l3_egress_create\n"); return rv; } FECS_ID[j] = fec; printf("FEC_ID[%d]: %#x\n", j, fec); bcm_ipmc_addr_t_init(&data); data.flags = (is_device_or_above(unit, JERICHO2) ? 0 : BCM_IPMC_SOURCE_PORT_NOCHECK); data.mc_ip_addr = 0xE1010101; data.mc_ip_mask = -1; data.vrf = 400; data.s_ip_addr = 0x04070100 + j; data.s_ip_mask = -1; data.l3a_intf = fec; rv = bcm_ipmc_add(unit,&data); if (rv != BCM_E_NONE) { printf("Error, bcm_ipmc_add\n"); return rv; } } return rv; }
/** * DOC: asynchronous flip implementation * * Asynchronous page flip is the implementation for the DRM_MODE_PAGE_FLIP_ASYNC * flag. Currently async flip is only supported via the drmModePageFlip IOCTL. * Correspondingly, support is currently added for primary plane only. * * Async flip can only change the plane surface address, so anything else * changing is rejected from the intel_atomic_check_async() function. * Once this check is cleared, flip done interrupt is enabled using * the intel_crtc_enable_flip_done() function. * * As soon as the surface address register is written, flip done interrupt is * generated and the requested events are sent to the usersapce in the interrupt * handler itself. The timestamp and sequence sent during the flip done event * correspond to the last vblank and have no relation to the actual time when * the flip done event was sent. */ static int intel_atomic_check_async(struct intel_atomic_state *state) { struct drm_i915_private *i915 = to_i915(state->base.dev); const struct intel_crtc_state *old_crtc_state, *new_crtc_state; const struct intel_plane_state *new_plane_state, *old_plane_state; struct intel_crtc *crtc; struct intel_plane *plane; int i; for_each_oldnew_intel_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) { if (intel_crtc_needs_modeset(new_crtc_state)) { drm_dbg_kms(&i915->drm, "Modeset Required. Async flip not supported\n"); return -EINVAL; } if (!new_crtc_state->hw.active) { drm_dbg_kms(&i915->drm, "CRTC inactive\n"); return -EINVAL; } if (old_crtc_state->active_planes != new_crtc_state->active_planes) { drm_dbg_kms(&i915->drm, "Active planes cannot be changed during async flip\n"); return -EINVAL; } } for_each_oldnew_intel_plane_in_state(state, plane, old_plane_state, new_plane_state, i) { if (!plane->async_flip) return -EINVAL; switch (new_plane_state->hw.fb->modifier) { case I915_FORMAT_MOD_X_TILED: case I915_FORMAT_MOD_Y_TILED: case I915_FORMAT_MOD_Yf_TILED: break; default: drm_dbg_kms(&i915->drm, "Linear memory/CCS does not support async flips\n"); return -EINVAL; } if (old_plane_state->view.color_plane[0].stride != new_plane_state->view.color_plane[0].stride) { drm_dbg_kms(&i915->drm, "Stride cannot be changed in async flip\n"); return -EINVAL; } if (old_plane_state->hw.fb->modifier != new_plane_state->hw.fb->modifier) { drm_dbg_kms(&i915->drm, "Framebuffer modifiers cannot be changed in async flip\n"); return -EINVAL; } if (old_plane_state->hw.fb->format != new_plane_state->hw.fb->format) { drm_dbg_kms(&i915->drm, "Framebuffer format cannot be changed in async flip\n"); return -EINVAL; } if (old_plane_state->hw.rotation != new_plane_state->hw.rotation) { drm_dbg_kms(&i915->drm, "Rotation cannot be changed in async flip\n"); return -EINVAL; } if (!drm_rect_equals(&old_plane_state->uapi.src, &new_plane_state->uapi.src) || !drm_rect_equals(&old_plane_state->uapi.dst, &new_plane_state->uapi.dst)) { drm_dbg_kms(&i915->drm, "Plane size/co-ordinates cannot be changed in async flip\n"); return -EINVAL; } if (old_plane_state->hw.alpha != new_plane_state->hw.alpha) { drm_dbg_kms(&i915->drm, "Alpha value cannot be changed in async flip\n"); return -EINVAL; } if (old_plane_state->hw.pixel_blend_mode != new_plane_state->hw.pixel_blend_mode) { drm_dbg_kms(&i915->drm, "Pixel blend mode cannot be changed in async flip\n"); return -EINVAL; } if (old_plane_state->hw.color_encoding != new_plane_state->hw.color_encoding) { drm_dbg_kms(&i915->drm, "Color encoding cannot be changed in async flip\n"); return -EINVAL; } if (old_plane_state->hw.color_range != new_plane_state->hw.color_range) { drm_dbg_kms(&i915->drm, "Color range cannot be changed in async flip\n"); return -EINVAL; } } return 0; }
/** * ath5k_hw_get_frame_duration() - Get tx time of a frame * @ah: The &struct ath5k_hw * @len: Frame's length in bytes * @rate: The @struct ieee80211_rate * @shortpre: Indicate short preample * * Calculate tx duration of a frame given it's rate and length * It extends ieee80211_generic_frame_duration for non standard * bwmodes. */ int ath5k_hw_get_frame_duration(struct ath5k_hw *ah, enum nl80211_band band, int len, struct ieee80211_rate *rate, bool shortpre) { int sifs, preamble, plcp_bits, sym_time; int bitrate, bits, symbols, symbol_bits; int dur; if (!ah->ah_bwmode) { __le16 raw_dur = ieee80211_generic_frame_duration(ah->hw, NULL, band, len, rate); dur = le16_to_cpu(raw_dur); if (shortpre) dur -= 96; return dur; } bitrate = rate->bitrate; preamble = AR5K_INIT_OFDM_PREAMPLE_TIME; plcp_bits = AR5K_INIT_OFDM_PLCP_BITS; sym_time = AR5K_INIT_OFDM_SYMBOL_TIME; switch (ah->ah_bwmode) { case AR5K_BWMODE_40MHZ: sifs = AR5K_INIT_SIFS_TURBO; preamble = AR5K_INIT_OFDM_PREAMBLE_TIME_MIN; break; case AR5K_BWMODE_10MHZ: sifs = AR5K_INIT_SIFS_HALF_RATE; preamble *= 2; sym_time *= 2; bitrate = DIV_ROUND_UP(bitrate, 2); break; case AR5K_BWMODE_5MHZ: sifs = AR5K_INIT_SIFS_QUARTER_RATE; preamble *= 4; sym_time *= 4; bitrate = DIV_ROUND_UP(bitrate, 4); break; default: sifs = AR5K_INIT_SIFS_DEFAULT_BG; break; } bits = plcp_bits + (len << 3); symbol_bits = bitrate * sym_time; symbols = DIV_ROUND_UP(bits * 10, symbol_bits); dur = sifs + preamble + (sym_time * symbols); return dur; }
#include <stdio.h> int main (void){ int K, S; scanf("%d %d", &K, &S); int X,Y,Z; int count=0; for (X=0; X<=K; X++){ for (Y=0; Y<=K; Y++){ if (0<=S-X-Y && S-X-Y<=K) {count=count+1;} } } printf("%d", count); return 0; }
/** * Adapter layer nexthop module init * @return OFP_ERR_XX */ int32_ofp adpt_nexthop_init(void) { g_p_adpt_nexthop_master = malloc(sizeof(adpt_nexthop_master_t)); ADPT_MEM_PTR_CHECK(g_p_adpt_nexthop_master); memset(g_p_adpt_nexthop_master, 0, sizeof(adpt_nexthop_master_t)); ADPT_ERROR_RETURN(adpt_nexthop_create_output_all_nh()); return OFP_ERR_SUCCESS; }
#include<stdio.h> #include<string.h> int main() { int i,l,c=0,C; char s1[101],S2[101]; gets(s1); l=strlen(s1); for(i=0;i<l;i++){ if(s1[i]>=65&&s1[i]<=90){ c++; } } if(c==l){ for(i=0;i<l;i++){ s1[i]=s1[i]+32; } printf("%s\n",s1); } else if(c==l-1){ if(s1[0]>=97&&s1[0]<=122){ for(i=0;i<l;i++){ if(s1[i]>=65&&s1[i]<=90){ s1[i]=97+s1[i]-65; } else if(s1[i]>=90&&s1[i]<=122){ s1[i]=65+s1[i]-97; } } } printf("%s\n",s1); } else{ printf("%s\n",s1); } return(0); }
/** * Sets the data stored at the specified index * @param l The list * @param index The new element's index * @param new_content A pointer to the new element's content * @param free_old Whether to free memory used by the old contents */ void listSet(List* l, int index, void* new_content, char free_old){ ListElement* el = listGetElement(l, index); if(el == NULL) return; if(free_old) free(el->content); el->content = new_content; }
/* by Christian Cann Schuldt Jensen ~ CeeJay.dk Curves, uses S-curves to increase contrast, without clipping highlights and shadows. */ float4 CurvesPass( float4 colorInput ) { float3 lumCoeff = float3(0.2126, 0.7152, 0.0722); float Curves_contrast_blend = Curves_contrast; float PI = acos(-1); #if Curves_mode != 2 float luma = dot(lumCoeff, colorInput.rgb); float3 chroma = colorInput.rgb - luma; #endif #if Curves_mode == 2 float3 x = colorInput.rgb; #elif Curves_mode == 1 float3 x = chroma; x = x * 0.5 + 0.5; #else float x = luma; #endif #if Curves_formula == 1 x = sin(PI * 0.5 * x); x *= x; #endif #if Curves_formula == 2 x = x - 0.5; x = ( x / (0.5 + abs(x)) ) + 0.5; #endif #if Curves_formula == 3 x = x*x*(3.0-2.0*x); #endif #if Curves_formula == 4 x = (1.0524 * exp(6.0 * x) - 1.05248) / (20.0855 + exp(6.0 * x)); #endif #if Curves_formula == 5 x = x * (x * (1.5-x) + 0.5); Curves_contrast_blend = Curves_contrast * 2.0; #endif #if Curves_formula == 6 x = x*x*x*(x*(x*6.0 - 15.0) + 10.0); #endif #if Curves_formula == 7 x = x - 0.5; x = x / ((abs(x)*1.25) + 0.375 ) + 0.5; #endif #if Curves_formula == 8 x = (x * (x * (x * (x * (x * (x * (1.6 * x - 7.2) + 10.8) - 4.2) - 3.6) + 2.7) - 1.8) + 2.7) * x * x; #endif #if Curves_formula == 9 x = -0.5 * (x*2.0-1.0) * (abs(x*2.0-1.0)-2.0) + 0.5; #endif #if Curves_formula == 10 #if Curves_mode == 0 float xstep = step(x,0.5); float xstep_shift = (xstep - 0.5); float shifted_x = x + xstep_shift; #else float3 xstep = step(x,0.5); float3 xstep_shift = (xstep - 0.5); float3 shifted_x = x + xstep_shift; #endif x = abs(xstep - sqrt(-shifted_x * shifted_x + shifted_x) ) - xstep_shift; Curves_contrast_blend = Curves_contrast * 0.5; #endif #if Curves_formula == 11 float a = 1.00; float b = 0.00; float c = 1.00; float d = 0.20; x = 0.5 * ((-a + 3*b -3*c + d)*x*x*x + (2*a -5*b + 4*c - d)*x*x + (-a+c)*x + 2*b); #endif #if Curves_formula == 12 float a = 0.00; float b = 0.00; float c = 1.00; float d = 1.00; float r = (1-x); float r2 = r*r; float r3 = r2 * r; float x2 = x*x; float x3 = x2*x; x = a*(1-x)*(1-x)*(1-x) + 3*b*(1-x)*(1-x)*x + 3*c*(1-x)*x*x + d*x*x*x; #endif #if Curves_formula == 13 - alternative implementation. float3 a = float3(0.00,0.00,0.00); float3 b = float3(0.25,0.15,0.85); float3 c = float3(0.75,0.85,0.15); float3 d = float3(1.00,1.00,1.00); float3 ab = lerp(a,b,x); float3 bc = lerp(b,c,x); float3 cd = lerp(c,d,x); float3 abbc = lerp(ab,bc,x); float3 bccd = lerp(bc,cd,x); float3 dest = lerp(abbc,bccd,x); x = dest; #endif #if Curves_formula == 14 x = 1.0 / (1.0 + exp(-(x * 10.0 - 5.0))); #endif #if Curves_mode == 2 float3 color = x; colorInput.rgb = lerp(colorInput.rgb, color, Curves_contrast_blend); #elif Curves_mode == 1 x = x * 2.0 - 1.0; float3 color = luma + x; colorInput.rgb = lerp(colorInput.rgb, color, Curves_contrast_blend); #else //Only Luma x = lerp(luma, x, Curves_contrast_blend); colorInput.rgb = x + chroma; #endif return colorInput; }
#ifndef Fireworks_Core_FWParameterBase_h #define Fireworks_Core_FWParameterBase_h // -*- C++ -*- // // Package: Core // Class : FWParameterBase // /**\class FWParameterBase FWParameterBase.h Fireworks/Core/interface/FWParameterBase.h Description: <one line class summary> Usage: <usage> */ // // Original Author: Chris Jones // Created: Sat Feb 23 13:35:15 EST 2008 // // system include files #include <string> // user include files #include "Fireworks/Core/interface/FWConfigurable.h" // forward declarations class FWConfiguration; class FWParameterizable; class FWParameterBase : public FWConfigurable { public: FWParameterBase(FWParameterizable* iParent, const std::string& iName); ~FWParameterBase() override; // ---------- const member functions --------------------- //virtual void addTo(FWConfiguration& ) const = 0; const std::string& name() const { return m_name; } // ---------- static member functions -------------------- // ---------- member functions --------------------------- //virtual void setFrom(const FWConfiguration&) = 0; FWParameterBase(const FWParameterBase&) = delete; // stop default const FWParameterBase& operator=(const FWParameterBase&) = delete; // stop default private: // ---------- member data -------------------------------- std::string m_name; }; #endif
/** * context_destroy * * Destroys a context struct by freeing allocated memory, calling the * appropriate cleanup functions and finally freeing the struct itself. * * Parameters: * * cnt - the context struct to destroy * * Returns: nothing */ static void context_destroy(struct context *cnt) { unsigned int j; for (j = 0; config_params[j].param_name != NULL; j++) { if (config_params[j].copy == copy_string) { void **val; val = (void *)((char *)cnt+(int)config_params[j].conf_value); if (*val) { free(*val); *val = NULL; } } } free(cnt); }
/** * Send the list of supported SASL mechanisms */ static bool send_sasl_mechs(private_pt_tls_server_t *this) { enumerator_t *enumerator; bio_writer_t *writer = NULL; char *name; bool res; enumerator = sasl_mechanism_create_enumerator(TRUE); while (enumerator->enumerate(enumerator, &name)) { if (!writer) { writer = bio_writer_create(32); } DBG1(DBG_TNC, "offering SASL %s", name); writer->write_data8(writer, chunk_from_str(name)); } enumerator->destroy(enumerator); if (!writer) { return FALSE; } res = pt_tls_write(this->tls, PT_TLS_SASL_MECHS, this->identifier++, writer->get_buf(writer)); writer->destroy(writer); return res; }
/** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Crazyflie control firmware * * Copyright (C) 2011-2012 Bitcraze AB * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, in version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * pm.h - Power Management driver and functions. */ #ifndef PM_H_ #define PM_H_ #include "autoconf.h" #include "adc.h" #include "syslink.h" #include "deck.h" typedef enum { battery, charging, charged, lowPower, shutDown, } PMStates; typedef enum { charge100mA, charge500mA, chargeMax, } PMChargeStates; typedef enum { USBNone, USB500mA, USBWallAdapter, } PMUSBPower; typedef void (*graceful_shutdown_callback_t)(); void pmInit(void); bool pmTest(void); /** * Power management task */ void pmTask(void *param); void pmSetChargeState(PMChargeStates chgState); void pmSyslinkUpdate(SyslinkPacket *slp); /** * Returns the battery voltage i volts as a float */ float pmGetBatteryVoltage(void); /** * Returns the min battery voltage i volts as a float */ float pmGetBatteryVoltageMin(void); /** * Returns the max battery voltage i volts as a float */ float pmGetBatteryVoltageMax(void); /** * Updates and calculates battery values. * Should be called for every new adcValues sample. */ void pmBatteryUpdate(AdcGroup* adcValues); /** * Returns true if the battery is below its low capacity threshold for an * extended period of time. */ bool pmIsBatteryLow(void); /** * Returns true if the charger is currently connected */ bool pmIsChargerConnected(void); /** * Returns true if the battery is currently charging */ bool pmIsCharging(void); /** * Returns true if the battery is currently in use */ bool pmIsDischarging(void); /** * Enable or disable external battery voltage measuring. */ void pmEnableExtBatteryVoltMeasuring(const deckPin_t pin, float multiplier); /** * Measure an external voltage. */ float pmMeasureExtBatteryVoltage(void); /** * Enable or disable external battery current measuring. */ void pmEnableExtBatteryCurrMeasuring(const deckPin_t pin, float ampPerVolt); /** * Measure an external current. */ float pmMeasureExtBatteryCurrent(void); /* * Ignore charging/charge state in the PM state machine. * This can be useful if a platform doesn't have a charger. */ void pmIgnoreChargedState(bool ignore); /** * Register a callback to be run when the NRF51 signals shutdown */ bool pmRegisterGracefulShutdownCallback(graceful_shutdown_callback_t cb); #endif /* PM_H_ */
/* * Successful return must release the task reference with * put_task_struct */ static bool ref_get_pid_and_task(struct vas_user_win_ref *task_ref, struct task_struct **tskp, struct pid **pidp) { struct task_struct *tsk; struct pid *pid; pid = task_ref->pid; tsk = get_pid_task(pid, PIDTYPE_PID); if (!tsk) { pid = task_ref->tgid; tsk = get_pid_task(pid, PIDTYPE_PID); if (WARN_ON_ONCE(!tsk)) return false; } if (tsk->flags & PF_EXITING) { put_task_struct(tsk); return false; } *tskp = tsk; *pidp = pid; return true; }
/* * \brief Function to configure I2C module pin mux * * \return None */ static void Board_configI2cPinMux(void) { hSysCfg->PINMUX4 &= (~(CSL_SYSCFG_PINMUX4_PINMUX4_15_12_MASK | CSL_SYSCFG_PINMUX4_PINMUX4_11_8_MASK )); hSysCfg->PINMUX4 |= BOARD_PINMUX4_I2C_ENABLE; }
/** * lim_update_ibss_prop_add_ies() - update IBSS prop IE * @pMac : Pointer to Global MAC structure * @pDstData_buff : A pointer to pointer of dst buffer * @pDstDataLen : A pointer to pointer of dst buffer length * @pModifyIE : A pointer to tSirModifyIE * * This function replaces previous ibss prop_ie with new ibss prop_ie. * * Return: * True or false depending upon whether IE is updated or not */ static bool lim_update_ibss_prop_add_ies(tpAniSirGlobal pMac, uint8_t **pDstData_buff, uint16_t *pDstDataLen, tSirModifyIE *pModifyIE) { int32_t oui_length; uint8_t *ibss_ie = NULL; uint8_t *vendor_ie; #define MAC_VENDOR_OUI "\x00\x16\x32" #define MAC_VENDOR_SIZE 3 ibss_ie = pModifyIE->pIEBuffer; oui_length = pModifyIE->oui_length; if ((0 == oui_length) || (NULL == ibss_ie)) { pe_err("Invalid set IBSS vendor IE command length %d", oui_length); return false; } vendor_ie = (uint8_t *)wlan_get_vendor_ie_ptr_from_oui(MAC_VENDOR_OUI, MAC_VENDOR_SIZE, *pDstData_buff, *pDstDataLen); if (vendor_ie) { QDF_ASSERT((vendor_ie[1] + 2) == pModifyIE->ieBufferlength); qdf_mem_copy(vendor_ie, pModifyIE->pIEBuffer, pModifyIE->ieBufferlength); } else { uint16_t new_length; uint8_t *new_ptr; if (USHRT_MAX - pModifyIE->ieBufferlength < *pDstDataLen) { pe_err("U16 overflow due to %d + %d", pModifyIE->ieBufferlength, *pDstDataLen); return false; } new_length = pModifyIE->ieBufferlength + *pDstDataLen; new_ptr = qdf_mem_malloc(new_length); if (NULL == new_ptr) { pe_err("Memory allocation failed"); return false; } qdf_mem_copy(new_ptr, *pDstData_buff, *pDstDataLen); qdf_mem_copy(&new_ptr[*pDstDataLen], pModifyIE->pIEBuffer, pModifyIE->ieBufferlength); qdf_mem_free(*pDstData_buff); *pDstDataLen = new_length; *pDstData_buff = new_ptr; } return true; }
/* FC_DecryptDigestUpdate continues a multiple-part decryption and digesting * operation. */ CK_RV FC_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) { SFTK_FIPSCHECK(); CHECK_FORK(); return NSC_DecryptDigestUpdate(hSession, pEncryptedPart,ulEncryptedPartLen, pPart,pulPartLen); }
/* * Return the absolute difference in nanoseconds between * the dm_timestamp objects ts1 and ts2. * * Callers that need to know whether ts1 is before, equal to, or after ts2 * in addition to the magnitude should use dm_timestamp_compare. */ uint64_t dm_timestamp_delta(struct dm_timestamp *ts1, struct dm_timestamp *ts2) { uint64_t t1, t2; t1 = _timestamp_to_uint64(ts1); t2 = _timestamp_to_uint64(ts2); if (t1 > t2) return t1 - t2; return t2 - t1; }
/*********************************************************************** * reg_get_logfont * * Tries to retrieve logfont info from the specified key and value */ static BOOL reg_get_logfont(LPCWSTR key, LPCWSTR value, LOGFONTW *lf) { HKEY hkey; LOGFONTW lfbuf; DWORD type, size; BOOL found = FALSE; HKEY base_keys[2]; int i; base_keys[0] = get_volatile_regkey(); base_keys[1] = HKEY_CURRENT_USER; for(i = 0; i < 2 && !found; i++) { if(RegOpenKeyW(base_keys[i], key, &hkey) == ERROR_SUCCESS) { size = sizeof(lfbuf); if(RegQueryValueExW(hkey, value, NULL, &type, (LPBYTE)&lfbuf, &size) == ERROR_SUCCESS && type == REG_BINARY) { if( size == sizeof(lfbuf)) { found = TRUE; memcpy(lf, &lfbuf, size); } else if( size == sizeof( LOGFONT16)) { found = TRUE; SYSPARAMS_LogFont16To32W( (LOGFONT16*) &lfbuf, lf); } else WARN("Unknown format in key %s value %s, size is %d\n", debugstr_w( key), debugstr_w( value), size); } RegCloseKey(hkey); } } if( found && lf->lfHeight > 0) { lf->lfHeight = -MulDiv( lf->lfHeight, get_display_dpi(), 72); } return found; }
#include <stdio.h> int main(int argc, char const *argv[]) { int n,occ; scanf("%d",&n); n=n-10; occ=0; if(n==1)occ=4; else if (n>1 && n<=9) occ=4; else if(n==10)occ=4*3+3; else if (n==11)occ=4; else occ=0; printf("%d",occ); return 0; }
/* PlaceTabs -- * Compute all tab parcels. */ static void PlaceTabs( Notebook *nb, Ttk_Box tabrowBox, Ttk_PositionSpec tabPlacement) { Ttk_Layout tabLayout = nb->notebook.tabLayout; int nTabs = Ttk_NumberSlaves(nb->notebook.mgr); int i; for (i = 0; i < nTabs; ++i) { Tab *tab = Ttk_SlaveData(nb->notebook.mgr, i); Ttk_State tabState = TabState(nb, i); if (tab->state != TAB_STATE_HIDDEN) { Ttk_Padding expand = Ttk_UniformPadding(0); Tcl_Obj *expandObj = Ttk_QueryOption(tabLayout,"-expand",tabState); if (expandObj) { Ttk_GetBorderFromObj(NULL, expandObj, &expand); } tab->parcel = Ttk_ExpandBox( Ttk_PositionBox(&tabrowBox, tab->width, tab->height, tabPlacement), expand); } } }
/*********************************************************************** * Pass1MSReplaceFileName *********************************************************************** * SYNOPSIS: Add the line number information from the current * object record to the given segment's table. * CALLED BY: Pass1MS_Load * RETURN: Nothing * SIDE EFFECTS: a few. * * STRATEGY: * If segment has no line information yet, create a line map and * initial block, pointing the lineH and lineT to it. * * while there are line number records remaining: * Lock down the tail line block. If it's not at capacity, relocate & * copy as many line number records as will fit in the block. * * If any line numbers remain, allocate and initialize a new block. * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * ardeb 3/ 1/91 Initial Revision * ***********************************************************************/ static void Pass1MSReplaceFileName( ID oldName, ID newName) { int i; ObjLineHeader *olh; ObjLine *ol; VMBlockHandle next, last; for (i = Vector_Length(segments)-1; i >= 0; i--) { SegDesc *sd; Vector_Get(segments, i, &sd); next = sd->lineT; if (next != 0) { word curSize; word newSize; MemHandle mem; word spaceLeft; int numLeft; int prevStart = -1; int prevLine = -1; int nlines; Boolean first = TRUE; VMInfo(symbols, next, &curSize, (MemHandle *)NULL, (VMID *)NULL); olh = (ObjLineHeader *)VMLock(symbols, next, &mem); if(olh->num > 0) { ObjLine *olend; ol = ObjFirstEntry(olh, ObjLine); olend = ol + olh->num; nlines = olh->num; while (ol < olend) { nlines--; if(first) { if(*(ID *)ol == oldName) { *(ID *)ol = newName; VMDirty(symbols, next); } first = FALSE; } else if (ol->line == 0) { ol++; if(*(ID *)ol == oldName) { *(ID *)ol = newName; VMDirty(symbols, next); } } ol++; } } last = next; next = olh->next; VMUnlockDirty(symbols, last); } } RenameFileSrcMapEntry(oldName, newName); }
/*----------------------------------------------------------------------*/ /* Randomly select the source nodes and sink nodes */ void select_source_sinks() { int64_t i, *int_ptr, *temp_list; struct imbalance *ptr; float ab[2]; *ab = 0.9; ab[1] = n_node - 0.99; if ((temp_list=(int64_t *)malloc(n_node*sizeof(int64_t)))==NULL) { err(4); exit(1); } for (i=0,int_ptr=temp_list;i<n_node;i++,int_ptr++) *int_ptr = 0; for (i=0,ptr=source_list;i<n_source;i++,ptr++) { ptr->node = uniform(ab); if (temp_list[ptr->node] == 1) { ptr--; i--; } else temp_list[ptr->node] = 1; } for (i=0,ptr=sink_list;i<n_sink;i++,ptr++) { ptr->node = uniform(ab); if (temp_list[ptr->node] == 1) { ptr--; i--; } else temp_list[ptr->node] = 1; } free(temp_list); }
#include<stdio.h> #include<math.h> int Walk(int, int, int, int, int); int map[20][20]; int main() { char input[21]; int i, j, ans, w, h, sH, sW; while(1) { sH = sW = 0; scanf("%d %d", &w, &h); if(w == 0 && h == 0) break; for(i = 0; i < h; i++) { scanf(" %s", input); for(j = 0; j < w; j++) { if(input[j] == '.') { map[i][j] = 1; } else if(input[j] == '#') { map[i][j] = 0; } else { map[i][j] = 1; sH = i; sW = j; } } } ans = Walk(0, sH, sW, h, w); printf("%d\n", ans); } return 0; } int Walk(int count, int h, int w, int maxH, int maxW) { int i, j, ans, dh, dw, ch, cw; map[h][w] |= 2; ans = count + 1; for(i = 0; i < 4; i++) { dw = cos(90 * i * M_PI / 180); dh = sin(90 * i * M_PI / 180); ch = h + dh; cw = w + dw; if(ch > -1 && ch < maxH && cw > -1 && cw < maxW && (map[ch][cw] & 3) == 1) { ans = Walk(ans ,ch, cw, maxH, maxW); } } return ans; }
/*! * call this instead of stub and we'll guarantee to find a host that's up. * * \todo In the future, we should also put in a protocol to find the sync site. */ afs_int32 ubik_Call(int (*aproc) (), struct ubik_client *aclient, afs_int32 aflags, long p1, long p2, long p3, long p4, long p5, long p6, long p7, long p8, long p9, long p10, long p11, long p12, long p13, long p14, long p15, long p16) { afs_int32 rcode, code, count; int pass, needsync, inlist, j; struct rx_connection *tc; struct rx_peer *rxp; short origLevel; if (aflags & UBIK_CALL_NEW) return ubik_Call_New(aproc, aclient, aflags, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16); if (!aclient) return UNOENT; LOCK_UBIK_CLIENT(aclient); restart: origLevel = aclient->initializationState; rcode = UNOSERVERS; inlist = needsync = 0; LOCK_UCLNT_CACHE; for (j = 0; ((j < SYNCCOUNT) && calls_needsync[j]); j++) { if (calls_needsync[j] == (int *)aproc) { inlist = needsync = 1; break; } } UNLOCK_UCLNT_CACHE; for (pass = 0; pass < 2; pass++) { for (count = 0;; count++) { if (needsync) { if (aclient->syncSite) { code = IndexOf(aclient, aclient->syncSite); aclient->syncSite = 0; if (code != -1) count = code; } } tc = aclient->conns[count]; if (tc && rx_ConnError(tc)) { aclient->conns[count] = tc = ubik_RefreshConn(tc); } if (!tc) break; if ((pass == 0) && (aclient->states[count] & CFLastFailed)) { continue; } rcode = (*aproc) (tc, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16); if (aclient->initializationState != origLevel) { if (rcode) goto restart; else goto done; } if (rcode < 0) { aclient->states[count] |= CFLastFailed; } else if (rcode == UNOTSYNC) { needsync = 1; } else if (rcode != UNOQUORUM) { aclient->states[count] &= ~CFLastFailed; goto done; } } } done: if (needsync) { if (!inlist) { LOCK_UCLNT_CACHE; calls_needsync[synccount % SYNCCOUNT] = (int *)aproc; synccount++; UNLOCK_UCLNT_CACHE; inlist = 1; } if (!rcode) { rxp = rx_PeerOf(aclient->conns[count]); aclient->syncSite = rx_HostOf(rxp); } } UNLOCK_UBIK_CLIENT(aclient); return rcode; }
/* Make OP describe an input Pmode address operand. VALUE is the value of the address, but it may need to be converted to Pmode first. */ static inline void create_address_operand (struct expand_operand *op, rtx value) { create_expand_operand (op, EXPAND_ADDRESS, value, Pmode, false); }
/** * @brief Configures the Tampers Sampling Frequency. * @param RTC_TamperSamplingFreq: Specifies the tampers Sampling Frequency. * This parameter can be one parameter from the * @ref RTC_TamperSamplingFreq_TypeDef enumeration. * @retval None */ void RTC_TamperSamplingFreqConfig(RTC_TamperSamplingFreq_TypeDef RTC_TamperSamplingFreq) { assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(RTC_TamperSamplingFreq)); RTC->WPR = 0xCA; RTC->WPR = 0x53; RTC->TCR2 &= (uint8_t)~(RTC_TCR2_TAMPFREQ); RTC->TCR2 |= (uint8_t)RTC_TamperSamplingFreq; RTC->WPR = 0xFF; }
/** * ipa_rm_stat() - print RM stat * @buf: [in] The user buff used to print * @size: [in] The size of buf * Returns: number of bytes used on success, negative on failure * * This function is called by ipa_debugfs in order to receive * a full picture of the current state of the RM */ int ipa_rm_stat(char *buf, int size) { unsigned long flags; int i, cnt = 0, result = EINVAL; struct ipa_rm_resource *resource = NULL; u32 sum_bw_prod = 0; u32 sum_bw_cons = 0; if (!buf || size < 0) return result; spin_lock_irqsave(&ipa_rm_ctx->ipa_rm_lock, flags); for (i = 0; i < IPA_RM_RESOURCE_MAX; ++i) { if (!IPA_RM_RESORCE_IS_PROD(i)) continue; result = ipa_rm_dep_graph_get_resource( ipa_rm_ctx->dep_graph, i, &resource); if (!result) { result = ipa_rm_resource_producer_print_stat( resource, buf + cnt, size-cnt); if (result < 0) goto bail; cnt += result; } } for (i = 0; i < IPA_RM_RESOURCE_MAX; i++) { if (IPA_RM_RESORCE_IS_PROD(i)) sum_bw_prod += ipa_rm_ctx->prof_vote.bw_resources[i]; else sum_bw_cons += ipa_rm_ctx->prof_vote.bw_resources[i]; } result = scnprintf(buf + cnt, size - cnt, "All prod bandwidth: %d, All cons bandwidth: %d\n", sum_bw_prod, sum_bw_cons); cnt += result; result = scnprintf(buf + cnt, size - cnt, "Voting: voltage %d, bandwidth %d\n", ipa_rm_ctx->prof_vote.curr_volt, ipa_rm_ctx->prof_vote.curr_bw); cnt += result; result = cnt; bail: spin_unlock_irqrestore(&ipa_rm_ctx->ipa_rm_lock, flags); return result; }
/*! * @brief This API initiliazes the AVR SPI module. */ void spi_init(void) { SPI_MOSI_DDR |= (0x01 << SPI_MOSI_PIN); SPI_SCK_DDR |= (0x01 << SPI_SCK_PIN); SPI_SS_DDR |= (0x01 << SPI_SS_PIN); SPI_SS_PORT |= (0x01 << SPI_SS_PIN); SPI_SD_CS_DDR |= (0x01 << SPI_SD_CS_PIN); SPI_SD_CS_PORT |= (0x01 << SPI_SD_CS_PIN); SPI_DISP_CS_DDR |= (0x01 << SPI_DISP_CS_PIN); SPI_DISP_CS_PORT |= (0x01 << SPI_DISP_CS_PIN); SPI_BME280_CS_DDR |= (0x01 << SPI_BME280_CS_PIN); SPI_BME280_CS_PORT |= (0x01 << SPI_BME280_CS_PIN); SPI_ICM20948_CS_DDR |= (0x01 << SPI_ICM20948_CS_PIN); SPI_ICM20948_CS_PORT |= (0x01 << SPI_ICM20948_CS_PIN); SPCR |= (1 << SPE) | (0x01 << MSTR); }
/*-----------------------------------------------------------------------------*/ /* Check the touch LED and color sensors */ /*-----------------------------------------------------------------------------*/ void iqCheckSensors() { static bool robotTouchSensorPressed; if( robotTouchSensor != PORTNONE ) { if( getTouchLEDValue( robotTouchSensor ) ) { if(!robotTouchSensorPressed) { robotEnabled = !robotEnabled; robotTouchSensorPressed = true; } } else { robotTouchSensorPressed = false; } } if( robotColorSensor != PORTNONE ) { if( getColorProximity( robotColorSensor ) > 200 ) { TSimpleColors color; color = getColorName( robotColorSensor ); if( color == colorRed ) robotEnabled = false; if( color == colorGreen ) robotEnabled = true; } } if( robotTouchSensor != PORTNONE ) { if( robotRunning ) { if(robotEnabled) setTouchLEDColor( robotTouchSensor, colorGreen ); else setTouchLEDColor( robotTouchSensor, colorRed ); } else setTouchLEDColor( robotTouchSensor, colorNone ); } }
#include <stdio.h> int main(void) { int n,seg,i,sq1=2,sq2=2; scanf("%d",&n); if(n<4) printf("%d",1+n); else if(n==4) printf("%d",n); else { for(i=sq1+sq2;(sq1*sq2)<n;i=sq1+sq2) { if(sq1==sq2) sq2++; else sq1++; /*printf("\nl %d r %d\n",sq1,sq2);*/ } printf("%d",i); } }
// Copyright (c) 2010 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "EbmlIDs.h" #include "WebMElement.h" #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <time.h> #define kVorbisPrivateMaxSize 4000 #define UInt64 uint64_t void writeHeader(EbmlGlobal *glob) { EbmlLoc start; Ebml_StartSubElement(glob, &start, EBML); Ebml_SerializeUnsigned(glob, EBMLVersion, 1); Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); // EBML Read Version Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); // EBML Max ID Length Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); // EBML Max Size Length Ebml_SerializeString(glob, DocType, "webm"); // Doc Type Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); // Doc Type Version Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); // Doc Type Read Version Ebml_EndSubElement(glob, &start); } void writeSimpleBlock(EbmlGlobal *glob, unsigned char trackNumber, short timeCode, int isKeyframe, unsigned char lacingFlag, int discardable, unsigned char *data, unsigned long dataLength) { unsigned long blockLength = 4 + dataLength; unsigned char flags = 0x00 | (isKeyframe ? 0x80 : 0x00) | (lacingFlag << 1) | discardable; Ebml_WriteID(glob, SimpleBlock); blockLength |= 0x10000000; // TODO check length < 0x0FFFFFFFF Ebml_Serialize(glob, &blockLength, sizeof(blockLength), 4); trackNumber |= 0x80; // TODO check track nubmer < 128 Ebml_Write(glob, &trackNumber, 1); // Ebml_WriteSigned16(glob, timeCode,2); //this is 3 bytes Ebml_Serialize(glob, &timeCode, sizeof(timeCode), 2); flags = 0x00 | (isKeyframe ? 0x80 : 0x00) | (lacingFlag << 1) | discardable; Ebml_Write(glob, &flags, 1); Ebml_Write(glob, data, dataLength); } static UInt64 generateTrackID(unsigned int trackNumber) { UInt64 t = time(NULL) * trackNumber; UInt64 r = rand(); r = r << 32; r += rand(); // UInt64 rval = t ^ r; return t ^ r; } void writeVideoTrack(EbmlGlobal *glob, unsigned int trackNumber, int flagLacing, const char *codecId, unsigned int pixelWidth, unsigned int pixelHeight, unsigned int displayWidth, unsigned int displayHeight) { EbmlLoc start; UInt64 trackID; Ebml_StartSubElement(glob, &start, TrackEntry); Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber); trackID = generateTrackID(trackNumber); Ebml_SerializeUnsigned(glob, TrackUID, trackID); Ebml_SerializeString(glob, CodecName, "VP8"); // TODO shouldn't be fixed Ebml_SerializeUnsigned(glob, TrackType, 1); // video is always 1 Ebml_SerializeString(glob, CodecID, codecId); { EbmlLoc videoStart; Ebml_StartSubElement(glob, &videoStart, Video); Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth); Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight); if (pixelWidth != displayWidth) { Ebml_SerializeUnsigned(glob, DisplayWidth, displayWidth); } if (pixelHeight != displayHeight) { Ebml_SerializeUnsigned(glob, DisplayHeight, displayHeight); } Ebml_EndSubElement(glob, &videoStart); // Video } Ebml_EndSubElement(glob, &start); // Track Entry } void writeAudioTrack(EbmlGlobal *glob, unsigned int trackNumber, int flagLacing, const char *codecId, double samplingFrequency, unsigned int channels, uint64_t codecDelay, uint64_t seekPreRoll, unsigned char *private, unsigned long privateSize) { EbmlLoc start; UInt64 trackID; Ebml_StartSubElement(glob, &start, TrackEntry); Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber); trackID = generateTrackID(trackNumber); Ebml_SerializeUnsigned(glob, TrackUID, trackID); Ebml_SerializeUnsigned(glob, TrackType, 2); // audio is always 2 Ebml_SerializeUnsigned(glob, CodecDelay, codecDelay); Ebml_SerializeUnsigned(glob, SeekPreRoll, seekPreRoll); // I am using defaults for thesed required fields /* Ebml_SerializeUnsigned(glob, FlagEnabled, 1); Ebml_SerializeUnsigned(glob, FlagDefault, 1); Ebml_SerializeUnsigned(glob, FlagForced, 1); Ebml_SerializeUnsigned(glob, FlagLacing, flagLacing);*/ Ebml_SerializeString(glob, CodecID, codecId); Ebml_SerializeData(glob, CodecPrivate, private, privateSize); Ebml_SerializeString(glob, CodecName, "OPUS"); // fixed for now { EbmlLoc AudioStart; Ebml_StartSubElement(glob, &AudioStart, Audio); Ebml_SerializeFloat(glob, SamplingFrequency, samplingFrequency); Ebml_SerializeUnsigned(glob, Channels, channels); Ebml_EndSubElement(glob, &AudioStart); } Ebml_EndSubElement(glob, &start); } void writeSegmentInformation(EbmlGlobal *ebml, EbmlLoc *startInfo, unsigned long timeCodeScale, double duration) { Ebml_StartSubElement(ebml, startInfo, Info); Ebml_SerializeUnsigned(ebml, TimecodeScale, timeCodeScale); Ebml_SerializeFloat(ebml, Segment_Duration, duration * 1000.0); // Currently fixed to using milliseconds Ebml_SerializeString(ebml, 0x4D80, "QTmuxingAppLibWebM-0.0.1"); Ebml_SerializeString(ebml, 0x5741, "QTwritingAppLibWebM-0.0.1"); Ebml_EndSubElement(ebml, startInfo); } /* void Mkv_InitializeSegment(Ebml& ebml_out, EbmlLoc& ebmlLoc) { Ebml_StartSubElement(ebml_out, ebmlLoc, 0x18538067); } void Mkv_InitializeSeek(Ebml& ebml_out, EbmlLoc& ebmlLoc) { Ebml_StartSubElement(ebml_out, ebmlLoc, 0x114d9b74); } void Mkv_WriteSeekInformation(Ebml& ebml_out, SeekStruct& seekInformation) { EbmlLoc ebmlLoc; Ebml_StartSubElement(ebml_out, ebmlLoc, 0x4dbb); Ebml_SerializeString(ebml_out, 0x53ab, seekInformation.SeekID); Ebml_SerializeUnsigned(ebml_out, 0x53ac, seekInformation.SeekPosition); Ebml_EndSubElement(ebml_out, ebmlLoc); } void Mkv_WriteSegmentInformation(Ebml& ebml_out, SegmentInformationStruct& segmentInformation) { Ebml_SerializeUnsigned(ebml_out, 0x73a4, segmentInformation.segmentUID); if (segmentInformation.filename != 0) Ebml_SerializeString(ebml_out, 0x7384, segmentInformation.filename); Ebml_SerializeUnsigned(ebml_out, 0x2AD7B1, segmentInformation.TimecodeScale); Ebml_SerializeUnsigned(ebml_out, 0x4489, segmentInformation.Duration); // TODO date Ebml_SerializeWString(ebml_out, 0x4D80, L"MKVMUX"); Ebml_SerializeWString(ebml_out, 0x5741, segmentInformation.WritingApp); } void Mkv_InitializeTrack(Ebml& ebml_out, EbmlLoc& ebmlLoc) { Ebml_StartSubElement(ebml_out, ebmlLoc, 0x1654AE6B); } static void Mkv_WriteGenericTrackData(Ebml& ebml_out, TrackStruct& track) { Ebml_SerializeUnsigned(ebml_out, 0xD7, track.TrackNumber); Ebml_SerializeUnsigned(ebml_out, 0x73C5, track.TrackUID); Ebml_SerializeUnsigned(ebml_out, 0x83, track.TrackType); Ebml_SerializeUnsigned(ebml_out, 0xB9, track.FlagEnabled ? 1 :0); Ebml_SerializeUnsigned(ebml_out, 0x88, track.FlagDefault ? 1 :0); Ebml_SerializeUnsigned(ebml_out, 0x55AA, track.FlagForced ? 1 :0); if (track.Language != 0) Ebml_SerializeString(ebml_out, 0x22B59C, track.Language); if (track.CodecID != 0) Ebml_SerializeString(ebml_out, 0x86, track.CodecID); if (track.CodecPrivate != 0) Ebml_SerializeData(ebml_out, 0x63A2, track.CodecPrivate, track.CodecPrivateLength); if (track.CodecName != 0) Ebml_SerializeWString(ebml_out, 0x258688, track.CodecName); } void Mkv_WriteVideoTrack(Ebml& ebml_out, TrackStruct & track, VideoTrackStruct& video) { EbmlLoc trackHeadLoc, videoHeadLoc; Ebml_StartSubElement(ebml_out, trackHeadLoc, 0xAE); // start Track Mkv_WriteGenericTrackData(ebml_out, track); Ebml_StartSubElement(ebml_out, videoHeadLoc, 0xE0); // start Video Ebml_SerializeUnsigned(ebml_out, 0x9A, video.FlagInterlaced ? 1 :0); Ebml_SerializeUnsigned(ebml_out, 0xB0, video.PixelWidth); Ebml_SerializeUnsigned(ebml_out, 0xBA, video.PixelHeight); Ebml_SerializeUnsigned(ebml_out, 0x54B0, video.PixelDisplayWidth); Ebml_SerializeUnsigned(ebml_out, 0x54BA, video.PixelDisplayHeight); Ebml_SerializeUnsigned(ebml_out, 0x54B2, video.displayUnit); Ebml_SerializeFloat(ebml_out, 0x2383E3, video.FrameRate); Ebml_EndSubElement(ebml_out, videoHeadLoc); Ebml_EndSubElement(ebml_out, trackHeadLoc); } void Mkv_WriteAudioTrack(Ebml& ebml_out, TrackStruct & track, AudioTrackStruct& video) { EbmlLoc trackHeadLoc, audioHeadLoc; Ebml_StartSubElement(ebml_out, trackHeadLoc, 0xAE); Mkv_WriteGenericTrackData(ebml_out, track); Ebml_StartSubElement(ebml_out, audioHeadLoc, 0xE0); // start Audio Ebml_SerializeFloat(ebml_out, 0xB5, video.SamplingFrequency); Ebml_SerializeUnsigned(ebml_out, 0x9F, video.Channels); Ebml_SerializeUnsigned(ebml_out, 0x6264, video.BitDepth); Ebml_EndSubElement(ebml_out, audioHeadLoc); // end audio Ebml_EndSubElement(ebml_out, trackHeadLoc); } void Mkv_WriteEbmlClusterHead(Ebml& ebml_out, EbmlLoc& ebmlLoc, ClusterHeadStruct & clusterHead) { Ebml_StartSubElement(ebml_out, ebmlLoc, 0x1F43B675); Ebml_SerializeUnsigned(ebml_out, 0x6264, clusterHead.TimeCode); } void Mkv_WriteSimpleBlockHead(Ebml& ebml_out, EbmlLoc& ebmlLoc, SimpleBlockStruct& block) { Ebml_StartSubElement(ebml_out, ebmlLoc, 0xA3); Ebml_Write1UInt(ebml_out, block.TrackNumber); Ebml_WriteSigned16(ebml_out,block.TimeCode); unsigned char flags = 0x00 | (block.iskey ? 0x80:0x00) | (block.lacing << 1) | block.discardable; Ebml_Write1UInt(ebml_out, flags); // TODO this may be the wrong function Ebml_Serialize(ebml_out, block.data, block.dataLength); Ebml_EndSubElement(ebml_out,ebmlLoc); } */
/* * @brief Changes the baudrate of UART channel. * * @param UART_t * Pointer to the UART APP handle. * @param baud Value of new baudrate. * @param oversampling Number of samples to be considered for each symbol. 16 is the standard value. * * @return UART_STATUS_t UART_STATUS_SUCCESS if baudrate changed successfully. * UART_STATUS_BUSY if the UART channel is busy. * * \par<b>Description:</b><br> * The function stops the channel, calculates the clock divider values to achieve the desired baudrate. * Sets the divider values and reconfigures the channel as per the configuration in the UI. The channel is * enabled at the end of configuration. */ UART_STATUS_t UART_SetBaudrate(const UART_t * handle, uint32_t baud, uint32_t oversampling) { UART_STATUS_t ret_stat = UART_STATUS_BUSY; const UART_TX_CONFIG_t * ptr_tx_conf = handle->config->tx_pin_config; XMC_ASSERT("UART_SetBaudrate: UART APP handle invalid", ((handle != NULL)&& ((handle->config != NULL) && (handle->runtime != NULL)))) if ((handle->runtime->tx_busy == false) && (handle->runtime->rx_busy == false)) { if (handle->config->mode != UART_MODE_LOOPBACK) { XMC_GPIO_SetMode(ptr_tx_conf->port, ptr_tx_conf->pin, XMC_GPIO_MODE_INPUT_TRISTATE); } if (XMC_UART_CH_Stop(handle->channel) == XMC_UART_CH_STATUS_OK) { ret_stat = (UART_STATUS_t)XMC_UART_CH_SetBaudrate(handle->channel, baud, oversampling); if (ret_stat == UART_STATUS_SUCCESS) { XMC_UART_CH_SetSamplePoint(handle->channel, (uint32_t)(oversampling >> 1U)+1U); } XMC_UART_CH_Start(handle->channel); if (handle->config->mode != UART_MODE_LOOPBACK) { XMC_GPIO_Init(ptr_tx_conf->port, ptr_tx_conf->pin, ptr_tx_conf->config); } } else { ret_stat = UART_STATUS_BUSY; } } return ret_stat; }
/* * __wt_async_create -- * Start the async subsystem and worker threads. */ int __wt_async_create(WT_SESSION_IMPL *session, const char *cfg[]) { WT_CONNECTION_IMPL *conn; bool run; conn = S2C(session); run = false; WT_RET(__async_config(session, conn, cfg, &run)); if (!run) return (0); return (__async_start(session)); }
#include<stdio.h> #define ll long long ll solve(ll l,ll r) { ll ans=l; ll filter=1LL; while(1) { while(filter&ans) filter<<=1; if((filter+ans)<=r) ans+=filter; else return ans; } } int main() { ll q; scanf("%lld",&q); while(q--) { ll l,r; scanf("%lld%lld",&l,&r); printf("%lld\n",solve(l,r)); } return 0; }
/* * preenBail * Routine that other routines can call if they would go into a * state where they need user input. They can send an optional * message string to be printed before the exit. Caller should * send a NULL string if they don't have an exit message. */ void preenBail(char *outString) { if (Preen) { if (outString) (void) printf("%s", outString); (void) printf(gettext("FILE SYSTEM FIX REQUIRES USER " "INTERVENTION; RUN fsck MANUALLY.\n")); exit(36); } }
/*============================== usb_findcart Checks if the game is running on a 64Drive, EverDrive or a SummerCart64. ==============================*/ static void usb_findcart() { u32 buff; #if USE_OSRAW osPiRawReadIo(D64_CIBASE_ADDRESS + D64_REGISTER_MAGIC, &buff); #else osPiReadIo(D64_CIBASE_ADDRESS + D64_REGISTER_MAGIC, &buff); #endif if (buff == D64_MAGIC) { usb_cart = CART_64DRIVE; return; } #if USE_OSRAW osPiRawReadIo(SC64_REG_VERSION, &buff); #else osPiReadIo(SC64_REG_VERSION, &buff); #endif if (buff == SC64_VERSION_A) { usb_cart = CART_SC64; return; } usb_everdrive_writereg(ED_REG_KEY, ED_REGKEY); usb_everdrive_readreg(ED_REG_VERSION, &buff); if (buff == ED7_VERSION || buff == ED3_VERSION) { IO_WRITE(PI_STATUS_REG, 3); IO_WRITE(PI_BSD_DOM1_LAT_REG, 0x40); IO_WRITE(PI_BSD_DOM1_PWD_REG, 0x12); IO_WRITE(PI_BSD_DOM1_PGS_REG, 0x07); IO_WRITE(PI_BSD_DOM1_RLS_REG, 0x03); IO_WRITE(PI_BSD_DOM2_LAT_REG, 0x05); IO_WRITE(PI_BSD_DOM2_PWD_REG, 0x0C); IO_WRITE(PI_BSD_DOM2_PGS_REG, 0x0D); IO_WRITE(PI_BSD_DOM2_RLS_REG, 0x02); IO_WRITE(PI_BSD_DOM1_LAT_REG, 0x04); IO_WRITE(PI_BSD_DOM1_PWD_REG, 0x0C); usb_everdrive_writereg(ED_REG_SYSCFG, 0); usb_everdrive_writereg(ED_REG_USBCFG, ED_USBMODE_RDNOP); usb_cart = CART_EVERDRIVE; return; } }
/* Determine if PASS_NAME matches CRITERION. Not a pure predicate, since it can update CRITERION, to support matching the Nth invocation of a pass. Subroutine of should_skip_pass_p. */ static bool determine_pass_name_match (const char *pass_name, char *criterion) { size_t namelen = strlen (pass_name); if (! strncmp (pass_name, criterion, namelen)) { if (criterion[namelen] == '\0' || (criterion[namelen] == '1' && criterion[namelen + 1] == '\0')) return true; else { if (criterion[namelen + 1] == '\0') --criterion[namelen]; return false; } } else return false; }
/** * @brief Read single FIFO pattern cycle * @param SampleIndex Current sample index. * @retval BSP status */ static int32_t LSM6DSL_Read_Single_FIFO_Pattern_Cycle(uint16_t SampleIndex) { uint16_t pattern = 0; int32_t angular_velocity = 0; int32_t gyr_x = 0, gyr_y = 0, gyr_z = 0; int32_t ret = BSP_ERROR_NONE; int i; for (i = 0; i <= 2; i++) { if ((ret = IKS01A2_MOTION_SENSOR_FIFO_Get_Pattern(IKS01A2_LSM6DSL_0, &pattern)) != BSP_ERROR_NONE) { return ret; } if ((ret = IKS01A2_MOTION_SENSOR_FIFO_Get_Axis(IKS01A2_LSM6DSL_0, MOTION_GYRO, &angular_velocity)) != BSP_ERROR_NONE) { return ret; } switch (pattern) { case PATTERN_GYR_X_AXIS: gyr_x = angular_velocity; break; case PATTERN_GYR_Y_AXIS: gyr_y = angular_velocity; break; case PATTERN_GYR_Z_AXIS: gyr_z = angular_velocity; break; default: ret = BSP_ERROR_UNKNOWN_FAILURE; break; } } if (ret != BSP_ERROR_NONE) { return ret; } (void)snprintf(dataOut, MAX_BUF_SIZE, "[DATA %02d] %8ld %8ld %8ld\r\n", SampleIndex + 1U, gyr_x, gyr_y, gyr_z); printf("%s", dataOut); return ret; }
#include <stdlib.h> /* for qsort */ #include <string.h> /* for strlen */ #include <strings.h> /* for strcasecmp */ int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r); if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); } int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
/* * When VM captures mouse, the event is incomplete. We should filter it * out: a left-button-up event happened with no left-button-down preceded. * We don't know when mouse released, so have to check the signature often. */ static bool VirtinGrabbed(const struct VirtinEvent *ev) { static int precedeDown = VIRTIN_PRECEDE_DOWN_NO; if (ev->type == EV_KEY && ev->code == BTN_LEFT) { if (ev->value == 1) { precedeDown = VIRTIN_PRECEDE_DOWN_YES; } else if (precedeDown == VIRTIN_PRECEDE_DOWN_YES) { precedeDown = VIRTIN_PRECEDE_DOWN_NO; } else { precedeDown = VIRTIN_PRECEDE_DOWN_SYN; return false; } } if (precedeDown == VIRTIN_PRECEDE_DOWN_SYN) { precedeDown = VIRTIN_PRECEDE_DOWN_NO; return false; } return true; }
/** **************************************************************************************** * \brief Sets the clock of the PDM peripheral and enables the PDM * * \param[in] pdm_clock_divider The clock divider which determines the PDM clock * * \return None **************************************************************************************** */ static void pdm_set_master_clock(unsigned int pdm_clock_divider) { unsigned int div_field; if (pdm_clock_divider == 0) { div_field = 8; } else { div_field = pdm_clock_divider; } GLOBAL_INT_DISABLE(); uint16_t reg_val = GetWord16(PDM_DIV_REG); SetBits16(&reg_val, PDM_DIV, div_field); SetBits16(&reg_val, CLK_PDM_EN, 1); SetWord16(PDM_DIV_REG, reg_val); GLOBAL_INT_RESTORE(); }
/* * __wt_btcur_reset -- * Invalidate the cursor position. */ int __wt_btcur_reset(WT_CURSOR_BTREE *cbt) { WT_SESSION_IMPL *session; session = (WT_SESSION_IMPL *)cbt->iface.session; WT_STAT_FAST_CONN_INCR(session, cursor_reset); WT_STAT_FAST_DATA_INCR(session, cursor_reset); return (__cursor_reset(cbt)); }
/* this should be called under sched->mtx */ static int logical_is_exec_time(sched_if_t *impl, cron_event_t *event) { logical_state_t *state = (logical_state_t *)impl->state; int rc = 0; assert(event); assert(state); rc = event->epoch <= state->clock; return rc; }
#ifndef SimDataFormats_Forward_LHCTransportLink_h #define SimDataFormats_Forward_LHCTransportLink_h 1 // -*- C++ -*- // // Package: Forward // Class : LHCTransportLink // /**\class LHCTransportLink LHCTransportLink.h SimG4CMS/Forward/interface/LHCTransportLink.h Description: correspondence link between barcodes for GenParticle transported by Hector and original ones Usage: in SimTrack creation when the Hector beam transport is used */ // // Original Author: // Created: Fri May 29 17:00:00 CEST 2009 // // system include files #include <iostream> // user include files class LHCTransportLink { public: // ---------- Constructor and destructor ----------------- explicit LHCTransportLink(int& beforeHector, int& afterHector) : beforeHector_(beforeHector), afterHector_(afterHector){}; LHCTransportLink() : beforeHector_(0), afterHector_(0){}; // ---------- Member functions --------------------------- void fill(int& afterHector, int& beforeHector); int beforeHector() const; int afterHector() const; void clear(); private: // ---------- Private Data members ----------------------- int beforeHector_; int afterHector_; }; std::ostream& operator<<(std::ostream& o, const LHCTransportLink& t); #endif
/* * Destroys a window and all of its subwindows */ void glutDestroyWindow( int windowID ) { SFG_Window* window = fgWindowByID( windowID ); freeglut_return_if_fail( window != NULL ); { fgExecutionState ExecState = fgState.ExecState; fgAddToWindowDestroyList( window ); fgState.ExecState = ExecState; } }
/* - "current-waiting" is the number of open connections that have issued a */ /* reserve command while watching this tube but not yet received a response. */ static void enqueue_waiting_conn(Conn *c) { tube t; size_t i; global_stat.waiting_ct++; c->type |= CONN_TYPE_WAITING; for (i = 0; i < c->watch.used; i++) { t = c->watch.items[i]; t->stat.waiting_ct++; ms_append(&t->waiting, c); } }
//************************************************** // Only called by the SM HISR, so no critical reigon // static IPC_Buffer IPC_SmFifoRead (IPC_Fifo Fifo) { IPC_Buffer Buffer; IPC_U32 ReadIndex; ReadIndex = Fifo->ReadIndex; IPC_TRACE (IPC_Channel_Debug, "IPC_SmFifoRead", "Fifo %08X, %d entries, read: %d, Write %d", Fifo, IPC_FIFOCOUNT(Fifo), ReadIndex, Fifo->WriteIndex); if (ReadIndex == Fifo->WriteIndex) { IPC_TRACE (IPC_Channel_Sm, "IPC_SmFifoRead", "Fifo %08X, Empty", Fifo, 0, 0, 0); return (IPC_Buffer) 0; } Buffer = Fifo->Buffer[ReadIndex]; Fifo->ReadIndex = IPC_FIFOINCREMENT (ReadIndex); IPC_TRACE (IPC_Channel_Sm, "IPC_SmFifoRead", "Fifo %08X, Read %08X, %d entries", Fifo, Buffer, IPC_FIFOCOUNT(Fifo), 0); return Buffer; }
/* Convert integer to byte representation */ /* Array bytes must be of length >= CINT_LENGTH */ /* Return length of encoded value */ int int2cint(uint8_t *bytes, int value) { unsigned int uval = value < 0 ? 2*(-value)+1 : 2*value; int count = 0; uint8_t nbyte = uval & 0x7F; uval = uval >> 7; while (uval) { bytes[count++] = (1 << 7) + nbyte; nbyte = uval & 0x7F; uval = uval >> 7; } bytes[count++] = nbyte; return count; }
/** * ieee802154_get_fc_from_skb - get the frame control field from an skb * @skb: skb where the frame control field will be get from */ static inline __le16 ieee802154_get_fc_from_skb(const struct sk_buff *skb) { __le16 fc; if (WARN_ON(!skb_mac_header_was_set(skb) || (skb_tail_pointer(skb) - skb_mac_header(skb)) < IEEE802154_FC_LEN)) return cpu_to_le16(0); memcpy(&fc, skb_mac_header(skb), IEEE802154_FC_LEN); return fc; }
/** * Wait for link-up, with status indication * * @v netdev Network device * @v max_wait_ms Maximum time to wait, in ms */ int iflinkwait ( struct net_device *netdev, unsigned int max_wait_ms ) { int key; int rc; netdev_poll ( netdev ); if ( netdev_link_ok ( netdev ) ) return 0; printf ( "Waiting for link-up on %s...", netdev->name ); while ( 1 ) { if ( netdev_link_ok ( netdev ) ) { rc = 0; break; } if ( max_wait_ms-- == 0 ) { rc = netdev->link_rc; break; } step(); if ( iskey() ) { key = getchar(); if ( key == CTRL_C ) { rc = -ECANCELED; break; } } mdelay ( 1 ); } if ( rc == 0 ) { printf ( " ok\n" ); } else { printf ( " failed: %s\n", strerror ( rc ) ); } return rc; }
/*-------------------------------------------------------------------------*/ /* ** Function : csReset ** ** Description : This routine is a major entry point and is called ** by the protocol stack to shut down this network ** interface driver. This routine may be called ** several times for each operating system reboot ** to dynamically bring the network interface driver ** to a non-running state. ** ** This routine resets the CS8900 chip. ** ** Parameters : struct cs_softc *sc ** ** Implicit Inputs : None. ** ** Implicit Outputs : None. ** ** Return Value : void ** ** Side Effects : None. ** */ void csReset( void * arg) { struct cs_softc *sc = arg; sc->sc_ethercom.ec_if.if_flags &= ~IFF_RUNNING; csResetChip( sc ); }
/* calculate the fibonacci number at given offset */ static ssize_t fib_read(struct file *file, char *buf, size_t size, loff_t *offset) { ubn *N = fib_sequence(*offset); char *s = ubignum_2decimal(N); ubignum_free(N); int len = strlen(s) + 1; if (copy_to_user(buf, s, len)) return -EFAULT; return (ssize_t) len; }
/* strncpy does not null-terminate, this does it. */ static void safe_strncpy(char *targ, char *src, unsigned spaceavail) { unsigned goodcount = spaceavail-1; if (spaceavail < 1) { return; } strncpy(targ,src,goodcount); targ[goodcount] = 0; }
/* * dsym_get_type_by_name(): given a type field, returns the pointer to its * entry in the internal type table. * * input: const char *: the type name * dsym_type_t *: the return location for the pointer to the table entry * boolean_t: case-sensitive name compare * output: int: DSYM_SUCCESS or DSYM_INVALID_TYPE */ static dsym_errcode_t dsym_get_type_by_name(const char *type, dsym_type_t **entry, boolean_t cs) { int cnt = sizeof (types) / sizeof (dsym_type_t); int result; int i; for (i = 0; i < cnt; i++) { if (cs) { result = strcmp(type, types[i].dt_string); } else { result = strcasecmp(type, types[i].dt_string); } if (result == 0) { *entry = &types[i]; return (DSYM_SUCCESS); } } return (DSYM_INVALID_TYPE); }
/* * Get token at position i of existing line, or add new token from input * stream to line at posistion. Overwrite the trailing newline. */ static struct token skip_or_get_token(TokenArray *line, int i) { struct token t; if (i == array_len(line) - 1) { t = array_get(line, i); if (t.token == NEWLINE) { (void) array_pop_back(line); } } if (i == array_len(line)) { do { t = get_token(); } while (t.token == NEWLINE); assert(t.token != END); array_push_back(line, t); } else { assert(i >= 0); assert(i < array_len(line)); t = array_get(line, i); } return t; }
#include<stdio.h> typedef struct TREE{ int id; struct TREE *parent; struct TREE *child[2]; int depth; int height; }Tree; Tree tree[100]; int setDepthHeight(Tree *nt, int depth){ if( nt == NULL ){ return -1; } nt->depth = depth; int lh = setDepthHeight(nt->child[0], depth+1); int rh = setDepthHeight(nt->child[1], depth+1); nt->height = (lh>rh?lh:rh) + 1; return nt->height; } void preOrder(Tree *tr){ if( tr == NULL ){ return; } printf(" %d", tr->id); preOrder(tr->child[0]); preOrder(tr->child[1]); return; } void inOrder(Tree *tr){ if( tr == NULL ){ return; } inOrder(tr->child[0]); printf(" %d", tr->id); inOrder(tr->child[1]); return; } void postOrder(Tree *tr){ if( tr == NULL ){ return; } postOrder(tr->child[0]); postOrder(tr->child[1]); printf(" %d", tr->id); return; } void output(Tree *tr){ char *nodetype[3] = {"root", "internal node", "leaf"}; int pid, sibling = -1, degree = 0, ni; if( tr->child[0] != NULL ){ degree++; } if( tr->child[1] != NULL ){ degree++; } if( tr->parent != NULL ){ if( tr->parent->child[0] != NULL && tr->parent->child[0]->id != tr->id ){ sibling = tr->parent->child[0]->id; }else if( tr->parent->child[1] != NULL && tr->parent->child[1]->id != tr->id ){ sibling = tr->parent->child[1]->id; } if( degree == 0 ){ ni = 2; }else{ ni = 1; } pid = tr->parent->id; }else{ ni = 0; pid = -1; } printf("node %d: parent = %d, sibling = %d, degree = %d, depth = %d, height = %d, %s\n", tr->id, pid, sibling, degree, tr->depth, tr->height, nodetype[ni] ); return; } int main(){ int n, id, id2, i, j; Tree *root = NULL; scanf("%d", &n); for( i = 0; i < n; i++ ){ tree[i].id = -1; tree[i].parent = NULL; tree[i].child[0] = NULL; tree[i].child[1] = NULL; tree[i].depth = -1; tree[i].height = -1; } for( i = 0; i < n; i++ ){ scanf("%d", &id); tree[id].id = id; scanf("%d", &id2); if( 0 <= id2 && id2 < n ){ tree[id].child[0] = &tree[id2]; tree[id2].parent = &tree[id]; } scanf("%d", &id2); if( 0 <= id2 && id2 < n ){ tree[id].child[1] = &tree[id2]; tree[id2].parent = &tree[id]; } } for( i = 0; i < n; i++ ){ if( tree[i].parent == NULL ){ root = &tree[i]; break; } } setDepthHeight(root, 0); printf("Preorder\n"); preOrder(root); printf("\n"); printf("Inorder\n"); inOrder(root); printf("\n"); printf("Postorder\n"); postOrder(root); printf("\n"); return 0; }
/**************************************************************************** * * Copyright (C) 2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #pragma once #include <stdint.h> #include <drivers/device/i2c.h> #include <px4_platform_common/i2c_spi_buses.h> #include <uORB/topics/adc_report.h> #include <uORB/Publication.hpp> #include <lib/perf/perf_counter.h> #include <drivers/drv_hrt.h> #define ADDRESSPOINTER_REG_CONVERSATION 0x00 #define ADDRESSPOINTER_REG_CONFIG 0x01 #define ADDRESSPOINTER_REG_LO_THRESH 0x02 #define ADDRESSPOINTER_REG_HI_THRESH 0x03 #define CONVERSION_REG_RESET 0x00 #define CONFIG_HIGH_OS_RESET 0x80 #define CONFIG_HIGH_OS_NOACT 0x00 #define CONFIG_HIGH_OS_START_SINGLE 0x80 #define CONFIG_HIGH_MUX_RESET 0x00 #define CONFIG_HIGH_MUX_P0N1 0x00 #define CONFIG_HIGH_MUX_P0N3 0x10 #define CONFIG_HIGH_MUX_P1N3 0x20 #define CONFIG_HIGH_MUX_P2N3 0x30 #define CONFIG_HIGH_MUX_P0NG 0x40 #define CONFIG_HIGH_MUX_P1NG 0x50 #define CONFIG_HIGH_MUX_P2NG 0x60 #define CONFIG_HIGH_MUX_P3NG 0x70 #define CONFIG_HIGH_PGA_RESET 0x02 #define CONFIG_HIGH_PGA_6144 0x00 #define CONFIG_HIGH_PGA_4096 0x02 #define CONFIG_HIGH_PGA_2048 0x04 #define CONFIG_HIGH_PGA_1024 0x06 #define CONFIG_HIGH_PGA_0512 0x08 #define CONFIG_HIGH_PGA_0256 0x0a #define CONFIG_HIGH_MODE_RESET 0x01 #define CONFIG_HIGH_MODE_SS 0x01 #define CONFIG_HIGH_MODE_CC 0x00 #define CONFIG_LOW_DR_RESET 0x80 #define CONFIG_LOW_DR_8SPS 0x00 #define CONFIG_LOW_DR_16SPS 0x20 #define CONFIG_LOW_DR_32SPS 0x40 #define CONFIG_LOW_DR_64SPS 0x60 #define CONFIG_LOW_DR_128SPS 0x80 #define CONFIG_LOW_DR_250SPS 0xa0 #define CONFIG_LOW_DR_475SPS 0xc0 #define CONFIG_LOW_DR_860SPS 0xe0 #define CONFIG_LOW_COMP_MODE_RESET 0x00 #define CONFIG_LOW_COMP_MODE_TRADITIONAL 0x00 #define CONFIG_LOW_COMP_MODE_WINDOW 0x10 #define CONFIG_LOW_COMP_POL_RESET 0x00 #define CONFIG_LOW_COMP_POL_ACTIVE_LOW 0x00 #define CONFIG_LOW_COMP_POL_ACTIVE_HIGH 0x08 #define CONFIG_LOW_COMP_LAT_DEFAULT 0x00 #define CONFIG_LOW_COMP_LAT_NONE 0x00 #define CONFIG_LOW_COMP_LAT_LATCH 0x04 #define CONFIG_LOW_COMP_QU_DEFAULT 0x03 #define CONFIG_LOW_COMP_QU_AFTER1 0x00 #define CONFIG_LOW_COMP_QU_AFTER2 0x01 #define CONFIG_LOW_COMP_QU_AFTER4 0x02 #define CONFIG_LOW_COMP_QU_DISABLE 0x03 #define CONFIG_RESET_VALUE_HIGH 0x85 #define CONFIG_RESET_VALUE_LOW 0x83 using namespace time_literals; /* * This driver configure ADS1115 into 4 channels with gnd as baseline. * Start each sample cycle by setting sample channel. * PGA set to 6.144V * SPS set to 256 * Valid output ranges from 0 to 32767 on each channel. */ class ADS1115 : public device::I2C, public I2CSPIDriver<ADS1115> { public: ADS1115(const I2CSPIDriverConfig &config); ~ADS1115() override; int init() override; static void print_usage(); void RunImpl(); int probe() override; protected: void print_status() override; void exit_and_cleanup() override; private: uORB::Publication<adc_report_s> _to_adc_report{ORB_ID(adc_report)}; static const hrt_abstime SAMPLE_INTERVAL{50_ms}; adc_report_s _adc_report{}; perf_counter_t _cycle_perf; int _channel_cycle_count{0}; bool _reported_ready_last_cycle{false}; // ADS1115 logic part enum ChannelSelection { Invalid = -1, A0 = 0, A1, A2, A3 }; /* set multiplexer to specific channel */ int setChannel(ChannelSelection ch); /* return true if sample result is valid */ bool isSampleReady(); /* * get adc sample. return the channel being measured. * Invalid indicates sample failure. */ ChannelSelection getMeasurement(int16_t *value); /* * get adc sample and automatically switch to next channel and start another measurement */ ChannelSelection cycleMeasure(int16_t *value); int readReg(uint8_t addr, uint8_t *buf, size_t len); int writeReg(uint8_t addr, uint8_t *buf, size_t len); };
#include <stdio.h> #include <stdlib.h> int main() { long int m,n,a; double c,i,j; scanf("%ld %ld",&m,&n); scanf("%ld",&a); if(n%a==0) i=n/a; else i=(n/a)+1; if(m%a==0) j=m/a; else j=(m/a)+1; c=i*j; printf("%0.0lf\n", c); return 0; }
#include <stdio.h> int main(){ int num, d, i = 0, t[10001][2] = {}; char str[100]; while(gets(str)){ if(str[0] == 0) i++; else{ sscanf(str, "%d %d", &num, &d); t[num][i]++; } } for(i = 0;i < 10001;i++) if(t[i][0] && t[i][1]) printf("%d %d\n", i, t[i][0] + t[i][1]); return 0; }
/** * Gets the raw character buffer from the string. The returned buffer * will be nul-terminated, but note that strings may contain binary * data so there may be extra nul characters prior to the termination. * This function should be little-used, extend DBusString or add * stuff to dbus-sysdeps.c instead. It's an error to use this * function on a const string. * * @param str the string * @returns the data */ char* _dbus_string_get_data (DBusString *str) { DBUS_STRING_PREAMBLE (str); return (char*) real->str; }
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2020 Intel Corporation */ #ifndef _ICE_DCF_ETHDEV_H_ #define _ICE_DCF_ETHDEV_H_ #include "base/ice_common.h" #include "base/ice_adminq_cmd.h" #include "ice_ethdev.h" #include "ice_dcf.h" #define ICE_DCF_MAX_RINGS 1 struct ice_dcf_queue { uint64_t dummy; }; struct ice_dcf_adapter { struct ice_adapter parent; /* Must be first */ struct ice_dcf_hw real_hw; }; void ice_dcf_handle_pf_event_msg(struct ice_dcf_hw *dcf_hw, uint8_t *msg, uint16_t msglen); int ice_dcf_init_parent_adapter(struct rte_eth_dev *eth_dev); void ice_dcf_uninit_parent_adapter(struct rte_eth_dev *eth_dev); #endif /* _ICE_DCF_ETHDEV_H_ */
/** * hdd_unset_beacon_filter() - remove beacon filter * @adapter: Pointer to the hdd adapter * * Return: 0 on success and errno on failure */ static int hdd_unset_beacon_filter(hdd_adapter_t *adapter) { VOS_STATUS vos_status = VOS_STATUS_E_FAILURE; vos_status = sme_unset_beacon_filter(adapter->sessionId); if (!VOS_IS_STATUS_SUCCESS(vos_status)) return -EFAULT; return 0; }
// Construct a quaternion to rotate around a unit-length 3-D vector inline void vmath_quat_rotation(float radians, const float* v0, float* out) { float s, c, angle; angle = (radians * 0.5f); s = sinf(angle); c = cosf(angle); vmath_mul(v0, s, 3, out); out[3] = c; }
// Function for saturating the input to the required format. // This function isn't used currently because of SeeDot generated scales // ensuring the overflows aren't a possibility. inline INT_T saturate(INTM_T inp) { if (inp > INT_TMAX){ return (INT_T)INT_TMAX; } else if (inp < INT_TMIN) { return (INT_T)INT_TMIN; } else { return (INT_T)inp; } }
/** * Destroy a CSS parser * * \param parser The parser instance to destroy * \return CSS_OK on success, appropriate error otherwise */ css_error css__parser_destroy(css_parser *parser) { if (parser == NULL) return CSS_BADPARM; parserutils_stack_destroy(parser->open_items); parserutils_vector_destroy(parser->tokens); parserutils_stack_destroy(parser->states); css__lexer_destroy(parser->lexer); parserutils_inputstream_destroy(parser->stream); parser->alloc(parser, 0, parser->pw); return CSS_OK; }
//Backwards equation for v(P,T) for subregion k double _v_P_T_R3k(double press, double temp) { const int _I_v_T_P_R3k[34] = {-2, -2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 5, 5, 5, 6, 6, 6, 6, 8, 10, 12}; const int _J_v_T_P_R3k[34] = {10, 12, -5, 6, -12, -6, -2, -1, 0, 1, 2, 3, 14, -3, -2, 0, 1, 2, -8, -6, -3, -2, 0, 4, -12, -6, -3, -12, -10, -8, -5, -12, -12, -10}; const double _n_v_T_P_R3k[34] = {-401215699.576099, 48450147831.8406, 3.94721471363678E-15, 37262.9967374147, -3.69794374168666E-30, -3.80436407012452E-15, 4.75361629970233E-07, -8.79148916140706E-04, 0.844317863844331, 12.24331626566, -104.529634830279, 589.702771277429, -29102685116444.4, 1.7034307284185E-06, -2.77617606975748E-04, -3.44709605486686, 22.1333862447095, -194.646110037079, 8.08354639772825E-16, -1.8084520914547E-11, -6.96664158132412E-06, -1.81057560300994E-03, 2.55830298579027, 3289.13873658481, -1.73270241249904E-19, -6.61876792558034E-07, -3.9568892342125E-03, 6.04203299819132E-18, -4.00879935920517E-14, 1.60751107464958E-09, 3.83719409025556E-05, -6.49565446702457E-15, -1.49095328506E-12, 5.41449377329581E-09}; const double vStar = 77.0E-04; const double pStar = 25; const double tStar = 680; const double a = 0.802; const double b = 0.935; const double c = 1; const double d = 1; const double e = 1; const int N = 34; double omega = _omega_pi_theta_R3(press, temp, pStar, tStar, a, b, c, d, e, _I_v_T_P_R3k, _J_v_T_P_R3k, _n_v_T_P_R3k, N); return vStar * omega; }
/* radare - LGPL - Copyright 2017-2019 - wargio */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <r_lib.h> #include <r_util.h> #include <r_flag.h> #include <r_anal.h> #include <r_parse.h> static bool replace(int argc, const char *argv[], char *newstr) { int i,j,k; struct { const char *op; const char *str; } ops[] = { { "add", "A += B" }, { "adc", "A += B + carry" }, { "adiw", "A+1:A += B" }, { "sub", "A -= B" }, { "subi", "A -= B" }, { "sbc", "A -= (B + carry)" }, { "sbci", "A -= (B + carry)" }, { "sbiw", "A+1:A -= B" }, { "and", "A &= B" }, { "andi", "A &= B" }, { "or", "A |= B" }, { "ori", "A |= B" }, { "eor", "A ^= B" }, { "com", "A = 0xff - A" }, { "neg", "A = -A" }, { "sbr", "A |= B" }, { "cbr", "A &= (0xff - B)" }, { "inc", "A++" }, { "dec", "A--" }, { "tst", "A &= A" }, { "clr", "A ^= A" }, { "ser", "A = 0xff" }, { "mul", "r1:r0 = A * B" }, { "rjmp", "goto A" }, { "ijmp", "goto z" }, { "jmp", "goto A" }, { "rcall", "goto A" }, { "icall", "goto z" }, { "call", "goto A" }, { "ret", "return" }, { "iret", "return_interrupt()" }, { "cp", "var = A - B" }, { "cpc", "var = A - B - carry" }, { "cpi", "var = A - B" }, { "breq", "if (!var) goto A" }, { "brne", "if (var) goto A" }, { "brsh", "if (var >= 0) goto A" }, { "brlo", "if (var < 0) goto A" }, { "brmi", "if (var < 0) goto A" }, { "brpl", "if (var > 0) goto A" }, { "brge", "if (var >= 0) goto A" }, { "brlt", "if (var < 0) goto A" }, { "mov", "A = B" }, { "movw", "A+1:A = B+1:B" }, { "ldi", "A = B" }, { "lds", "A = *(B)" }, { "ld", "A = *(B)" }, { "ldd", "A = *(B)" }, { "lpm", "r0 = z" }, { "in", "A = B" }, { "out", "A = B" }, { "push", "push(A)" }, { "pop", "A = pop()" }, { "lsl", "A <<= 1" }, { "lsr", "A >>= 1" }, { "rol", "A = (A << 1) | (A >> 7)" }, { "ror", "A = (A << 7) | (A >> 1)" }, { "asr", "A >>= 1" }, { "swap", "A = ((A & 0xf0) >> 4) | ((A & 0x0f) << 4)" }, { "sec", "c = 1" }, { "clc", "c = 0" }, { "sen", "n = 1" }, { "cln", "n = 0" }, { "sez", "z = 1" }, { "clz", "z = 0" }, { "sei", "i = 1" }, { "cli", "i = 0" }, { "ses", "s = 1" }, { "cls", "s = 0" }, { "sev", "v = 1" }, { "clv", "v = 0" }, { "set", "t = 1" }, { "clt", "t = 0" }, { "seh", "h = 1" }, { "clh", "h = 0" }, { "nop", "" }, { "halt", "_halt()" }, { "wdr", "_watchdog_reset()" }, { "std", "*(A) = B" }, { "st", "*(A) = B" }, { "sts", "*(A) = B" }, { NULL } }; for (i = 0; ops[i].op; i++) { if (!strcmp (ops[i].op, argv[0])) { if (newstr) { for (j = k = 0; ops[i].str[j] != '\0'; j++, k++) { if (ops[i].str[j] >= 'A' && ops[i].str[j] <= 'J') { const char *w = argv[ops[i].str[j] - '@']; if (w) { strcpy (newstr + k, w); k += strlen(w) - 1; } } else { newstr[k] = ops[i].str[j]; } } newstr[k] = '\0'; } return true; } } /* TODO: this is slow */ if (newstr) { newstr[0] = '\0'; for (i = 0; i < argc; i++) { strcat (newstr, argv[i]); strcat (newstr, (i == 0 || i == argc - 1) ? " ":", "); } } return false; } #define WSZ 128 static int parse(RParse *p, const char *data, char *str) { int i, len = strlen (data); char w0[WSZ]; char w1[WSZ]; char w2[WSZ]; char w3[WSZ]; char w4[WSZ]; char *buf, *ptr, *optr; // malloc can be slow here :? if (!(buf = malloc (len + 1))) { return false; } memcpy (buf, data, len + 1); r_str_trim (buf); if (*buf) { w0[0] = '\0'; w1[0] = '\0'; w2[0] = '\0'; w3[0] = '\0'; w4[0] = '\0'; ptr = strchr (buf, ' '); if (!ptr) { ptr = strchr (buf, '\t'); } if (ptr) { *ptr = '\0'; for (ptr++; *ptr == ' '; ptr++) { //nothing to see here } strncpy (w0, buf, WSZ - 1); strncpy (w1, ptr, WSZ - 1); optr = ptr; ptr = strchr (ptr, ','); if (ptr) { *ptr = '\0'; for (ptr++; *ptr == ' '; ptr++) { //nothing to see here } strncpy (w1, optr, WSZ - 1); strncpy (w2, ptr, WSZ - 1); optr = ptr; ptr = strchr (ptr, ','); if (ptr) { *ptr = '\0'; for (ptr++; *ptr == ' '; ptr++) { //nothing to see here } strncpy (w2, optr, WSZ - 1); strncpy (w3, ptr, WSZ - 1); optr = ptr; // bonus ptr = strchr (ptr, ','); if (ptr) { *ptr = '\0'; for (ptr++; *ptr == ' '; ptr++) { //nothing to see here } strncpy (w3, optr, WSZ - 1); strncpy (w4, ptr, WSZ - 1); } } } } else { strncpy (w0, buf, WSZ - 1); } { const char *wa[] = { w0, w1, w2, w3, w4 }; int nw = 0; for (i = 0; i < 5; i++) { if (wa[i][0] != '\0') { nw++; } } (void)replace (nw, wa, str); } } free (buf); return true; } RParsePlugin r_parse_plugin_avr_pseudo = { .name = "avr.pseudo", .desc = "AVR pseudo syntax", .parse = parse }; #ifndef R2_PLUGIN_INCORE R_API RLibStruct radare_plugin = { .type = R_LIB_TYPE_PARSE, .data = &r_parse_plugin_avr_pseudo, .version = R2_VERSION }; #endif
/****************************************************************************** ** EXECUTEQUERY -- Execute the specified query in the DAL server, return ** the QResponse object handle. */ void VF_EXECUTEQUERY (Query *query, QResponse *qr) { *qr = voc_executeQuery (*query); }