text
stringlengths
9
5.83M
//*********************************************************************************** // Include files //*********************************************************************************** #include "gpio.h" #include "native_gecko.h" /* GATT database */ #include "gatt_db.h" #include "infrastructure.h" #include "em_core.h" #include "main.h" //*********************************************************************************** // defined files //*********************************************************************************** //*********************************************************************************** // global variables //*********************************************************************************** //*********************************************************************************** // function prototypes //*********************************************************************************** //*********************************************************************************** // functions //*********************************************************************************** void gpio_init(void){ // Set LED ports to be standard output drive with default off (cleared) GPIO_DriveStrengthSet(LED0_port, gpioDriveStrengthStrongAlternateStrong); //GPIO_DriveStrengthSet(LED0_port, gpioDriveStrengthWeakAlternateWeak); GPIO_PinModeSet(LED0_port, LED0_pin, gpioModePushPull, LED0_default); GPIO_DriveStrengthSet(LED1_port, gpioDriveStrengthStrongAlternateStrong); //GPIO_DriveStrengthSet(LED1_port, gpioDriveStrengthWeakAlternateWeak); GPIO_DriveStrengthSet(SENSOR_ENABLE_PORT, gpioDriveStrengthStrongAlternateStrong); GPIO_PinModeSet(LED1_port, LED1_pin, gpioModePushPull, LED1_default); GPIO_PinModeSet(BUTTON0_port,BUTTON0_pin, gpioModeInputPull, 1); GPIO_PinModeSet(BUTTON1_port,BUTTON1_pin, gpioModeInputPull, 1); GPIO_PinModeSet(SENSOR_ENABLE_PORT,SENSOR_ENABLE_PIN, gpioModeInputPull, 1); GPIO_PinOutClear(SENSOR_ENABLE_PORT,SENSOR_ENABLE_PIN); } void gpio_int_enable(){ GPIO_ExtIntConfig(BUTTON0_port,BUTTON0_pin,4,false,true,true); GPIO_ExtIntConfig(BUTTON1_port,BUTTON1_pin,6,false,true,true); NVIC_ClearPendingIRQ(GPIO_EVEN_IRQn); NVIC_EnableIRQ(GPIO_EVEN_IRQn); } void GPIO_EVEN_IRQHandler(void){ CORE_AtomicDisableIrq(); gpioINT=GPIO->IFC; EXTERNAL_SIGNAL=BUTTON_SIGNAL; gecko_external_signal(0x01); CORE_AtomicEnableIrq(); }
#pragma once #include "resource.h" //End code - add one more empty line:
#include <stdio.h> void del_digit(char str[]) { for(int i=0;i<100;i++){//とりあえず上限の100文字まで if(str[i]=='\0')break;//ナル文字でループ抜ける if(str[i]>='0'&&str[i]<='9'){//もし数字だった時 for(int j=i;j<100;j++){//残り全てを詰める str[j]=str[j+1]; } } } } int main(void) { char str[100]; printf("文字列strを入力!:str =  "); scanf("%s",str); printf("数字の削除!\n"); del_digit(str); printf("str = %s\n",str); return(0); }
/** @file @ingroup st @brief Symbol table package. @details The st library provides functions to create, maintain, and query symbol tables. @copyright@parblock Copyright (c) 1994-1998 The Regents of the Univ. of California. All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. @endparblock @copyright@parblock Copyright (c) 1999-2015, Regents of the University of Colorado All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the University of Colorado 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. @endparblock */ #ifndef ST_H_ #define ST_H_ /*---------------------------------------------------------------------------*/ /* Nested includes */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Constant declarations */ /*---------------------------------------------------------------------------*/ /** * @brief Value returned if memory is exhausted. */ #define ST_OUT_OF_MEM -10000 /** * @brief Default value for the maximum table density. * @see st_init_table_with_params */ #define ST_DEFAULT_MAX_DENSITY 5 /** * @brief Default value for the initial table size. * @see st_init_table_with_params */ #define ST_DEFAULT_INIT_TABLE_SIZE 11 /** * @brief Default table growth factor. * @see st_init_table_with_params */ #define ST_DEFAULT_GROW_FACTOR 2.0 /** * @brief Default table reorder flag. * @see st_init_table_with_params */ #define ST_DEFAULT_REORDER_FLAG 0 /*---------------------------------------------------------------------------*/ /* Stucture declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Type declarations */ /*---------------------------------------------------------------------------*/ /** * @brief Type of symbol tables. */ typedef struct st_table st_table; /** * @brief Type of symbol table generators. */ typedef struct st_generator st_generator; /** * @brief Type of return values for iterators. */ enum st_retval {ST_CONTINUE, ST_STOP, ST_DELETE}; /** * @brief Type for function passed to @ref st_foreach. */ typedef enum st_retval (*st_foreach_t)(void *, void *, void *); /** * @brief Type of comparison functions. */ typedef int (*st_compare_t)(void const *, void const *); /** * @brief Type of hash functions. */ typedef int (*st_hash_t)(void const *, int); /** * @brief Type of comparison functions with extra argument. */ typedef int (*st_compare_arg_t)(void const *, void const *, void const *); /** * @brief Type of hash functions with extra argument. */ typedef int (*st_hash_arg_t)(void const *, int, void const *); /*---------------------------------------------------------------------------*/ /* Variable declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Macro declarations */ /*---------------------------------------------------------------------------*/ /** @brief Checks whethere `key` is in `table`. @details Returns 1 if there is an entry under `key` in `table`, 0 otherwise. @sideeffect None @see st_lookup */ #define st_is_member(table,key) st_lookup(table,key,(void **) 0) /** @brief Iteration macro. @details An iteration macro which loops over all the entries in `table`, setting `key` to point to the key and `value` to the associated value (if it is not nil). `gen` is a generator variable used internally. Sample usage: void *key, *value; st_generator *gen; st_foreach_item(table, gen, &key, &value) { process_item(value); } @sideeffect None @see st_foreach_item_int st_foreach */ #define st_foreach_item(table, gen, key, value) \ for(gen=st_init_gen(table); st_gen(gen,key,value) || (st_free_gen(gen),0);) /** @brief Iteration macro. @details An iteration macro which loops over all the entries in `table`, setting `key` to point to the key and `value` to the associated value (if it is not nil). `value` is assumed to be a pointer to an integer. `gen` is a generator variable used internally. Sample usage: void *key; int value; st_generator *gen; st_foreach_item_int(table, gen, &key, &value) { process_item(value); } @sideeffect None @see st_foreach_item st_foreach */ #define st_foreach_item_int(table, gen, key, value) \ for(gen=st_init_gen(table); st_gen_int(gen,key,value) || (st_free_gen(gen),0);) /*---------------------------------------------------------------------------*/ /* Function prototypes */ /*---------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif st_table *st_init_table_with_params (st_compare_t, st_hash_t, int, int, double, int); st_table *st_init_table (st_compare_t, st_hash_t); st_table *st_init_table_with_params_and_arg (st_compare_arg_t, st_hash_arg_t, void const *, int, int, double, int); st_table *st_init_table_with_arg (st_compare_arg_t, st_hash_arg_t, void const *); void st_free_table (st_table *); int st_lookup (st_table *, void const *, void **); int st_lookup_int (st_table *, void const *, int *); int st_insert (st_table *, void *, void *); int st_add_direct (st_table *, void *, void *); int st_find_or_add (st_table *, void *, void ***); int st_find (st_table *, void const *, void ***); st_table *st_copy (st_table const *); int st_delete (st_table *, void **, void **); int st_delete_int (st_table *, void **, int *); int st_count(st_table const *); int st_foreach (st_table *, st_foreach_t, void *); int st_strhash (void const *, int); int st_numhash (void const *, int); int st_ptrhash (void const *, int); int st_numcmp (void const *, void const *); int st_ptrcmp (void const *, void const *); st_generator *st_init_gen (st_table const *); int st_gen (st_generator *, void **, void **); int st_gen_int (st_generator *, void **, int *); void st_free_gen (st_generator *); #ifdef __cplusplus } /* end of extern "C" */ #endif #endif /* ST_H_ */
#ifndef jparse_h #define jparse_h #include "json.h" struct YYLTYPE; typedef struct JP_Parse_Context { void *scanner; JSON *out_json; } JP_Parse_Context; #define JP_SCANNER ctx->scanner void jperror(struct YYLTYPE *yylloc, JP_Parse_Context *ctx, char const *s); #endif
/******************************************************************************* * Copyright (C) 2004-2006 Intel Corp. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of Intel Corp. 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 Intel Corp. OR THE 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. *******************************************************************************/ /** * @author Anas Nashif * @author Vadim Revyakin * @author Sumeet Kukreja, Dell Inc. */ #ifndef _WSMAN_NAMESPACES_H_ #define _WSMAN_NAMESPACES_H_ // NameSpaces #define XML_NS_SOAP_1_1 "http://schemas.xmlsoap.org/soap/envelope" #define XML_NS_SOAP_1_2 "http://www.w3.org/2003/05/soap-envelope" #define XML_NS_XML_NAMESPACES "http://www.w3.org/XML/1998/namespace" #define XML_NS_ADDRESSING "http://schemas.xmlsoap.org/ws/2004/08/addressing" #define XML_NS_DISCOVERY "http://schemas.xmlsoap.org/ws/2004/10/discovery" #define XML_NS_EVENTING "http://schemas.xmlsoap.org/ws/2004/08/eventing" #define XML_NS_ENUMERATION "http://schemas.xmlsoap.org/ws/2004/09/enumeration" #define XML_NS_TRANSFER "http://schemas.xmlsoap.org/ws/2004/09/transfer" #define XML_NS_XML_SCHEMA "http://www.w3.org/2001/XMLSchema" #define XML_NS_SCHEMA_INSTANCE "http://www.w3.org/2001/XMLSchema-instance" #define XML_NS_POLICY "http://schemas.xmlsoap.org/ws/2004/09/policy" #define XML_NS_TRUST "http://schemas.xmlsoap.org/ws/2005/02/trust" #define XML_NS_SE "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" #define XML_NS_SCHEMA_INSTANCE_PREFIX "xsi" #define XML_NS_SCHEMA_INSTANCE_NIL "nil" #define XML_NS_OPENWSMAN "http://schema.openwsman.org/2006/openwsman" #define XML_NS_CIM_SCHEMA "http://schemas.dmtf.org/wbem/wscim/1/common" #define XML_NS_CIM_CLASS "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2" #define XML_NS_CIM_BINDING "http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsd" #define XML_NS_CIM_INTRINSIC "http://schemas.openwsman.org/wbem/wscim/1/intrinsic" // WS-Management #define XML_NS_WS_MAN "http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" #define XML_NS_WSMAN_FAULT_DETAIL "http://schemas.dmtf.org/wbem/wsman/1/wsman/faultDetail" #define XML_NS_WS_MAN_CAT "http://schemas.xmlsoap.org/ws/2005/06/wsmancat" #define XML_NS_WSMAN_ID "http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd" #define DMTF_WSMAN_SPEC_1 #define SOAP1_2_CONTENT_TYPE "application/soap+xml;charset=UTF-8" #define SOAP_CONTENT_TYPE "application/soap+xml" #define CIMXML_CONTENT_TYPE "application/xml" #define SOAP_SKIP_DEF_FILTERS 0x01 #define SOAP_ACTION_PREFIX 0x02 // otherwise exact #define SOAP_ONE_WAY_OP 0x04 #define SOAP_NO_RESP_OP 0x08 #define SOAP_DONT_KEEP_INDOC 0x10 #define SOAP_CLIENT_RESPONSE 0x20 // internal use #define SOAP_CUSTOM_DISPATCHER 0x40 // internal use #define SOAP_IDENTIFY_DISPATCH 0x80 // internal use #define WSMID_IDENTIFY "Identify" #define WSMID_IDENTIFY_RESPONSE "IdentifyResponse" #define WSMID_PROTOCOL_VERSION "ProtocolVersion" #define WSMID_PRODUCT_VENDOR "ProductVendor" #define WSMID_PRODUCT_VERSION "ProductVersion" #define XML_SCHEMA_NIL "nil" #define WSA_TO_ANONYMOUS \ "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous" #define WSA_MESSAGE_ID "MessageID" #define WSA_ADDRESS "Address" #define WSA_EPR "EndpointReference" #define WSA_ACTION "Action" #define WSA_RELATES_TO "RelatesTo" #define WSA_TO "To" #define WSA_REPLY_TO "ReplyTo" #define WSA_FROM "From" #define WSA_FAULT_TO "FaultTo" #define WSA_REFERENCE_PROPERTIES "ReferenceProperties" #define WSA_REFERENCE_PARAMETERS "ReferenceParameters" #define WSA_ACTION_FAULT \ "http://schemas.xmlsoap.org/ws/2004/08/addressing/fault" #define SOAP_ENVELOPE "Envelope" #define SOAP_HEADER "Header" #define SOAP_BODY "Body" #define SOAP_FAULT "Fault" #define SOAP_CODE "Code" #define SOAP_VALUE "Value" #define SOAP_SUBCODE "Subcode" #define SOAP_REASON "Reason" #define SOAP_TEXT "Text" #define SOAP_LANG "lang" #define SOAP_DETAIL "Detail" #define SOAP_FAULT_DETAIL "FaultDetail" #define SOAP_MUST_UNDERSTAND "mustUnderstand" #define SOAP_VERSION_MISMATCH "VersionMismatch" #define SOAP_UPGRADE "Upgrade" #define SOAP_SUPPORTED_ENVELOPE "SupportedEnvelope" /* Action URI */ #define TRANSFER_ACTION_GET \ "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get" #define TRANSFER_ACTION_GETRESPONSE \ "http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse" #define TRANSFER_GET "Get" #define TRANSFER_GET_RESP "GetResponse" #define TRANSFER_ACTION_PUT \ "http://schemas.xmlsoap.org/ws/2004/09/transfer/Put" #define TRANSFER_ACTION_PUTRESPONSE \ "http://schemas.xmlsoap.org/ws/2004/09/transfer/PutResponse" #define TRANSFER_PUT "Put" #define TRANSFER_PUT_RESP "PutResponse" #define TRANSFER_ACTION_CREATE \ "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create" #define TRANSFER_CREATE "Create" #define TRANSFER_ACTION_DELETE \ "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete" #define TRANSFER_DELETE "Delete" #define TRANSFER_ACTION_DELETERESPONSE \ "http://schemas.xmlsoap.org/ws/2004/09/transfer/DeleteResponse" #define TRANSFER_DELETE_RESP "DeleteResponse" #define WSXF_ACTION_FAULT \ "http://schemas.xmlsoap.org/ws/2004/09/transfer/fault" #define ENUM_ACTION_ENUMERATE \ "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate" #define ENUM_ACTION_ENUMERATERESPONSE \ "http://schemas.xmlsoap.org/ws/2004/09/enumeration/EnumerateResponse" #define WSENUM_ENUMERATE "Enumerate" #define WSENUM_ENUMERATE_RESP "EnumerateResponse" #define ENUM_ACTION_RELEASE \ "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Release" #define WSENUM_RELEASE "Release" #define WSENUM_RELEASE_RESP "ReleaseResponse" #define ENUM_ACTION_PULL \ "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull" #define WSENUM_PULL "Pull" #define WSENUM_PULL_RESP "PullResponse" #define ENUM_ACTION_RENEW \ "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Renew" #define ENUM_ACTION_GETSTATUS \ "http://schemas.xmlsoap.org/ws/2004/09/enumeration/GetStatus" #define ENUM_ACTION_ENUMEND \ "http://schemas.xmlsoap.org/ws/2004/09/enumeration/EnumerationEnd" #define EVT_ACTION_SUBSCRIBE \ "http://schemas.xmlsoap.org/ws/2004/08/eventing/Subscribe" #define WSEVENT_SUBSCRIBE "Subscribe" #define WSEVENT_SUBSCRIBE_RESP "SubscribeResponse" #define EVT_ACTION_PULL \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/Pull" #define EVT_ACTION_GETSTATUS \ "http://schemas.xmlsoap.org/ws/2004/08/eventing/GetStaus" #define EVT_ACTION_UNSUBSCRIBE \ "http://schemas.xmlsoap.org/ws/2004/08/eventing/Unsubscribe" #define WSEVENT_UNSUBSCRIBE "Unsubscribe" #define WSEVENT_UNSUBSCRIBE_RESP "UnsubscribeResponse" #define EVT_ACTION_SUBEND \ "http://schemas.xmlsoap.org/ws/2004/08/eventing/SubscriptionEnd" #define EVT_ACTION_RENEW \ "http://schemas.xmlsoap.org/ws/2004/08/eventing/Renew" #define WSEVENT_RENEW "Renew" #define WSEVENT_RENEW_RESP "RenewResponse" #define WSMAN_ACTION_EVENTS \ "http://schemas.xmlsoap.org/wbmem/wsman/1/wsman/Events" #define WSMAN_ACTION_HEARTBEAT \ "http://schemas.xmlsoap.org/wbmem/wsman/1/wsman/Heartbeat" #define WSMAN_ACTION_DROPPEDEVENTS \ "http://schemas.xmlsoap.org/wbmem/wsman/1/wsman/DroppedEvents" #define WSMAN_ACTION_ACK \ "http://schemas.xmlsoap.org/wbmem/wsman/1/wsman/Ack" #define WSMAN_ACTION_EVENT \ "http://schemas.xmlsoap.org/wbmem/wsman/1/wsman/Event" #define WSENUM_ACTION_FAULT \ "http://schemas.xmlsoap.org/ws/2004/09/enumeration/fault" #define WSENUM_RENEW "Renew" #define WSENUM_RENEW_RESP "RenewResponse" #define WSENUM_GET_STATUS "GetStatus" #define WSENUM_GET_STATUS_RESP "GetStatusResponse" #define WSMAN_ACTION_FAULT \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/fault" #define WSENUM_END_TO "EndTo" #define WSENUM_EXPIRES "Expires" #define WSENUM_FILTER "Filter" #define WSENUM_DIALECT "Dialect" #define WSENUM_ENUMERATION_CONTEXT "EnumerationContext" #define WSENUM_MAX_TIME "MaxTime" #define WSENUM_MAX_ELEMENTS "MaxElements" #define WSENUM_MAX_CHARACTERS "MaxCharacters" #define WSENUM_ITEMS "Items" #define WSENUM_END_OF_SEQUENCE "EndOfSequence" #define WSENUM_ENUMERATION_END "EnumerationEnd" #define WSENUM_REASON "Reason" #define WSENUM_CODE "Code" #define WSENUM_SOURCE_SHUTTING_DOWN "SourceShuttingDown" #define WSENUM_SOURCE_CANCELING "SourceCanceling" #define WSEVENT_DELIVERY "Delivery" #define WSEVENT_NOTIFY_TO "NotifyTo" #define WSEVENT_ENDTO "EndTo" #define WSEVENT_EXPIRES "Expires" #define WSEVENT_DELIVERY_MODE "Mode" #define WSEVENT_SUBSCRIPTION_MANAGER "SubscriptionManager" #define WSEVENT_IDENTIFIER "Identifier" #define WSEVENT_FILTER "Filter" #define WSEVENT_DIALECT "Dialect" #define WSEVENT_ACTION_FAULT "http://schemas.xmlsoap.org/ws/2004/08/eventing/fault" //WS-Eventing delivery mode #define WSEVENT_DELIVERY_MODE_PUSH "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push" #define WSEVENT_DELIVERY_MODE_PUSHWITHACK "http://schemas.dmtf.org/wbem/wsman/1/wsman/PushWithAck" #define WSEVENT_DELIVERY_MODE_EVENTS "http://schemas.dmtf.org/wbem/wsman/1/wsman/Events" #define WSEVENT_DELIVERY_MODE_PULL "http://schemas.dmtf.org/wbem/wsman/1/wsman/Pull" #define WSMB_ASSOCIATED_INSTANCES "AssociatedInstances" #define WSMB_ASSOCIATION_INSTANCES "AssociationInstances" #define WSMB_OBJECT "Object" #define WSMB_ASSOCIATION_CLASS_NAME "AssociationClassName" #define WSMB_RESULT_CLASS_NAME "ResultClassName" #define WSMB_ROLE "Role" #define WSMB_RESULT_ROLE "ResultRole" #define WSMB_INCLUDE_RESULT_PROPERTY "IncludeResultProperty" #define CIM_RESOURCE_NS_PREFIX "p" #define WSM_SYSTEM "System" #define WSM_LOCALE "Locale" #define WSM_RESOURCE_URI "ResourceURI" #define WSM_SELECTOR_SET "SelectorSet" #define WSM_SELECTOR "Selector" #define WSM_NAME "Name" #define WSM_REQUEST_TOTAL "RequestTotalItemsCountEstimate" #define WSM_TOTAL_ESTIMATE "TotalItemsCountEstimate" #define WSM_OPTIMIZE_ENUM "OptimizeEnumeration" #define WSM_MAX_ELEMENTS "MaxElements" #define WSM_ENUM_EPR "EnumerateEPR" #define WSM_ENUM_OBJ_AND_EPR "EnumerateObjectAndEPR" #define WSM_ENUM_MODE "EnumerationMode" #define WSM_ITEM "Item" #define WSM_FRAGMENT_TRANSFER "FragmentTransfer" #define WSM_XML_FRAGMENT "XmlFragment" #define WSM_OPTION_SET "OptionSet" #define WSM_OPTION "Option" #define WSM_TOTAL "Total" #define WSM_HEARTBEATS "Heartbeats" #define WSM_EVENTS "Events" #define WSM_ACTION "Action" #define WSM_EVENT "Event" #define WSM_ACKREQUESTED "AckRequested" #define WSM_MAX_ENVELOPE_SIZE "MaxEnvelopeSize" #define WSM_OPERATION_TIMEOUT "OperationTimeout" #define WSM_FAULT_SUBCODE "FaultSubCode" #define WSM_FILTER "Filter" #define WSM_DIALECT "Dialect" #define WSM_CONTENTCODING "ContentEncoding" #define WSM_CONNECTIONRETRY "ConnectionRetry" #define WSM_SENDBOOKMARKS "SendBookmarks" #define WSM_BOOKMARK "Bookmark" #define WSM_DROPPEDEVENTS "DroppedEvents" #define WSM_AUTH "Auth" #define WSM_PROFILE "Profile" #define WSM_CERTIFICATETHUMBPRINT "CertificateThumbprint" #define WSM_DEFAULTBOOKMARK "http://schemas.dmtf.org/wbem/wsman/1/wsman/bookmark/earliest" #define WXF_RESOURCE_CREATED "ResourceCreated" // WSMB - Binding #define WSMB_POLYMORPHISM_MODE "PolymorphismMode" #define WSMB_INCLUDE_SUBCLASS_PROP "IncludeSubClassProperties" #define WSMB_EXCLUDE_SUBCLASS_PROP "ExcludeSubClassProperties" #define WSMB_NONE "None" #define WSMB_DERIVED_REPRESENTATION "DerivedRepresentation" #define WSMB_ACTION_FAULT "http://schemas.dmtf.org/wbem/wsman/1/cimbinding/fault" #define WSMB_SHOW_EXTENSION "ShowExtensions" /* ows:ExcludeNilProperties a per-request version of cim:omit_schema_optional in openwsman.conf */ #define WSMB_EXCLUDE_NIL_PROPS "ExcludeNilProperties" // Catalog #define WSMANCAT_RESOURCE "Resource" #define WSMANCAT_RESOURCE_URI "ResourceUri" #define WSMANCAT_VERSION "Version" #define WSMANCAT_NOTES "Notes" #define WSMANCAT_VENDOR "Vendor" #define WSMANCAT_DISPLAY_NAME "DisplayName" #define WSMANCAT_KEYWORDS "Keywords" #define WSMANCAT_ACCESS "Access" #define WSMANCAT_RELATIONSHIPS "Relationsships" #define WSMANCAT_COMPLIANCE "Compliance" #define WSMANCAT_OPERATION "Operation" #define WSMANCAT_SELECTOR_SET "SelectorSet" #define WSMANCAT_SELECTOR "Selector" #define WSMANCAT_OPTION_SET "OptionSet" #define WSMANCAT_ACTION "Action" #define WSMANCAT_SELECTOR_SET_REF "SelectorSetRef" #define WSMANCAT_LOCATION "Location" #define WSMANCAT_NAME "Name" #define WSMANCAT_TYPE "Type" // Filter Dialects #define WSM_SELECTOR_FILTER_DIALECT \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/SelectorFilter" #define WSM_WQL_FILTER_DIALECT \ "http://schemas.microsoft.com/wbem/wsman/1/WQL" #define WSM_XPATH_FILTER_DIALECT \ "http://www.w3.org/TR/1999/REC-xpath-19991116" #define WSM_CQL_FILTER_DIALECT \ "http://schemas.dmtf.org/wbem/cql/1/dsp0202.pdf" #define WSM_ASSOCIATION_FILTER_DIALECT \ "http://schemas.dmtf.org/wbem/wsman/1/cimbinding/associationFilter" #define WSM_XPATH_EVENTROOT_FILTER \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/filter/eventRootXPath" #define WSFW_RESPONSE_STR "Response" #define WSFW_INDOC "indoc" #define WSFW_ENUM_PREFIX "_en." #define CIM_NAMESPACE_SELECTOR "__cimnamespace" #define CIM_ALL_AVAILABLE_CLASSES "http://schemas.dmtf.org/wbem/wscim/1/*" #define XML_NS_CIM_ALL_CLASS "http://schemas.dmtf.org/wbem/wscim/1" #define CIM_ACTION_ENUMERATE_CLASS_NAMES "EnumerateClassNames" #define CIM_ACTION_ENUMERATE_INSTANCE_NAMES "EnumerateInstanceNames" #define CIM_ACTION_ENUMERATE_CLASSES "EnumerateClasses" #define CIM_ACTION_GET_CLASS "GetClass" #define CIM_ACTION_DELETE_CLASS "DeleteClass" #define WST_ISSUEDTOKENS "IssuedTokens" #define WST_REQUESTSECURITYTOKENRESPONSE "RequestSecurityTokenResponse" #define WST_TOKENTYPE "TokenType" #define WST_REQUESTEDSECURITYTOKEN "RequestedSecurityToken" #define WSSE_USERNAMETOKEN "UsernameToken" #define WSSE_USERNAME "Username" #define WSSE_PASSWORD "Password" #define WSP_APPLIESTO "AppliesTo" #define WST_USERNAMETOKEN \ "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#UsernameToken" #define WST_CERTIFICATETHUMBPRINT \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/token/certificateThumbprint" //HTTP(S) Security profiles #define WSMAN_SECURITY_PROFILE_HTTP_BASIC \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/http/basic" #define WSMAN_SECURITY_PROFILE_HTTP_DIGEST \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/http/digest" #define WSMAN_SECURITY_PROFILE_HTTPS_BASIC \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/basic" #define WSMAN_SECURITY_PROFILE_HTTPS_DIGEST \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/digest" #define WSMAN_SECURITY_PROFILE_HTTPS_MUTUAL \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/mutual" #define WSMAN_SECURITY_PROFILE_HTTPS_MUTUAL_BASIC \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/mutual/basic" #define WSMAN_SECURITY_PROFILE_HTTPS_MUTUAL_DIGEST \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/mutual/digest" #define WSMAN_SECURITY_PROFILE_HTTPS_SPNEGO_KERBEROS \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/spnego-kerberos" #define WSMAN_SECURITY_PROFILE_HTTPS_MUTUAL_SPNEGO_KERBEROS \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/mutual/spnego-kerberos" #define WSMAN_SECURITY_PROFILE_HTTP_SPNEGO_KERBEROS \ "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/http/spnego-kerberos" #endif
/* * Copyright (C) 2018 ETH Zurich, University of Bologna * * 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 __ARCHI_FLL_FLL_V0_H__ #define __ARCHI_FLL_FLL_V0_H__ #define SOC_FLL_CONFIG_REG_1 ( ARCHI_FLL_ADDR + 0x04 ) #define SOC_FLL_CONFIG_REG_2 ( ARCHI_FLL_ADDR + 0x08 ) #define SOC_FLL_CONFIG_REG_3 ( ARCHI_FLL_ADDR + 0x0C ) #define SOC_FLL_LOCK_REG ( ARCHI_FLL_ADDR + 0x20 ) #endif
//#define ENABLE_PWM
/* Napisz program, który wczyta znak z klawiatury i wyświetli na ekranie wczytany znak oraz jego kod ASCII w postaci dziesiętnej, szesnastkowej i ósemkowej. */ #include<stdio.h> main() { char c; printf("\nPodaj znak: "); scanf("%c", &c); printf("\nZnak [%c] w kodzie ASCII to\n dziesietna: %d\n szesnastkowa: %x \n i osemkowa: %o \n", c, c, c,c ); system("PAUSE"); return 0; }
#ifndef TGDXTexture_h__ #define TGDXTexture_h__ #include "TGBaseTexture.h" #include <d3dx9.h> struct TGDXTexture : public TGBaseTexture { public: TGDXTexture(PTGBaseTextureDescriptor& descr); ~TGDXTexture(); virtual void SetTextureData32(QSize size, DWORD pitch, BYTE* data); public: IDirect3DTexture9* Texture; IDirect3DDevice9* Device; }; #endif // TGDXTexture_h__
#include <stdio.h> #include <stdlib.h> typedef node { int data; node *next; } node; node* ReverseOrderOfList(node *root); void main() { node root = malloc(sizeof(node)); node middle = malloc(sizeof(node)); node last = malloc(sizeof(node)); root->data = 1; middle->data = 2; last->data=3; root->next = middle; middle->next = last; last->next = NULL; root = ReverseOrderOfList(&root); } /* first attempt at reversing order of a single linked list, runs in O(n) linear time. */ node* ReverseOrderOfList(node *root) { node newRoot = root; while(root) { /* set new root to current * make current -> next point to previous * move on */ newRoot = root->next; newRoot->next = root; root = root->next; } return newRoot; }
// DSPIC33EV256GM102 Configuration Bit Settings // 'C' source line config statements // FSEC #pragma config BWRP = OFF // Boot Segment Write-Protect Bit (Boot Segment may be written) #pragma config BSS = DISABLED // Boot Segment Code-Protect Level bits (No Protection (other than BWRP)) #pragma config BSS2 = OFF // Boot Segment Control Bit (No Boot Segment) #pragma config GWRP = OFF // General Segment Write-Protect Bit (General Segment may be written) #pragma config GSS = DISABLED // General Segment Code-Protect Level bits (No Protection (other than GWRP)) #pragma config CWRP = OFF // Configuration Segment Write-Protect Bit (Configuration Segment may be written) #pragma config CSS = DISABLED // Configuration Segment Code-Protect Level bits (No Protection (other than CWRP)) #pragma config AIVTDIS = DISABLE // Alternate Interrupt Vector Table Disable Bit (Disable Alternate Vector Table) // FBSLIM #pragma config BSLIM = 0x1FFF // Boot Segment Code Flash Page Address Limit Bits (Enter Hexadecimal value) // FOSCSEL #pragma config FNOSC = FRCPLL // Initial oscillator Source Selection Bits (Fast RC Oscillator with divide-by-N with PLL module (FRCPLL)) #pragma config IESO = ON // Two Speed Oscillator Start-Up Bit (Start up device with FRC,then automatically switch to user selected oscillator source) // FOSC #pragma config POSCMD = HS // Primary Oscillator Mode Select Bits (HS Crystal Oscillator mode) #pragma config OSCIOFNC = OFF // OSC2 Pin I/O Function Enable Bit (OSC2 is clock output) #pragma config IOL1WAY = ON // Peripheral Pin Select Configuration Bit (Allow Only One reconfiguration) #pragma config FCKSM = CSECMD // Clock Switching Mode Bits (Clock Switching is enabled,Fail-safe Clock Monitor is disabled) #pragma config PLLKEN = ON // PLL Lock Enable Bit (Clock switch to PLL source will wait until the PLL lock signal is valid) // FWDT #pragma config WDTPOST = PS32768 // Watchdog Timer Postscaler Bits (1:32,768) #pragma config WDTPRE = PR128 // Watchdog Timer Prescaler Bit (1:128) #pragma config FWDTEN = ON // Watchdog Timer Enable Bits (WDT Enabled) #pragma config WINDIS = OFF // Watchdog Timer Window Enable Bit (Watchdog timer in Non-Window Mode) #pragma config WDTWIN = WIN25 // Watchdog Window Select Bits (WDT Window is 25% of WDT period) // FPOR #pragma config BOREN0 = ON // Brown Out Reset Detection Bit (BOR is Enabled) // FICD #pragma config ICS = PGD1 // ICD Communication Channel Select Bits (Communicate on PGEC1 and PGED1) // FDMTINTVL #pragma config DMTIVTL = 0xFFFF // Lower 16 Bits of 32 Bit DMT Window Interval (Enter Hexadecimal value) // FDMTINTVH #pragma config DMTIVTH = 0xFFFF // Upper 16 Bits of 32 Bit DMT Window Interval (Enter Hexadecimal value) // FDMTCNTL #pragma config DMTCNTL = 0xFFFF // Lower 16 Bits of 32 Bit DMT Instruction Count Time-Out Value (Enter Hexadecimal value) // FDMTCNTH #pragma config DMTCNTH = 0xFFFF // Upper 16 Bits of 32 Bit DMT Instruction Count Time-Out Value (Enter Hexadecimal value) // FDMT #pragma config DMTEN = ENABLE // Dead Man Timer Enable Bit (Dead Man Timer is Enabled and cannot be disabled by software) // FDEVOPT #pragma config PWMLOCK = ON // PWM Lock Enable Bit (Certain PWM registers may only be written after key sequence) #pragma config ALTI2C1 = OFF // Alternate I2C1 Pins Selection Bit (I2C1 mapped to SDA1/SCL1 pins) // FALTREG #pragma config CTXT1 = NONE // Interrupt Priority Level (IPL) Selection Bits For Alternate Working Register Set 1 (Not Assigned) #pragma config CTXT2 = NONE // Interrupt Priority Level (IPL) Selection Bits For Alternate Working Register Set 2 (Not Assigned) // #pragma config statements should precede project file includes. // Use project enums instead of #define for ON and OFF. #include <xc.h> #include <libpic30.h> #define FPLL 140000000 //(7.33M*76)/4 #define FCY 67802500 // Fcy = 1/2Fpll #define BAUD115200 ((FCY/115200)/16) - 1 #define DELAY_8_7uS asm volatile ("REPEAT, #605"); Nop(); //TX=PIN 11 //ADC=PIN 2 //frecuencia=PIN 15 void initAdc1(void); void Delay_us(unsigned int); int i; unsigned int signal=0; void PWM_init(void) { /* Set PWM Period on Primary Time Base */ PTPER = 1400; /* Set Phase Shift */ PHASE1 = 0; PHASE2 = 720; PHASE3 = 200; /* Set Duty Cycles */ PDC1 = 700; PDC2 = 700; PDC3 = 700; /* Set Dead Time Values */ DTR1 = DTR2 = DTR3 = 10; ALTDTR1 = ALTDTR2 = ALTDTR3 = 10; /* Set PWM Mode to Push-Pull */ IOCON1 = IOCON2 = IOCON3 = 0xC800; /* Set Primary Time Base, Edge-Aligned Mode and Independent Duty Cycles */ PWMCON1 = PWMCON2 = PWMCON3 = 0; /* Configure Faults */ FCLCON1 = FCLCON2 = FCLCON3 = 0x0003; /* 1:1 Prescaler */ PTCON2 = 0x0000; /* Enable PWM Module */ PTCON = 0x8000; } void PLL_init(void) { OSCCONbits.COSC=011; PLLFBD=74; //M=76 CLKDIVbits.PLLPOST=0; //N2=2 CLKDIVbits.PLLPRE=0; //N1=2 /* PROBAR CODIGO __builtin_write_OSCCONH(0x03); __builtin_write_OSCCONL(0x01); while (OSCCONbits.COSC != 0x3); while (_LOCK == 0); // Wait for PLL lock at 40 MIPS */ } void UART_init(void) { U2MODEbits.UARTEN = 0; // // digital output TRISBbits.TRISB4 = 0; // map MONITOR_TX pin to port RB4, which is remappable RP36 // RPOR1bits.RP36R = 0x03; // map UART2 TXD to pin RB4 // set up the UART for default baud, 1 start, 1 stop, no parity U2MODEbits.STSEL = 0; // 1-Stop bit U2MODEbits.PDSEL = 0; // No Parity, 8-Data bits U2MODEbits.ABAUD = 0; // Auto-Baud disabled U2MODEbits.BRGH = 0; // Standard-Speed mode U2BRG = BAUD115200; // Baud Rate setting for 115200 U2STAbits.UTXISEL0 = 0; // Interrupt after TX buffer done U2STAbits.UTXISEL1 = 1; IEC1bits.U2TXIE = 1; // Enable UART TX interrupt IFS1bits.U2TXIF = 0; // Clear TX2 Interrupt flag U2MODEbits.UARTEN = 1; // Enable UART (this bit must be set *BEFORE* UTXEN) U2STAbits.UTXEN = 1; DELAY_8_7uS // (1/115200) } void __attribute__((interrupt, no_auto_psv)) _U2TXInterrupt(void) { IFS1bits.U2TXIF = 0; // Clear TX2 Interrupt flag } void initAdc1(void) { // Set port configuration //ANSELA = ANSELB = 0x0000; // Ensure AN0/RA0 is analog Initialize and enable ADC module ANSELAbits.ANSA0=1; TRISAbits.TRISA0=1; AD1CON1 = 0x0000; AD1CON2 = 0x0000; AD1CON3bits.SAMC = 1; AD1CON3bits.ADCS = 0; AD1CON4 = 0x0000; AD1CHS0 = 0x0000;//selecciona AN0 AD1CHS123 = 0x0000; AD1CSSH = 0x0000; AD1CSSL = 0x0000; AD1CON1bits.ADON = 1; Delay_us(20); } void Delay_us(unsigned int delay) {for (i = 0; i < delay; i++) {__asm__ volatile ("repeat #70"); __asm__ volatile ("nop");} } void main(void) { int mil=0,cent=0,dec=0,uni=0; char tabla[10]={48,49,50,51,52,53,54,55,56,57}; PLL_init(); PWM_init(); UART_init(); initAdc1(); TRISBbits.TRISB6 = 0; while(1) { AD1CON1bits.SAMP = 1; // Start sampling Delay_us(10); // Wait for sampling time (10us) AD1CON1bits.SAMP = 0; // Start the conversion while (!AD1CON1bits.DONE); // Wait for the conversion to complete signal = ADC1BUF0; // Read the conversion result mil=signal/1000; cent=signal%1000/100; dec=(signal%100)/10; uni=(signal%100)%10; while (U2STAbits.UTXBF); U2TXREG=tabla[mil]; while (U2STAbits.UTXBF); U2TXREG=tabla[cent]; while (U2STAbits.UTXBF); U2TXREG=tabla[dec]; while (U2STAbits.UTXBF); U2TXREG=tabla[uni]; while (U2STAbits.UTXBF); //wait until TXREG is available U2TXREG = 10; if (PORTBbits.RB6 == 0){ PORTBbits.RB6 = 1;} else{ PORTBbits.RB6 = 0;} } }
#include "../h/rt.h" #include "../h/record.h" #define randval (RSCALE*(k_random=(RANDA*k_random+RANDC)&MAXLONG)) /* * ?x - produce a randomly selected element of x. */ random(nargs, arg1v, arg1, arg0) int nargs; struct descrip arg1v, arg1, arg0; { register int val, i, j; register union block *bp; long l1; double r1; char sbuf[MAXSTRING]; union block *ep; struct descrip *dp; extern char *alcstr(); SetBound; arg1v = arg1; deref(&arg1); if (NULLDESC(arg1)) runerr(113, &arg1); if (QUAL(arg1)) { /* random char in string */ if ((val = STRLEN(arg1)) <= 0) fail(); hneed(sizeof(struct b_tvsubs)); mksubs(&arg1v, &arg1, (int)(randval*val)+1, 1, &arg0); ClearBound; return; } switch (TYPE(arg1)) { case T_CSET: cvstr(&arg1, sbuf); if ((val = STRLEN(arg1)) <= 0) fail(); sneed(1); STRLEN(arg0) = 1; STRLOC(arg0) = alcstr(STRLOC(arg1)+(int)(randval*val), 1); ClearBound; return; case T_REAL: r1 = BLKLOC(arg1)->realval; if (r1 < 0 || r1 > MAXSHORT) runerr(205, &arg1); val = (int)r1; goto getrand; case T_INTEGER: val = INTVAL(arg1); if (val < 0) runerr(205, &arg1); getrand: if (val == 0) /* return real in range [0,1) */ mkreal(randval, &arg0); else /* return integer in range [1,val] */ mkint((long)(randval*val) + 1, &arg0); ClearBound; return; #ifndef BIT32 case T_LONGINT: runerr(205, &arg1); #endif case T_LIST: bp = BLKLOC(arg1); val = bp->list.cursize; if (val <= 0) fail(); i = (int)(randval*val) + 1; j = 1; bp = BLKLOC(BLKLOC(arg1)->list.listhead); while (i >= j + bp->listb.nused) { j += bp->listb.nused; if (TYPE(bp->listb.listnext) != T_LISTB) syserr("list reference out of bounds in random"); bp = BLKLOC(bp->listb.listnext); } i += bp->listb.first - j; if (i >= bp->listb.nelem) i -= bp->listb.nelem; dp = &bp->listb.lelem[i]; arg0.type = D_VAR + ((int *)dp - (int *)bp); BLKLOC(arg0) = dp; ClearBound; return; case T_TABLE: bp = BLKLOC(arg1); val = bp->table.cursize; if (val <= 0) fail(); i = (int)(randval*val) + 1; for (j = 0; j < NBUCKETS; j++) { for (ep = BLKLOC(bp->table.buckets[j]); ep != NULL; ep = BLKLOC(ep->telem.blink)) { if (--i <= 0) { dp = &ep->telem.tval; arg0.type = D_VAR + ((int *)dp - (int *)bp); BLKLOC(arg0) = dp; ClearBound; return; } } } case T_RECORD: bp = BLKLOC(arg1); val = bp->record.recptr->nfields; if (val <= 0) fail(); dp = &bp->record.fields[(int)(randval*val)]; arg0.type = D_VAR + ((int *)dp - (int *)bp); BLKLOC(arg0) = dp; ClearBound; return; default: runerr(113, &arg1); } } struct b_iproc Brandom = { T_PROC, sizeof(struct b_proc), EntryPoint(random), 2, -1, -1, 0, {1, "?"} };
int multiply(int a, int b) //Умножение { int result; result = a * b; return result; }
#define _OZ000100000200045dP_H_ #define OZClassPart0001000002fffffd_0_in_000100000200045c 1 #define OZClassPart0001000002fffffe_0_in_000100000200045c 1 #define OZClassPart000100000200045c_0_in_000100000200045c 0 #define OZClassPart0000000000000000_0_in_0000000000000000 999 typedef struct OZ000100000200045dPart_Rec { OZ_AllocateInfoRec alloc_info; /* protected (pointer) */ OZ_Object ozaCollection; int pad0; /* protected (data) */ int ozIndex; unsigned int ozNum; /* protected (zero) */ } OZ000100000200045dPart_Rec, *OZ000100000200045dPart; #ifdef OZ_ObjectPart_Iterator_Assoc_0_0__ #undef OZ_ObjectPart_Iterator_Assoc_0_0__ #endif #define OZ_ObjectPart_Iterator_Assoc_0_0__ OZ000100000200045dPart #endif _OZ000100000200045dP_H_
#include "..\inc\cfg_items.h" //Конфигурация #ifdef NEWSGOLD #define DEFAULT_DISK "4" #else #define DEFAULT_DISK "0" #endif __root const CFG_HDR cfghdr0={CFG_UINT,"UIN",0,0xFFFFFFFF}; __root const unsigned int UIN=0; __root const CFG_HDR cfghdr1={CFG_STR_PASS,"Password",0,8}; __root const char PASS[9]=""; //Network settings __root const CFG_HDR cfghdr2={CFG_LEVEL,"Hosts and paths",1,0}; __root const CFG_HDR cfghdr2_1={CFG_STR_WIN1251,"Host",0,127}; __root const char NATICQ_HOST[128]="ig.boba.su;ig1.boba.su;ig2.boba.su;ig3.boba.su;ig4.boba.su;ig5.boba.su"; __root const CFG_HDR cfghdr2_2={CFG_UINT,"Default port",0,65535}; __root const unsigned int NATICQ_PORT=5050; __root const CFG_HDR cfghdr2_3={CFG_UINT,"Reconnect timeout",0,65535}; __root const unsigned int RECONNECT_TIME=10; __root const CFG_HDR cfghdr2_4={CFG_STR_UTF8,"History path",0,63}; __root const char HIST_PATH[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\history\\"; __root const CFG_HDR cfghdr2_5={CFG_STR_UTF8,"Smiles File",0,63}; __root const char SMILE_FILE[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\smiles.cfg"; __root const CFG_HDR cfghdr2_6={CFG_STR_UTF8,"Smiles .png path",0,63}; __root const char SMILE_PATH[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\smiles\\"; __root const CFG_HDR cfghdr2_7={CFG_STR_UTF8,"Images .png path",0,63}; __root const char ICON_PATH[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\img\\"; __root const CFG_HDR cfghdr2_8={CFG_STR_UTF8,"XStatus .png path",0,63}; __root const char XSTATUSES_PATH[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\ximg\\"; __root const CFG_HDR cfghdr2_9={CFG_STR_UTF8,"Templates path",0,63}; __root const char TEMPLATES_PATH[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\templates\\"; #ifdef NEWSGOLD __root const CFG_HDR cfghdr2_9_1={CFG_UINT,"First status icon",0,10000}; __root const unsigned int ST_FIRST=8000; __root const CFG_HDR cfghdr2_9_2={CFG_UINT,"First xstatus icon",0,10000}; __root const unsigned int X_FIRST=8100; #endif __root const CFG_HDR cfghdr3={CFG_LEVEL,"",0,0}; //View settings __root const CFG_HDR cfghdr4={CFG_LEVEL,"Interface",1,0}; //Status icon on mainscreen position #ifdef NEWSGOLD __root const CFG_HDR cfghdr4_0={CFG_CBOX,"Show icon on",0,4}; __root const unsigned int ICON_ON = 1; __root const CFG_CBOX_ITEM cfgcbox4_0_1[4]={"None","IDLE","Iconbar","Everywhere"}; __root const CFG_HDR cfghdr4_0_2={CFG_CHECKBOX,"XStatus in iconbar",0,1}; __root const unsigned int XST_IC = 0; #endif __root const CFG_HDR cfghdr4_1={CFG_COORDINATES,"Idle icon position",0,0}; __root const unsigned int IDLEICON_X=0; __root const unsigned int IDLEICON_Y=50; //Popup chat __root const CFG_HDR cfghdr4_2={CFG_CBOX,"Popup",0,3}; __root const int DEVELOP_IF = 0; __root const CFG_CBOX_ITEM cfgcbox4_2[3]={"Allways", "If Kbd Unlock","Never"}; //Strong away __root const CFG_HDR cfghdr4_3={CFG_CBOX,"Notify when occupied",0,2}; __root const int STRONG_AWAY = 0; __root const CFG_CBOX_ITEM cfgcbox4_3[2]={"Notify", "Don't notify"}; //Sorting __root const CFG_HDR cfghdr4_4={CFG_CBOX,"Sort CList",0,2}; __root const int SORT_CLIST = 0; __root const CFG_CBOX_ITEM cfgcbox4_4[2]={"By Name","By Status"}; //First letter when typing __root const CFG_HDR cfghdr4_5={CFG_CBOX,"First letter",0,2}; __root const int FIRST_LETTER = 0; __root const CFG_CBOX_ITEM cfgcbox4_5[2]={"Small","Big"}; // tridog, 01.05.2009 // Опциональное отобрадение контакта loopbak __root const CFG_HDR cfghdr4_6={CFG_CHECKBOX,"Show loopback",0,2}; __root const int b_loopback=1; // //Twitch - счетчик непрочитанных для каждого контакта в кл __root const CFG_HDR cfghdr4_13={CFG_CHECKBOX,"Count messages in CL",0,2}; __root const int cl_unreaded_cnt=1; //Fonts and colors __root const CFG_HDR cfghdr4_7={CFG_LEVEL,"Font and colors",1,0}; __root const CFG_HDR cfghdr4_7_1={CFG_UINT,"My string color",0,1000}; __root const unsigned int I_COLOR=3; __root const CFG_HDR cfghdr4_7_2={CFG_UINT,"Your string color",0,1000}; __root const unsigned int TO_COLOR=2; __root const CFG_HDR cfghdr4_7_3={CFG_UINT,"XStatus color",0,1000}; __root const unsigned int X_COLOR=2; __root const CFG_HDR cfghdr4_7_4={CFG_UINT,"Main font size",0,6}; __root const unsigned int ED_FONT_SIZE=1; __root const CFG_HDR cfghdr4_7_5={CFG_UINT,"Header font size",0,6}; __root const unsigned int ED_H_FONT_SIZE=2; __root const CFG_HDR cfghdr4_7_6={CFG_UINT,"XStatus font size",0,6}; __root const unsigned int ED_X_FONT_SIZE=1; __root const CFG_HDR cfghdr4_7_7={CFG_UINT,"My old string color",0,1000}; __root const unsigned int O_I_COLOR=15; __root const CFG_HDR cfghdr4_7_8={CFG_UINT,"Your old string color",0,1000}; __root const unsigned int O_TO_COLOR=14; __root const CFG_HDR cfghdr4_7_9={CFG_UINT,"XStatus old color",0,1000}; __root const unsigned int O_X_COLOR=14; __root const CFG_HDR cfghdr4_7_10={CFG_UINT,"Main old font size",0,6}; __root const unsigned int O_ED_FONT_SIZE=1; __root const CFG_HDR cfghdr4_7_11={CFG_UINT,"Header old font size",0,6}; __root const unsigned int O_ED_H_FONT_SIZE=2; __root const CFG_HDR cfghdr4_7_12={CFG_UINT,"XStatus old font size",0,6}; __root const unsigned int O_ED_X_FONT_SIZE=1; __root const CFG_HDR cfghdr4_7_13={CFG_UINT,"Acked color",0,1000}; __root const unsigned int ACK_COLOR=4; __root const CFG_HDR cfghdr4_7_14={CFG_UINT,"Unacked color",0,1000}; __root const unsigned int UNACK_COLOR=20; __root const CFG_HDR cfghdr4_8={CFG_LEVEL,"",0,0}; //Illumination by BoBa 19.04.2007 __root const CFG_HDR cfghdr4_9={CFG_LEVEL,"Illumination setup",1,0}; __root const CFG_HDR cfghdr4_9_1={CFG_INT,"Display on Recv",0,100}; __root const unsigned int ILL_DISP_RECV=10; __root const CFG_HDR cfghdr4_9_2={CFG_INT,"Keys on Recv",0,100}; __root const unsigned int ILL_KEYS_RECV=10; __root const CFG_HDR cfghdr4_9_3={CFG_INT,"Timeout on Recv",0,60}; __root const unsigned int ILL_RECV_TMR=10; __root const CFG_HDR cfghdr4_9_4={CFG_INT,"Fade on Recv",0,1000}; __root const unsigned int ILL_RECV_FADE=256; __root const CFG_HDR cfghdr4_9_5={CFG_INT,"Display on Send",0,100}; __root const unsigned int ILL_DISP_SEND=10; __root const CFG_HDR cfghdr4_9_6={CFG_INT,"Keys on Send",0,100}; __root const unsigned int ILL_KEYS_SEND=0; __root const CFG_HDR cfghdr4_9_7={CFG_INT,"Timeout on Send",0,60}; __root const unsigned int ILL_SEND_TMR=5; __root const CFG_HDR cfghdr4_9_8={CFG_INT,"Fade on Send",0,1000}; __root const unsigned int ILL_SEND_FADE=256; __root const CFG_HDR cfghdr4_9_9={CFG_INT,"Fade on Off",0,1000}; __root const unsigned int ILL_OFF_FADE=256; __root const CFG_HDR cfghdr4_10={CFG_LEVEL,"",0,0}; // tridog, 18 april 2009 // Делаем многопрофильность __root const CFG_HDR cfghdr4_11={CFG_LEVEL,"Name in X-Task",1,0}; // Выводить ли иконку непрочитанных сообщений __root const CFG_HDR cfghdr4_11_1={CFG_CHECKBOX,"Icon on unread message",0,2}; __root const int b__task_unread_icon=1; // Выводить ли количество непрочитанных сообщений __root const CFG_HDR cfghdr4_11_2={CFG_CHECKBOX,"Count unreaded messages",0,2}; __root const int b__task_unread_count=0; // UIN/Profile name __root const CFG_HDR cfghdr4_11_3={CFG_CBOX,"Show in X-Task",0,2}; __root const int task_show = 0; __root const CFG_CBOX_ITEM cfgcbox4_11_3[2]={"UIN", "Profile"}; __root const CFG_HDR cfghdr4_12={CFG_LEVEL,"",0,0}; // __root const CFG_HDR cfghdr5={CFG_LEVEL,"",0,0}; //History __root const CFG_HDR cfghdr6={CFG_LEVEL,"History",1,0}; //Enable history logging __root const CFG_HDR cfghdr6_1={CFG_CBOX,"Enable logs",0,2}; __root const int LOG_ALL = 1; __root const CFG_CBOX_ITEM cfgcbox6_1[2]={"No","Yes"}; //History type __root const CFG_HDR cfghdr6_2={CFG_CBOX,"History for",0,2}; __root const int HISTORY_TYPE = 0; __root const CFG_CBOX_ITEM cfgcbox6_2[2]={"All","Everyone"}; //Enable status logging __root const CFG_HDR cfghdr6_3={CFG_CBOX,"Log status changes",0,2}; __root const int LOG_STATCH = 0; __root const CFG_CBOX_ITEM cfgcbox6_3[2]={"No","Yes"}; //Enable X-status logging __root const CFG_HDR cfghdr6_4={CFG_CBOX,"Log X-Text",0,2}; __root const int LOG_XTXT = 1; __root const CFG_CBOX_ITEM cfgcbox6_4[2]={"No","Yes"}; //Auto request X-status if entering to chat __root const CFG_HDR cfghdr6_5={CFG_CBOX,"Auto Request XText",0,2}; __root const int ENA_AUTO_XTXT = 1; __root const CFG_CBOX_ITEM cfgcbox6_5[2]={"No","Yes"}; //Don't log X-status, if it same as prevision __root const CFG_HDR cfghdr6_6={CFG_CBOX,"Not log same XText",0,2}; __root const int NOT_LOG_SAME_XTXT = 1; __root const CFG_CBOX_ITEM cfgcbox6_6[2]={"No","Yes"}; //Buffer for fill from history __root const CFG_HDR cfghdr6_7={CFG_CBOX,"History read buffer",0,6}; __root const int HISTORY_BUFFER = 3; __root const CFG_CBOX_ITEM cfgcbox6_7[6]={"Disabled","128 bytes","256 bytes","512 bytes","1 kbyte","2 kbyte"}; __root const CFG_HDR cfghdr7={CFG_LEVEL,"",0,0}; //Notify __root const CFG_HDR cfghdr8={CFG_LEVEL,"Notify power",1,0}; __root const CFG_HDR cfghdr8_1={CFG_UINT,"Sound Volume",0,6}; __root const unsigned int sndVolume=3; __root const CFG_HDR cfghdr8_2={CFG_UINT,"Vibra power",0,100}; __root const unsigned int vibraPower=100; __root const CFG_HDR cfghdr8_3={CFG_CBOX,"Vibration type",0,2}; __root const int VIBR_TYPE = 0; __root const CFG_CBOX_ITEM cfgcbox8_3[2]={"Single","Double"}; __root const CFG_HDR cfghdr8_4={CFG_CBOX,"Vibra on connect",0,2}; __root const int VIBR_ON_CONNECT = 0; __root const CFG_CBOX_ITEM cfgcbox8_4[2]={"No","Yes"}; #ifdef ELKA __root const CFG_HDR cfghdr8_7={CFG_CBOX,"Blink SLI",0,4}; __root const int SLI_State = 0; __root const CFG_CBOX_ITEM cfgcbox8_7[4]={"No","Shine","Blink slow","Blink fast"}; #endif __root const CFG_HDR cfghdr8_5={CFG_LEVEL,"Sounds setup",1,0}; __root const CFG_HDR cfghdr8_5_1={CFG_STR_UTF8,"snd Startup",0,63}; __root const char sndStartup[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\Sounds\\sndStartup.wav"; __root const CFG_HDR cfghdr8_5_2={CFG_STR_UTF8,"snd SrvMsg",0,63}; __root const char sndSrvMsg[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\Sounds\\sndSrvMsg.wav"; __root const CFG_HDR cfghdr8_5_3={CFG_STR_UTF8,"snd Global",0,63}; __root const char sndGlobal[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\Sounds\\sndGlobal.wav"; __root const CFG_HDR cfghdr8_5_4={CFG_STR_UTF8,"snd Msg",0,63}; __root const char sndMsg[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\Sounds\\sndMsg.wav"; __root const CFG_HDR cfghdr8_5_5={CFG_STR_UTF8,"snd MsgSent",0,63}; __root const char sndMsgSent[64]=DEFAULT_DISK ":\\ZBin\\NatICQ\\Sounds\\sndMsgSent.wav"; __root const CFG_HDR cfghdr8_6={CFG_LEVEL,"",0,0}; __root const CFG_HDR cfghdr9={CFG_LEVEL,"",0,0}; // <tridog/> // 2.01.2011. Автостатус. __root const CFG_HDR cfghdr10={CFG_LEVEL,"Autostatus",1,0}; __root const CFG_HDR cfghdr10_1={CFG_LEVEL,"Autostatus on idle",1,0}; __root const CFG_HDR cfghdr10_1_3={CFG_CBOX, "Set status", 0, 5}; // Статус, который будет установлен после истечения таймаута __root const int AUTOSTATUS_IDLE_STATUS = 0; __root const CFG_CBOX_ITEM cfgcbox10_1[5]={"None","Away","Not available","Occupied","Do not disturb"}; __root const CFG_HDR cfghdr10_1_2={CFG_UINT,"Time (minutes)",1,60}; // Таймаут включения (в минутах) __root const unsigned int AUTOSTATUS_IDLE_TIME = 5; __root const CFG_HDR cfghdr10_2={CFG_LEVEL,"",0,0}; #ifdef NEWSGOLD __root const CFG_HDR cfghdr10_3={CFG_LEVEL,"Autostatus on headset pluging",1,0}; __root const CFG_HDR cfghdr10_3_2={CFG_CBOX, "Set status", 0, 5}; // Статус, который будет установлен при подключении гарнитуры __root const int AUTOSTATUS_HEADSET_STATUS = 0; __root const CFG_CBOX_ITEM cfgcbox10_3[5]={"None","Away","Not available","Occupied","Do not disturb"}; __root const CFG_HDR cfghdr10_4={CFG_LEVEL,"",0,0}; #endif __root const CFG_HDR cfghdr11={CFG_LEVEL,"",0,0}; // </tridog>
#include <std.h> inherit OBJECT; string type; void set_type(string str); string query_type(); string check_skills(); void init() { add_action("eat", "eat"); } void create() { ::create(); set_short("A strange herb"); set_name("herb"); set_long((: check_skills :)); set_weight(2); set_value(0); set_id(({ "forage_herb_ob", "herb", "plant" })); set_property("brewable", 1); } void set_type(string str) { type = str; set_id(({ "herb", "plant", str })); } string query_type() { return type; } string check_skills() { int skil; if(this_player()->query_subclass() != "ranger") return "It's a funny looking plant.\n"; skil = this_player()->query_skill("nature"); if(skil < 10) return "It's a funny looking plant.\n"; if(skil < 20) if(type != "poison") return "It's a good plant for brewing.\n"; else return "It would be dangerous to brew with this plant.\n"; return "It appears to be a herb of "+type+".\n"; } int eat(string str) { if(!id(str)) return 0; if(this_player()->query_current_attacker()) { notify_fail("You are too busy to eat anything!\n"); return 0; } write("You chew on the bitter herb."); say(this_player()->query_cap_name()+" chews on an herb and grimaces at the taste."); if(type == "poison") { this_player()->add_poisoning(20); write("You begin to feel nausious."); remove(); return 1; } if(type == "healing") { this_player()->add_hp(20); remove(); return 1; } if(type == "antidote") { this_player()->add_poisoning(-20); remove(); return 1; } }
#include "key.h" #define KEY_PRESS_RELEASE_CHECK_COUNT 1000 void Key_Poll_Init(void) { Macro_Set_Bit(rRCC_APB2ENR,2); Macro_Write_Block(rGPIOA_CRH,0xfff,0x444,20); } void Key_EXTI_Init(void) { Macro_Set_Bit(rRCC_APB2ENR,2); // PortA clk enable Macro_Set_Bit(rRCC_APB2ENR,0); // Alternate function IO clock enable Macro_Write_Block(rGPIOA_CRH,0xfff,0x444,20); // GPA15_13 configuration (input floating) rEXTI_PR = (0x7<<13); // GPA15_13 pending clear rNVIC_ICPR1 = 1<<8; // IRQ pendign clear Macro_Set_Bit(rNVIC_ISER1,8); // IRQ40 INT enable Macro_Write_Block(rAFIO_EXTICR4,0xfff,0x000,4); // GPA15_13 select Macro_Write_Block(rEXTI_IMR,0x7,0x7,13); // EXT15_13 intr unmask Macro_Write_Block(rEXTI_FTSR,0x7,0x7,13); // Falling edge } U32 Key_Get_Pressed(void) { U32 j, key, old_key = 0; U32 count = 0; for(j = 0 ; j < 3000 ; j++) { key = 0; switch((Macro_Extract_Area(rGPIOA_IDR,0x7,13))) { case 0x6 : key = 1; goto EXIT; case 0x5 : key = 4; goto EXIT; case 0x3 : key = 2; goto EXIT; } EXIT: if(old_key == key) { count++; } else { old_key = key; count = 0; } if(count >= KEY_PRESS_RELEASE_CHECK_COUNT) return key; } return 0; } void Key_Wait_Key_Released(void) { while(Key_Get_Pressed()); } U32 Key_Wait_Key_Pressed(void) { U32 k; do { k = Key_Get_Pressed(); }while(!k); return k; }
#ifndef _QUERY_H_ #define _QUERY_H_ // DATA STRUCTURE /* Since WORDNODEs and DOCUMENTNODEs have exactly what is needed for ranking the urls, the QHOLDER is a structure that holds WORDNODES for only the words from the query, and they point to DOCUMENTNODES for each word The list of DOCUMENTNODES is the results list of the URLs from the query if the two words are 'OR'ed, add every node to this list from both WORDNODES and add freq if there it is not a unique docID It the words are 'AND'ed together, find only the docs that overlap and add only those to the result list. */ typedef struct _QHOLDER { WORDNODE *start; WORDNODE *end; DOCUMENTNODE *results; // will be the list of docIDs for the query } _QHOLDER; typedef struct _QHOLDER QHOLDER; // FUNCTIONS /* function to make query all lowercase. Loops through all chars in the user input string and switch them to lowercase */ void makeLower(char *str); /* Starts at index->start, and runs through wordnodes until word is found. If if doesn't find the word, flag = 0. If it is found, flag = 1. Returns */ WORDNODE *searchIndex(int *flag, char *str, INVERTED_INDEX *index); /* Takes the int doc_id and makes it a string Open file with the doc_id name Extract first line (which should be the url) Returnt the url */ char *getURL(int doc_id, char *target_dir); // initializes the new index void initializeQHOLDER(void); // adds a wordnode to the qholder for each word form the query // that is in the index // it adds the next WORDNODE to the end of the qholder each time void addWORDNODE(WORDNODE *wn); /* Parses user input into seperate words to account for multiple word searches */ int getNextWord(const char* input, int currentPosition, char **wordList, int i); WORDNODE *searchQHOLDER(int *flag1, char *word); /* - wordnodes should be in qholder - First looks for an OR in the list - if there is an or - add DOCNODES from each wordnode to results - if there is overlap with DOCNODES, just add frequencies together - for the second worded - start at beginning of list - if encounter an OR, add 2 to i - add when there are still at least two words left not including ORs - add DNODES only if they overlap returns 0 if is not completed */ int rankWords(char **wordList, int listSize); /* - add DOCNODES from each wordnode to results - if there is overlap with DOCNODES, just add frequencies together - for the second worded */ void ORrank(WORDNODE *c1, WORDNODE *c2); /* - if encounter an OR, add 2 to i - add when there are still at least two words left not including ORs - add DNODES only if they overlap */ void ANDrank(WORDNODE *c1, WORDNODE *c2); /* Goes through DOCUMENTNODES and prints out the docid and the corresponding URLs */ void printDOCs(char *target_dir); /* recursively goes through list of DOCUMENTNODES and if there is no overlap among the DOCUMENTNODES, it returns 0 */ int sortList(); #endif
/* * led.c * * Created on: 31 ago. 2020 * Author: MAGT */ #include "../headers/led.h" /******************************************************************************* * GLOBAL VARIABLES WITH LOCAL SCOPE ******************************************************************************/ static led_t LEDS[16]; static uint8_t INITIALIZED_LEDS[16]; static uint8_t LED_TIMERS[16]; static uint8_t timer_id; static uint32_t led_timer; static uint8_t init; /******************************************************************************* * FUNCTION PROTOTYPES WITH LOCAL SCOPE ******************************************************************************/ /** * @brief Get normalized state of a LED, where the normalized state 1 indicates the LED in ON * and the normalized state 0 indicates the LED is OFF. * @param state the electrical state of the pin * @param pin_mode whether the led is turned on with 1 or 0 */ bool get_normalized_state(bool state, uint8_t pin_mode); bool unnormalize_state(bool norm_state, uint8_t pin_mode); static void timer_callback(void); /******************************************************************************* * FUNCTION DEFINITIONS WITH LOCAL SCOPE ******************************************************************************/ bool get_normalized_state(bool state, uint8_t pin_mode){ if(pin_mode == TURNS_ON_WITH_0){ state = !state; } return state; } bool unnormalize_state(bool norm_state, uint8_t pin_mode){ if(pin_mode == TURNS_ON_WITH_0){ norm_state = !norm_state; } return norm_state; } void timer_callback(void){ led_timer++; } /******************************************************************************* * FUNCTION DEFINITIONS WITH GLOBAL SCOPE ******************************************************************************/ void led_init_driver(void){ if(!init){ init = 1; //me aseguro que no se haya inicializado ya pwm_init_driver(); //inicializo dependencias timerInit(); timer_id = timerGetId(); //genero una base de tiempo if(timer_id != TIMER_INVALID_ID){ timerStart(timer_id, (uint32_t)TIMER_MS2TICKS(LED_TIMEBASE), TIM_MODE_PERIODIC, timer_callback); } } } int8_t led_init_led(pin_t pin, uint8_t pin_mode){ int8_t id = led_get_id(); int8_t pwm_id; if(id != UNAVAILABLE_SPACE){ //valores iniciales importantes LEDS[id].brightness = 100; LEDS[id].dt = 50; LEDS[id].led_id = id; LEDS[id].led_pin = pin; LEDS[id].led_pin_mode = pin_mode; pwm_id = pwm_init_signal(pin); //genero una pwm para el led if(pwm_id != UNAVAILABLE_SPACE){ LEDS[id].pwm_id = pwm_id; } else{ id = UNAVAILABLE_SPACE; } } else{ id = UNAVAILABLE_SPACE; } return id; } void led_destroy_led(int8_t led_id){ #if (DEVELOPMENT_MODEE == 1) if(led_id < MAX_LEDS){ INITIALIZED_LEDS[led_id] = 0; //libero espacio pwm_destroy(LEDS[led_id].pwm_id); //destruyo dependencias } #else INITIALIZED_LEDS[led_id] = 0; pwm_destroy(LEDS[led_id].pwm_id); #endif } int8_t led_get_id(void){ uint8_t i; uint8_t found_space = 0; int8_t id = -1; for(i = 0; i < MAX_LEDS; i++){ //me fijo si hay espacio if( !(INITIALIZED_LEDS[i]) ){ INITIALIZED_LEDS[i] = 1; found_space = 1; break; } } if(found_space){ id = i; } else{ id = -1; } return id; } void led_configure_brightness(int8_t led_id, uint8_t brightness){ #if (DEVELOPMENT_MODEE == 1) if(led_id >= 0 && led_id < MAX_LEDS){ if(INITIALIZED_LEDS[led_id]){ if(brightness >= 0 && brightness <= 100){ LEDS[led_id].brightness = brightness; } } } #else LEDS[led_id].brightness = brightness; #endif } void led_configure_time(int8_t led_id, uint32_t time){ #if (DEVELOPMENT_MODEE == 1) if(led_id >= 0 && led_id < MAX_LEDS){ if(INITIALIZED_LEDS[led_id]){ LEDS[led_id].time = time; } } #else LEDS[led_id].time = time; #endif } void led_configure_period(int8_t led_id, uint32_t period){ #if (DEVELOPMENT_MODEE == 1) if(led_id >= 0 && led_id < MAX_LEDS){ if(INITIALIZED_LEDS[led_id]){ LEDS[led_id].period = period; } } #else LEDS[led_id].period = period; #endif } void led_configure_flashes(int8_t led_id, uint32_t flashes){ #if (DEVELOPMENT_MODEE == 1) if(led_id >= 0 && led_id < MAX_LEDS){ if(INITIALIZED_LEDS[led_id]){ LEDS[led_id].flashes = flashes; } } #else LEDS[led_id].flashes = flashes; #endif } void led_configure_fade(int8_t led_id, uint32_t fade){ #if (DEVELOPMENT_MODEE == 1) if(led_id >= 0 && led_id < MAX_LEDS){ if(INITIALIZED_LEDS[led_id]){ LEDS[led_id].fade = fade; } } #else LEDS[led_id].fade = fade; #endif } void led_configure_dt(int8_t led_id, uint8_t dt){ #if (DEVELOPMENT_MODEE == 1) if(led_id >= 0 && led_id < MAX_LEDS){ if(INITIALIZED_LEDS[led_id]){ LEDS[led_id].dt = dt; } } #else LEDS[led_id].dt = dt; #endif } void led_set_state(int8_t led_id, uint8_t norm_state){ #if (DEVELOPMENT_MODEE == 1) if(led_id >= 0 && led_id < MAX_LEDS){ if(INITIALIZED_LEDS[led_id]){ //si esta inicializado el led if(norm_state){ pwm_query(LEDS[led_id].pwm_id, PWM_FREQ, LEDS[led_id].brightness, HIGH); //si me piden prender el led, activo la pwm } else{ pwm_unquery(LEDS[led_id].pwm_id, unnormalize_state(LOW, LEDS[led_id].led_pin_mode)); //si me piden apagar, desactivo la pwm } LEDS[led_id].state = norm_state; //guardo el estao if(LEDS[led_id].time){ LEDS[led_id].time_start = led_timer; //si time != 0 entonces guardo cuando empieza a contar LED_TIMERS[led_id] = 1; } } } #else if(norm_state){ pwm_query(LEDS[led_id].pwm_id, PWM_FREQ, LEDS[led_id].brightness, HIGH); } else{ pwm_unquery(LEDS[led_id].pwm_id, unnormalize_state(LOW, LEDS[led_id].led_pin_mode)); } LEDS[led_id].state = norm_state; if(LEDS[led_id].time){ LEDS[led_id].time_start = led_timer; //si time != 0 entonces guardo cuando empieza a contar LED_TIMERS[led_id] = 1; } #endif } void led_flash(int8_t led_id){ uint8_t cur_norm_state; #if (DEVELOPMENT_MODEE == 1) if(led_id >= 0 && led_id < MAX_LEDS){ if(INITIALIZED_LEDS[led_id]){ LEDS[led_id].curr_flashes = 0; //reset contador de flashes LEDS[led_id].flashing = 1; //levanto flag de flash LEDS[led_id].time_start = led_timer; LED_TIMERS[led_id] = 1; pwm_query(LEDS[led_id].pwm_id, PWM_FREQ, LEDS[led_id].brightness, HIGH); //inicio la pwm LEDS[led_id].state = HIGH; LEDS[led_id].curr_flashes += 1; //y ya registro el primer flash } } #else LEDS[led_id].curr_flashes = 0; LEDS[led_id].flashing = 1; LEDS[led_id].time_start = led_timer; LED_TIMERS[led_id] = 1; cur_norm_state = get_normalized_state(gpioRead(LEDS[led_id].led_pin), LEDS[led_id].led_pin_mode); if(!cur_norm_state){ pwm_query(LEDS[led_id].pwm_id, PWM_FREQ, LEDS[led_id].brightness, HIGH); } else{ pwm_unquery(LEDS[led_id].pwm_id, unnormalize_state(LOW, LEDS[led_id].led_pin_mode)); } LEDS[led_id].state = !cur_norm_state; LEDS[led_id].curr_flashes += 1; #endif } void led_poll(void){ uint8_t i; uint8_t cur_norm_state; for(i = 0; i<MAX_LEDS; i++){ //De todos los leds if(INITIALIZED_LEDS[i]){ //si alguno esta inicializado if(LED_TIMERS[i]){ //si alguno esta esperando if(LEDS[i].flashing){ //si esta en modo flash if(LEDS[i].state == HIGH){ //si esta prendido if( (float)(led_timer) - (float)(LEDS[i].time_start) > (((float)((((float)LEDS[i].period))*(((float)(100-LEDS[i].dt))/100.0)))/((float)LED_TIMEBASE))){ pwm_unquery(LEDS[i].pwm_id, unnormalize_state(LOW, LEDS[i].led_pin_mode)); //si ya paso el tiempo, apago la pwm LEDS[i].state = LOW; LEDS[i].time_start = led_timer; //vuelvo a tomar el tiempo } } else{ //si esta apagado if( (float)(led_timer) - (float)(LEDS[i].time_start) > (((float)((((float)LEDS[i].period))*(((float)(LEDS[i].dt))/100.0)))/((float)LED_TIMEBASE))){ if(LEDS[i].flashes - LEDS[i].curr_flashes > 0){ //si aun debo hacer mas flashes pwm_query(LEDS[i].pwm_id, PWM_FREQ, LEDS[i].brightness, HIGH); //si ya paso el tiempo, activo la pwm LEDS[i].state = HIGH; LEDS[i].time_start = led_timer; //vuelvo a tomar el tiempo LEDS[i].curr_flashes += 1; //registro otro flash } else{ LED_TIMERS[i] = 0; //si ya no me quedan mas flashes, registro que el led ya no esta esperando para prenderse/apagarse } } } } else{ //si no esta en modo flash if(((float)(led_timer)) - ((float)(LEDS[i].time_start)) > (((float)(LEDS[i].time))/((float)(LED_TIMEBASE)))){ //si ya paso el tiempo cur_norm_state = get_normalized_state(gpioRead(LEDS[i].led_pin), LEDS[i].led_pin_mode); if(!cur_norm_state){ pwm_query(LEDS[i].pwm_id, PWM_FREQ, LEDS[i].brightness, HIGH); //si lo que habia hecho era apagarlo, lo vuelvo a prender un tiempo @time despues } else{ pwm_unquery(LEDS[i].pwm_id, unnormalize_state(LOW, LEDS[i].led_pin_mode)); //idem si lo que habia hecho fue prenderlo } LEDS[i].state = !cur_norm_state; LED_TIMERS[i] = 0; //y marco que ya no debe cambiar con el tiempo } } } } } }
// The MIT License (MIT) // // Copyright (c) 2019-2021 A. Orlenko // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <lauxlib.h> #include <lua.h> #include "compat-5.3.h" size_t MLUA_WRAPPED_ERROR_SIZE = 0; size_t MLUA_WRAPPED_PANIC_SIZE = 0; const void *MLUA_WRAPPED_ERROR_KEY = NULL; const void *MLUA_WRAPPED_PANIC_KEY = NULL; extern void wrapped_error_traceback(lua_State *L, int error_idx, int traceback_idx); extern int mlua_hook_proc(lua_State *L, lua_Debug *ar); #define max(a, b) (a > b ? a : b) // I believe luaL_traceback < 5.4 requires this much free stack to not error. // 5.4 uses luaL_Buffer const int LUA_TRACEBACK_STACK = 11; typedef struct { const char *data; size_t len; } StringArg; static void handle_wrapped_error(lua_State *L) { if (lua_checkstack(L, LUA_TRACEBACK_STACK) != 0) { luaL_traceback(L, L, NULL, 0); // Convert to CallbackError and attach traceback wrapped_error_traceback(L, -2, -1); lua_pop(L, 1); } else { // Convert to CallbackError with error message as a traceback wrapped_error_traceback(L, -1, 0); } } // A wrapper around Rust function to protect from triggering longjmp in Rust. // Rust callback expected to return positive number of output values or // -1 in case of error, -2 in case of panic. static int lua_call_rust(lua_State *L) { int nargs = lua_gettop(L); // We need one extra stack space to store preallocated memory, and at least 2 // stack spaces overall for handling error metatables in rust fn int extra_stack = 1; if (nargs < 2) { extra_stack = 2 - nargs; } luaL_checkstack(L, extra_stack, "not enough stack space for callback error handling"); // We cannot shadow rust errors with Lua ones, we pre-allocate enough memory // to store a wrapped error or panic *before* we proceed. lua_newuserdata(L, max(MLUA_WRAPPED_ERROR_SIZE, MLUA_WRAPPED_PANIC_SIZE)); lua_rotate(L, 1, 1); lua_CFunction rust_callback = lua_touserdata(L, lua_upvalueindex(1)); int ret = rust_callback(L); if (ret < 0) { if (ret == -1 /* WrappedError */) { handle_wrapped_error(L); } lua_error(L); } return ret; } void lua_call_mlua_hook_proc(lua_State *L, lua_Debug *ar) { luaL_checkstack(L, 2, "not enough stack space for callback error handling"); lua_newuserdata(L, max(MLUA_WRAPPED_ERROR_SIZE, MLUA_WRAPPED_PANIC_SIZE)); lua_rotate(L, 1, 1); int ret = mlua_hook_proc(L, ar); if (ret < 0) { if (ret == -1 /* WrappedError */) { handle_wrapped_error(L); } lua_error(L); } } static inline lua_Integer lua_popinteger(lua_State *L) { lua_Integer index = lua_tointeger(L, -1); lua_pop(L, 1); return index; } // // Common functions // int lua_gc_s(lua_State *L) { int data = lua_popinteger(L); int what = lua_popinteger(L); int ret = lua_gc(L, what, data); lua_pushinteger(L, ret); return 1; } int luaL_ref_s(lua_State *L) { int ret = luaL_ref(L, -2); lua_pushinteger(L, ret); return 1; } int lua_pushlstring_s(lua_State *L) { StringArg *s = lua_touserdata(L, -1); lua_pop(L, 1); lua_pushlstring(L, s->data, s->len); return 1; } int lua_tolstring_s(lua_State *L) { void *len = lua_touserdata(L, -1); lua_pop(L, 1); const char *s = lua_tolstring(L, -1, len); lua_pushlightuserdata(L, (void *)s); return 2; } int lua_newthread_s(lua_State *L) { lua_newthread(L); return 1; } int lua_newuserdata_s(lua_State *L) { size_t size = lua_tointeger(L, -1); lua_pop(L, 1); lua_newuserdata(L, size); return 1; } int lua_newwrappederror_s(lua_State *L) { lua_newuserdata(L, MLUA_WRAPPED_ERROR_SIZE); return 1; } int lua_pushcclosure_s(lua_State *L) { int n = lua_gettop(L) - 1; lua_CFunction fn = lua_touserdata(L, -1); lua_pop(L, 1); lua_pushcclosure(L, fn, n); return 1; } int lua_pushrclosure_s(lua_State *L) { int n = lua_gettop(L); lua_pushcclosure(L, lua_call_rust, n); return 1; } int luaL_requiref_s(lua_State *L) { const char *modname = lua_touserdata(L, -3); lua_CFunction openf = lua_touserdata(L, -2); int glb = lua_tointeger(L, -1); lua_pop(L, 3); luaL_requiref(L, modname, openf, glb); return 1; } // // Table functions // int lua_newtable_s(lua_State *L) { lua_createtable(L, 0, 0); return 1; } int lua_createtable_s(lua_State *L) { int nrec = lua_popinteger(L); int narr = lua_popinteger(L); lua_createtable(L, narr, nrec); return 1; } int lua_gettable_s(lua_State *L) { lua_gettable(L, -2); return 1; } int lua_settable_s(lua_State *L) { lua_settable(L, -3); return 0; } int lua_geti_s(lua_State *L) { lua_Integer index = lua_popinteger(L); lua_geti(L, -1, index); return 1; } int lua_rawset_s(lua_State *L) { lua_rawset(L, -3); return 0; } int lua_rawseti_s(lua_State *L) { lua_Integer index = lua_popinteger(L); lua_rawseti(L, -2, index); return 0; } int lua_rawsetp_s(lua_State *L) { void *p = lua_touserdata(L, -1); lua_pop(L, 1); lua_rawsetp(L, -2, p); return 0; } int lua_rawsetfield_s(lua_State *L) { StringArg *s = lua_touserdata(L, -2); lua_pushlstring(L, s->data, s->len); lua_replace(L, -3); lua_rawset(L, -3); return 0; } int lua_rawinsert_s(lua_State *L) { lua_Integer index = lua_popinteger(L); lua_Integer size = lua_rawlen(L, -2); for (lua_Integer i = size; i >= index; i--) { // table[i+1] = table[i] lua_rawgeti(L, -2, i); lua_rawseti(L, -3, i + 1); } lua_rawseti(L, -2, index); return 0; } int lua_rawremove_s(lua_State *L) { lua_Integer index = lua_popinteger(L); lua_Integer size = lua_rawlen(L, -1); for (lua_Integer i = index; i < size; i++) { lua_rawgeti(L, -1, i + 1); lua_rawseti(L, -2, i); } lua_pushnil(L); lua_rawseti(L, -2, size); return 0; } int luaL_len_s(lua_State *L) { lua_pushinteger(L, luaL_len(L, -1)); return 1; } int lua_next_s(lua_State *L) { int ret = lua_next(L, -2); lua_pushinteger(L, ret); return ret == 0 ? 1 : 3; } // // Moved from Rust to C // // Wrapper to lookup in `field_getters` first, then `methods`, ending // original `__index`. Used only if `field_getters` or `methods` set. int meta_index_impl(lua_State *state) { // stack: self, key luaL_checkstack(state, 2, NULL); // lookup in `field_getters` table if (lua_isnil(state, lua_upvalueindex(2)) == 0) { lua_pushvalue(state, -1); // `key` arg if (lua_rawget(state, lua_upvalueindex(2)) != LUA_TNIL) { lua_insert(state, -3); // move function lua_pop(state, 1); // remove `key` lua_call(state, 1, 1); return 1; } lua_pop(state, 1); // pop the nil value } // lookup in `methods` table if (lua_isnil(state, lua_upvalueindex(3)) == 0) { lua_pushvalue(state, -1); // `key` arg if (lua_rawget(state, lua_upvalueindex(3)) != LUA_TNIL) { lua_insert(state, -3); lua_pop(state, 2); return 1; } lua_pop(state, 1); // pop the nil value } // lookup in `__index` lua_pushvalue(state, lua_upvalueindex(1)); switch (lua_type(state, -1)) { case LUA_TNIL: lua_pop(state, 1); // pop the nil value const char *field = lua_tostring(state, -1); luaL_error(state, "attempt to get an unknown field '%s'", field); break; case LUA_TTABLE: lua_insert(state, -2); lua_gettable(state, -2); break; case LUA_TFUNCTION: lua_insert(state, -3); lua_call(state, 2, 1); break; } return 1; } // Similar to `meta_index_impl`, checks `field_setters` table first, then // `__newindex` metamethod. Used only if `field_setters` set. int meta_newindex_impl(lua_State *state) { // stack: self, key, value luaL_checkstack(state, 2, NULL); // lookup in `field_setters` table lua_pushvalue(state, -2); // `key` arg if (lua_rawget(state, lua_upvalueindex(2)) != LUA_TNIL) { lua_remove(state, -3); // remove `key` lua_insert(state, -3); // move function lua_call(state, 2, 0); return 0; } lua_pop(state, 1); // pop the nil value // lookup in `__newindex` lua_pushvalue(state, lua_upvalueindex(1)); switch (lua_type(state, -1)) { case LUA_TNIL: lua_pop(state, 1); // pop the nil value const char *field = lua_tostring(state, -2); luaL_error(state, "attempt to set an unknown field '%s'", field); break; case LUA_TTABLE: lua_insert(state, -3); lua_settable(state, -3); break; case LUA_TFUNCTION: lua_insert(state, -4); lua_call(state, 3, 0); break; } return 0; } // See Function::bind int bind_call_impl(lua_State *state) { int nargs = lua_gettop(state); int nbinds = lua_tointeger(state, lua_upvalueindex(2)); luaL_checkstack(state, nbinds + 2, NULL); lua_settop(state, nargs + nbinds + 1); lua_rotate(state, -(nargs + nbinds + 1), nbinds + 1); lua_pushvalue(state, lua_upvalueindex(1)); lua_replace(state, 1); for (int i = 0; i < nbinds; i++) { lua_pushvalue(state, lua_upvalueindex(i + 3)); lua_replace(state, i + 2); } lua_call(state, nargs + nbinds, LUA_MULTRET); return lua_gettop(state); } // Returns 1 if a value at index `index` is a special wrapped struct identified // by `key` int is_wrapped_struct(lua_State *state, int index, const void *key) { if (key == NULL) { // Not yet initialized? return 0; } void *ud = lua_touserdata(state, index); if (ud == NULL || lua_getmetatable(state, index) == 0) { return 0; } lua_rawgetp(state, LUA_REGISTRYINDEX, key); int res = lua_rawequal(state, -1, -2); lua_pop(state, 2); return res; } // Takes an error at the top of the stack and converts Lua errors into a string // with attached traceback. If the error is a WrappedError or WrappedPanic, does // not modify it. This function does its best to avoid triggering another error // and shadowing previous rust errors. int error_traceback(lua_State *state) { if (lua_checkstack(state, 2) == 0) { // If we don't have enough stack space to even check the error type, do // nothing so we don't risk shadowing a rust panic. return 1; } if (MLUA_WRAPPED_PANIC_KEY == NULL || is_wrapped_struct(state, -1, MLUA_WRAPPED_PANIC_KEY) || is_wrapped_struct(state, -1, MLUA_WRAPPED_ERROR_KEY)) { return 1; } const char *s = luaL_tolstring(state, -1, NULL); if (lua_checkstack(state, LUA_TRACEBACK_STACK) != 0) { luaL_traceback(state, state, s, 1); lua_remove(state, -2); } return 1; } int error_traceback_s(lua_State *L) { lua_State *L1 = lua_touserdata(L, -1); lua_pop(L, 1); return error_traceback(L1); } // A `pcall` implementation that does not allow Lua to catch Rust panics. // Instead, panics automatically resumed. int lua_nopanic_pcall(lua_State *state) { luaL_checkstack(state, 2, NULL); int top = lua_gettop(state); if (top == 0) { lua_pushstring(state, "not enough arguments to pcall"); lua_error(state); } if (lua_pcall(state, top - 1, LUA_MULTRET, 0) == LUA_OK) { lua_pushboolean(state, 1); lua_insert(state, 1); return lua_gettop(state); } if (is_wrapped_struct(state, -1, MLUA_WRAPPED_PANIC_KEY)) { lua_error(state); } lua_pushboolean(state, 0); lua_insert(state, -2); return 2; } // A `xpcall` implementation that does not allow Lua to catch Rust panics. // Instead, panics automatically resumed. static int xpcall_msgh(lua_State *state) { luaL_checkstack(state, 2, NULL); if (is_wrapped_struct(state, -1, MLUA_WRAPPED_PANIC_KEY)) { return 1; } lua_pushvalue(state, lua_upvalueindex(1)); lua_insert(state, 1); lua_call(state, lua_gettop(state) - 1, LUA_MULTRET); return lua_gettop(state); } int lua_nopanic_xpcall(lua_State *state) { luaL_checkstack(state, 2, NULL); int top = lua_gettop(state); if (top < 2) { lua_pushstring(state, "not enough arguments to xpcall"); lua_error(state); } lua_pushvalue(state, 2); lua_pushcclosure(state, xpcall_msgh, 1); lua_copy(state, 1, 2); lua_replace(state, 1); if (lua_pcall(state, lua_gettop(state) - 2, LUA_MULTRET, 1) == LUA_OK) { lua_pushboolean(state, 1); lua_insert(state, 2); return lua_gettop(state) - 1; } if (is_wrapped_struct(state, -1, MLUA_WRAPPED_PANIC_KEY)) { lua_error(state); } lua_pushboolean(state, 0); lua_insert(state, -2); return 2; }
/********************************************************************************************************* ** ** 中国软件开源组织 ** ** 嵌入式实时操作系统 ** ** SylixOS(TM) LW : long wing ** ** Copyright All Rights Reserved ** **--------------文件信息-------------------------------------------------------------------------------- ** ** 文 件 名: pciVendor.h ** ** 创 建 人: Han.Hui (韩辉) ** ** 文件创建日期: 2013 年 09 月 28 日 ** ** 描 述: PCI 设备供应商信息板卡ID. *********************************************************************************************************/ #ifndef __PCI_VENDOR_H #define __PCI_VENDOR_H /********************************************************************************************************* 裁剪宏 *********************************************************************************************************/ #if (LW_CFG_DEVICE_EN > 0) && (LW_CFG_PCI_EN > 0) /********************************************************************************************************* Vendor and card ID's: sort these numerically according to vendor (and according to card ID within vendor). Send all updates to <linux-pcisupport@cck.uni-kl.de>. *********************************************************************************************************/ #define PCI_VENDOR_ID_COMPAQ 0x0e11 #define PCI_DEVICE_ID_COMPAQ_1280 0x3033 #define PCI_DEVICE_ID_COMPAQ_TRIFLEX 0x4000 #define PCI_DEVICE_ID_COMPAQ_SMART2P 0xae10 #define PCI_DEVICE_ID_COMPAQ_NETEL100 0xae32 #define PCI_DEVICE_ID_COMPAQ_NETEL10 0xae34 #define PCI_DEVICE_ID_COMPAQ_NETFLEX3I 0xae35 #define PCI_DEVICE_ID_COMPAQ_NETEL100D 0xae40 #define PCI_DEVICE_ID_COMPAQ_NETEL100PI 0xae43 #define PCI_DEVICE_ID_COMPAQ_NETEL100I 0xb011 #define PCI_DEVICE_ID_COMPAQ_THUNDER 0xf130 #define PCI_DEVICE_ID_COMPAQ_NETFLEX3B 0xf150 #define PCI_VENDOR_ID_NCR 0x1000 #define PCI_DEVICE_ID_NCR_53C810 0x0001 #define PCI_DEVICE_ID_NCR_53C820 0x0002 #define PCI_DEVICE_ID_NCR_53C825 0x0003 #define PCI_DEVICE_ID_NCR_53C815 0x0004 #define PCI_DEVICE_ID_NCR_53C860 0x0006 #define PCI_DEVICE_ID_NCR_53C896 0x000b #define PCI_DEVICE_ID_NCR_53C895 0x000c #define PCI_DEVICE_ID_NCR_53C885 0x000d #define PCI_DEVICE_ID_NCR_53C875 0x000f #define PCI_DEVICE_ID_NCR_53C875J 0x008f #define PCI_VENDOR_ID_ATI 0x1002 #define PCI_DEVICE_ID_ATI_68800 0x4158 #define PCI_DEVICE_ID_ATI_215CT222 0x4354 #define PCI_DEVICE_ID_ATI_210888CX 0x4358 #define PCI_DEVICE_ID_ATI_215GB 0x4742 #define PCI_DEVICE_ID_ATI_215GD 0x4744 #define PCI_DEVICE_ID_ATI_215GI 0x4749 #define PCI_DEVICE_ID_ATI_215GP 0x4750 #define PCI_DEVICE_ID_ATI_215GQ 0x4751 #define PCI_DEVICE_ID_ATI_215GT 0x4754 #define PCI_DEVICE_ID_ATI_215GTB 0x4755 #define PCI_DEVICE_ID_ATI_210888GX 0x4758 #define PCI_DEVICE_ID_ATI_215LG 0x4c47 #define PCI_DEVICE_ID_ATI_264LT 0x4c54 #define PCI_DEVICE_ID_ATI_264VT 0x5654 #define PCI_VENDOR_ID_VLSI 0x1004 #define PCI_DEVICE_ID_VLSI_82C592 0x0005 #define PCI_DEVICE_ID_VLSI_82C593 0x0006 #define PCI_DEVICE_ID_VLSI_82C594 0x0007 #define PCI_DEVICE_ID_VLSI_82C597 0x0009 #define PCI_DEVICE_ID_VLSI_82C541 0x000c #define PCI_DEVICE_ID_VLSI_82C543 0x000d #define PCI_DEVICE_ID_VLSI_82C532 0x0101 #define PCI_DEVICE_ID_VLSI_82C534 0x0102 #define PCI_DEVICE_ID_VLSI_82C535 0x0104 #define PCI_DEVICE_ID_VLSI_82C147 0x0105 #define PCI_DEVICE_ID_VLSI_VAS96011 0x0702 #define PCI_VENDOR_ID_ADL 0x1005 #define PCI_DEVICE_ID_ADL_2301 0x2301 #define PCI_VENDOR_ID_NS 0x100b #define PCI_DEVICE_ID_NS_87415 0x0002 #define PCI_DEVICE_ID_NS_87410 0xd001 #define PCI_VENDOR_ID_TSENG 0x100c #define PCI_DEVICE_ID_TSENG_W32P_2 0x3202 #define PCI_DEVICE_ID_TSENG_W32P_b 0x3205 #define PCI_DEVICE_ID_TSENG_W32P_c 0x3206 #define PCI_DEVICE_ID_TSENG_W32P_d 0x3207 #define PCI_DEVICE_ID_TSENG_ET6000 0x3208 #define PCI_VENDOR_ID_WEITEK 0x100e #define PCI_DEVICE_ID_WEITEK_P9000 0x9001 #define PCI_DEVICE_ID_WEITEK_P9100 0x9100 #define PCI_VENDOR_ID_DEC 0x1011 #define PCI_DEVICE_ID_DEC_BRD 0x0001 #define PCI_DEVICE_ID_DEC_TULIP 0x0002 #define PCI_DEVICE_ID_DEC_TGA 0x0004 #define PCI_DEVICE_ID_DEC_TULIP_FAST 0x0009 #define PCI_DEVICE_ID_DEC_TGA2 0x000D #define PCI_DEVICE_ID_DEC_FDDI 0x000F #define PCI_DEVICE_ID_DEC_TULIP_PLUS 0x0014 #define PCI_DEVICE_ID_DEC_21142 0x0019 #define PCI_DEVICE_ID_DEC_21052 0x0021 #define PCI_DEVICE_ID_DEC_21150 0x0022 #define PCI_DEVICE_ID_DEC_21152 0x0024 #define PCI_VENDOR_ID_CIRRUS 0x1013 #define PCI_DEVICE_ID_CIRRUS_7548 0x0038 #define PCI_DEVICE_ID_CIRRUS_5430 0x00a0 #define PCI_DEVICE_ID_CIRRUS_5434_4 0x00a4 #define PCI_DEVICE_ID_CIRRUS_5434_8 0x00a8 #define PCI_DEVICE_ID_CIRRUS_5436 0x00ac #define PCI_DEVICE_ID_CIRRUS_5446 0x00b8 #define PCI_DEVICE_ID_CIRRUS_5480 0x00bc #define PCI_DEVICE_ID_CIRRUS_5464 0x00d4 #define PCI_DEVICE_ID_CIRRUS_5465 0x00d6 #define PCI_DEVICE_ID_CIRRUS_6729 0x1100 #define PCI_DEVICE_ID_CIRRUS_6832 0x1110 #define PCI_DEVICE_ID_CIRRUS_7542 0x1200 #define PCI_DEVICE_ID_CIRRUS_7543 0x1202 #define PCI_DEVICE_ID_CIRRUS_7541 0x1204 #define PCI_VENDOR_ID_IBM 0x1014 #define PCI_DEVICE_ID_IBM_FIRE_CORAL 0x000a #define PCI_DEVICE_ID_IBM_TR 0x0018 #define PCI_DEVICE_ID_IBM_82G2675 0x001d #define PCI_DEVICE_ID_IBM_MCA 0x0020 #define PCI_DEVICE_ID_IBM_82351 0x0022 #define PCI_DEVICE_ID_IBM_SERVERAID 0x002e #define PCI_DEVICE_ID_IBM_TR_WAKE 0x003e #define PCI_DEVICE_ID_IBM_MPIC 0x0046 #define PCI_DEVICE_ID_IBM_3780IDSP 0x007d #define PCI_DEVICE_ID_IBM_MPIC_2 0xffff #define PCI_VENDOR_ID_WD 0x101c #define PCI_DEVICE_ID_WD_7197 0x3296 #define PCI_VENDOR_ID_AMD 0x1022 #define PCI_DEVICE_ID_AMD_LANCE 0x2000 #define PCI_DEVICE_ID_AMD_SCSI 0x2020 #define PCI_VENDOR_ID_TRIDENT 0x1023 #define PCI_DEVICE_ID_TRIDENT_9397 0x9397 #define PCI_DEVICE_ID_TRIDENT_9420 0x9420 #define PCI_DEVICE_ID_TRIDENT_9440 0x9440 #define PCI_DEVICE_ID_TRIDENT_9660 0x9660 #define PCI_DEVICE_ID_TRIDENT_9750 0x9750 #define PCI_VENDOR_ID_AI 0x1025 #define PCI_DEVICE_ID_AI_M1435 0x1435 #define PCI_VENDOR_ID_MATROX 0x102B #define PCI_DEVICE_ID_MATROX_MGA_2 0x0518 #define PCI_DEVICE_ID_MATROX_MIL 0x0519 #define PCI_DEVICE_ID_MATROX_MYS 0x051A #define PCI_DEVICE_ID_MATROX_MIL_2 0x051b #define PCI_DEVICE_ID_MATROX_MIL_2_AGP 0x051f #define PCI_DEVICE_ID_MATROX_MGA_IMP 0x0d10 #define PCI_VENDOR_ID_CT 0x102c #define PCI_DEVICE_ID_CT_65545 0x00d8 #define PCI_DEVICE_ID_CT_65548 0x00dc #define PCI_DEVICE_ID_CT_65550 0x00e0 #define PCI_DEVICE_ID_CT_65554 0x00e4 #define PCI_DEVICE_ID_CT_65555 0x00e5 #define PCI_VENDOR_ID_MIRO 0x1031 #define PCI_DEVICE_ID_MIRO_36050 0x5601 #define PCI_VENDOR_ID_NEC 0x1033 #define PCI_DEVICE_ID_NEC_PCX2 0x0046 #define PCI_VENDOR_ID_FD 0x1036 #define PCI_DEVICE_ID_FD_36C70 0x0000 #define PCI_VENDOR_ID_SI 0x1039 #define PCI_DEVICE_ID_SI_5591_AGP 0x0001 #define PCI_DEVICE_ID_SI_6202 0x0002 #define PCI_DEVICE_ID_SI_503 0x0008 #define PCI_DEVICE_ID_SI_ACPI 0x0009 #define PCI_DEVICE_ID_SI_5597_VGA 0x0200 #define PCI_DEVICE_ID_SI_6205 0x0205 #define PCI_DEVICE_ID_SI_501 0x0406 #define PCI_DEVICE_ID_SI_496 0x0496 #define PCI_DEVICE_ID_SI_601 0x0601 #define PCI_DEVICE_ID_SI_5107 0x5107 #define PCI_DEVICE_ID_SI_5511 0x5511 #define PCI_DEVICE_ID_SI_5513 0x5513 #define PCI_DEVICE_ID_SI_5571 0x5571 #define PCI_DEVICE_ID_SI_5591 0x5591 #define PCI_DEVICE_ID_SI_5597 0x5597 #define PCI_DEVICE_ID_SI_7001 0x7001 #define PCI_VENDOR_ID_HP 0x103c #define PCI_DEVICE_ID_HP_J2585A 0x1030 #define PCI_DEVICE_ID_HP_J2585B 0x1031 #define PCI_VENDOR_ID_PCTECH 0x1042 #define PCI_DEVICE_ID_PCTECH_RZ1000 0x1000 #define PCI_DEVICE_ID_PCTECH_RZ1001 0x1001 #define PCI_DEVICE_ID_PCTECH_SAMURAI_0 0x3000 #define PCI_DEVICE_ID_PCTECH_SAMURAI_1 0x3010 #define PCI_DEVICE_ID_PCTECH_SAMURAI_IDE 0x3020 #define PCI_VENDOR_ID_DPT 0x1044 #define PCI_DEVICE_ID_DPT 0xa400 #define PCI_VENDOR_ID_OPTI 0x1045 #define PCI_DEVICE_ID_OPTI_92C178 0xc178 #define PCI_DEVICE_ID_OPTI_82C557 0xc557 #define PCI_DEVICE_ID_OPTI_82C558 0xc558 #define PCI_DEVICE_ID_OPTI_82C621 0xc621 #define PCI_DEVICE_ID_OPTI_82C700 0xc700 #define PCI_DEVICE_ID_OPTI_82C701 0xc701 #define PCI_DEVICE_ID_OPTI_82C814 0xc814 #define PCI_DEVICE_ID_OPTI_82C822 0xc822 #define PCI_DEVICE_ID_OPTI_82C825 0xd568 #define PCI_VENDOR_ID_SGS 0x104a #define PCI_DEVICE_ID_SGS_2000 0x0008 #define PCI_DEVICE_ID_SGS_1764 0x0009 #define PCI_VENDOR_ID_BUSLOGIC 0x104B #define PCI_DEVICE_ID_BUSLOGIC_MULTIMASTER_NC 0x0140 #define PCI_DEVICE_ID_BUSLOGIC_MULTIMASTER 0x1040 #define PCI_DEVICE_ID_BUSLOGIC_FLASHPOINT 0x8130 #define PCI_VENDOR_ID_TI 0x104c #define PCI_DEVICE_ID_TI_TVP4010 0x3d04 #define PCI_DEVICE_ID_TI_TVP4020 0x3d07 #define PCI_DEVICE_ID_TI_PCI1130 0xac12 #define PCI_DEVICE_ID_TI_PCI1031 0xac13 #define PCI_DEVICE_ID_TI_PCI1131 0xac15 #define PCI_DEVICE_ID_TI_PCI1250 0xac16 #define PCI_DEVICE_ID_TI_PCI1220 0xac17 #define PCI_VENDOR_ID_OAK 0x104e #define PCI_DEVICE_ID_OAK_OTI107 0x0107 #define PCI_VENDOR_ID_WINBOND2 0x1050 #define PCI_DEVICE_ID_WINBOND2_89C940 0x0940 #define PCI_VENDOR_ID_MOTOROLA 0x1057 #define PCI_DEVICE_ID_MOTOROLA_MPC105 0x0001 #define PCI_DEVICE_ID_MOTOROLA_MPC106 0x0002 #define PCI_DEVICE_ID_MOTOROLA_RAVEN 0x4801 #define PCI_DEVICE_ID_MOTOROLA_HAWK 0x4803 #define PCI_VENDOR_ID_PROMISE 0x105a #define PCI_DEVICE_ID_PROMISE_20246 0x4d33 #define PCI_DEVICE_ID_PROMISE_5300 0x5300 #define PCI_VENDOR_ID_N9 0x105d #define PCI_DEVICE_ID_N9_I128 0x2309 #define PCI_DEVICE_ID_N9_I128_2 0x2339 #define PCI_DEVICE_ID_N9_I128_T2R 0x493d #define PCI_VENDOR_ID_UMC 0x1060 #define PCI_DEVICE_ID_UMC_UM8673F 0x0101 #define PCI_DEVICE_ID_UMC_UM8891A 0x0891 #define PCI_DEVICE_ID_UMC_UM8886BF 0x673a #define PCI_DEVICE_ID_UMC_UM8886A 0x886a #define PCI_DEVICE_ID_UMC_UM8881F 0x8881 #define PCI_DEVICE_ID_UMC_UM8886F 0x8886 #define PCI_DEVICE_ID_UMC_UM9017F 0x9017 #define PCI_DEVICE_ID_UMC_UM8886N 0xe886 #define PCI_DEVICE_ID_UMC_UM8891N 0xe891 #define PCI_VENDOR_ID_X 0x1061 #define PCI_DEVICE_ID_X_AGX016 0x0001 #define PCI_VENDOR_ID_PICOP 0x1066 #define PCI_DEVICE_ID_PICOP_PT86C52X 0x0001 #define PCI_DEVICE_ID_PICOP_PT80C524 0x8002 #define PCI_VENDOR_ID_APPLE 0x106b #define PCI_DEVICE_ID_APPLE_BANDIT 0x0001 #define PCI_DEVICE_ID_APPLE_GC 0x0002 #define PCI_DEVICE_ID_APPLE_HYDRA 0x000e #define PCI_VENDOR_ID_NEXGEN 0x1074 #define PCI_DEVICE_ID_NEXGEN_82C501 0x4e78 #define PCI_VENDOR_ID_QLOGIC 0x1077 #define PCI_DEVICE_ID_QLOGIC_ISP1020 0x1020 #define PCI_DEVICE_ID_QLOGIC_ISP1022 0x1022 #define PCI_VENDOR_ID_CYRIX 0x1078 #define PCI_DEVICE_ID_CYRIX_5510 0x0000 #define PCI_DEVICE_ID_CYRIX_PCI_MASTER 0x0001 #define PCI_DEVICE_ID_CYRIX_5520 0x0002 #define PCI_DEVICE_ID_CYRIX_5530_LEGACY 0x0100 #define PCI_DEVICE_ID_CYRIX_5530_SMI 0x0101 #define PCI_DEVICE_ID_CYRIX_5530_IDE 0x0102 #define PCI_DEVICE_ID_CYRIX_5530_AUDIO 0x0103 #define PCI_DEVICE_ID_CYRIX_5530_VIDEO 0x0104 #define PCI_VENDOR_ID_LEADTEK 0x107d #define PCI_DEVICE_ID_LEADTEK_805 0x0000 #define PCI_VENDOR_ID_CONTAQ 0x1080 #define PCI_DEVICE_ID_CONTAQ_82C599 0x0600 #define PCI_DEVICE_ID_CONTAQ_82C693 0xc693 #define PCI_VENDOR_ID_FOREX 0x1083 #define PCI_VENDOR_ID_OLICOM 0x108d #define PCI_DEVICE_ID_OLICOM_OC3136 0x0001 #define PCI_DEVICE_ID_OLICOM_OC2315 0x0011 #define PCI_DEVICE_ID_OLICOM_OC2325 0x0012 #define PCI_DEVICE_ID_OLICOM_OC2183 0x0013 #define PCI_DEVICE_ID_OLICOM_OC2326 0x0014 #define PCI_DEVICE_ID_OLICOM_OC6151 0x0021 #define PCI_VENDOR_ID_SUN 0x108e #define PCI_DEVICE_ID_SUN_EBUS 0x1000 #define PCI_DEVICE_ID_SUN_HAPPYMEAL 0x1001 #define PCI_DEVICE_ID_SUN_SIMBA 0x5000 #define PCI_DEVICE_ID_SUN_PBM 0x8000 #define PCI_DEVICE_ID_SUN_SABRE 0xa000 #define PCI_VENDOR_ID_CMD 0x1095 #define PCI_DEVICE_ID_CMD_640 0x0640 #define PCI_DEVICE_ID_CMD_643 0x0643 #define PCI_DEVICE_ID_CMD_646 0x0646 #define PCI_DEVICE_ID_CMD_647 0x0647 #define PCI_DEVICE_ID_CMD_670 0x0670 #define PCI_VENDOR_ID_VISION 0x1098 #define PCI_DEVICE_ID_VISION_QD8500 0x0001 #define PCI_DEVICE_ID_VISION_QD8580 0x0002 #define PCI_VENDOR_ID_BROOKTREE 0x109e #define PCI_DEVICE_ID_BROOKTREE_848 0x0350 #define PCI_DEVICE_ID_BROOKTREE_849A 0x0351 #define PCI_DEVICE_ID_BROOKTREE_8474 0x8474 #define PCI_VENDOR_ID_SIERRA 0x10a8 #define PCI_DEVICE_ID_SIERRA_STB 0x0000 #define PCI_VENDOR_ID_ACC 0x10aa #define PCI_DEVICE_ID_ACC_2056 0x0000 #define PCI_VENDOR_ID_WINBOND 0x10ad #define PCI_DEVICE_ID_WINBOND_83769 0x0001 #define PCI_DEVICE_ID_WINBOND_82C105 0x0105 #define PCI_DEVICE_ID_WINBOND_83C553 0x0565 #define PCI_VENDOR_ID_DATABOOK 0x10b3 #define PCI_DEVICE_ID_DATABOOK_87144 0xb106 #define PCI_VENDOR_ID_PLX 0x10b5 #define PCI_DEVICE_ID_PLX_9050 0x9050 #define PCI_DEVICE_ID_PLX_9060 0x9060 #define PCI_DEVICE_ID_PLX_9060ES 0x906E #define PCI_DEVICE_ID_PLX_9060SD 0x906D #define PCI_DEVICE_ID_PLX_9080 0x9080 #define PCI_VENDOR_ID_MADGE 0x10b6 #define PCI_DEVICE_ID_MADGE_MK2 0x0002 #define PCI_DEVICE_ID_MADGE_C155S 0x1001 #define PCI_VENDOR_ID_3COM 0x10b7 #define PCI_DEVICE_ID_3COM_3C339 0x3390 #define PCI_DEVICE_ID_3COM_3C590 0x5900 #define PCI_DEVICE_ID_3COM_3C595TX 0x5950 #define PCI_DEVICE_ID_3COM_3C595T4 0x5951 #define PCI_DEVICE_ID_3COM_3C595MII 0x5952 #define PCI_DEVICE_ID_3COM_3C900TPO 0x9000 #define PCI_DEVICE_ID_3COM_3C900COMBO 0x9001 #define PCI_DEVICE_ID_3COM_3C905TX 0x9050 #define PCI_DEVICE_ID_3COM_3C905T4 0x9051 #define PCI_DEVICE_ID_3COM_3C905B_TX 0x9055 #define PCI_VENDOR_ID_SMC 0x10b8 #define PCI_DEVICE_ID_SMC_EPIC100 0x0005 #define PCI_VENDOR_ID_AL 0x10b9 #define PCI_DEVICE_ID_AL_M1445 0x1445 #define PCI_DEVICE_ID_AL_M1449 0x1449 #define PCI_DEVICE_ID_AL_M1451 0x1451 #define PCI_DEVICE_ID_AL_M1461 0x1461 #define PCI_DEVICE_ID_AL_M1489 0x1489 #define PCI_DEVICE_ID_AL_M1511 0x1511 #define PCI_DEVICE_ID_AL_M1513 0x1513 #define PCI_DEVICE_ID_AL_M1521 0x1521 #define PCI_DEVICE_ID_AL_M1523 0x1523 #define PCI_DEVICE_ID_AL_M1531 0x1531 #define PCI_DEVICE_ID_AL_M1533 0x1533 #define PCI_DEVICE_ID_AL_M3307 0x3307 #define PCI_DEVICE_ID_AL_M4803 0x5215 #define PCI_DEVICE_ID_AL_M5219 0x5219 #define PCI_DEVICE_ID_AL_M5229 0x5229 #define PCI_DEVICE_ID_AL_M5237 0x5237 #define PCI_DEVICE_ID_AL_M7101 0x7101 #define PCI_VENDOR_ID_MITSUBISHI 0x10ba #define PCI_VENDOR_ID_SURECOM 0x10bd #define PCI_DEVICE_ID_SURECOM_NE34 0x0e34 #define PCI_VENDOR_ID_NEOMAGIC 0x10c8 #define PCI_DEVICE_ID_NEOMAGIC_MAGICGRAPH_NM2070 0x0001 #define PCI_DEVICE_ID_NEOMAGIC_MAGICGRAPH_128V 0x0002 #define PCI_DEVICE_ID_NEOMAGIC_MAGICGRAPH_128ZV 0x0003 #define PCI_DEVICE_ID_NEOMAGIC_MAGICGRAPH_NM2160 0x0004 #define PCI_VENDOR_ID_ASP 0x10cd #define PCI_DEVICE_ID_ASP_ABP940 0x1200 #define PCI_DEVICE_ID_ASP_ABP940U 0x1300 #define PCI_DEVICE_ID_ASP_ABP940UW 0x2300 #define PCI_VENDOR_ID_MACRONIX 0x10d9 #define PCI_DEVICE_ID_MACRONIX_MX98713 0x0512 #define PCI_DEVICE_ID_MACRONIX_MX987x5 0x0531 #define PCI_VENDOR_ID_CERN 0x10dc #define PCI_DEVICE_ID_CERN_SPSB_PMC 0x0001 #define PCI_DEVICE_ID_CERN_SPSB_PCI 0x0002 #define PCI_DEVICE_ID_CERN_HIPPI_DST 0x0021 #define PCI_DEVICE_ID_CERN_HIPPI_SRC 0x0022 #define PCI_VENDOR_ID_NVIDIA 0x10de #define PCI_VENDOR_ID_IMS 0x10e0 #define PCI_DEVICE_ID_IMS_8849 0x8849 #define PCI_VENDOR_ID_TEKRAM2 0x10e1 #define PCI_DEVICE_ID_TEKRAM2_690c 0x690c #define PCI_VENDOR_ID_TUNDRA 0x10e3 #define PCI_DEVICE_ID_TUNDRA_CA91C042 0x0000 #define PCI_VENDOR_ID_AMCC 0x10e8 #define PCI_DEVICE_ID_AMCC_MYRINET 0x8043 #define PCI_DEVICE_ID_AMCC_PARASTATION 0x8062 #define PCI_DEVICE_ID_AMCC_S5933 0x807d #define PCI_DEVICE_ID_AMCC_S5933_HEPC3 0x809c #define PCI_VENDOR_ID_INTERG 0x10ea #define PCI_DEVICE_ID_INTERG_1680 0x1680 #define PCI_DEVICE_ID_INTERG_1682 0x1682 #define PCI_VENDOR_ID_REALTEK 0x10ec #define PCI_DEVICE_ID_REALTEK_8029 0x8029 #define PCI_DEVICE_ID_REALTEK_8129 0x8129 #define PCI_DEVICE_ID_REALTEK_8139 0x8139 #define PCI_VENDOR_ID_TRUEVISION 0x10fa #define PCI_DEVICE_ID_TRUEVISION_T1000 0x000c #define PCI_VENDOR_ID_INIT 0x1101 #define PCI_DEVICE_ID_INIT_320P 0x9100 #define PCI_DEVICE_ID_INIT_360P 0x9500 #define PCI_VENDOR_ID_TTI 0x1103 #define PCI_DEVICE_ID_TTI_HPT343 0x0003 #define PCI_VENDOR_ID_VIA 0x1106 #define PCI_DEVICE_ID_VIA_82C505 0x0505 #define PCI_DEVICE_ID_VIA_82C561 0x0561 #define PCI_DEVICE_ID_VIA_82C586_1 0x0571 #define PCI_DEVICE_ID_VIA_82C576 0x0576 #define PCI_DEVICE_ID_VIA_82C585 0x0585 #define PCI_DEVICE_ID_VIA_82C586_0 0x0586 #define PCI_DEVICE_ID_VIA_82C595 0x0595 #define PCI_DEVICE_ID_VIA_82C597_0 0x0597 #define PCI_DEVICE_ID_VIA_82C926 0x0926 #define PCI_DEVICE_ID_VIA_82C416 0x1571 #define PCI_DEVICE_ID_VIA_82C595_97 0x1595 #define PCI_DEVICE_ID_VIA_82C586_2 0x3038 #define PCI_DEVICE_ID_VIA_82C586_3 0x3040 #define PCI_DEVICE_ID_VIA_86C100A 0x6100 #define PCI_DEVICE_ID_VIA_82C597_1 0x8597 #define PCI_VENDOR_ID_VORTEX 0x1119 #define PCI_DEVICE_ID_VORTEX_GDT60x0 0x0000 #define PCI_DEVICE_ID_VORTEX_GDT6000B 0x0001 #define PCI_DEVICE_ID_VORTEX_GDT6x10 0x0002 #define PCI_DEVICE_ID_VORTEX_GDT6x20 0x0003 #define PCI_DEVICE_ID_VORTEX_GDT6530 0x0004 #define PCI_DEVICE_ID_VORTEX_GDT6550 0x0005 #define PCI_DEVICE_ID_VORTEX_GDT6x17 0x0006 #define PCI_DEVICE_ID_VORTEX_GDT6x27 0x0007 #define PCI_DEVICE_ID_VORTEX_GDT6537 0x0008 #define PCI_DEVICE_ID_VORTEX_GDT6557 0x0009 #define PCI_DEVICE_ID_VORTEX_GDT6x15 0x000a #define PCI_DEVICE_ID_VORTEX_GDT6x25 0x000b #define PCI_DEVICE_ID_VORTEX_GDT6535 0x000c #define PCI_DEVICE_ID_VORTEX_GDT6555 0x000d #define PCI_DEVICE_ID_VORTEX_GDT6x17RP 0x0100 #define PCI_DEVICE_ID_VORTEX_GDT6x27RP 0x0101 #define PCI_DEVICE_ID_VORTEX_GDT6537RP 0x0102 #define PCI_DEVICE_ID_VORTEX_GDT6557RP 0x0103 #define PCI_DEVICE_ID_VORTEX_GDT6x11RP 0x0104 #define PCI_DEVICE_ID_VORTEX_GDT6x21RP 0x0105 #define PCI_DEVICE_ID_VORTEX_GDT6x17RP1 0x0110 #define PCI_DEVICE_ID_VORTEX_GDT6x27RP1 0x0111 #define PCI_DEVICE_ID_VORTEX_GDT6537RP1 0x0112 #define PCI_DEVICE_ID_VORTEX_GDT6557RP1 0x0113 #define PCI_DEVICE_ID_VORTEX_GDT6x11RP1 0x0114 #define PCI_DEVICE_ID_VORTEX_GDT6x21RP1 0x0115 #define PCI_DEVICE_ID_VORTEX_GDT6x17RP2 0x0120 #define PCI_DEVICE_ID_VORTEX_GDT6x27RP2 0x0121 #define PCI_DEVICE_ID_VORTEX_GDT6537RP2 0x0122 #define PCI_DEVICE_ID_VORTEX_GDT6557RP2 0x0123 #define PCI_DEVICE_ID_VORTEX_GDT6x11RP2 0x0124 #define PCI_DEVICE_ID_VORTEX_GDT6x21RP2 0x0125 #define PCI_VENDOR_ID_EF 0x111a #define PCI_DEVICE_ID_EF_ATM_FPGA 0x0000 #define PCI_DEVICE_ID_EF_ATM_ASIC 0x0002 #define PCI_VENDOR_ID_FORE 0x1127 #define PCI_DEVICE_ID_FORE_PCA200PC 0x0210 #define PCI_DEVICE_ID_FORE_PCA200E 0x0300 #define PCI_VENDOR_ID_IMAGINGTECH 0x112f #define PCI_DEVICE_ID_IMAGINGTECH_ICPCI 0x0000 #define PCI_VENDOR_ID_PHILIPS 0x1131 #define PCI_DEVICE_ID_PHILIPS_SAA7145 0x7145 #define PCI_DEVICE_ID_PHILIPS_SAA7146 0x7146 #define PCI_VENDOR_ID_CYCLONE 0x113c #define PCI_DEVICE_ID_CYCLONE_SDK 0x0001 #define PCI_VENDOR_ID_ALLIANCE 0x1142 #define PCI_DEVICE_ID_ALLIANCE_PROMOTIO 0x3210 #define PCI_DEVICE_ID_ALLIANCE_PROVIDEO 0x6422 #define PCI_DEVICE_ID_ALLIANCE_AT24 0x6424 #define PCI_DEVICE_ID_ALLIANCE_AT3D 0x643d #define PCI_VENDOR_ID_SK 0x1148 #define PCI_DEVICE_ID_SK_FP 0x4000 #define PCI_DEVICE_ID_SK_TR 0x4200 #define PCI_DEVICE_ID_SK_GE 0x4300 #define PCI_VENDOR_ID_VMIC 0x114a #define PCI_DEVICE_ID_VMIC_VME 0x7587 #define PCI_VENDOR_ID_DIGI 0x114f #define PCI_DEVICE_ID_DIGI_EPC 0x0002 #define PCI_DEVICE_ID_DIGI_RIGHTSWITCH 0x0003 #define PCI_DEVICE_ID_DIGI_XEM 0x0004 #define PCI_DEVICE_ID_DIGI_XR 0x0005 #define PCI_DEVICE_ID_DIGI_CX 0x0006 #define PCI_DEVICE_ID_DIGI_XRJ 0x0009 #define PCI_DEVICE_ID_DIGI_EPCJ 0x000a #define PCI_DEVICE_ID_DIGI_XR_920 0x0027 #define PCI_VENDOR_ID_MUTECH 0x1159 #define PCI_DEVICE_ID_MUTECH_MV1000 0x0001 #define PCI_VENDOR_ID_RENDITION 0x1163 #define PCI_DEVICE_ID_RENDITION_VERITE 0x0001 #define PCI_DEVICE_ID_RENDITION_VERITE2100 0x2000 #define PCI_VENDOR_ID_TOSHIBA 0x1179 #define PCI_DEVICE_ID_TOSHIBA_601 0x0601 #define PCI_DEVICE_ID_TOSHIBA_TOPIC95 0x060a #define PCI_DEVICE_ID_TOSHIBA_TOPIC97 0x060f #define PCI_VENDOR_ID_RICOH 0x1180 #define PCI_DEVICE_ID_RICOH_RL5C465 0x0465 #define PCI_DEVICE_ID_RICOH_RL5C466 0x0466 #define PCI_DEVICE_ID_RICOH_RL5C475 0x0475 #define PCI_DEVICE_ID_RICOH_RL5C478 0x0478 #define PCI_VENDOR_ID_ARTOP 0x1191 #define PCI_DEVICE_ID_ARTOP_ATP8400 0x0004 #define PCI_DEVICE_ID_ARTOP_ATP850UF 0x0005 #define PCI_VENDOR_ID_ZEITNET 0x1193 #define PCI_DEVICE_ID_ZEITNET_1221 0x0001 #define PCI_DEVICE_ID_ZEITNET_1225 0x0002 #define PCI_VENDOR_ID_OMEGA 0x119b #define PCI_DEVICE_ID_OMEGA_82C092G 0x1221 #define PCI_VENDOR_ID_LITEON 0x11ad #define PCI_DEVICE_ID_LITEON_LNE100TX 0x0002 #define PCI_VENDOR_ID_NP 0x11bc #define PCI_DEVICE_ID_NP_PCI_FDDI 0x0001 #define PCI_VENDOR_ID_ATT 0x11c1 #define PCI_DEVICE_ID_ATT_L56XMF 0x0440 #define PCI_VENDOR_ID_SPECIALIX 0x11cb #define PCI_DEVICE_ID_SPECIALIX_IO8 0x2000 #define PCI_DEVICE_ID_SPECIALIX_XIO 0x4000 #define PCI_DEVICE_ID_SPECIALIX_RIO 0x8000 #define PCI_VENDOR_ID_AURAVISION 0x11d1 #define PCI_DEVICE_ID_AURAVISION_VXP524 0x01f7 #define PCI_VENDOR_ID_IKON 0x11d5 #define PCI_DEVICE_ID_IKON_10115 0x0115 #define PCI_DEVICE_ID_IKON_10117 0x0117 #define PCI_VENDOR_ID_ZORAN 0x11de #define PCI_DEVICE_ID_ZORAN_36057 0x6057 #define PCI_DEVICE_ID_ZORAN_36120 0x6120 #define PCI_VENDOR_ID_KINETIC 0x11f4 #define PCI_DEVICE_ID_KINETIC_2915 0x2915 #define PCI_VENDOR_ID_COMPEX 0x11f6 #define PCI_DEVICE_ID_COMPEX_ENET100VG4 0x0112 #define PCI_DEVICE_ID_COMPEX_RL2000 0x1401 #define PCI_VENDOR_ID_RP 0x11fe #define PCI_DEVICE_ID_RP32INTF 0x0001 #define PCI_DEVICE_ID_RP8INTF 0x0002 #define PCI_DEVICE_ID_RP16INTF 0x0003 #define PCI_DEVICE_ID_RP4QUAD 0x0004 #define PCI_DEVICE_ID_RP8OCTA 0x0005 #define PCI_DEVICE_ID_RP8J 0x0006 #define PCI_DEVICE_ID_RPP4 0x000A #define PCI_DEVICE_ID_RPP8 0x000B #define PCI_DEVICE_ID_RP8M 0x000C #define PCI_VENDOR_ID_CYCLADES 0x120e #define PCI_DEVICE_ID_CYCLOM_Y_Lo 0x0100 #define PCI_DEVICE_ID_CYCLOM_Y_Hi 0x0101 #define PCI_DEVICE_ID_CYCLOM_Z_Lo 0x0200 #define PCI_DEVICE_ID_CYCLOM_Z_Hi 0x0201 #define PCI_VENDOR_ID_ESSENTIAL 0x120f #define PCI_DEVICE_ID_ESSENTIAL_ROADRUNNER 0x0001 #define PCI_VENDOR_ID_O2 0x1217 #define PCI_DEVICE_ID_O2_6729 0x6729 #define PCI_DEVICE_ID_O2_6730 0x673a #define PCI_DEVICE_ID_O2_6832 0x6832 #define PCI_DEVICE_ID_O2_6836 0x6836 #define PCI_VENDOR_ID_3DFX 0x121a #define PCI_DEVICE_ID_3DFX_VOODOO 0x0001 #define PCI_DEVICE_ID_3DFX_VOODOO2 0x0002 #define PCI_VENDOR_ID_SIGMADES 0x1236 #define PCI_DEVICE_ID_SIGMADES_6425 0x6401 #define PCI_VENDOR_ID_CCUBE 0x123f #define PCI_VENDOR_ID_DIPIX 0x1246 #define PCI_VENDOR_ID_STALLION 0x124d #define PCI_DEVICE_ID_STALLION_ECHPCI832 0x0000 #define PCI_DEVICE_ID_STALLION_ECHPCI864 0x0002 #define PCI_DEVICE_ID_STALLION_EIOPCI 0x0003 #define PCI_VENDOR_ID_OPTIBASE 0x1255 #define PCI_DEVICE_ID_OPTIBASE_FORGE 0x1110 #define PCI_DEVICE_ID_OPTIBASE_FUSION 0x1210 #define PCI_DEVICE_ID_OPTIBASE_VPLEX 0x2110 #define PCI_DEVICE_ID_OPTIBASE_VPLEXCC 0x2120 #define PCI_DEVICE_ID_OPTIBASE_VQUEST 0x2130 #define PCI_VENDOR_ID_SATSAGEM 0x1267 #define PCI_DEVICE_ID_SATSAGEM_PCR2101 0x5352 #define PCI_DEVICE_ID_SATSAGEM_TELSATTURBO 0x5a4b #define PCI_VENDOR_ID_HUGHES 0x1273 #define PCI_DEVICE_ID_HUGHES_DIRECPC 0x0002 #define PCI_VENDOR_ID_ENSONIQ 0x1274 #define PCI_DEVICE_ID_ENSONIQ_AUDIOPCI 0x5000 #define PCI_VENDOR_ID_ALTEON 0x12ae #define PCI_DEVICE_ID_ALTEON_ACENIC 0x0001 #define PCI_VENDOR_ID_PICTUREL 0x12c5 #define PCI_DEVICE_ID_PICTUREL_PCIVST 0x0081 #define PCI_VENDOR_ID_NVIDIA_SGS 0x12d2 #define PCI_DEVICE_ID_NVIDIA_SGS_RIVA128 0x0018 #define PCI_VENDOR_ID_CBOARDS 0x1307 #define PCI_DEVICE_ID_CBOARDS_DAS1602_16 0x0001 #define PCI_VENDOR_ID_SYMPHONY 0x1c1c #define PCI_DEVICE_ID_SYMPHONY_101 0x0001 #define PCI_VENDOR_ID_TEKRAM 0x1de1 #define PCI_DEVICE_ID_TEKRAM_DC290 0xdc29 #define PCI_VENDOR_ID_3DLABS 0x3d3d #define PCI_DEVICE_ID_3DLABS_300SX 0x0001 #define PCI_DEVICE_ID_3DLABS_500TX 0x0002 #define PCI_DEVICE_ID_3DLABS_DELTA 0x0003 #define PCI_DEVICE_ID_3DLABS_PERMEDIA 0x0004 #define PCI_DEVICE_ID_3DLABS_MX 0x0006 #define PCI_VENDOR_ID_AVANCE 0x4005 #define PCI_DEVICE_ID_AVANCE_ALG2064 0x2064 #define PCI_DEVICE_ID_AVANCE_2302 0x2302 #define PCI_VENDOR_ID_NETVIN 0x4a14 #define PCI_DEVICE_ID_NETVIN_NV5000SC 0x5000 #define PCI_VENDOR_ID_S3 0x5333 #define PCI_DEVICE_ID_S3_PLATO_PXS 0x0551 #define PCI_DEVICE_ID_S3_ViRGE 0x5631 #define PCI_DEVICE_ID_S3_TRIO 0x8811 #define PCI_DEVICE_ID_S3_AURORA64VP 0x8812 #define PCI_DEVICE_ID_S3_TRIO64UVP 0x8814 #define PCI_DEVICE_ID_S3_ViRGE_VX 0x883d #define PCI_DEVICE_ID_S3_868 0x8880 #define PCI_DEVICE_ID_S3_928 0x88b0 #define PCI_DEVICE_ID_S3_864_1 0x88c0 #define PCI_DEVICE_ID_S3_864_2 0x88c1 #define PCI_DEVICE_ID_S3_964_1 0x88d0 #define PCI_DEVICE_ID_S3_964_2 0x88d1 #define PCI_DEVICE_ID_S3_968 0x88f0 #define PCI_DEVICE_ID_S3_TRIO64V2 0x8901 #define PCI_DEVICE_ID_S3_PLATO_PXG 0x8902 #define PCI_DEVICE_ID_S3_ViRGE_DXGX 0x8a01 #define PCI_DEVICE_ID_S3_ViRGE_GX2 0x8a10 #define PCI_DEVICE_ID_S3_ViRGE_MX 0x8c01 #define PCI_DEVICE_ID_S3_ViRGE_MXP 0x8c02 #define PCI_DEVICE_ID_S3_ViRGE_MXPMV 0x8c03 #define PCI_DEVICE_ID_S3_SONICVIBES 0xca00 #define PCI_VENDOR_ID_INTEL 0x8086 #define PCI_DEVICE_ID_INTEL_82375 0x0482 #define PCI_DEVICE_ID_INTEL_82424 0x0483 #define PCI_DEVICE_ID_INTEL_82378 0x0484 #define PCI_DEVICE_ID_INTEL_82430 0x0486 #define PCI_DEVICE_ID_INTEL_82434 0x04a3 #define PCI_DEVICE_ID_INTEL_82092AA_0 0x1221 #define PCI_DEVICE_ID_INTEL_82092AA_1 0x1222 #define PCI_DEVICE_ID_INTEL_7116 0x1223 #define PCI_DEVICE_ID_INTEL_82596 0x1226 #define PCI_DEVICE_ID_INTEL_82865 0x1227 #define PCI_DEVICE_ID_INTEL_82557 0x1229 #define PCI_DEVICE_ID_INTEL_82437 0x122d #define PCI_DEVICE_ID_INTEL_82371FB_0 0x122e #define PCI_DEVICE_ID_INTEL_82371FB_1 0x1230 #define PCI_DEVICE_ID_INTEL_82371MX 0x1234 #define PCI_DEVICE_ID_INTEL_82437MX 0x1235 #define PCI_DEVICE_ID_INTEL_82441 0x1237 #define PCI_DEVICE_ID_INTEL_82380FB 0x124b #define PCI_DEVICE_ID_INTEL_82439 0x1250 #define PCI_DEVICE_ID_INTEL_82371SB_0 0x7000 #define PCI_DEVICE_ID_INTEL_82371SB_1 0x7010 #define PCI_DEVICE_ID_INTEL_82371SB_2 0x7020 #define PCI_DEVICE_ID_INTEL_82437VX 0x7030 #define PCI_DEVICE_ID_INTEL_82439TX 0x7100 #define PCI_DEVICE_ID_INTEL_82371AB_0 0x7110 #define PCI_DEVICE_ID_INTEL_82371AB 0x7111 #define PCI_DEVICE_ID_INTEL_82371AB_2 0x7112 #define PCI_DEVICE_ID_INTEL_82371AB_3 0x7113 #define PCI_DEVICE_ID_INTEL_82443LX_0 0x7180 #define PCI_DEVICE_ID_INTEL_82443LX_1 0x7181 #define PCI_DEVICE_ID_INTEL_82443BX_0 0x7190 #define PCI_DEVICE_ID_INTEL_82443BX_1 0x7191 #define PCI_DEVICE_ID_INTEL_82443BX_2 0x7192 #define PCI_DEVICE_ID_INTEL_P6 0x84c4 #define PCI_DEVICE_ID_INTEL_82450GX 0x84c5 #define PCI_VENDOR_ID_KTI 0x8e2e #define PCI_DEVICE_ID_KTI_ET32P2 0x3000 #define PCI_VENDOR_ID_ADAPTEC 0x9004 #define PCI_DEVICE_ID_ADAPTEC_7810 0x1078 #define PCI_DEVICE_ID_ADAPTEC_7850 0x5078 #define PCI_DEVICE_ID_ADAPTEC_7855 0x5578 #define PCI_DEVICE_ID_ADAPTEC_5800 0x5800 #define PCI_DEVICE_ID_ADAPTEC_1480A 0x6075 #define PCI_DEVICE_ID_ADAPTEC_7860 0x6078 #define PCI_DEVICE_ID_ADAPTEC_7861 0x6178 #define PCI_DEVICE_ID_ADAPTEC_7870 0x7078 #define PCI_DEVICE_ID_ADAPTEC_7871 0x7178 #define PCI_DEVICE_ID_ADAPTEC_7872 0x7278 #define PCI_DEVICE_ID_ADAPTEC_7873 0x7378 #define PCI_DEVICE_ID_ADAPTEC_7874 0x7478 #define PCI_DEVICE_ID_ADAPTEC_7895 0x7895 #define PCI_DEVICE_ID_ADAPTEC_7880 0x8078 #define PCI_DEVICE_ID_ADAPTEC_7881 0x8178 #define PCI_DEVICE_ID_ADAPTEC_7882 0x8278 #define PCI_DEVICE_ID_ADAPTEC_7883 0x8378 #define PCI_DEVICE_ID_ADAPTEC_7884 0x8478 #define PCI_DEVICE_ID_ADAPTEC_1030 0x8b78 #define PCI_VENDOR_ID_ADAPTEC2 0x9005 #define PCI_DEVICE_ID_ADAPTEC2_2940U2 0x0010 #define PCI_DEVICE_ID_ADAPTEC2_7890 0x001f #define PCI_DEVICE_ID_ADAPTEC2_3940U2 0x0050 #define PCI_DEVICE_ID_ADAPTEC2_7896 0x005f #define PCI_VENDOR_ID_ATRONICS 0x907f #define PCI_DEVICE_ID_ATRONICS_2015 0x2015 #define PCI_VENDOR_ID_HOLTEK 0x9412 #define PCI_DEVICE_ID_HOLTEK_6565 0x6565 #define PCI_VENDOR_ID_TIGERJET 0xe159 #define PCI_DEVICE_ID_TIGERJET_300 0x0001 #define PCI_VENDOR_ID_ARK 0xedd8 #define PCI_DEVICE_ID_ARK_STING 0xa091 #define PCI_DEVICE_ID_ARK_STINGARK 0xa099 #define PCI_DEVICE_ID_ARK_2000MT 0xa0a1 #endif /* (LW_CFG_DEVICE_EN > 0) && */ /* (LW_CFG_PCI_EN > 0) */ #endif /* __PCI_VENDOR_H */ /********************************************************************************************************* END *********************************************************************************************************/
#include <stdio.h> #include <stdlib.h> #include <string.h> void printarr(char str[]){ int len = strlen(str); for(int i=0;i<len;i++){ printf("%c",str[i]); } printf("\n"); } void reset(char str[]){ //memset(str, 0, sizeof(str)); int len = strlen(str); for(int i=0;i<len;i++){ str[i]=0; } } void rev(char str[]){ int len = strlen(str); char temp; for(int i=0;i<len/2;i++){ temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; } } void add(char str1[],char str2[],char fibo[]){ int l1 = strlen(str1); int l2 = strlen(str2); int len,a,b,c,carry; rev(str1); rev(str2); len = (l1>l2) ? l1 : l2; for(int i=0;i<len;i++){ carry=0,a=0,b=0,c=0; if(str1[i]-'0'!=-48) a=str1[i]-'0'; if(str2[i]-'0'!=-48) b=str2[i]-'0'; if(fibo[i]-'0'!=-48) c=fibo[i]-'0'; carry=(a+b+c)/10; fibo[i]=((a+b+c)%10)+'0'; if(carry!=0) fibo[i+1]= carry +'0'; } rev(str1); rev(str2); rev(fibo); } int main() { int n; printf("Enter a number:\t"); scanf("%d",&n); char str1[100000]="0",str2[100000]="1",fibo[100000]; if(n==1)fibo[0]='0'; if(n==2)fibo[0]='1'; for(int i=3;i<=n;i++){ reset(fibo); add(str1,str2,fibo); reset(str1); strcpy(str1, str2); reset(str2); strcpy(str2,fibo); } printf("Your Fibonacii Number is : \t"); printarr(fibo); printf("\n\nNumber of digits in your fibonacii is :\t"); printf("%d\n",strlen(fibo)); return 0; }
#ifndef LCD2004_I2C_H #define LCD2004_I2C_H //---------------------------------------------------------- #include <avr_cmsis.h> #include <driver_h\i2c.h> // TWI драйвер #include <util/delay.h> #include <avr/pgmspace.h> //--------------------------------------------------------------- //*************************************************************** // * // Настройки экрана по-умолчанию * // * //*************************************************************** // адрес экрана (PCF8574 - 0b0100xxx;PCF8574A - 0b0111xxx) * #define Addres_lcd 0b0111111 // * //--------------------------------------------------------------* // Сдвиг экрана * #define Shift_Disp 0 // отключен * //--------------------------------------------------------------* // Смещение курсора при записи символа * #define Shift_Curr 1 // включен * //--------------------------------------------------------------* // Курсор мигающий * #define Blink 0 // 0-отключен/1-включен * //--------------------------------------------------------------* // Курсор _ * #define Cursor 0 // 0-отключен/1-включен * //--------------------------------------------------------------* // Дисплей * #define Display 1 // 0-отключен/1-включен * //--------------------------------------------------------------* // Шрифт: * #define Font 0 // 5*7px * //--------------------------------------------------------------* // кол-во строк: * #define Lines 1 // 1-2_строки * //--------------------------------------------------------------* // Программная задержка для Lcd_clear() * #define delay_lcd_clear() _delay_ms(1600) // * //*************************************************************** //*************************************************************** // * // Структура для настройки дисплея * // * //--------------------------------------------------------------* typedef union // * { // * struct // * { // * uint8_t shift_disp:1;// Одновременный сдвиг экрана при записи * // символа запрещен=0/разрешен=1 * uint8_t shift_curr:1;// смещение курсора при записи символа * // влево=0/вправо=1 * //--------------------------------------------------------------* uint8_t blink: 1; // Курсор мигающий выключить=0/включить=1 * uint8_t cursor: 1; // Курсор _ выключить=0/включить=1 * uint8_t display:1; // Дисплей выключить=0/включить=1 * //--------------------------------------------------------------* uint8_t font: 1; // Шрифт: 5*7px=0/5*10px=1 * uint8_t lines: 1; // кол-во строк: 1строка=0/2строки=1 * uint8_t bits: 1; // Разряд шины: 4бит=0/8бит=1 * }; // * uint8_t set; // доступ к целому регистру * }SetLCD_t; // * //*************************************************************** //*************************************************************** // * // Описание функций для работы с экраном по-умолчанию * // * //--------------------------------------------------------------* // Инициализация экрана по-умолчанию * #define Init_lcd_def() Init_LCD(Addres_lcd) // * //--------------------------------------------------------------* // Загрузить настройки в экрана * #define Setting_LCD_def(set) setting_lcd(Addres_lcd, set) // * //--------------------------------------------------------------* // Переместить курсор в позиция х-у * #define GoTo(x,y) CursorGoTo(Addres_lcd,x,y) // * //--------------------------------------------------------------* // Очистить экран * #define Lcd_clear() LCD_clear(Addres_lcd) // * //--------------------------------------------------------------* // Дисплей Включить/выключить * void Lcd_Display(void); // * //--------------------------------------------------------------* // Нижнее подчеркивание Включить/выключить * void Cursor_underline(void); // * //--------------------------------------------------------------* // Курсор подчеркнутый Мигание курсора * void Cursor_blink(void); // Включить/выключить * //--------------------------------------------------------------* // Подстветка включить/выключить * void BackLight(void); // * //--------------------------------------------------------------* // Вывод строки из RAM * #define Lcd_SendString(string) LCD_SendString(Addres_lcd, string)//* //--------------------------------------------------------------* // Вывод строки из ROM * // prog_char string[]="ALEKSEY" * #define Lcd_SendStringFlash(string) LCD_SendStringFlash(Addres_lcd, string) //*************************************************************** //*************************************************************** // * // Описание функций для работы с экраном * // * //--------------------------------------------------------------* // Инициализация экрана по адресу SetLCD_t Init_LCD(uint8_t add_lcd); //--------------------------------------------------------------* // Полная очистка экрана void LCD_clear(uint8_t add_lcd); //--------------------------------------------------------------* void setting_lcd(uint8_t add_lcd, SetLCD_t SetLCD); //--------------------------------------------------------------* // Переход курсора по экрану: х-строки; у-столбцы * void CursorGoTo(uint8_t add_lcd, uint8_t x, uint8_t y); // * //--------------------------------------------------------------* // Отправка данных из RAM Памяти * // Результат функции успех передачи данных Успех-1/Провал-0 * void LCD_SendString(uint8_t addres_lcd, char *str); // * //--------------------------------------------------------------* // Отправка данных из Flash Памяти * void LCD_SendStringFlash(uint8_t addres_lcd, prog_char *str);//* //*************************************************************** #endif
#include <sys/types.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <unistd.h> unsigned int MakeSocket(void); int ConnectToServer(struct sockaddr_in* server_address, char* _ip, unsigned int _port, int _socketFD); void DataTransferWithServer(unsigned int _numOfTransfers, unsigned int _socketFD, char* _massage); void CloseConnectWithServer(unsigned int _socketFD);
/* * Ex2_Factorial_Recursion.c * * Created on: Jul 14, 2021 * Author: Arsany */ #include "stdio.h" int findFactorial(int x); void main() { int a; printf("Enter an positive integer: "); fflush(stdin); fflush(stdout); scanf("%d",&a); printf("Factorial of %d = %d",a,findFactorial(a)); } int findFactorial(int x) { if(x==0||x==1) return 1; else return x*findFactorial(x-1); }
//LCD_Operate.c #include <iom128v.h> #include <macros.h> #include "LCD_Operate.h" #include "USART_Operate.h" //LCD测忙 unsigned char LCD_Busy(void) { if(lcd_busy) return 1; else return 0; } //LCD用color颜色清屏 void LCD_Clear_Screen(unsigned char *color) { GpuSend("CLS("); GpuSend(color); GpuSend(");\r\n"); } //LCD设置亮度0-100 void LCD_Set_Brightness(unsigned char *brightness) { GpuSend("SEBL("); GpuSend(brightness); GpuSend(");\r\n"); } //设备初始化页面 void LCD_Init_Devices(void) { GpuSend("DR0;"); GpuSend("CLS(15);"); GpuSend("SBC(15);"); GpuSend("DS32(14,50,'设备初始化中',0);"); GpuSend("DS32(60,90,'请稍候...',0);"); GpuSend("\r\n"); GpuSend("\r\n"); } //待机页面 void LCD_Standby(void) { GpuSend("CLS(15);"); GpuSend("SBC(15);"); GpuSend("DS32(30,20,'请按下指纹',0);"); GpuSend("DS24(26,60,'或输入学号密码',0);"); GpuSend("CBOX(40,100,180,120,0,0);"); GpuSend("DS12(44,105,'学号为8位数字',14);"); GpuSend("CBOX(40,130,180,150,0,0);"); GpuSend("DS12(44,135,'初始密码与学号相同',14);"); GpuSend("\r\n"); } //输入页面 void LCD_input(void) { GpuSend("CLS(15);"); GpuSend("SBC(15);"); GpuSend("DS32(30,20,'请按下指纹',0);"); GpuSend("DS24(26,60,'或输入学号密码',0);"); GpuSend("CBOX(40,100,180,120,0,0);"); GpuSend("CBOX(40,130,180,150,0,0);"); GpuSend("\r\n"); } //指纹错误页面 void LCD_fingerprint_wrong(void) { GpuSend("CLS(15);"); GpuSend("SBC(15);"); GpuSend("DS32(14,20,'指纹输入错误',0);"); GpuSend("DS24(14,60,'请用学号密码进入',0);"); GpuSend("CBOX(40,100,180,120,0,0);"); GpuSend("DS12(44,105,'学号为8位数字',14);"); GpuSend("CBOX(40,130,180,150,0,0);"); GpuSend("DS12(44,135,'初始密码与学号相同',14);"); GpuSend("\r\n"); } //注册指纹 void LCD_sign_up(void) { GpuSend("CLS(15);"); GpuSend("SBC(15);"); GpuSend("DS32(30,72,'请按下指纹',0);"); GpuSend("\r\n"); }
#include<stdio.h> #include "main.h" Student record; void insert_data(){ int n; printf("Enter the Number of student of student data you would like to enter: "); scanf("%d",&n); for(int i=0;i<n;i++){ printf("\nname: "); scanf("%[^\n]s",&record.name[i]); printf("\nemail: "); scanf("%[^\n]s",record.email); printf("\nRoll Number: "); scanf("%d",&record.roll); printf("\nDepartment(cse): "); scanf("%s",record.dept); printf("\nCGPA: "); scanf("%f",&record.cgpa); printf("\nCurrent Year: "); scanf("%d",&record.year); printf("\nYear of Passing: "); scanf("%d",&record.batch); printf("\nFee(y:Yes/ n:No): "); scanf("%c", &record.fee); } } int main(void){ insert_data(); printf("%s,%s,%d,%s,%f,%d,%d,%c", record.name,record.email,record.roll,record.dept,record.cgpa,record.year,record.batch,record.fee); return 0; }
#include <jos/x86.h> #include <jos/mmu.h> #include <jos/error.h> #include <jos/string.h> #include <jos/assert.h> #include <jos/elf.h> #include <jos/env.h> #include <jos/pmap.h> #define RELOC(x) ((x)-KERNBASE) #define ENVGENSHIFT 12 #include <jos/env.h> #include "x86/cpu.h" #include "list.h" #include "system.h" #include "string.h" ListHead block,ready; //#include <kern/pmap.h> //#include <kern/trap.h> //#include <kern/monitor.h> extern void printk(const char*,...); extern void env_init_percpu(void); //struct Env ENV[NENV]; struct Env* envs; struct Env* curenv =NULL; static struct Env *env_free_list; void region_alloc(pde_t*,void*,size_t); struct PageInfo* page_alloc(int); // void set_tss(); struct Segdesc gdt[] = { // 0x0 - unused (always faults -- for trapping NULL far pointers) [0] = SEG_NULL , //[1 >> 3] = SEG_NULL,//SEG(STA_X | STA_R, 0x0, 0xffffffff, 0), //[2 >> 3] = SEG_NULL,//SEG(STA_W, 0x0, 0xffffffff, 0), // 0x8 - kernel code segment [GD_KT >> 3] = SEG(STA_X | STA_R, 0x0, 0xffffffff, 0), // 0x10 - kernel data segment [GD_KD >> 3] = SEG(STA_W, 0x0, 0xffffffff, 0), // 0x18 - user code segment [GD_UT >> 3] = SEG(STA_X | STA_R, 0x0, 0xffffffff, 3), // 0x20 - user data segment [GD_UD >> 3] = SEG(STA_W, 0x0, 0xffffffff, 3), // 0x28 - tss, initialized in trap_init_percpu() [GD_TSS0 >> 3] = SEG_NULL }; struct Pseudodesc gdt_pd = { sizeof(gdt) - 1, (unsigned long) gdt }; void env_init(){ //set_tss(); //printk("asdf\n"); printk("%d\n",NENV); for(int i=NENV-1;i>=0;i--){ envs[i].env_id=0; envs[i].env_parent_id=0; envs[i].env_type=ENV_TYPE_IDLE; envs[i].env_status=0; envs[i].env_runs=0; envs[i].env_pgdir=NULL; envs[i].env_link = env_free_list; envs[i].fcnt=0; env_free_list = &envs[i]; //envs[i] } //envs[NENV-1].env_status=ENV_RUNNABLE; curenv=&envs[NENV-1]; //env_free_list=envs[0].env_link; //printk("asdf\n"); env_init_percpu(); set_tss(); printk("%x\n",env_free_list); printk("%x\n",envs); list_init(&block); list_init(&ready); } void env_init_percpu(void) { lgdt(&gdt_pd); // The kernel never uses GS or FS, so we leave those set to // the user data segment. asm volatile("movw %%ax,%%gs" :: "a" (GD_UD|3)); asm volatile("movw %%ax,%%fs" :: "a" (GD_UD|3)); // The kernel does use ES, DS, and SS. We'll change between // the kernel and user data segments as needed. asm volatile("movw %%ax,%%es" :: "a" (GD_KD)); asm volatile("movw %%ax,%%ds" :: "a" (GD_KD)); asm volatile("movw %%ax,%%ss" :: "a" (GD_KD)); // Load the kernel text segment into CS. asm volatile("ljmp %0,$1f\n 1:\n" :: "i" (GD_KT)); // For good measure, clear the local descriptor table (LDT), // since we don't use it. lldt(0); } static int env_setup_vm(struct Env *e) { struct PageInfo *p = NULL; // Allocate a page for the page directory if (!(p = page_alloc(ALLOC_ZERO))) return -E_NO_MEM; // Now, set e->env_pgdir and initialize the page directory. // // Hint: // - The VA space of all envs is identical above UTOP // (except at UVPT, which we've set below). // See inc/memlayout.h for permissions and layout. // Can you use kern_pgdir as a template? Hint: Yes. // (Make sure you got the permissions right in Lab 2.) // - The initial VA below UTOP is empty. // - You do not need to make any more calls to page_alloc. // - Note: In general, pp_ref is not maintained for // physical pages mapped only above UTOP, but env_pgdir // is an exception -- you need to increment env_pgdir's // pp_ref for env_free to work correctly. // - The functions in kern/pmap.h are handy. // LAB 3: Your code here. e->env_pgdir = page2kva(p); p->pp_ref++; memcpy(e->env_pgdir,kern_pgdir,PGSIZE); // UVPT maps the env's own page table read-only. // Permissions: kernel R, user R e->env_pgdir[PDX(UVPT)] = PADDR(e->env_pgdir) | PTE_P | PTE_U; return 0; } void set_tf(struct Env* e) { memset(&e->env_tf, 0, sizeof(e->env_tf)); e->env_tf.ds = GD_UD | 3; e->env_tf.es = GD_UD | 3; e->env_tf.ss = GD_UD | 3; e->env_tf.esp = USTACKTOP; e->env_tf.cs = GD_UT | 3; e->env_tf.eflags=0x202; //e->env_tf.eflags=0x0; } int env_alloc(struct Env **newenv_store, envid_t parent_id) { int32_t generation; int r; struct Env *e; if (!(e = env_free_list)) return -E_NO_FREE_ENV; if ((r = env_setup_vm(e)) < 0) return r; generation = (e->env_id + (1 << ENVGENSHIFT)) & ~(NENV - 1); if (generation <= 0) // Don't create a negative env_id. generation = 1 << ENVGENSHIFT; e->env_id = generation | (e - envs); e->env_parent_id = parent_id; e->env_type = ENV_TYPE_USER; e->env_status = ENV_RUNNABLE; e->env_runs = 0; set_tf(e); // You will set e->env_tf.tf_eip later. // commit the allocation env_free_list = e->env_link; *newenv_store = e; // printk("hahahahahahahahahahaha\n"); // printk("[%08x] new env %08x\n", curenv ? curenv->env_id : 0, e->env_id); return 0; } uint32_t bootmain2(pde_t* pgdir); uint32_t bootmain(pde_t* pgdir,int); void region_alloc(pde_t*,void*,size_t); void env_pop_tf(struct TrapFrame *tf) { // printk("really?\n"); asm volatile("movl %0,%%esp\n" "\tpopal\n" "\tpopl %%es\n" "\tpopl %%ds\n" "\taddl $8,%%esp\n" /* skip tf_trapno and tf_errcode */ "\tiret" : : "r" (tf) : "memory"); //panic("iret failed"); /* mostly to placate the compiler */ //printk("iret fail\n"); while(1); } static void load_icode(struct Env *e,int fd) { lcr3(PADDR(e->env_pgdir)); e->env_tf.eip=bootmain(e->env_pgdir,fd); lcr3(PADDR(kern_pgdir)); } struct Env* env_create(int fd) { struct Env* env; env_alloc(&env,0); load_icode(env,fd); return env; } void env_run(struct Env *e) { if(curenv && curenv->env_status==ENV_RUNNING) curenv->env_status=ENV_RUNNABLE; // printk("running\n"); if(curenv!=e) { // printk("swich\n"); // printk("%x\n",e->env_tf.eip); curenv = e; //curenv->env_tf.eip=0x804824b; //printk("%x\n",curenv->env_tf.eip); e->env_status=ENV_RUNNING; e->env_runs++; // set_tss(); lcr3(PADDR(e->env_pgdir)); } else curenv=e,curenv->env_status=ENV_RUNNING; //printk("afff%x\n",curenv->env_tf.eip); env_pop_tf(&e->env_tf); } void env_run2(struct Env *e) { if(curenv && curenv->env_status==ENV_RUNNING) curenv->env_status=ENV_RUNNABLE; // printk("running\n"); if(curenv!=e) { // printk("swich\n"); // printk("%x\n",e->env_tf.eip); curenv = e; //curenv->env_tf.eip=0x804824b; //printk("%x\n",curenv->env_tf.eip); e->env_status=ENV_RUNNING; e->env_runs++; // set_tss(); lcr3(PADDR(e->env_pgdir)); } else curenv=e,curenv->env_status=ENV_RUNNING; //printk("%x\n",curenv->env_tf.eip); ((void(*)(void))curenv->env_tf.eip)(); //printk("%x\n",curenv->env_tf.eip); env_pop_tf(&e->env_tf); } static struct Taskstate ts; extern char bootstacktop[]; extern char bootstack[]; void set_tss() { ts.ts_esp0 =(uint32_t) (bootstacktop); ts.ts_ss0 = GD_KD; gdt[GD_TSS0 >> 3] = (struct Segdesc)SEG16(STS_T32A,(uint32_t) (&ts),sizeof(struct Taskstate), 0); gdt[GD_TSS0 >> 3].sd_s = 0; ltr(GD_TSS0); } void env_free(struct Env *e) { pte_t *pt; uint32_t pdeno, pteno; physaddr_t pa; // If freeing the current environment, switch to kern_pgdir // before freeing the page directory, just in case the page // gets reused. if (e == curenv) lcr3(PADDR(kern_pgdir)); // Note the environment's demise. printk("[%08x] free env %08x\n", curenv ? curenv->env_id : 0, e->env_id); // Flush all mapped pages in the user portion of the address space static_assert(UTOP % PTSIZE == 0); for (pdeno = 0; pdeno < PDX(UTOP); pdeno++) { if(!(e->env_pgdir[pdeno] & PTE_P)||(kern_pgdir[pdeno]&PTE_P)) continue; // only look at mapped page tables // if (!(e->env_pgdir[pdeno] & PTE_P)) // continue; // find the pa and va of the page table pa = PTE_ADDR(e->env_pgdir[pdeno]); pt = (pte_t*) KADDR(pa); // unmap all PTEs in this page table for (pteno = 0; pteno <= PTX(~0); pteno++) { if (pt[pteno] & PTE_P) page_remove(e->env_pgdir, PGADDR(pdeno, pteno, 0)); } // free the page table itself e->env_pgdir[pdeno] = 0; page_decref(pa2page(pa)); } // free the page directory pa = PADDR(e->env_pgdir); e->env_pgdir = 0; page_decref(pa2page(pa)); // return the environment to the free list e->env_status = ENV_FREE; e->env_link = env_free_list; env_free_list = e; } int fork() { // printk("fork start\n"); // printk("%d\n",curenv->env_parent_id); envid_t parent_id=curenv->env_id; struct Env *e=NULL; int flag=env_alloc(&e,parent_id); if(flag!=0) { printk("flag=0\n"); while(1); //assert(0); } int i,j; for(i=0;i<1024;i++) { if(!(e->env_pgdir[i]&PTE_P) && (curenv->env_pgdir[i]&PTE_P)) { pte_t *pte=(pte_t*)page2kva(pa2page(curenv->env_pgdir[i])); for(j=0;j<1024;j++) { if(pte[j]) { struct PageInfo *pp=page_alloc(1); page_insert(e->env_pgdir,pp,(void*)((i<<22)|(j<<12)),PTE_U|PTE_W); // printk("%x\n",pp); memcpy((void *)page2kva(pp),(void *)page2kva(pa2page(pte[j])),4096); } } } } e->env_tf=curenv->env_tf; // printk("%x\n",curenv->env_tf.eip); // printk("%d\n",curenv->env_id); e->env_tf.eax=0; /* for(i=0;i<NENV;i++) if(envs[i].env_status==ENV_RUNNING) printk("%d ",i); printk("\n"); for(i=0;i<NENV;i++) if(envs[i].env_status==ENV_RUNNABLE) printk("%d ",i); printk("\n"); */ // printk("fork end\n"); return e->env_id; } struct Env* seek_next() { // return NULL; // if(curenv==NULL) return NULL; struct Env* e; e=curenv; // if(curenv->env_status==ENV_RUNNING) // curenv->env_status=ENV_RUNNABLE; //struct Env* temp=NULL; int i; for(i=0;i<=NENV+1;i++) { //if(e->env_id==0) continue if(e==&envs[NENV-1]) //if(e-envs==NENV-1) e=envs; else e++; if(e==curenv) continue; // if(e->env_id==0) continue; // if(e->env_status==ENV_SLEEP) // e->sleep_time--; // if(e->sleep_time==0) // e->env_status=ENV_RUNNABLE; if(e->env_status==ENV_RUNNABLE) // if(temp==NULL)temp=e; return e; } // if(temp==NULL) return curenv; return NULL; } void env_sleep(struct Env *e,int sec) { e->env_status=ENV_SLEEP; e->sleep_time=sec; struct Env* next=seek_next(); if(next!=NULL) env_run(next); else { printk("nothing more to do\n"); while(1); } } void env_exit(struct Env*e) { env_free(e); struct Env* next=seek_next(); if(next==NULL) { printk("nothing more to do\n"); while(1); } else { printk("env_exit\n"); printk("%d\n",e->env_id); printk("%d\n",next->env_id); if(next!=NULL)env_run(next); } } extern void i386_init(); extern void monitor(); volatile int tick=0; #define INTERVAL 10 extern int kbd_proc_data(); /*void timer_event() { //printk("1\n"); tick++; }*/ void timer_event(void) { //while(1); tick++; int i; int flag=0; kbd_proc_data(); for(i=0;i<NENV-1;i++) { struct Env*e=&envs[i]; if(e->env_status==ENV_RUNNING||e->env_status==ENV_RUNNABLE) flag=1; if(e->env_status==ENV_SLEEP) { flag=1; e->sleep_time--; // printk("here\n"); // while(1); if(e->sleep_time==0) e->env_status=ENV_RUNNABLE; } } //printk("timer event\n"); if(tick%INTERVAL) //if(1) { struct Env* e=seek_next(); //printk("im not here\n"); // printk("%d %d\n",e->env_id,curenv->env_id); if(/*e==&envs[NENV-1] && e!=curenv&& */flag==0) { curenv=&envs[NENV-1]; monitor(NULL); //printk("1\n"); } else if(e!=NULL && e!=curenv&& e!=&envs[NENV-1]) {env_run(e);} } // else printk("null\n"); /* if(tick==1000) { // env_exit(curenv); // printk("fork\n"); } */ //if(e!=NULL) env_run(e); if(!flag) { curenv=&envs[NENV-1]; monitor(NULL); //printk("nothing more to do\n"); // while(1); } } int envid2index(int envid) { int i=0; for(i=0;i<NENV;i++) if(envs[i].env_id==envid) return i; return -1; } int fork2(void *thread) { envid_t parent_id=curenv->env_id; struct Env *e=NULL; int flag=env_alloc(&e,parent_id); if(flag!=0) { printk("flag=0\n"); while(1); } int i; for(i=0;i<1024;i++) e->env_pgdir[i]=curenv->env_pgdir[i]; int id=envid2index(parent_id); e->env_type=ENV_TYPE_THREAD; e->env_tf.esp=envs[id].env_tf.esp-PGSIZE*(++envs[id].thread_num); e->env_tf.eip=(uint32_t)thread; return e->env_id; } extern void monitor(struct Trapframe *tf); void thread_exit() { //uint32_t pa=PADDR(curenv->env_pgdir); //curenv->env_pgdir=0; //page_decref(pa2page(pa)); curenv->env_status=ENV_FREE; //curenv->env_status=ENV_NOT_RUNNABLE; //curenv->env_link=env_free_list; //envs[curenv->env_parent_id].thread_num--; //env_free_list=curenv; monitor(NULL); }
/** * Created by Freddie Rice * Main file for the parallel practice */ /* Includes */ #include "config.h" int main() { return 0; }
/*++ Copyright (C) Microsoft. All rights reserved. Module Name: memutils.c Abstract: Implementation of the Boot Environment Library's memory management APIs for the initialization and destruction of the library's memory manager. Environment: Boot --*/ // ------------------------------------------------------------------- Includes #include "mm.h" // -------------------------------------------------------------------- Globals VA_TRANSLATION_TYPE MmTranslationType = VA_TRANSLATION_TYPE_MAX; #if defined(BOOTENV_MEMORY_CHECK) #define MC_DEFAULT_VALIDATE_COUNT 100 ULONG McpCriticalInterfaceCount = 0; ULONG McpInterfaceCount = 0; ULONG McpValidateCount = MC_DEFAULT_VALIDATE_COUNT; #endif // ----------------------------------------------------------------- Prototypes NTSTATUS MmpFreeApplicationAllocations ( VOID ); NTSTATUS MmpFreeLibraryAllocations ( VOID ); // ------------------------------------------------------------------ Functions NTSTATUS BlpMmInitialize ( __in PALLOCATED_MEMORY AllocatedMemory, __in VA_TRANSLATION_TYPE CurrentTranslationType, __in PLIBRARY_PARAMETERS Parameters ) /*++ Routine Description: Initializes the Boot Environment Library's memory subsystem. This process includes the initialization of the page and heap allocators as well as performing any steps required to enable virtual address translation. Arguments: AllocatedMemory - Supplies the list of memory currently allocated by previous boot applications. CurrentTranslationType - Supplies the address translation mode of the calling boot application. Parameters - Supplies application-supplied parameters for configuring the boot library. This contains tuning values for the page allocator and heap allocator as well as the type of virtual address translation the boot application should use. Return Value: STATUS_SUCCESS when successful. STATUS_NO_MEMORY if allocation made for initialization failed. STATUS_INVALID_PARAMETER if there is an error creating the allocated memory descriptor list based on the list the caller provided or if current translation type is invalid. --*/ { NTSTATUS Status; BlpInterfaceEnter(InterfaceMm); // // Any routine that can result in the allocation of a global memory // descriptor, needs to announce its execution. First initialize // the state that this function uses, and then call it. // MmDescriptorCallTreeCount = 0; MmEnterDescriptorLibraryApi(); // // N.B. If the previous boot application was executing with virtual // address translation enabled, then the input parameter were // mapped and could be referenced. If not, then the current boot // application is not currently executing with address translation // enabled and the input parameters can still be referenced. // if ((VA_TRANSLATION_TYPE_MAX <= CurrentTranslationType) || (VA_TRANSLATION_TYPE_MAX <= Parameters->TranslationType)) { Status = STATUS_INVALID_PARAMETER; goto BlMmInitializeEnd; } // // Initialize global static memory descriptors. // MmMdInitialize(0, Parameters); // // Perform any required architecture initialization before either // the heap or page allocator are initialized. // Status = MmArchInitialize(0, AllocatedMemory, CurrentTranslationType, Parameters->TranslationType); if (!NT_SUCCESS(Status)) { goto BlMmInitializeEnd; } // // Initialize the Page Allocator. // Status = MmPaInitialize(AllocatedMemory, Parameters->MinimumPageAllocation); if (!NT_SUCCESS(Status)) { goto BlMmInitializePaInitFailure; } // // Remove any bad memory from the system memory map. // // N.B. If the bad page list is fragmented, or large, removing bad // memory from the system can cause a large spike in memory // descriptor usage. Therefore it's best to do this after switching // to dynamic descriptors, although it does result in a // *slightly* increased probability of boot allocations conflicting // with bad memory. But this situation is unavoidable since the // firmware might have already loaded the boot manager into bad // memory to begin with. // BlMmRemoveBadMemory(); // // Initialize the structures for tracking virtual address usage. // #if !defined(MM_MIN) Status = MmTrInitialize(); if (!NT_SUCCESS(Status)) { goto BlMmInitializeTrInitFailure; } #endif // // Turn on virtual address translation. This routine will additionally // map the boot application one to one. // // N.B. This must be done after the page allocator has been // initialized since physical pages may need to be allocated for // platform paging structures. // // During Phase 1, MmArchInitialize will virtually map regions from // the previously allocated memory regions, some of which may be deferred // until phase 2. // Status = MmArchInitialize(1, AllocatedMemory, CurrentTranslationType, Parameters->TranslationType); if (!NT_SUCCESS(Status)) { goto BlMmInitializeArch1InitFailure; } // // Save the type of address translation in a global variable. This // is useful for determining if we can forward any MM API requests // based on translation type. This is commonly used by the Page Allocator. // For example, a BlMmAllocatePages request will be forwarded to // BlMmAllocatePhysicalPages if address translation is not enabled. // MmTranslationType = Parameters->TranslationType; // // Initialize the Heap Allocator. // Status = MmHaInitialize(Parameters->MinimumHeapSize, Parameters->HeapAllocationAttributes); if (!NT_SUCCESS(Status)) { goto BlMmInitializeHaInitFailure; } // // Initialize dynamic memory descriptors if needed by the application. // MmMdInitialize(1, Parameters); // // During Phase 2, virtual mappings for any regions that were deferred // will be established. The virtual mapping may be deferred for some regions // due to small amount of fixed memory descriptors available prior to // dynamic memory descriptors being initialized. // Status = MmArchInitialize(2, AllocatedMemory, CurrentTranslationType, Parameters->TranslationType); if (!NT_SUCCESS(Status)) { goto BlMmInitializeArch2InitFailure; } // // Initialize the block memory allocator. // Status = MmBaInitialize(); if (!NT_SUCCESS(Status)) { goto BlMmInitializeBaInitFailure; } goto BlMmInitializeEnd; BlMmInitializeBaInitFailure: BlMmInitializeArch2InitFailure: MmMdDestroy(); MmHaDestroy(); BlMmInitializeHaInitFailure: BlMmInitializeArch1InitFailure: MmPaDestroy(0); #if !defined(MM_MIN) MmTrDestroy(); BlMmInitializeTrInitFailure: #endif MmArchDestroy(); MmPaDestroy(1); BlMmInitializePaInitFailure: // // Free the global memory descriptors consumed during initialization. // BlMmInitializeEnd: MmLeaveDescriptorLibraryApi(); BlpInterfaceExit(InterfaceMm); return Status; } NTSTATUS BlpMmDestroy ( __in ULONG Phase ) /*++ Routine Description: Destruction routine for the Boot Environment Library's memory management subsystem. All initialization and allocations made by the library are undone. Arguments: Phase - Supplies the destruction phase. Return Value: STATUS_SUCCESS when successful. STATUS_NO_MEMORY if descriptors could not be copied to the global scratch array. Other failure status codes possible depending on firmware implementation of destroy routine. --*/ { NTSTATUS ReturnStatus; NTSTATUS Status; BlpInterfaceEnter(InterfaceMm); ReturnStatus = STATUS_SUCCESS; // // In the first phase of library destruction, free all application // allocations. During the second phase of destruction, destroy library // allocations and restore the memory context of the calling application. // switch (Phase) { case 0: #if !defined(NTKERNEL) Status = MmpFreeApplicationAllocations(); if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } #endif !defined(NTKERNEL) break; case 1: // // Destroy the block memory allocator. // Status = MmBaDestroy(); if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } // // Free any outstanding library allocations that do not have the // library late free attribute set. // #if !defined(NTKERNEL) Status = MmpFreeLibraryAllocations(); if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } #endif !defined(NTKERNEL) // // Perform dynamic descriptor buffer destruction if required. // N.B. This must be done before the heap is destroyed. // Status = MmMdDestroy(); if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } // // Free the heap allocator. It is not important to free the actual // pages allocated for the heap since the page allocator will reclaim // them when destroying itself. However, it is important that the heap // allocator update it's internal status. // Status = MmHaDestroy(); if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } // // Free all virtual memory allocations. // Status = MmPaDestroy(0); if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } // // Release the database of active virtual mappings tracked by the // translation subcomponent. The database includes virtual mappings for // the page allocator allocations freed above. // #if !defined(MM_MIN) Status = MmTrDestroy(); if (!NT_SUCCESS(Status)) { return Status; } #endif // // Restore the memory context of the calling application. // Status = MmArchDestroy(); if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } // // Free all physical memory allocations, including the page tables. // Status = MmPaDestroy(1); if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } break; default: ASSERT(FALSE); ReturnStatus = STATUS_INVALID_PARAMETER; } BlpInterfaceExit(InterfaceMm); return ReturnStatus; } ULONG_PTR BlMmGetKsegBase ( VOID ) /*++ Routine Description: Returns the base address of kernel address space. Arguments: None. Return Value: When address translation is disabled, zero is returned. When address translation is enabled, the following is returned: KSEG0_BASE on AMD64. KSEG0_BASE or ALTERNATE_BASE on X86, depending on the presence of /3GB in the boot application's options. --*/ { BlpInterfaceEnter(InterfaceMm); BlpInterfaceExit(InterfaceMm); return MmArchKsegBase; } ULONG_PTR BlMmGetKsegBias ( VOID ) /*++ Routine Description: Returns the ASLR bias to the base address of kernel address space. Arguments: None. Return Value: When address translation is disabled, zero is returned. When address translation is enabled, the ASLR KSEG0 base bias is returned. --*/ { BlpInterfaceEnter(InterfaceMm); BlpInterfaceExit(InterfaceMm); return MmArchKsegBias; } MEMORY_TYPE MmFwpGetOsMemoryType ( __in EFI_MEMORY_TYPE EfiMemoryType, __in ULONGLONG EfiMemoryAttributes ) /*++ Routine Description: Maps an EFI Memory Type to an OS defined memory type. Arguments: EfiMemoryType - Efi memory type to convert. EfiMemoryAttributes - Efi memory attribute for the memory type. Return Value: OS defined memory type. --*/ { MEMORY_TYPE MemoryType; UNREFERENCED_PARAMETER(EfiMemoryAttributes); switch (EfiMemoryType) { case EfiReservedMemoryType: MemoryType = MEMORY_TYPE_PLATFORM_RESERVED; break; case EfiLoaderCode: case EfiLoaderData: MemoryType = MEMORY_TYPE_BOOT_APPLICATION; break; case EfiBootServicesCode: case EfiBootServicesData: MemoryType = MEMORY_TYPE_BOOT_SERVICE_CODE; break; case EfiRuntimeServicesCode: MemoryType = MEMORY_TYPE_RUNTIME_SERVICE_CODE; break; case EfiRuntimeServicesData: MemoryType = MEMORY_TYPE_RUNTIME_SERVICE_DATA; break; case EfiConventionalMemory: MemoryType = MEMORY_TYPE_FREE; break; case EfiUnusableMemory: MemoryType = MEMORY_TYPE_BAD; break; case EfiACPIReclaimMemory: MemoryType = MEMORY_TYPE_ACPI_TABLES; break; case EfiACPIMemoryNVS: MemoryType = MEMORY_TYPE_ACPI; break; case EfiMemoryMappedIO: MemoryType = MEMORY_TYPE_MMIO_SPACE; break; case EfiMemoryMappedIOPortSpace: MemoryType = MEMORY_TYPE_MMIO_PORT_SPACE; break; case EfiPalCode: MemoryType = MEMORY_TYPE_PAL_CODE; break; default: MemoryType = MEMORY_TYPE_PLATFORM_RESERVED; break; } return MemoryType; } // ------------------------------------------------------------------ Debug API NTSTATUS MmValidate ( VOID ) /*++ Routine Description: Attempts to validate both the Page Allocator and the Heap Allocator against internal data structure inconsistencies. Arguments: None. Return Value: STATUS_SUCCESS if successful or if validation is not possible in the current operating mode. STATUS_UNSUCCESSFUL if any inconsistencies are found in internal data structures for either the page allocator or the heap allocator. --*/ { NTSTATUS Status; // // When operating with address translation enabled, page allocator and // heap allocator structures are generally not accessible during periods // when address translation is off. This implies that we must exit // immediately without performing any validation if the current address // translation state does not match the one used when initializing the // memory manager. // if ((BlMmQueryTranslationType() != VA_TRANSLATION_TYPE_NONE) && (BlMmIsTranslationEnabled() == FALSE)) { Status = STATUS_SUCCESS; goto MmValidateEnd; } // // Hand off to the validation routines. // Status = MmPaValidate(); if (!NT_SUCCESS(Status)) { goto MmValidateEnd; } Status = MmHaValidate(); if (!NT_SUCCESS(Status)) { goto MmValidateEnd; } MmValidateEnd: return Status; } VOID BlpMcCriticalInterfaceEnter ( __in INTERFACE_NAME Name ) /*++ Routine Description: This routine will disable validation of memory manager internal data structures. This routine is called on the entrance to a time sensitive or critical interface. Arguments: Name - Supplies the API or API class which is starting. Return Value: None. --*/ { UNREFERENCED_PARAMETER(Name); #if defined(BOOTENV_MEMORY_CHECK) McpCriticalInterfaceCount += 1; #endif return; } VOID BlpMcCriticalInterfaceExit ( __in INTERFACE_NAME Name ) /*++ Routine Description: If there are no more outstanding critical regions, this routine will reenable the validation of memory manager internal data structures. This routine is called on the exit of a time sensitive or critical interface. Arguments: Name - Supplies the API or API class which is exiting. Return Value: None. --*/ { UNREFERENCED_PARAMETER(Name); #if defined(BOOTENV_MEMORY_CHECK) ASSERT(McpCriticalInterfaceCount != 0); McpCriticalInterfaceCount -= 1; #endif return; } VOID BlpMcInterfaceEnter ( __in INTERFACE_NAME Name ) /*++ Routine Description: Validates the internal data structures for the Boot Environment Library's memory manager. This routine is called on the entrance to a Boot Environment Library API or API class. Arguments: Name - Supplies the API or API class which is starting. Return Value: None. --*/ { UNREFERENCED_PARAMETER(Name); #if defined(BOOTENV_MEMORY_CHECK) if (McpCriticalInterfaceCount == 0) { McpInterfaceCount += 1; if (McpInterfaceCount >= McpValidateCount) { MmValidate(); McpInterfaceCount = 0; } } #endif return; } VOID BlpMcInterfaceExit ( __in INTERFACE_NAME Name ) /*++ Routine Description: Validates the internal data structures for the Boot Environment Library's memory manager. This routine is called on the exit of a Boot Environment Library API or API class. Arguments: Name - Supplies the API or API class which is exiting. Return Value: None. --*/ { UNREFERENCED_PARAMETER(Name); #if defined(BOOTENV_MEMORY_CHECK) if (McpCriticalInterfaceCount == 0) { McpInterfaceCount += 1; if (McpInterfaceCount >= McpValidateCount) { MmValidate(); McpInterfaceCount = 0; } } #endif return; } // --------------------------------------------------------- Internal Functions NTSTATUS MmpFreeApplicationAllocations ( VOID ) /*++ Routine Description: This routine will free memory allocated by a boot application. Arguments: None. Return Value: NT status code. --*/ { LIST_ENTRY AllocatedMemoryMap; ULONG AllocationFlags; GENERIC_BUFFER DescriptorBuffer; PMEMORY_DESCRIPTOR MemoryRange; PLIST_ENTRY NextEntry; PHYSICAL_ADDRESS PhysicalAddress; NTSTATUS ReturnStatus; NTSTATUS Status; UNPACKED_MEMORY_TYPE UnpackedMemoryType; PVOID VirtualAddress; ReturnStatus = STATUS_SUCCESS; // // Obtain a memory map of all allocated memory ranges. // AllocationFlags = MEMORYMAP_TYPE_MAPPED_ALLOCATED | MEMORYMAP_TYPE_UNMAPPED_ALLOCATED; BlInitGenericBuffer(&DescriptorBuffer, NULL, 0); Status = BlMmGetMemoryMap(&AllocatedMemoryMap, &DescriptorBuffer, AllocationFlags, MDL_FLAGS_ALLOCATE_DESCRIPTORS); if (!NT_SUCCESS(Status)) { return Status; } // // Walk the allocated memory map in search of allocations made by the boot // application. For each application allocation, free the the memory // range. // for (NextEntry = AllocatedMemoryMap.Flink; NextEntry != &AllocatedMemoryMap; NextEntry = NextEntry->Flink) { MemoryRange = CONTAINING_RECORD(NextEntry, MEMORY_DESCRIPTOR, ListEntry); UnpackedMemoryType.MemoryType = MemoryRange->MemoryType; if ((UnpackedMemoryType.Class != MEMORY_CLASS_APPLICATION) || (UnpackedMemoryType.SubType < MEMORY_APPLICATION_TYPE_DEFINABLE_START)) { continue; } if (MemoryRange->MappedBasePage != 0) { VirtualAddress = PAGE_TO_ADDRESS(MemoryRange->MappedBasePage); Status = BlMmFreePages(VirtualAddress); } else { PhysicalAddress.QuadPart = PAGE_TO_PHYSICAL_ADDRESS(MemoryRange->BasePage); Status = BlMmFreePhysicalPages(PhysicalAddress); } if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } } BlMmFreeHeap(DescriptorBuffer.Buffer); return ReturnStatus; } NTSTATUS MmpFreeLibraryAllocations ( VOID ) /*++ Routine Description: This routine will free memory allocated by the boot library. Arguments: None. Return Value: NT status code. --*/ { LIST_ENTRY AllocatedMemoryMap; ULONG AllocationFlags; ULONG AvoidLibraryFreeAttributes; GENERIC_BUFFER DescriptorBuffer; PMEMORY_DESCRIPTOR MemoryRange; PLIST_ENTRY NextEntry; PHYSICAL_ADDRESS PhysicalAddress; NTSTATUS ReturnStatus; NTSTATUS Status; UNPACKED_MEMORY_TYPE UnpackedMemoryType; PVOID VirtualAddress; ReturnStatus = STATUS_SUCCESS; // // During page allocator destruction the free page APIs will not zero // memory, therefore, since one of the goals of this routine is to make // sure that any outstanding library allocations are not left containing // sensitive data, insist that the page allocator is not in destruction. // ASSERT(MmPaModuleInitializationStatus() != ModuleInDestruction); // // Obtain a memory map of all allocated memory ranges. // AllocationFlags = MEMORYMAP_TYPE_MAPPED_ALLOCATED | MEMORYMAP_TYPE_UNMAPPED_ALLOCATED; BlInitGenericBuffer(&DescriptorBuffer, NULL, 0); Status = BlMmGetMemoryMap(&AllocatedMemoryMap, &DescriptorBuffer, AllocationFlags, MDL_FLAGS_ALLOCATE_DESCRIPTORS); if (!NT_SUCCESS(Status)) { return Status; } // // Walk the allocated memory map in search of allocations made by the boot // library. For each library allocation, free the the memory range. // for (NextEntry = AllocatedMemoryMap.Flink; NextEntry != &AllocatedMemoryMap; NextEntry = NextEntry->Flink) { MemoryRange = CONTAINING_RECORD(NextEntry, MEMORY_DESCRIPTOR, ListEntry); // // Don't free library allocations that have the library only free // or free last attributes as this could result in persistent data // getting zero'd, or prevent a clean shutdown of the library. // AvoidLibraryFreeAttributes = MEMORY_ATTRIBUTE_DESCRIPTION_LIBRARY_FREE_LAST | MEMORY_ATTRIBUTE_DESCRIPTION_LIBRARY_ONLY_FREE; UnpackedMemoryType.MemoryType = MemoryRange->MemoryType; if ((UnpackedMemoryType.Class != MEMORY_CLASS_LIBRARY) || ((MemoryRange->Attributes & AvoidLibraryFreeAttributes) != 0)) { continue; } if (MemoryRange->MappedBasePage != 0) { VirtualAddress = PAGE_TO_ADDRESS(MemoryRange->MappedBasePage); Status = BlMmFreePages(VirtualAddress); } else { PhysicalAddress.QuadPart = PAGE_TO_PHYSICAL_ADDRESS(MemoryRange->BasePage); Status = BlMmFreePhysicalPages(PhysicalAddress); } if (!NT_SUCCESS(Status)) { ReturnStatus = Status; } } BlMmFreeHeap(DescriptorBuffer.Buffer); return ReturnStatus; }
#include <assert.h> #include <lightning/types.h> #include <samplerate.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include "mem.h" #include "src.h" struct SRC { SRC_STATE *state; }; SRC SRC_init() { SRC src; NEW(src); /* initialize SRC_STATE */ int error; src->state = src_new(SRC_SINC_FASTEST, 1, &error); if (src->state == NULL) { fprintf(stderr, "Could not initialize sample rate converter: %s\n", src_strerror(error)); exit(EXIT_FAILURE); } return src; } int SRC_process(SRC src, double src_ratio, AudioData data, /* frames used from input buffers */ nframes_t *input_frames_used, /* frames generated in output buffers */ nframes_t *output_frames_gen, /* flag that will be set to non-zero if we exhaust the input buffer */ int *end) { assert(src); SRC_DATA src_data; int error; src_data.src_ratio = src_ratio; if (data.input_frames < data.output_frames) { src_data.end_of_input = 1; *end = 1; } else { src_data.end_of_input = 0; *end = 0; } /* convert audio data */ src_data.input_frames = data.input_frames; src_data.output_frames = data.output_frames; src_data.data_in = data.input; src_data.data_out = data.output; error = src_process(src->state, &src_data); if (error) { return error; } *input_frames_used = src_data.input_frames_used; *output_frames_gen = src_data.output_frames_gen; if (*output_frames_gen == 0 && src_data.end_of_input) { *end = 1; } else { *end = 0; } return 0; } const char * SRC_strerror(int error) { return src_strerror(error); } void SRC_free(SRC *src) { assert(src && *src); src_delete((*src)->state); FREE(*src); }
/* ** verbose.h for raytracer in /home/le-mai_s/recode/TP/raytracer1/Raytracer/include ** ** Made by sebastien le-maire ** Login <le-mai_s@epitech.net> ** ** Started on Fri Oct 23 11:41:43 2015 sebastien le-maire ** Last update Sun Oct 25 00:01:08 2015 sebastien le-maire */ #ifndef VERBOSE_H_ # define VERBOSE_H_ /* ** Verbose error mlx */ # define MSG_ERR_INIT_MSDL "Error: initialisation of minisdl failed !\n" /* ** Verbose param */ # define MSG_ERR_NB_ARG "Usage: ./rt file\n" /* ** Verbose malloc */ # define MSG_ERR_MALLOC "Error: allocation of memory failed !\n" /* ** Verbose parsing */ # define MSG_ERR_OPEN "Error: Open of file failed !\n" # define MSG_ERR_SPOT "=> initialisation of spot failed !\n" # define MSG_ERR_EYES "=> initialisation of eyes failed !\n" # define MSG_ERR_OBJS "=> initialisation of object failed !\n" # define MSG_ERR_POS "Error: Possition [x] [y] [z]\n" # define MSG_ERR_ROT "Error: Rotation [x] [y] [z]\n" # define MSG_ERR_COL "Error: Color is missing\n" # define MSG_ERR_OBJ_NOT_FOUND "Error: Object not found !\n" # define MSG_ERR_NB_PARAM_OBJ "Error: Object incomplete !\n" # define MSG_ERR_NB_COL_OBJS "Error: Color [color one] [color two]\n" # define MSG_ERR_PARAM_OBJ "Error: Param is positive numbers !\n" # define MSG_ERR_NB_LIM_OBJS "Error: limits [min] [max]!\n" # define MSG_ERR_SHINE "Error: Shine is missing\n" # define MSG_ERR_REFLECT "Error: Reflection is missing\n" # define MSG_ERR_REFRACT "Error: Refraction is missing\n" # define MSG_ERR_PROC "Error: procedural texture is missing\n" #endif /* !VERBOSE_H_ */
#ifndef lint static char sccsid[] = "@(#)eritio.c 1.9 (ULTRIX) 12/16/86"; #endif lint /* * .TITLE ERITIO - I/O for Event Record Input Transformer * .IDENT /1-001/ * * COPYRIGHT (C) 1985 DIGITAL EQUIPMENT CORP., * CSSE SOFTWARE ENGINEERING * MARLBOROUGH, MASSACHUSETTS * * THIS SOFTWARE IS FURNISHED UNDER A LICENSE FOR USE ONLY ON A * SINGLE COMPUTER SYSTEM AND MAY BE COPIED ONLY WITH THE INCLUSION * OF THE ABOVE COPYRIGHT NOTICE. THIS SOFTWARE, OR ANY OTHER * COPIES THEREOF, MAY NOT BE PROVIDED OR OTHERWISE MADE AVAILABLE * TO ANY OTHER PERSON EXCEPT FOR USE ON SUCH SYSTEM AND TO ONE WHO * AGREES TO THESE LICENSE TERMS. TITLE TO AND OWNERSHIP OF THE * SOFTWARE SHALL AT ALL TIMES REMAIN IN DEC. * * THE INFORMATION IN THIS SOFTWARE IS SUBJECT TO CHANGE WITHOUT * NOTICE AND SHOULD NOT BE CONSTRUED AS A COMMITMENT BY DIGITAL * EQUIPMENT CORPORATION. * * DEC ASSUMES NO RESPONSIBILITY FOR THE USE OR RELIABILITY OF{* ITS SOFTWARE ON EQUIPMENT WHICH IS NOT SUPPLIED BY DEC. * *++ * * FACILITY: [ FMA Software Tools - Detail Design ] * * ABSTRACT: * * This module contains the functions to open, close and read * raw system events from any operating system.{* * * ENVIRONMENT: ULTRIX-32 C * * AUTHOR: Luis Arce, CREATION DATE: 19-Nov-85 * * MODIFIED BY: * Bob Winant 12-31-85 * *-- */ #include <stdio.h> #include "erms.h" #include "eims.h" #include "eiliterals.h" #include "select.h" #define SEGHEADSIZ 8 extern short corrupt_flag; /* value from ulfile.c */ extern long rec_len; /* value from ulfile.c */ static char *event_ptr = NULL; /* * .SBTTL EI$OPEN - Obtains access to raw error information *++ * FUNCTIONAL DESCRIPTION: * * - Selects user's input location (file or mailbox). * - Opens file or mailbox. * * FORMAL PARAMETERS: * * filename Name of the file to be opened * mode Mode to open the file (used as a flag to * open mailbox). * * * IMPLICIT INPUTS: NONE * * IMPLICIT OUTPUTS: A raw system event file * * COMPLETION STATUS: EI$OPN (file or socket open - success) * EI$NOP (file or socket not opened - failure) * EI$FNX (file doesn't exist - failure) * * SIDE EFFECTS: Raw data will be accessible * *-- */ /*... ROUTINE ei$open (filename, mode) */ long ei$open (filename, mode) char *filename; short mode; { return open_file(filename, mode); } /*... ENDROUTINE EI$OPEN */ /* * .SBTTL EI$CLOSE - Closes the error log file or socket *++ * FUNCTIONAL DESCRIPTION: * * - Closes the input file or socket * - Does necessary clean-up * * FORMAL PARAMETERS: * * mode flag specifying whether using a mailbox * or not * * IMPLICIT INPUTS: NONE * * IMPLICIT OUTPUTS: NONE * * COMPLETION STATUS: EI$FCL (file or socket closed - success) * EI$FNC (file or socket not closed) * * SIDE EFFECTS: Access to raw data ended * *-- */ /*... ROUTINE EI$CLOSE (mode) */ long ei$close (mode) short mode; { return close_file(mode); } /*... ENDROUTINE EI$CLOSE */ /* * .SBTTL EI$GET - Gets a record from the file or socket *++ * FUNCTIONAL DESCRIPTION: * * - Reads a record from file or socket. * - Transforms raw record to standard record * - Updates File Control Block * - Returns standard record or EOF * * FORMAL PARAMETERS: * * eisptr Pointer to an EIS * disptr Pointer to a DIS * cdsptr Pointer to a CDS * sdsptr Pointer to a SDS * * IMPLICIT INPUTS: NONE * * IMPLICIT OUTPUTS: NONE * * COMPLETION STATUS: EI$SUCC - std buffers filled (success) * EI$RDR - error encountered * during read. * EI$EOF - end-of-file encountered (success) * EI$CORRUPT - corrupted/invalid entry * found in raw event file * EI$FAIL - failure * EI$NULL - All ptrs point to null (failure) * * SIDE EFFECTS: An EIMS standard event (minus any ADS's) * record will be created. * *-- * * * DEFINITIONS: * * raw_pkt Error log packet as read from the * error log file or from a socket * * xform_rec A raw_pkt that has been transformed * * std_rec One or more xform_rec(s) that are * merged to create the ERMS standard * record consisting of the standard * segments (EIS, DIS, SDS, CDS) * * * input output * ----- ------ * OS raw_pkt * xform raw_pkt xform_rec * xform_merge xform_rec std_rec * */ /*... ROUTINE ei$get (eisptr, disptr, cdsptr, sdsptr) */ long ei$get (eisptr, disptr, cdsptr, sdsptr) EIS *eisptr; DIS *disptr; CDS *cdsptr; SDS *sdsptr; { /************ Processing routine(s) and variables ***************/ extern long check_selection(); extern char *read_file(); extern void ei$bld(); extern void bld_corrupt_eis(); void zero_out(); long status; if ((eisptr == NULL) && (disptr == NULL) && (cdsptr == NULL) && (sdsptr == NULL)) return (EI$NULL); for (;;) { event_ptr = read_file(&status); if (status != EI$SUCC) { if (status != EI$CORRUPT) return(status); bld_corrupt_eis(eisptr); /* build eis only */ disptr = NULL; cdsptr = NULL; sdsptr = NULL; return (EI$CORRUPT); } if ((status = check_selection()) == ES$SUCC) { /* good rec - build segs */ zero_out(eisptr,sizeof(EIS)); zero_out(disptr,sizeof(DIS)); zero_out(cdsptr,sizeof(CDS)); zero_out(sdsptr,sizeof(SDS)); ei$bld(eisptr, disptr, cdsptr, sdsptr, event_ptr); return (EI$SUCC); } else if ((status == ES$EOF) || (status == EI$EOF)) return (EI$EOF); } } /*... ENDROUTINE EI$GET */ void zero_out (loc,len) char *loc; short len; { short i; for (i = 0; i < len; i++) loc[i] = '\0'; } /* * .SBTTL EI$ADS_GET - Produces an ads from current event info *++ * FUNCTIONAL DESCRIPTION: * * This routine fills in the buffer space allocated by the caller * with any additional information contained in the event record * currently being processed. If the raw event record being processed * was found to be corrupt, the adsptr is simply pointed to the actual * data, as there is nothing more to do. Otherwise, the regular * segment build process is done. * * FORMAL PARAMETERS: * * adsptr Pointer to buffer space to load the * information into. * * IMPLICIT INPUTS: A raw system event from which to * extract the information. * * EIMS table definition(s) for the ADS * associated with the event. * * IMPLICIT OUTPUTS: A complete EIMS standard event. * * COMPLETION STATUS: EI$SUCC - Success always returned * * SIDE EFFECTS: EIMS standard event record created. * *-- */ /*... ROUTINE EI$ADS_GET (adsptr) */ long ei$ads_get(adsptr) ADS *adsptr; { extern long ads_bld(); long i, j, stat; char *adstmp; adstmp = (char *)adsptr; adsptr->type = ES$ADS; if (corrupt_flag == EI$TRUE) { adsptr->length = rec_len + ES$ADSVBA + SEGHEADSIZ; for (j = 0, i = (ES$ADSVBA + SEGHEADSIZ); i < rec_len; ++i, ++j) adstmp[i] = event_ptr[j]; return(EI$SUCC); } else stat = (ads_bld(adsptr, event_ptr)); return (stat); } /*... ENDROUTINE EI$ADS_GET */
/* Author : Xitiz Basnet Subject : Programming Fundamentals Lab Sheet NO : 24 Program :WAP to add 3X3 array Date: January 30 , 2017 */ #include<stdio.h> #include<conio.h> int main() { int i,j; int m1[3][3]={{1,2,5},{2,3,5},{1,3,4}}; int m2[3][3]={{5,5,5},{2,6,3},{1,5,7}}; for(i=0;i<3;i++) { for(j=0;j<3;j++) { m1[i][j]=m1[i][j]+m2[i][j]; } } printf("\nThe addition of matrix is:\n\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("\t%d",m1[i][j]); } printf("\n"); } getch(); return 0; }
/* * This program contains the implementation of single linkedlist. * Using basic push and pop operations. */ #include<stdio.h> #include<stdlib.h> /* Definition of the Linked list */ struct node { int index; struct node *prev; struct node *next; }; void printList(struct node *head){ while(head!=NULL){ printf("%d ",head->index); head=head->next; } } /* Function to perform push operation */ void push(struct node **head, int data){ struct node* new_node=(struct node*)malloc(sizeof(struct node)); struct node *temp=*head; new_node->index=data; new_node->prev=NULL; new_node->next=*head; if(*head!=NULL){ temp->prev=new_node; } *head=new_node; } void reverseList(struct node **head){ struct node *current=*head; struct node *tmp; while(current!=NULL){ tmp=current->prev; current->prev=current->next; current->next=tmp; *head=current; current=current->prev; } } int main(){ struct node* head=NULL; push(&head,2); push(&head,5); push(&head,10); push(&head,15); printf("Before Reversal\n"); printList(head); printf("\nAfter Reversal\n"); reverseList(&head); printList(head); return 0; }
#include <stdio.h> #include <stdlib.h> int main(){ int a; printf("podaj wysokosc: "); scanf("%i", &a); printf("\n"); for (int i=0; i<=a;i++){ printf("\t"); for(int b=0; b<a-i; b++){ printf(" "); } for(int d=0; d<i; d++){ printf("%%"); } for(int e=0; e<i-1; e++){ printf("%%"); } printf("\n"); } }
// Copyright 2020 Espressif Systems (Shanghai) PTE 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. #pragma once #include <stdint.h> #include <stdbool.h> #include <esp_err.h> #include <esp_event.h> #include "esp_qcloud_mem.h" #include "esp_qcloud_utils.h" #include "cJSON.h" #ifdef __cplusplus extern "C" { #endif /** * @brief QCloud Length of configuration information. */ #define CLIENT_ID_MAX_SIZE (80) /**< MAX size of client ID */ #define PRODUCT_ID_SIZE (10) /**< MAX size of product ID */ #define PRODUCT_SECRET_MAX_SIZE (32) /**< MAX size of product secret */ #define DEVICE_NAME_MAX_SIZE (48) /**< MAX size of device name */ #define DEVICE_SECRET_SIZE (24) /**< MAX size of device secret */ #define DEVICE_CERT_FILE_NAME_MAX_SIZE (128) /**< MAX size of device cert file name */ #define AUTH_TOKEN_MAX_SIZE (32) /**< MAX size of auth token */ /** * @brief ESP QCloud Event Base. */ ESP_EVENT_DECLARE_BASE(QCLOUD_EVENT); /** * @brief ESP QCloud Events. */ typedef enum { QCLOUD_EVENT_IOTHUB_INIT_DONE = 1, /**< QCloud core Initialisation Done */ QCLOUD_EVENT_IOTHUB_BOND_DEVICE, /**< QCloud bind device */ QCLOUD_EVENT_IOTHUB_UNBOND_DEVICE, /**< QCloud unbind device */ QCLOUD_EVENT_IOTHUB_BIND_EXCEPTION, /**< QCloud bind exception */ QCLOUD_EVENT_LOG_FLASH_FULL, /**< QCloud log storage full */ } esp_qcloud_event_t; /** * @brief ESP QCloud Auth mode. */ typedef enum { QCLOUD_AUTH_MODE_INVALID, /**< Invalid mode */ QCLOUD_AUTH_MODE_KEY, /**< Key authentication */ QCLOUD_AUTH_MODE_CERT, /**< Certificate authentication */ QCLOUD_AUTH_MODE_DYNREG, /**< Dynamic authentication */ } esp_qcloud_auth_mode_t; /** * @brief ESP QCloud Parameter Value type. */ typedef enum { QCLOUD_VAL_TYPE_INVALID = 0, /**< Invalid */ QCLOUD_VAL_TYPE_BOOLEAN, /**< Boolean */ QCLOUD_VAL_TYPE_INTEGER, /**< Integer. Mapped to a 32 bit signed integer */ QCLOUD_VAL_TYPE_FLOAT, /**< Floating point number */ QCLOUD_VAL_TYPE_STRING, /**< NULL terminated string */ } esp_qcloud_param_val_type_t; /** * @brief ESP QCloud Value. */ typedef struct { esp_qcloud_param_val_type_t type; float f; /**< Float */ union { bool b; /**< Boolean */ int i; /**< Integer */ char *s; /**< NULL terminated string */ }; } esp_qcloud_param_val_t; /** * @brief Interface method get_param. * */ typedef esp_err_t (*esp_qcloud_get_param_t)(const char *id, esp_qcloud_param_val_t *val); /** * @brief Interface method set_param. * */ typedef esp_err_t (*esp_qcloud_set_param_t)(const char *id, const esp_qcloud_param_val_t *val); /** * @brief Add device callback function, set and get. * * @param[in] get_param_cb Get param interface. * @param[in] set_param_cb Set param interface. * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_device_add_cb(const esp_qcloud_get_param_t get_param_cb, const esp_qcloud_set_param_t set_param_cb); /** * @brief Create device. * * @note Need product id, device name, device key. * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_create_device(void); /** * @brief Add firmware version information. * * @param[in] version Current firmware version. * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_device_add_fw_version(const char *version); /** * @brief Get firmware version information. * * @return Pointer to firmware version. */ const char *esp_qcloud_get_version(void); /** * @brief Get device name. * * @return Pointer to device name. */ const char *esp_qcloud_get_device_name(void); /** * @brief Get product id. * * @return Pointer to product id. */ const char *esp_qcloud_get_product_id(void); /** * @brief Get authentication mode. * * @return Current authentication model. */ esp_qcloud_auth_mode_t esp_qcloud_get_auth_mode(void); /** * @brief Get device secret. * * @return Pointer to device secret. */ const char *esp_qcloud_get_device_secret(void); /** * @brief Get Certification. * * @return Pointer to certification. */ const char *esp_qcloud_get_cert_crt(void); /** * @brief Get private key. * * @return Pointer to private key. */ const char *esp_qcloud_get_private_key(void); /** * @brief Add properties to your device * * @note You need to register these properties on Qcloud, Ensure property identifier is correct. * * @param[in] id property identifier. * @param[in] type property type. * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_device_add_param(const char *id, esp_qcloud_param_val_type_t type); /** * @brief Set local properties. * * @note When a control message is received, the function will be called. * This is an internal function, You can not modify it. * You need to pass your function through esp_qcloud_device_add_cb. * * @param[in] request_params * @param[in] reply_data * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_handle_set_param(const cJSON *request_params, cJSON *reply_data); /** * @brief Get local properties. * * @note When a control message is received, the function will be called. * This is an internal function, You can not modify it. * You need to pass your function through esp_qcloud_device_add_cb. * * @param[in] request_data * @param[in] reply_data * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_handle_get_param(const cJSON *request_data, cJSON *reply_data); /** * @brief Initialize Qcloud and establish MQTT service. * * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_iothub_init(void); /** * @brief Run Qcloud service and register related parameters. * * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_iothub_start(void); /** * @brief Stop Qcloud service and release related resources. * * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_iothub_stop(void); /** * @brief Use token to bind with Qcloud. * * @param[in] token Token comes from WeChat applet. * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_iothub_bind(const char *token, uint32_t timeout); /** * @brief Get Qcloud service status. * * @return true Connect * @return false Disconnect */ bool esp_qcloud_iothub_is_connected(void); /** * @brief Enable OTA * * @note Calling this API enables OTA as per the ESP QCloud specification. * Please check the various ESP QCloud configuration options to * use the different variants of OTA. Refer the documentation for * additional details. * * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_qcloud_iothub_ota_enable(void); #ifdef __cplusplus } #endif
/// Rooms for Tirun's Barrier reef /// written by Ironman #include <std.h> #include <waterworld.h> inherit ROOM; void create() { ::create(); set_properties((["water":1,"light":3,"night light":3])); set_long("There seems to be an overabundance of sea grass on the reef here." " The sea grass comes in a wide variety of colors and forms." " A colony of pelagic fish have chosen the sea grass as their nesting grounds." " Unfortunately for the sea grass, most of the fish and turtles find them to be quite tasty treats." ); set_exits(([ "northeast":ROOMS2"room-2i2.c", "southeast":ROOMS2"room-2i4.c", "southwest":ROOMS2"room-2g4.c" ])); set_items(([ "sea grass":"The sea grass is a main staple of food for most of the creatures that live in the reef ecosystem.", "pelagic fish":"A general classification for fish including herring, mackerel and cods." ])); new(PEARLS"blue_clam.c")->move(this_object()); } // Mob regeneration void reset() { ::reset(); MOB2"selection_lvl2.c"->execute_selection_lvl2(random(7),this_object()); }
#include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <time.h> typedef struct _Numbers{ int numbers[100]; int numere_adaugate; int max_numbers; int index; } Numbers; pthread_mutex_t m; pthread_cond_t c; void* bear(void* a) { Numbers *nrs; nrs=(Numbers *) a; while(nrs->numere_adaugate != nrs->max_numbers) { pthread_mutex_lock(&m); if(nrs->numere_adaugate != nrs->max_numbers) { nrs->numbers[nrs->index]=1; nrs->index++; nrs->numere_adaugate++; } else { pthread_cond_signal(&c); } pthread_mutex_unlock(&m); } pthread_mutex_lock(&m); pthread_cond_signal(&c); pthread_mutex_unlock(&m); return NULL; } void* farmer(void* a) { Numbers *nrs; nrs=(Numbers *) a; while(nrs->numere_adaugate != nrs->max_numbers) { pthread_mutex_lock(&m); while(nrs->numere_adaugate != nrs->max_numbers) { pthread_cond_wait(&c, &m); } nrs->numbers[nrs->index]=1; nrs->index++; nrs->numere_adaugate++; pthread_mutex_unlock(&m); } return NULL; } int main(int argc, char** argv) { Numbers nrs; nrs.max_numbers = 4; nrs.index=0; pthread_t t[1]; pthread_mutex_init(&m, NULL); pthread_cond_init(&c, NULL); pthread_create(&t[0], NULL, farmer, (void *)&nrs); pthread_create(&t[1], NULL, bear, (void *)&nrs); pthread_join(t[0], NULL); pthread_join(t[1],NULL); pthread_mutex_destroy(&m); pthread_cond_destroy(&c); printf("fsges"); return 0; }
#ifndef K_IRONWING_H #define K_IRONWING_H #define QUESTION 0 #define ANSWER 1 ///// Most information for this game was researched using the following ; // // encyclopedia wikipedia ---- en.wikipedia.org // oceans online ---- www.oceansonline.com // sea and sky ---- www.seasky.org // australian museum online ---- www.amonline.net.au/fishes // pbs online-Nova ---- www.pbs.org/wgbh/nova // scuba travel ---- www.scubatravel.co.uk // string* trivia = ({ ({"What is the other common name for a seacow?","manatee"}), ({"What is the genus designation for the many races of seacows?","trichechus"}), ({"What other animal does the seahorse commonly use in a symbionic relationship to shield it from predators?","tube worms"}), ({"What breed of slug are immune to the toxins of most anemones and sponges??","nudibranch"}), ({"What crustacean likes to clean the bacteria off of sea anemone?","shrimp"}), ({"In what capacity does a sea anemone act for shrimps and clown fish that choose to form a symbionic with them?","defense"}), ({"What is the main source of food for shrimps?","bacteria"}), ({"What is the other name for squids and octopi ?","cephalopod"}), ({"What type of animal is a nautilus ?","cephalopod"}), ({"What is the divide that seperates the sections of a Nautilus' shell called ?","septum"}), ({"What is the tube called that connects all the chambers of a nautilus' shell called ?","siphuncle"}), ({"By what means does a nautilus maintain it's bouyancy in the water ? (2 words)","osmotic pressure"}), ({"What are the coloumns that a sponge forms called ?","spicules"}), ({"What is the method called by which sponges feed ?","filtration"}), ({"What breed of slug is immunte to a sponges toxins? In fact, this slug makes use of the toins for their own defense.","nudibranch"}), ({"What is the scientific classification for sponges?","porifera"}), ({"What is a stingray's tail made out of ?","cartilage"}), ({"What plant is a main food source for many fish in a reef biosystem ?","seagrass"}), ({"What is the rear fin of a fish called (2 words)?","caudal fin"}), ({"What do butterfly fish eat (2 words)?","sea anemones"}), ({"What is another name for anemone fish (2 words) ?","clown fish"}), ({"What body part on a lampray seperates them from eels (4 words) ?","dorsal and caudal fins"}), ({"What is a lampray's PRIMARY source of nurishment which they usually get from fish ?","blood"}), ({"What is a seal's main food sources (___ and ___) ?","fish and crawfish"}), ({"What protects a seal's organs from both attacks and thermal changes ?","blubber"}), ({"What is carbon dioxide poisoning commonly called by divers (two words) ?","the bends"}), ({"What can a seal store in their muscle tissues to assist them with diving for prey ?","oxygen"}), ({"Where do most breeds of crocodile live?","aquifer"}), ({"What is the region where salt and fresh water mix at the mouth of a river/bay called ?","aquifer"}), ({"What body part allows a crocodile to see underwater (2 words)?","nictitating membrane"}), ({"What is the average length of a barracuda (in inches) ?","24"}), ({"What is the technique called when prey is herded into an area and picked off slowly ?","corralling"}), ({"What is the technique called when an entire school of fish charge at one target ?","swarming"}), ({"What animal do some species of shrimp help by eating bacteria off of them in exchange for shelter from predators (2 words)?","sea anemone"}), ({"What do smaller fish commonly do to fool predators into thinking they're noe big fish (___ in ____s) ?","swim in schools"}), ({"In feet, how long can a tube worm grow (enter a #) ?","8"}), ({"What hair-like body parts act like gills for the tube worms?","filaments"}), ({"What chemical process do the bacteria near the thermal vents use to 'eat'?","chemosyntesis"}), ({"What causes the pompeii worm's gills to appear red?","haemoglobin"}), ({"What kills the pompeii worms when a sample is attepted to be retrieved for study ?","decompression"}), ({"What chemical/element does chemosyntesis use to make energy ?","sulfur"}), ({"What animal is a close relative of the Dugong ?","manatee"}), ({"In pounds, what is a dugong maximum adult wieght from currently known specimens (enter a #) ?","300"}), ({"In feet, what is a dugong maximum adult length from currently known specimens (enter a #) ?","9"}), ({"Other then the nudibranch slug, name one natural predator of corel and sponge (4 words, first 3 are -'d).","crown-of-thorns starfish"}), ({"What animal is a natural predator of the crown-of-thorns starfish (2 words)?","triton trumpet"}), ({"What process does an anti-coaguant slow down if not stop (2 words)?","blood clotting"}), ({"What type of animal is a Triton Trumpet?","snail"}), ({"What class of enzyme is used to paralyze a victim?","neuro-toxin"}), ({"What colors are a Tirun Cod's markings? (___ and ___)","silver and red"}), ({"How heavy in pounds can a Tirun Cod grow?","30"}), ({"How many legs does a crab have?","6"}), ({"What gang does Pelican Pete belong too?","fighting pelicans"}), ({"What is a Flaming Pelican (c) served in (3 words) ?","pelican egg shell"}), ({"Who is the general of the Atlantian armies?","kraken"}), ({"Who is the admiral of the Atlantian navies?","man-o-war"}), ({"What spell was used by Poseidon, The mer-king, to stop Tridryill's evil from consuming this world and level his stronghold?","tsunami"}), ({"What was the first stones, which Poseidon constructed, called (3 words)?","pearls of atlantis"}), ({"In what substance was Tridryill's remains imprisoned in by Poseidon?","amber"}), ({"Near which city did the Atantian armed forces surface during their war with Tridryill?","tirun"}), ({"What is the more common name for 'Tilapias' ?","whitefish"}), ({"What family do the Tilapias belong too ?","cichid"}), ({"What body part seperates the tilapias from basses and perchs (2 words) ?","dorsal fin"}), ({"How many Dorsal fins does a Tilapia have (1 word) ?","one"}), ({"What part of a porgy has evolved to assist them with eating their diet of shellfish and crustaceans (1 word) ?","jaws"}), ({"What is the adjective used to describe a creature that perfers to dwell on the bottom of the ocean or bay?","bentic"}), ({"What term means the adjusting of one's body chemistry to withstand the changes to one's enviroment?","osmoregulation"}), ({"What is the average weight in pounds of a salmon? (enter a number)","50"}), ({"What adjective is used to describe an animal that is born in freshwater but live most of their lives in saltwater?","anadromous"}), ({"What is an eel's average lifespan (enter a number) ?","19"}), ({"what is the term for a 'hibernation-like' state that slows the metabolism but not nessesarily to the point of sleep?","torpor"}), ({"What is a baby eel called once it hatches and before it grows into an adult?","elver"}), ({"What adjective describes animals that start life in saltwater and migrate into freshwater for the adulthood stage of their lives until they spawn?","catadromous"}), ({"What is the scientific classification of 'family' for the 'short-finned ell'?","anguillidae"}), ({"What family do 'Lion Fish' belong to? What type of fish is it? (____ fish)","scorpion fish"}), ({"In what body part are the spines containing the Lion fish's toxins located?(4 words=___ and ___ ___)","dorsal and pectoral fins"}), ({"In what capacity is the lion fish's toxins used?","defense"}), ({"What is the perfered food of a Lion Fish?","shrimp"}), ({"What organ contains the Lion fish's toxins within it's fins (plural form)?","spines"}), ({"What is the average length of a Lantern Fisn (give a number) in inches ?","6"}), ({"What is the scientific name for a Lantern Fish (two words) ?","symbolophorus bamardi"}), ({"What is the organ called that produces the light for the Lantern fish ?","photophores"}), ({"What is the process called by which an organism produces light?","bioluminescence"}), ({"Biolumenecent in fish is believed to be used for (___ and ___) ?","hunting and mating"}), ({"What do Hatchet fish usually eat (other then being scavengers) ?","copepods"}), ({"At what depth, in feet, can you start to see Hatchet Fish(enter a number) ?","600"}), ({"How is the Photophore organs located on the Hatchet Fish (hint-- Caudally means in the tail section) ?","ventrally"}), ({"What is a pelican eel's other name (2 words)?","pelican eel"}), ({"Which classification of order does the Pelican Eel belong too?","saccopharyngiformes"}), ({"What order of animals are yellow corals a member of ?","alcyonacea"}), ({"What do members of the Alcyonacea order of animals lack that other corals have (___ ___ of ____) ?","outer shell of calcium"}), ({"What are the yellow coral's 'branchs' called ?","spicules"}), ({"How many tenticles do each spicule on a yellow coral have ? (enter a #)","8"}), ({"What is the scientific name for cup corels (two words) ?","tubaestraea aurea"}), ({"What do cup corals lack that other corals have ?","symbiotic algae"}), ({"What is the leafy sea dragons 2 make foods (___ and ___) ?","amphipods and algea"}), ({"In months, what age do leafy sea dragons start mating (enter a #) ?","12"}), ({"About how many eggs does a female leafy sea dragon lay on the males brood patch (enter a #) ?","250"}), ({"What part of the fire corals produces it's defensive acids (and gives the fire coral its name) ?","nematocysts"}), ({"About how many species of angler fish are there(give a number)?","200"}), ({"What order of animals do angler fish belong to?","lophiiformes"}), ({"What are the three families that angler fish fall into?\n(Common names) (format -> ___ fish, ___ fish and ___ fish)","frog fish, monk fish and bat fish"}), ({"What is the organ called that an angler fish uses for hunting?","illicium"}), ({"What is the bioluminecent growth at the end of an angler fish's illicium called?","esca"}), ({"What are the three families that angler fish fall into?\n(Common names) (format -> ___, ___ and ___)","antennariidae,lophiidae and ogcocephalidae"}), ({"What scientific family do Ore fish fall into?","regalecidae"}), ({"What other animal are ore fish a close relative of?","lampray eel"}), ({"At a world record for fish, what is the average length in meters of an ore fish (give a number)?","11"}), ({"In kilograms, what is the heaviest ore fish on record? (give a number)","272"}), ({"what is the scientific name for a Vampire squid (2 words) ?","vamproteuthis infernalis"}), ({"What is the other common name for the fangtooth (____ fish) ?","ogre fish"}), ({"What is the maximum depth, in feet, that the fangtooth have been found at ?(enter a number)","18000"}), ({"What do vampire squids possess a battery of that distinguish them from other cephalopods (2 words)?","sensory filaments"}), ({"What differentiates a slipper sea cucumber from other types of sea cucumbers?(a ___ ___)","a flat body"}), ({"What does a sea urchin use to defend against predators?","spikes"}), ({"What animal class are sea urchins a member of?","echinodea"}), ({"What do all members of the echinodea class of animals have in common?(2 words)","radial symmetry"}), ({"How many poisonous spines does a rockfish house in their dorsal fins? (enter a number)","13"}), ({"What is the average length in centimeters of a stonefish (use #'s : __ to __ ) ?","35 to 50"}), ({"What part of a frogfish has evolved to form 'feet', allowing them to 'walk' along the coral reefs? (two words)","pectoral fins"}), ({"What are two of the hawkbill turtle's main foods?(___ and ___)","nudibranchs and sponges"}), ({"What is the hawkbill turtle's scientific name?","eretmochelys imbricata"}), ({"What is the average weight of a Hawkbill Turtle in kilgrams?(enter a #)","80"}), ({"What is the record weight in kilograms for the largest Hawkbill Turle?(enter a number)","127"}), ({"What is the average length of a Hawkbill turtle along it's dorsal carapace or shell?(enter a #)","90"}), ({"What is the average weight of a leatherback turtle in pounds??(enter a #)","1500"}), ({"What is the average speed in KNOTS for a leatherback turtle?(enter a #)","25"}), ({"What does the term KNOTS mean? ( ____ ____ per ____)","nautical miles per hour"}), ({"What animal do leatherbacks eat that most other animals can not?","jellyfish"}), ({"What do marine iguanas eat?","algea"}), ({"What must a marine iguana do once it surfaces from eating algea? (___ itself)","warm itself"}), ({"What does a marine iguana use to rid itself of excess sea salt?(2 words)","nasal glands"}), ({"How much more potent is a sea snake's venom over a king cobra?(___ times)","ten times"}), ({"What is the approximate size of the sea snake in meters?(give a #)","2"}), ({"What is the most common reef dwelling sea snake? (3 words)","olive sea snake"}), ({"What is the central section of an ocptopi's body called?","mantle"}), ({"What body part seperates the giant octopi from their smaller cousins?(_____ between _____ ______)","membrane between their tenticles"}), ({"What is the average length in feet of a large octopi's tenticles?(enter a #)","16"}), ({"In feet, what is the longest large octopi's tenticle on record?(enter a #)","20"}), ({"What is the heaviest large octopi's tenticle in pounds on record?(enter a #)","608"}), ({"What is the 'ink' that an octopus ejects in actuality?(it's ____)","saliva"}), ({"What is the outer layer of skin called on an animal?","epidermis"}), ({"What sense does the suckers on an octopus' tenticles possess?","taste"}), ({"What type of dorsal fin, or tail, does a Mako shark possess?(___ tail)","homocercal tail"}), ({"What is the anatomical name for the are directly below a Mako shark's Dorsal fin? (I do NOT mean that either...)","caudal peduncle"}), ({"What is the term that refers to the flow of water and/or the study of the flow of water?","hydrodynamics"}), ({"What is the top recorded speed of a Mako Shark in MPH?","42"}), ({"What is the term for animals that bear live off-spring like the reef sharks?","vivparous"}), ({"How many off-spring does a Mako shark average per litter? (__ to __ pups)","2 to 4 pups"}), ({"What is the length of a Mako Shark Pup at birth in cm?? (__ to __ cm)","33 to 52 cm"}), ({"What is a baby seacow called?","calf"}) }); #endif
#include <stdio.h> int main(void) { int i = 500000000000; long long j = 500000000000; printf("i = %d\n", i); printf("j = %lld\n", j); return 0; }
/******************************************************************************* MPLAB Harmony Application Splash Screen Source File Company: Microchip Technology Inc. File Name: screen_FPSCMotion.c Summary: This file contains the source code for the demo FPS motion screen. Description: This file contains the source code for the MPLAB Harmony application. It implements the logic of the application's state machine and it may call API routines of other MPLAB Harmony modules in the system, such as drivers, system services, and middleware. However, it does not call any of the system interfaces (such as the "Initialize" and "Tasks" functions) of any of the modules in the system or make any assumptions about when those functions are called. That is the responsibility of the configuration-specific system files. *******************************************************************************/ // DOM-IGNORE-BEGIN /******************************************************************************* Copyright (c) 2013-2014 released Microchip Technology Inc. All rights reserved. Microchip licenses to you the right to use, modify, copy and distribute Software only when embedded on a Microchip microcontroller or digital signal controller that is integrated into your product or third party product (pursuant to the sublicense terms in the accompanying license agreement). You should refer to the license agreement accompanying this Software for additional information regarding your rights and obligations. SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. *******************************************************************************/ // DOM-IGNORE-END // ***************************************************************************** // ***************************************************************************** // Section: Included Files // ***************************************************************************** // ***************************************************************************** #include "gfx/legato/generated/screen/le_gen_screen_FPSImages.h" #include "definitions.h" #include <stdio.h> #include <string.h> #include "system/time/sys_time.h" #define AVE_FPS_COUNT 10 #define FPS_UPDATE_TIMER_PERIOD_MS 1000 #define MAX_NUM_IMAGES 2 //#define ENABLE_FULL_SCREEN_IMAGE_TEST 1 static volatile leBool aveFPSValid = LE_FALSE; static int aveCounter = 0; static uint32_t prevDrawCountAve[AVE_FPS_COUNT] = {0}; static uint32_t prevDrawCount; static uint32_t prevVsyncCount; static SYS_TIME_HANDLE fpsUpdateTimer; uint32_t imgSize; uint32_t imgType; uint32_t imgIndex; static char charBuff[16] = {0}; static leDynamicString fpsBtnText; static leDynamicString refreshRateText; static leDynamicString imgSizeText; static leTableString imageTypeStr; typedef enum { IMG_40x40, IMG_100x100, IMG_200x200, #ifdef ENABLE_FULL_SCREEN_IMAGE_TEST IMG_480x270, #endif IMG_MAX_SIZE, } IMAGE_SIZE_T; typedef enum { //IMG_PNG_8888, //IMG_JPG_24, IMG_RAW_565, IMG_RAW_RLE_565, #if defined(PRE_PROCESSED_IMAGES_SUPPORTED) IMG_RAW_BLIT, #endif IMG_MAX_TYPE, } IMAGE_TYPE_T; typedef struct { leImage * imgAsst[MAX_NUM_IMAGES]; } IMAGE_LIST_T; char * imageSizeNames[IMG_MAX_SIZE] = { "40x40", "100x100", "200x200", #ifdef ENABLE_FULL_SCREEN_IMAGE_TEST "480x270", #endif }; unsigned int imageTypeNames[IMG_MAX_TYPE] = { stringID_Raw565, stringID_RawRLE565, }; /*IMAGE_LIST_T imagesPNG[] = { [IMG_40x40] = { {&PNG_GFX_mchp_40x40, &PNG_GFX_mplab_40x40}, }, #ifdef PNG_100x100_NOT_SUPPORTED [IMG_100x100] = { {NULL, NULL}, }, #else [IMG_100x100] = { {&PNG_GFX_mchp_100x100, &PNG_GFX_mplab_100x100}, }, #endif [IMG_200x200] = { {NULL, NULL}, }, #ifdef ENABLE_FULL_SCREEN_IMAGE_TEST [IMG_480x270] = { {NULL, NULL}, }, #endif };*/ /*IMAGE_LIST_T imagesJPG[] = { [IMG_40x40] = { {&JPG_GFX_mchp_40x40, &JPG_GFX_mplab_40x40}, }, [IMG_100x100] = { {&JPG_GFX_mchp_100x100, &JPG_GFX_mplab_100x100}, }, [IMG_200x200] = { {&JPG_GFX_mchp_200x200, &JPG_GFX_mplab_200x200}, }, #ifdef ENABLE_FULL_SCREEN_IMAGE_TEST [IMG_480x270] = { {&JPG_GFX_mchp_480x270, &JPG_GFX_mplab_480x270}, }, #endif };*/ IMAGE_LIST_T imagesRAW[] = { { /* IMG_40x40 */ { &RAW_GFX_mchp_40x40, &RAW_GFX_mplab_40x40 }, }, { /* IMG_100x100 */ { &RAW_GFX_mchp_100x100, &RAW_GFX_mplab_100x100 }, }, { /* IMG_200x200 */ { &RAW_GFX_mchp_200x200, &RAW_GFX_mplab_200x200 }, }, #ifdef ENABLE_FULL_SCREEN_IMAGE_TEST { /* IMG_480x270 */ { &RAW_GFX_mchp_480x270, &RAW_GFX_mplab_480x270 }, }, #endif }; IMAGE_LIST_T imagesRAWRLE[] = { { /* IMG_40x40 */ { &RAWRLE_GFX_mchp_40x40, &RAWRLE_GFX_mplab_40x40 }, }, { /* IMG_100x100 */ { &RAWRLE_GFX_mchp_100x100, &RAWRLE_GFX_mplab_100x100 }, }, { /* IMG_200x200 */ { &RAWRLE_GFX_mchp_200x200, &RAWRLE_GFX_mplab_200x200 }, }, #ifdef ENABLE_FULL_SCREEN_IMAGE_TEST { /* IMG_480x270 */ { &RAWRLE_GFX_mchp_480x270, &RAWRLE_GFX_mplab_480x270 }, }, #endif }; #if defined(PRE_PROCESSED_IMAGES_SUPPORTED) IMAGE_LIST_T imagesRAWBLIT[] = { [IMG_40x40] = { {&BLIT_GFX_mchp_40x40, &BLIT_GFX_mplab_40x40}, }, [IMG_100x100] = { {&BLIT_GFX_mchp_100x100, &BLIT_GFX_mplab_100x100}, }, [IMG_200x200] = { {&BLIT_GFX_mchp_200x200, &BLIT_GFX_mplab_200x200}, }, #ifdef ENABLE_FULL_SCREEN_IMAGE_TEST [IMG_480x270] = { {&BLIT_GFX_mchp_480x270, &BLIT_GFX_mplab_480x270}, }, #endif }; #endif static enum { SCREEN_DO_NOTHING = 0, SCREEN_IMAGE_SIZE_UP, SCREEN_IMAGE_SIZE_DOWN, SCREEN_IMAGE_MODE_NEXT, SCREEN_IMAGE_MODE_PREV, SCREEN_NEXT, SCREEN_WAIT_FOR_NEXT, SCREEN_MOVE_TO_NEXT, SCREEN_DONE } screenState; static void resetFPS(void) { aveFPSValid = LE_FALSE; aveCounter = 0; sprintf(charBuff, "---"); fpsBtnText.fn->setFromCStr(&fpsBtnText, charBuff); Screen3_ImageUpdateValue->fn->setString(Screen3_ImageUpdateValue, (leString*)&fpsBtnText); prevDrawCount = 0; prevVsyncCount = 0; } static void fpsUpdateTimer_Callback() { unsigned int rate; unsigned int i; if(Screen3_ImageUpdateValue == NULL) return; //Update the 10-pt rolling average prevDrawCountAve[aveCounter] = (leGetRenderState()->drawCount - prevDrawCount); //If not pressed, show current FPS if(Screen3_ImageUpdateValue->fn->getPressed(Screen3_ImageUpdateValue) == LE_FALSE) { //Update FPS rate = (leGetRenderState()->drawCount - prevDrawCount)/ (FPS_UPDATE_TIMER_PERIOD_MS/1000); sprintf(charBuff, "%u curr", rate); } //If pressed, show average FPS else { for (i = 0, rate = 0; i < AVE_FPS_COUNT; i++) { rate += prevDrawCountAve[i]; } if (aveFPSValid) { sprintf(charBuff, "%u avg", (rate / ((AVE_FPS_COUNT)*(FPS_UPDATE_TIMER_PERIOD_MS / 1000)))); } else { sprintf(charBuff, "---"); } } if (aveCounter < (AVE_FPS_COUNT - 1)) { aveCounter++; } else { aveCounter = 0; aveFPSValid = LE_TRUE; } fpsBtnText.fn->setFromCStr(&fpsBtnText, charBuff); Screen3_ImageUpdateValue->fn->setString(Screen3_ImageUpdateValue, (leString*)&fpsBtnText); //Update Refresh Rate uint32_t vsyncCount = leGetRenderState()->dispDriver->getVSYNCCount(); rate = (vsyncCount - prevVsyncCount) / (FPS_UPDATE_TIMER_PERIOD_MS/1000); //If vsyncCount does not increase, assume fixed refresh rate using vsyncCount //value if (rate == 0) rate = vsyncCount; sprintf(charBuff, "%u", rate); refreshRateText.fn->setFromCStr(&refreshRateText, charBuff); Screen3_ImageRefreshValue->fn->setString(Screen3_ImageRefreshValue, (leString*)&refreshRateText); prevDrawCount = leGetRenderState()->drawCount; prevVsyncCount = vsyncCount; // DecrementCount(Counter1LabelWidget); } static void increaseImageSize() { if(imgSize < IMG_MAX_SIZE - 1) { imgSize += 1; } else { return; } // Special handling, PNG sizes are limited to 100x100 due // to memory limitations /*if ((imgType == IMG_PNG_8888) && (imgSize > IMG_100x100)) { imgSize = IMG_100x100; }*/ //Update image size label sprintf(charBuff, "%s", imageSizeNames[imgSize]); imgSizeText.fn->setFromCStr(&imgSizeText, charBuff); Screen3_ImageSizeValue->fn->setString(Screen3_ImageSizeValue, (leString*)&imgSizeText); resetFPS(); } static void decreaseImageSize() { if(imgSize > 0) { imgSize -= 1; } else { return; } //Update image size label sprintf(charBuff, "%s", imageSizeNames[imgSize]); imgSizeText.fn->setFromCStr(&imgSizeText, charBuff); Screen3_ImageSizeValue->fn->setString(Screen3_ImageSizeValue, (leString*)&imgSizeText); resetFPS(); } static void nextImageType() { if(imgType < IMG_MAX_TYPE - 1) { imgType += 1; } else { return; } //Update image type label imageTypeStr.fn->setID(&imageTypeStr, imageTypeNames[imgType]); Screen3_ImageTypeValue->fn->setString(Screen3_ImageTypeValue, (leString*)&imageTypeStr); resetFPS(); } static void prevImageType() { if(imgType > 0) { imgType -= 1; } else { return; } //Update image type label imageTypeStr.fn->setID(&imageTypeStr, imageTypeNames[imgType]); Screen3_ImageTypeValue->fn->setString(Screen3_ImageTypeValue, (leString*)&imageTypeStr); resetFPS(); } static void nextImage() { if(imgIndex < MAX_NUM_IMAGES - 1) { imgIndex += 1; } else { imgIndex = 0; } // if (imgType == IMG_PNG_8888) // { // if (imagesPNG[imgSize].imgAsst[imgIndex] != NULL) // { // laImageWidget_SetImage(imgWidget, // imagesPNG[imgSize].imgAsst[imgIndex]); // } // else // { // // } // } // else if (imgType == IMG_JPG_24) // { // if (imagesJPG[imgSize].imgAsst[imgIndex] != NULL) // { // laImageWidget_SetImage(imgWidget, // imagesJPG[imgSize].imgAsst[imgIndex]); // } // } if (imgType == IMG_RAW_565) { if (imagesRAW[imgSize].imgAsst[imgIndex] != NULL) { Screen3_ImageRenderArea->fn->setImage(Screen3_ImageRenderArea, imagesRAW[imgSize].imgAsst[imgIndex]); } } else if (imgType == IMG_RAW_RLE_565) { if (imagesRAWRLE[imgSize].imgAsst[imgIndex] != NULL) { Screen3_ImageRenderArea->fn->setImage(Screen3_ImageRenderArea, imagesRAWRLE[imgSize].imgAsst[imgIndex]); } } #if defined(PRE_PROCESSED_IMAGES_SUPPORTED) // else if (imgType == IMG_RAW_BLIT) // { // if (imagesRAWBLIT[imgSize].imgAsst[imgIndex] != NULL) // { // laImageWidget_SetImage(imgWidget, // imagesRAWBLIT[imgSize].imgAsst[imgIndex]); // } // } #endif } void Screen3_OnShow() { leFont* font = NULL; font = leStringTable_GetStringFont(&stringTable, stringID_NumsLittle, 0); leDynamicString_Constructor(&fpsBtnText); fpsBtnText.fn->setFont(&fpsBtnText, font); leDynamicString_Constructor(&refreshRateText); refreshRateText.fn->setFont(&refreshRateText, font); font = leStringTable_GetStringFont(leGetState()->stringTable, stringID_NumsTiny, 0); leDynamicString_Constructor(&imgSizeText); imgSizeText.fn->setFont(&imgSizeText, font); leTableString_Constructor(&imageTypeStr, stringID_Raw565); imgSize = IMG_40x40; imgType = IMG_RAW_565; imgIndex = 0; // initialize image size label sprintf(charBuff, "%s", imageSizeNames[imgSize]); imgSizeText.fn->setFromCStr(&imgSizeText, charBuff); Screen3_ImageSizeValue->fn->setString(Screen3_ImageSizeValue, (leString*)&imgSizeText); // initialize image type label imageTypeStr.fn->setID(&imageTypeStr, imageTypeNames[imgType]); Screen3_ImageTypeValue->fn->setString(Screen3_ImageTypeValue, (leString*)&imageTypeStr); resetFPS(); memset(prevDrawCountAve, 0, sizeof(prevDrawCountAve)); fpsUpdateTimer = SYS_TIME_CallbackRegisterMS(fpsUpdateTimer_Callback, 1, FPS_UPDATE_TIMER_PERIOD_MS, SYS_TIME_PERIODIC); screenState = SCREEN_DO_NOTHING; } void Screen3_OnHide() { SYS_TIME_TimerDestroy(fpsUpdateTimer); fpsBtnText.fn->destructor(&fpsBtnText); refreshRateText.fn->destructor(&refreshRateText); imgSizeText.fn->destructor(&imgSizeText); imageTypeStr.fn->destructor(&imageTypeStr); } void Screen3_OnUpdate() { switch (screenState) { case SCREEN_DO_NOTHING: { if(leGetRenderState()->frameState == LE_FRAME_READY && leEvent_GetCount() == 0) { nextImage(); } break; } case SCREEN_IMAGE_SIZE_UP: { if(leGetRenderState()->frameState == LE_FRAME_READY && leEvent_GetCount() == 0) { increaseImageSize(); screenState = SCREEN_DO_NOTHING; } break; } case SCREEN_IMAGE_SIZE_DOWN: { if(leGetRenderState()->frameState == LE_FRAME_READY && leEvent_GetCount() == 0) { decreaseImageSize(); screenState = SCREEN_DO_NOTHING; } break; } case SCREEN_IMAGE_MODE_NEXT: { if(leGetRenderState()->frameState == LE_FRAME_READY && leEvent_GetCount() == 0) { nextImageType(); screenState = SCREEN_DO_NOTHING; } break; } case SCREEN_IMAGE_MODE_PREV: { if(leGetRenderState()->frameState == LE_FRAME_READY && leEvent_GetCount() == 0) { prevImageType(); screenState = SCREEN_DO_NOTHING; } break; } case SCREEN_NEXT: { screenState = SCREEN_WAIT_FOR_NEXT; SYS_TIME_TimerStop(fpsUpdateTimer); aveFPSValid = LE_FALSE; break; } case SCREEN_WAIT_FOR_NEXT: { if(leGetRenderState()->frameState == LE_FRAME_READY && leEvent_GetCount() == 0) { screenState = SCREEN_MOVE_TO_NEXT; } break; } case SCREEN_MOVE_TO_NEXT: { legato_showScreen(screenID_Screen1); screenState = SCREEN_DONE; break; } case SCREEN_DONE: default: break; } } // event handlers void event_Screen3_ImageSizeDownButton_OnPressed(leButtonWidget* btn) { if(screenState == SCREEN_DO_NOTHING) { screenState = SCREEN_IMAGE_SIZE_DOWN; } } void event_Screen3_ImageSizeUpButton_OnPressed(leButtonWidget* btn) { if(screenState == SCREEN_DO_NOTHING) { screenState = SCREEN_IMAGE_SIZE_UP; } } void event_Screen3_ImageTypePrevButton_OnPressed(leButtonWidget* btn) { if(screenState == SCREEN_DO_NOTHING) { screenState = SCREEN_IMAGE_MODE_PREV; } } void event_Screen3_ImageTypeNextButton_OnPressed(leButtonWidget* btn) { if(screenState == SCREEN_DO_NOTHING) { screenState = SCREEN_IMAGE_MODE_NEXT; } } void event_Screen3_ImageNextButton_OnPressed(leButtonWidget* btn) { if(screenState == SCREEN_DO_NOTHING) { screenState = SCREEN_NEXT; } } /******************************************************************************* End of File */
$NetBSD: patch-libretro-common_features_features__cpu.c,v 1.1 2019/05/20 12:42:40 nia Exp $ Use clock_gettime on BSD. --- libretro-common/features/features_cpu.c.orig 2019-05-08 06:06:23.000000000 +0000 +++ libretro-common/features/features_cpu.c @@ -26,6 +26,7 @@ #if defined(_WIN32) #include <direct.h> #else +#define _POSIX_C_SOURCE 200112 #include <unistd.h> #endif @@ -167,7 +168,7 @@ retro_perf_tick_t cpu_features_get_perf_ tv_sec = (long)((ularge.QuadPart - epoch) / 10000000L); tv_usec = (long)(system_time.wMilliseconds * 1000); time_ticks = (1000000 * tv_sec + tv_usec); -#elif defined(__linux__) || defined(__QNX__) || defined(__MACH__) +#elif defined(__linux__) || defined(BSD) || defined(__QNX__) || defined(__MACH__) struct timespec tv = {0}; if (ra_clock_gettime(CLOCK_MONOTONIC, &tv) == 0) time_ticks = (retro_perf_tick_t)tv.tv_sec * 1000000000 +
/* *************************************************************** *Author:ua_long *Function:translate the is to os file to print to the screen . *Date: date **************************************************************** */ #include<stdio.h> int main(void) { char n ; while ((n=getc(stdin)) != EOF) { if ((putc(n ,stdout)) == EOF) printf ("error!\n") ; //else printf ("%5c", n) ; } printf("\n") ; if (ferror(stdin)) printf ("error: input\n") ; return 0; }
/* ** EPITECH PROJECT, 2020 ** rpg ** File description: ** init.c */ #include "init.h" #include "particule.h" void init(main_t *main_struct) { for (int i = 0; init_funcs[i].ptr != NULL; i++) init_funcs[i].ptr(main_struct); main_struct->part1 = create_particle((V2I){76, 76}, sfWhite); main_struct->part2 = create_particle((V2I){76, 76}, sfRed); create_sound(main_struct); init_cred(main_struct); init_option(main_struct); init_screen_menu(main_struct); }
#include<stdio.h> #include<math.h> struct node{ struct node *right; struct node *left; struct node *parent; int key; }; typedef struct node * Node; #define NIL NULL Node root; Node treeMinimum(Node x){ while(x->left!=NIL){ x=x->left; } return x; //ok } Node treeMaximum(Node x){ while(x->right!=NIL){ x=x->right; } return x; //ok } Node treeSearch(Node u, int k){ if(u==NIL || k==u->key){ return u; } if(k<u->key){ return treeSearch(u->left,k); } else{ return treeSearch(u->right,k); } //ok } Node treeSuccessor(Node x){ Node y; if(x->right!=NIL){ return treeMinimum(x->right); } y=x->parent; while(y!=NIL && x==y->right){ x=y; y=y->parent; } return y; } //treeSearch(root,x)を使っているのでz==treeSearch void treeDelete(Node z){ Node y; // node to be deleted Node x; // child of y if(z->left == NIL || z->right == NIL){ y=z; }else{ //Treeに当たるものがないので書かないでやってみる y=treeSuccessor(z); } if(y->left !=NIL){ x=y->left; } else{ x=y->right; } if(x!=NIL){ x->parent=y->parent; } if(y->parent==NIL){ root=x; }else if(y==y->parent->left){ y->parent->left=x; }else{ y->parent->right=x; } if(y!=z){ z->key=y->key; } } void insert(int k){ Node y = NIL; Node x = root; Node z; z = malloc(sizeof(struct node)); z->key = k; z->left = NIL; z->right = NIL; while(x!=NIL){ y=x; if(z->key < x->key){ x=x->left; }else{ x=x->right; } } z->parent=y; if(y==NIL){ root=z; }else if(z->key < y->key){ y->left=z; }else{ y->right=z; } } void inorder(Node u){ if(u!=NIL){ inorder(u->left); printf(" %d",u->key); inorder(u->right); } } void preorder(Node u){ if(u==NIL){ return; } printf(" %d",u->key); preorder(u->left); preorder(u->right); } int main(){ int n, i, x; char com[20]; scanf("%d", &n); for ( i = 0; i < n; i++ ){ scanf("%s", com); if ( com[0] == 'f' ){ scanf("%d", &x); Node t = treeSearch(root, x); if ( t != NIL ) printf("yes\n"); else printf("no\n"); } else if ( com[0] == 'i' ){ scanf("%d", &x); insert(x); } else if ( com[0] == 'p' ){ inorder(root); printf("\n"); preorder(root); printf("\n"); } else if ( com[0] == 'd' ){ scanf("%d", &x); treeDelete(treeSearch(root, x)); } } return 0; }
#include<stdlib.h> #include<stdio.h> #include"grille.h" int main() { init_grid_ncurses(); /*add_cell(&g, 20, 20); add_cell(&g, 20, 21); add_cell(&g, 20, 22); add_cell(&g, 20, 26); add_cell(&g, 20, 27); add_cell(&g, 20, 28); add_cell(&g, 18, 24); add_cell(&g, 17, 24); add_cell(&g, 16, 24); add_cell(&g, 22, 24); add_cell(&g, 23, 24); add_cell(&g, 24, 24);*/ /*add_cell(&g, 50, 50); add_cell(&g, 51, 50); add_cell(&g, 52, 50); add_cell(&g, 50, 51); add_cell(&g, 50, 52); add_cell(&g, 52, 51); add_cell(&g, 52, 52);*/ add_cell(100, 50); add_cell(101, 50); add_cell(101, 51); add_cell(101, 52); add_cell(102, 51); randomize_grid(); start_game(); }
#include<stdio.h> int i; int Linear_search(int arr[],int x,int n) { for (i=0;i<n;i++) { if(arr[i]==x) printf("array index arr[%d]=%d",i,arr[i]); if(i==n) printf("not found"); } /*i=0; while(i<n&&arr[i]!=x) { i++; } if(i==n) printf("Not found\n"); else printf("%d is in index %d\n",x,i);*/ } int main() { int n,x,arr[50]; printf("enter array size:"); scanf("%d",&n); printf("enter array: "); for (i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("enter searching value:"); scanf("%d",&x); int m=Linear_search(arr,x,n); return 0; }
*/ /* inherited classes #ifndef _OZ000100000200044bP_H_ #define _OZ000100000200044bP_H_ #define OZClassPart0001000002fffffd_0_in_000100000200044b 1 #define OZClassPart0001000002fffffe_0_in_000100000200044b 1 #define OZClassPart000100000200044b_0_in_000100000200044b 0 #endif _OZ000100000200044bP_H_
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_helpers.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mtuomine <mtuomine@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/08 16:32:23 by mtuomine #+# #+# */ /* Updated: 2019/12/08 17:13:35 by mtuomine ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void print_permissions(mode_t mode) { ft_printf("%c", (mode & S_IRUSR) ? 'r' : '-'); ft_printf("%c", (mode & S_IWUSR) ? 'w' : '-'); ft_printf("%c", (mode & S_IXUSR) ? 'x' : '-'); ft_printf("%c", (mode & S_IRGRP) ? 'r' : '-'); ft_printf("%c", (mode & S_IWGRP) ? 'w' : '-'); ft_printf("%c", (mode & S_IXGRP) ? 'x' : '-'); ft_printf("%c", (mode & S_IROTH) ? 'r' : '-'); ft_printf("%c", (mode & S_IWOTH) ? 'w' : '-'); ft_printf("%c", (mode & S_IXOTH) ? 'x' : '-'); } void print_type(mode_t mode) { if (S_ISREG(mode)) ft_printf("%c", '-'); else if (S_ISDIR(mode)) ft_printf("%c", 'd'); else if (S_ISLNK(mode)) ft_printf("%c", 'l'); else if (S_ISSOCK(mode)) ft_printf("%c", 's'); else if (S_ISCHR(mode)) ft_printf("%c", 'c'); else if (S_ISBLK(mode)) ft_printf("%c", 'b'); else if (S_ISFIFO(mode)) ft_printf("%c", 'f'); print_permissions(mode); } void reset_column(int *i, t_layout *layout) { if (*i == layout->columns) { ft_printf("\n"); *i = 0; } }
/* PMSIS includes */ #include "pmsis.h" #include "omp.h" #define ARRAY_SIZE 512 uint32_t a[ARRAY_SIZE] = {0}; uint32_t b[ARRAY_SIZE] = {0}; uint32_t c[ARRAY_SIZE] = {0}; uint32_t errors = 0; /* Cluster main entry, executed by core 0. */ void cluster_delegate(void *arg) { printf("Cluster master core entry\n"); int32_t counter = 0; #pragma omp parallel { printf("[%d %d] Fork entry\n", pi_cluster_id(), omp_get_thread_num() ); #pragma omp barrier { #pragma omp atomic counter ++; } } printf("Core counter: %d\n", counter); if (counter != omp_get_num_threads()) { errors = 1; } printf("Cluster master core exit\n"); } void helloworld(void) { printf("Entering main controller\n"); uint32_t core_id = pi_core_id(), cluster_id = pi_cluster_id(); printf("[%d %d] Hello World!\n", cluster_id, core_id); struct pi_device cluster_dev; struct pi_cluster_conf cl_conf; /* Init cluster configuration structure. */ pi_cluster_conf_init(&cl_conf); cl_conf.id = 0; /* Set cluster ID. */ /* Configure & open cluster. */ pi_open_from_conf(&cluster_dev, &cl_conf); if (pi_cluster_open(&cluster_dev)) { printf("Cluster open failed !\n"); pmsis_exit(-1); } /* Prepare cluster task and send it to cluster. */ struct pi_cluster_task cl_task; pi_cluster_send_task_to_cl(&cluster_dev, pi_cluster_task(&cl_task, cluster_delegate, NULL)); pi_cluster_close(&cluster_dev); if (errors) { printf("Test failed!\n"); } else { printf("Test success!\n"); } pmsis_exit(errors); } /* Program Entry. */ int main(void) { printf("\n\n\t *** PMSIS HelloWorld ***\n\n"); return pmsis_kickoff((void *) helloworld); }
#ifndef _BLOOM_H #define _BLOOM_H #include <stdlib.h> #include <stdint.h> typedef struct { size_t asize; unsigned char *a; } BLOOM; BLOOM *bloom_create(size_t size); int bloom_destroy(BLOOM *bloom); int bloom_setbit(BLOOM *bloom, int n, ...); int bloom_check(BLOOM *bloom, int n, ...); #endif
/* Fast Artificial Neural Network Library (fann) Copyright (C) 2003-2012 Steffen Nissen (sn@leenissen.dk) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> /* strtof */ #include "floatfann.h" int main(int argc, char *argv[]) { fann_type *calc_out; fann_type input[3]; struct fann *ann = fann_create_from_file("fann_interface/net_eeg_data_float.net"); input[0] = strtof (argv[1], NULL); input[1] = strtof (argv[2], NULL); input[2] = strtof (argv[3], NULL); calc_out = fann_run(ann, input); // printf("is it blink? (%f,%f,%f) -> %f \n", input[0], input[1], input[2], calc_out[0]); printf("%f", calc_out[0]); fann_destroy(ann); return 0; }
/* AUTOGEN File: rtdb_sizeof_tmp.c */ #include <stdio.h> #include <stdint.h> #include "Sim2Turtle.h" int main(void) { FILE* f; f= fopen("rtdb_size.tmp", "w"); fprintf(f, "%lu\n", sizeof(Sim2Turtle)); fclose(f); return 0; } /* EOF: rtdb_sizeof_tmp.c */
/* * Copyright (c) 2015-~ lkwywhy * * This source code is released for free distribution under the terms of the * GNU General Public License * * Author: lkwywhy<lkwywhy@163.com> * Created Time: Mon 06 Jul 2015 03:06:04 PM CST * File Name: ./log.h * * Description: */ #ifndef _LOG_H #define _LOG_H #include <boost/log/trivial.hpp> int log_test(); int log_init() #endif
#include <stdio.h> void print() { printf("this is print\n"); }
/* THIS FILE HAS BEEN GENERATED, DO NOT MODIFY IT. */ /* * Copyright (C) 2018 ETH Zurich, University of Bologna * and GreenWaves Technologies * * 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 __INCLUDE_ARCHI_PWM_V1_PWM_V1_REGFIELDS_H__ #define __INCLUDE_ARCHI_PWM_V1_PWM_V1_REGFIELDS_H__ #if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__) #include <stdint.h> #include "archi/utils.h" #endif // // REGISTERS FIELDS // // ADV_TIMER0 start command bitfield. (access: R/W) #define PWM_T0_CMD_START_BIT 0 #define PWM_T0_CMD_START_WIDTH 1 #define PWM_T0_CMD_START_MASK 0x1 // ADV_TIMER0 stop command bitfield. (access: R/W) #define PWM_T0_CMD_STOP_BIT 1 #define PWM_T0_CMD_STOP_WIDTH 1 #define PWM_T0_CMD_STOP_MASK 0x2 // ADV_TIMER0 update command bitfield. (access: R/W) #define PWM_T0_CMD_UPDATE_BIT 2 #define PWM_T0_CMD_UPDATE_WIDTH 1 #define PWM_T0_CMD_UPDATE_MASK 0x4 // ADV_TIMER0 reset command bitfield. (access: R/W) #define PWM_T0_CMD_RESET_BIT 3 #define PWM_T0_CMD_RESET_WIDTH 1 #define PWM_T0_CMD_RESET_MASK 0x8 // ADV_TIMER0 arm command bitfield. (access: R/W) #define PWM_T0_CMD_ARM_BIT 4 #define PWM_T0_CMD_ARM_WIDTH 1 #define PWM_T0_CMD_ARM_MASK 0x10 // ADV_TIMER0 input source configuration bitfield: - 0-31: GPIO[0] to GPIO[31] - 32-35: Channel 0 to 3 of ADV_TIMER0 - 36-39: Channel 0 to 3 of ADV_TIMER1 - 40-43: Channel 0 to 3 of ADV_TIMER2 - 44-47: Channel 0 to 3 of ADV_TIMER3 (access: R/W) #define PWM_T0_CONFIG_INSEL_BIT 0 #define PWM_T0_CONFIG_INSEL_WIDTH 8 #define PWM_T0_CONFIG_INSEL_MASK 0xff // ADV_TIMER0 trigger mode configuration bitfield: - 3'h0: trigger event at each clock cycle. - 3'h1: trigger event if input source is 0 - 3'h2: trigger event if input source is 1 - 3'h3: trigger event on input source rising edge - 3'h4: trigger event on input source falling edge - 3'h5: trigger event on input source falling or rising edge - 3'h6: trigger event on input source rising edge when armed - 3'h7: trigger event on input source falling edge when armed (access: R/W) #define PWM_T0_CONFIG_MODE_BIT 8 #define PWM_T0_CONFIG_MODE_WIDTH 3 #define PWM_T0_CONFIG_MODE_MASK 0x700 // ADV_TIMER0 clock source configuration bitfield: - 1'b0: FLL - 1'b1: reference clock at 32kHz (access: R/W) #define PWM_T0_CONFIG_CLKSEL_BIT 11 #define PWM_T0_CONFIG_CLKSEL_WIDTH 1 #define PWM_T0_CONFIG_CLKSEL_MASK 0x800 // ADV_TIMER0 center-aligned mode configuration bitfield: - 1'b0: The counter counts up and down alternatively. - 1'b1: The counter counts up and resets to 0 when reach threshold. (access: R/W) #define PWM_T0_CONFIG_UPDOWNSEL_BIT 12 #define PWM_T0_CONFIG_UPDOWNSEL_WIDTH 1 #define PWM_T0_CONFIG_UPDOWNSEL_MASK 0x1000 // ADV_TIMER0 prescaler value configuration bitfield. (access: R/W) #define PWM_T0_CONFIG_PRESC_BIT 16 #define PWM_T0_CONFIG_PRESC_WIDTH 8 #define PWM_T0_CONFIG_PRESC_MASK 0xff0000 // ADV_TIMER0 threshold low part configuration bitfield. It defines start counter value. (access: R/W) #define PWM_T0_THRESHOLD_TH_LO_BIT 0 #define PWM_T0_THRESHOLD_TH_LO_WIDTH 16 #define PWM_T0_THRESHOLD_TH_LO_MASK 0xffff // ADV_TIMER0 threshold high part configuration bitfield. It defines end counter value. (access: R/W) #define PWM_T0_THRESHOLD_TH_HI_BIT 16 #define PWM_T0_THRESHOLD_TH_HI_WIDTH 16 #define PWM_T0_THRESHOLD_TH_HI_MASK 0xffff0000 // ADV_TIMER0 channel 0 threshold configuration bitfield. (access: R/W) #define PWM_T0_TH_CHANNEL0_TH_BIT 0 #define PWM_T0_TH_CHANNEL0_TH_WIDTH 16 #define PWM_T0_TH_CHANNEL0_TH_MASK 0xffff // ADV_TIMER0 channel 0 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T0_TH_CHANNEL0_MODE_BIT 16 #define PWM_T0_TH_CHANNEL0_MODE_WIDTH 3 #define PWM_T0_TH_CHANNEL0_MODE_MASK 0x70000 // ADV_TIMER0 channel 1 threshold configuration bitfield. (access: R/W) #define PWM_T0_TH_CHANNEL1_TH_BIT 0 #define PWM_T0_TH_CHANNEL1_TH_WIDTH 16 #define PWM_T0_TH_CHANNEL1_TH_MASK 0xffff // ADV_TIMER0 channel 1 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T0_TH_CHANNEL1_MODE_BIT 16 #define PWM_T0_TH_CHANNEL1_MODE_WIDTH 3 #define PWM_T0_TH_CHANNEL1_MODE_MASK 0x70000 // ADV_TIMER0 channel 2 threshold configuration bitfield. (access: R/W) #define PWM_T0_TH_CHANNEL2_TH_BIT 0 #define PWM_T0_TH_CHANNEL2_TH_WIDTH 16 #define PWM_T0_TH_CHANNEL2_TH_MASK 0xffff // ADV_TIMER0 channel 2 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T0_TH_CHANNEL2_MODE_BIT 16 #define PWM_T0_TH_CHANNEL2_MODE_WIDTH 3 #define PWM_T0_TH_CHANNEL2_MODE_MASK 0x70000 // ADV_TIMER0 channel 3 threshold configuration bitfield. (access: R/W) #define PWM_T0_TH_CHANNEL3_TH_BIT 0 #define PWM_T0_TH_CHANNEL3_TH_WIDTH 16 #define PWM_T0_TH_CHANNEL3_TH_MASK 0xffff // ADV_TIMER0 channel 3 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T0_TH_CHANNEL3_MODE_BIT 16 #define PWM_T0_TH_CHANNEL3_MODE_WIDTH 3 #define PWM_T0_TH_CHANNEL3_MODE_MASK 0x70000 // ADV_TIMER1 start command bitfield. (access: R/W) #define PWM_T1_CMD_START_BIT 0 #define PWM_T1_CMD_START_WIDTH 1 #define PWM_T1_CMD_START_MASK 0x1 // ADV_TIMER1 stop command bitfield. (access: R/W) #define PWM_T1_CMD_STOP_BIT 1 #define PWM_T1_CMD_STOP_WIDTH 1 #define PWM_T1_CMD_STOP_MASK 0x2 // ADV_TIMER1 update command bitfield. (access: R/W) #define PWM_T1_CMD_UPDATE_BIT 2 #define PWM_T1_CMD_UPDATE_WIDTH 1 #define PWM_T1_CMD_UPDATE_MASK 0x4 // ADV_TIMER1 reset command bitfield. (access: R/W) #define PWM_T1_CMD_RESET_BIT 3 #define PWM_T1_CMD_RESET_WIDTH 1 #define PWM_T1_CMD_RESET_MASK 0x8 // ADV_TIMER1 arm command bitfield. (access: R/W) #define PWM_T1_CMD_ARM_BIT 4 #define PWM_T1_CMD_ARM_WIDTH 1 #define PWM_T1_CMD_ARM_MASK 0x10 // ADV_TIMER1 input source configuration bitfield: - 0-31: GPIO[0] to GPIO[31] - 32-35: Channel 0 to 3 of ADV_TIMER0 - 36-39: Channel 0 to 3 of ADV_TIMER1 - 40-43: Channel 0 to 3 of ADV_TIMER2 - 44-47: Channel 0 to 3 of ADV_TIMER3 (access: R/W) #define PWM_T1_CONFIG_INSEL_BIT 0 #define PWM_T1_CONFIG_INSEL_WIDTH 8 #define PWM_T1_CONFIG_INSEL_MASK 0xff // ADV_TIMER1 trigger mode configuration bitfield: - 3'h0: trigger event at each clock cycle. - 3'h1: trigger event if input source is 0 - 3'h2: trigger event if input source is 1 - 3'h3: trigger event on input source rising edge - 3'h4: trigger event on input source falling edge - 3'h5: trigger event on input source falling or rising edge - 3'h6: trigger event on input source rising edge when armed - 3'h7: trigger event on input source falling edge when armed (access: R/W) #define PWM_T1_CONFIG_MODE_BIT 8 #define PWM_T1_CONFIG_MODE_WIDTH 3 #define PWM_T1_CONFIG_MODE_MASK 0x700 // ADV_TIMER1 clock source configuration bitfield: - 1'b0: FLL - 1'b1: reference clock at 32kHz (access: R/W) #define PWM_T1_CONFIG_CLKSEL_BIT 11 #define PWM_T1_CONFIG_CLKSEL_WIDTH 1 #define PWM_T1_CONFIG_CLKSEL_MASK 0x800 // ADV_TIMER1 center-aligned mode configuration bitfield: - 1'b0: The counter counts up and down alternatively. - 1'b1: The counter counts up and resets to 0 when reach threshold. (access: R/W) #define PWM_T1_CONFIG_UPDOWNSEL_BIT 12 #define PWM_T1_CONFIG_UPDOWNSEL_WIDTH 1 #define PWM_T1_CONFIG_UPDOWNSEL_MASK 0x1000 // ADV_TIMER1 prescaler value configuration bitfield. (access: R/W) #define PWM_T1_CONFIG_PRESC_BIT 16 #define PWM_T1_CONFIG_PRESC_WIDTH 8 #define PWM_T1_CONFIG_PRESC_MASK 0xff0000 // ADV_TIMER1 threshold low part configuration bitfield. It defines start counter value. (access: R/W) #define PWM_T1_THRESHOLD_TH_LO_BIT 0 #define PWM_T1_THRESHOLD_TH_LO_WIDTH 16 #define PWM_T1_THRESHOLD_TH_LO_MASK 0xffff // ADV_TIMER1 threshold high part configuration bitfield. It defines end counter value. (access: R/W) #define PWM_T1_THRESHOLD_TH_HI_BIT 16 #define PWM_T1_THRESHOLD_TH_HI_WIDTH 16 #define PWM_T1_THRESHOLD_TH_HI_MASK 0xffff0000 // ADV_TIMER1 channel 0 threshold configuration bitfield. (access: R/W) #define PWM_T1_TH_CHANNEL0_TH_BIT 0 #define PWM_T1_TH_CHANNEL0_TH_WIDTH 16 #define PWM_T1_TH_CHANNEL0_TH_MASK 0xffff // ADV_TIMER1 channel 0 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T1_TH_CHANNEL0_MODE_BIT 16 #define PWM_T1_TH_CHANNEL0_MODE_WIDTH 3 #define PWM_T1_TH_CHANNEL0_MODE_MASK 0x70000 // ADV_TIMER1 channel 1 threshold configuration bitfield. (access: R/W) #define PWM_T1_TH_CHANNEL1_TH_BIT 0 #define PWM_T1_TH_CHANNEL1_TH_WIDTH 16 #define PWM_T1_TH_CHANNEL1_TH_MASK 0xffff // ADV_TIMER1 channel 1 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T1_TH_CHANNEL1_MODE_BIT 16 #define PWM_T1_TH_CHANNEL1_MODE_WIDTH 3 #define PWM_T1_TH_CHANNEL1_MODE_MASK 0x70000 // ADV_TIMER1 channel 2 threshold configuration bitfield. (access: R/W) #define PWM_T1_TH_CHANNEL2_TH_BIT 0 #define PWM_T1_TH_CHANNEL2_TH_WIDTH 16 #define PWM_T1_TH_CHANNEL2_TH_MASK 0xffff // ADV_TIMER1 channel 2 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T1_TH_CHANNEL2_MODE_BIT 16 #define PWM_T1_TH_CHANNEL2_MODE_WIDTH 3 #define PWM_T1_TH_CHANNEL2_MODE_MASK 0x70000 // ADV_TIMER1 channel 3 threshold configuration bitfield. (access: R/W) #define PWM_T1_TH_CHANNEL3_TH_BIT 0 #define PWM_T1_TH_CHANNEL3_TH_WIDTH 16 #define PWM_T1_TH_CHANNEL3_TH_MASK 0xffff // ADV_TIMER1 channel 3 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T1_TH_CHANNEL3_MODE_BIT 16 #define PWM_T1_TH_CHANNEL3_MODE_WIDTH 3 #define PWM_T1_TH_CHANNEL3_MODE_MASK 0x70000 // ADV_TIMER2 start command bitfield. (access: R/W) #define PWM_T2_CMD_START_BIT 0 #define PWM_T2_CMD_START_WIDTH 1 #define PWM_T2_CMD_START_MASK 0x1 // ADV_TIMER2 stop command bitfield. (access: R/W) #define PWM_T2_CMD_STOP_BIT 1 #define PWM_T2_CMD_STOP_WIDTH 1 #define PWM_T2_CMD_STOP_MASK 0x2 // ADV_TIMER2 update command bitfield. (access: R/W) #define PWM_T2_CMD_UPDATE_BIT 2 #define PWM_T2_CMD_UPDATE_WIDTH 1 #define PWM_T2_CMD_UPDATE_MASK 0x4 // ADV_TIMER2 reset command bitfield. (access: R/W) #define PWM_T2_CMD_RESET_BIT 3 #define PWM_T2_CMD_RESET_WIDTH 1 #define PWM_T2_CMD_RESET_MASK 0x8 // ADV_TIMER2 arm command bitfield. (access: R/W) #define PWM_T2_CMD_ARM_BIT 4 #define PWM_T2_CMD_ARM_WIDTH 1 #define PWM_T2_CMD_ARM_MASK 0x10 // ADV_TIMER2 input source configuration bitfield: - 0-31: GPIO[0] to GPIO[31] - 32-35: Channel 0 to 3 of ADV_TIMER0 - 36-39: Channel 0 to 3 of ADV_TIMER1 - 40-43: Channel 0 to 3 of ADV_TIMER2 - 44-47: Channel 0 to 3 of ADV_TIMER3 (access: R/W) #define PWM_T2_CONFIG_INSEL_BIT 0 #define PWM_T2_CONFIG_INSEL_WIDTH 8 #define PWM_T2_CONFIG_INSEL_MASK 0xff // ADV_TIMER2 trigger mode configuration bitfield: - 3'h0: trigger event at each clock cycle. - 3'h1: trigger event if input source is 0 - 3'h2: trigger event if input source is 1 - 3'h3: trigger event on input source rising edge - 3'h4: trigger event on input source falling edge - 3'h5: trigger event on input source falling or rising edge - 3'h6: trigger event on input source rising edge when armed - 3'h7: trigger event on input source falling edge when armed (access: R/W) #define PWM_T2_CONFIG_MODE_BIT 8 #define PWM_T2_CONFIG_MODE_WIDTH 3 #define PWM_T2_CONFIG_MODE_MASK 0x700 // ADV_TIMER2 clock source configuration bitfield: - 1'b0: FLL - 1'b1: reference clock at 32kHz (access: R/W) #define PWM_T2_CONFIG_CLKSEL_BIT 11 #define PWM_T2_CONFIG_CLKSEL_WIDTH 1 #define PWM_T2_CONFIG_CLKSEL_MASK 0x800 // ADV_TIMER2 center-aligned mode configuration bitfield: - 1'b0: The counter counts up and down alternatively. - 1'b1: The counter counts up and resets to 0 when reach threshold. (access: R/W) #define PWM_T2_CONFIG_UPDOWNSEL_BIT 12 #define PWM_T2_CONFIG_UPDOWNSEL_WIDTH 1 #define PWM_T2_CONFIG_UPDOWNSEL_MASK 0x1000 // ADV_TIMER2 prescaler value configuration bitfield. (access: R/W) #define PWM_T2_CONFIG_PRESC_BIT 16 #define PWM_T2_CONFIG_PRESC_WIDTH 8 #define PWM_T2_CONFIG_PRESC_MASK 0xff0000 // ADV_TIMER2 threshold low part configuration bitfield. It defines start counter value. (access: R/W) #define PWM_T2_THRESHOLD_TH_LO_BIT 0 #define PWM_T2_THRESHOLD_TH_LO_WIDTH 16 #define PWM_T2_THRESHOLD_TH_LO_MASK 0xffff // ADV_TIMER2 threshold high part configuration bitfield. It defines end counter value. (access: R/W) #define PWM_T2_THRESHOLD_TH_HI_BIT 16 #define PWM_T2_THRESHOLD_TH_HI_WIDTH 16 #define PWM_T2_THRESHOLD_TH_HI_MASK 0xffff0000 // ADV_TIMER2 channel 0 threshold configuration bitfield. (access: R/W) #define PWM_T2_TH_CHANNEL0_TH_BIT 0 #define PWM_T2_TH_CHANNEL0_TH_WIDTH 16 #define PWM_T2_TH_CHANNEL0_TH_MASK 0xffff // ADV_TIMER2 channel 0 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T2_TH_CHANNEL0_MODE_BIT 16 #define PWM_T2_TH_CHANNEL0_MODE_WIDTH 3 #define PWM_T2_TH_CHANNEL0_MODE_MASK 0x70000 // ADV_TIMER2 channel 1 threshold configuration bitfield. (access: R/W) #define PWM_T2_TH_CHANNEL1_TH_BIT 0 #define PWM_T2_TH_CHANNEL1_TH_WIDTH 16 #define PWM_T2_TH_CHANNEL1_TH_MASK 0xffff // ADV_TIMER2 channel 1 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T2_TH_CHANNEL1_MODE_BIT 16 #define PWM_T2_TH_CHANNEL1_MODE_WIDTH 3 #define PWM_T2_TH_CHANNEL1_MODE_MASK 0x70000 // ADV_TIMER2 channel 2 threshold configuration bitfield. (access: R/W) #define PWM_T2_TH_CHANNEL2_TH_BIT 0 #define PWM_T2_TH_CHANNEL2_TH_WIDTH 16 #define PWM_T2_TH_CHANNEL2_TH_MASK 0xffff // ADV_TIMER2 channel 2 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T2_TH_CHANNEL2_MODE_BIT 16 #define PWM_T2_TH_CHANNEL2_MODE_WIDTH 3 #define PWM_T2_TH_CHANNEL2_MODE_MASK 0x70000 // ADV_TIMER2 channel 3 threshold configuration bitfield. (access: R/W) #define PWM_T2_TH_CHANNEL3_TH_BIT 0 #define PWM_T2_TH_CHANNEL3_TH_WIDTH 16 #define PWM_T2_TH_CHANNEL3_TH_MASK 0xffff // ADV_TIMER2 channel 3 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T2_TH_CHANNEL3_MODE_BIT 16 #define PWM_T2_TH_CHANNEL3_MODE_WIDTH 3 #define PWM_T2_TH_CHANNEL3_MODE_MASK 0x70000 // ADV_TIMER3 start command bitfield. (access: R/W) #define PWM_T3_CMD_START_BIT 0 #define PWM_T3_CMD_START_WIDTH 1 #define PWM_T3_CMD_START_MASK 0x1 // ADV_TIMER3 stop command bitfield. (access: R/W) #define PWM_T3_CMD_STOP_BIT 1 #define PWM_T3_CMD_STOP_WIDTH 1 #define PWM_T3_CMD_STOP_MASK 0x2 // ADV_TIMER3 update command bitfield. (access: R/W) #define PWM_T3_CMD_UPDATE_BIT 2 #define PWM_T3_CMD_UPDATE_WIDTH 1 #define PWM_T3_CMD_UPDATE_MASK 0x4 // ADV_TIMER3 reset command bitfield. (access: R/W) #define PWM_T3_CMD_RESET_BIT 3 #define PWM_T3_CMD_RESET_WIDTH 1 #define PWM_T3_CMD_RESET_MASK 0x8 // ADV_TIMER3 arm command bitfield. (access: R/W) #define PWM_T3_CMD_ARM_BIT 4 #define PWM_T3_CMD_ARM_WIDTH 1 #define PWM_T3_CMD_ARM_MASK 0x10 // ADV_TIMER3 input source configuration bitfield: - 0-31: GPIO[0] to GPIO[31] - 32-35: Channel 0 to 3 of ADV_TIMER0 - 36-39: Channel 0 to 3 of ADV_TIMER1 - 40-43: Channel 0 to 3 of ADV_TIMER2 - 44-47: Channel 0 to 3 of ADV_TIMER3 (access: R/W) #define PWM_T3_CONFIG_INSEL_BIT 0 #define PWM_T3_CONFIG_INSEL_WIDTH 8 #define PWM_T3_CONFIG_INSEL_MASK 0xff // ADV_TIMER3 trigger mode configuration bitfield: - 3'h0: trigger event at each clock cycle. - 3'h1: trigger event if input source is 0 - 3'h2: trigger event if input source is 1 - 3'h3: trigger event on input source rising edge - 3'h4: trigger event on input source falling edge - 3'h5: trigger event on input source falling or rising edge - 3'h6: trigger event on input source rising edge when armed - 3'h7: trigger event on input source falling edge when armed (access: R/W) #define PWM_T3_CONFIG_MODE_BIT 8 #define PWM_T3_CONFIG_MODE_WIDTH 3 #define PWM_T3_CONFIG_MODE_MASK 0x700 // ADV_TIMER3 clock source configuration bitfield: - 1'b0: FLL - 1'b1: reference clock at 32kHz (access: R/W) #define PWM_T3_CONFIG_CLKSEL_BIT 11 #define PWM_T3_CONFIG_CLKSEL_WIDTH 1 #define PWM_T3_CONFIG_CLKSEL_MASK 0x800 // ADV_TIMER3 center-aligned mode configuration bitfield: - 1'b0: The counter counts up and down alternatively. - 1'b1: The counter counts up and resets to 0 when reach threshold. (access: R/W) #define PWM_T3_CONFIG_UPDOWNSEL_BIT 12 #define PWM_T3_CONFIG_UPDOWNSEL_WIDTH 1 #define PWM_T3_CONFIG_UPDOWNSEL_MASK 0x1000 // ADV_TIMER3 prescaler value configuration bitfield. (access: R/W) #define PWM_T3_CONFIG_PRESC_BIT 16 #define PWM_T3_CONFIG_PRESC_WIDTH 8 #define PWM_T3_CONFIG_PRESC_MASK 0xff0000 // ADV_TIMER3 threshold low part configuration bitfield. It defines start counter value. (access: R/W) #define PWM_T3_THRESHOLD_TH_LO_BIT 0 #define PWM_T3_THRESHOLD_TH_LO_WIDTH 16 #define PWM_T3_THRESHOLD_TH_LO_MASK 0xffff // ADV_TIMER3 threshold high part configuration bitfield. It defines end counter value. (access: R/W) #define PWM_T3_THRESHOLD_TH_HI_BIT 16 #define PWM_T3_THRESHOLD_TH_HI_WIDTH 16 #define PWM_T3_THRESHOLD_TH_HI_MASK 0xffff0000 // ADV_TIMER3 channel 0 threshold configuration bitfield. (access: R/W) #define PWM_T3_TH_CHANNEL0_TH_BIT 0 #define PWM_T3_TH_CHANNEL0_TH_WIDTH 16 #define PWM_T3_TH_CHANNEL0_TH_MASK 0xffff // ADV_TIMER3 channel 0 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T3_TH_CHANNEL0_MODE_BIT 16 #define PWM_T3_TH_CHANNEL0_MODE_WIDTH 3 #define PWM_T3_TH_CHANNEL0_MODE_MASK 0x70000 // ADV_TIMER3 channel 1 threshold configuration bitfield. (access: R/W) #define PWM_T3_TH_CHANNEL1_TH_BIT 0 #define PWM_T3_TH_CHANNEL1_TH_WIDTH 16 #define PWM_T3_TH_CHANNEL1_TH_MASK 0xffff // ADV_TIMER3 channel 1 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T3_TH_CHANNEL1_MODE_BIT 16 #define PWM_T3_TH_CHANNEL1_MODE_WIDTH 3 #define PWM_T3_TH_CHANNEL1_MODE_MASK 0x70000 // ADV_TIMER3 channel 2 threshold configuration bitfield. (access: R/W) #define PWM_T3_TH_CHANNEL2_TH_BIT 0 #define PWM_T3_TH_CHANNEL2_TH_WIDTH 16 #define PWM_T3_TH_CHANNEL2_TH_MASK 0xffff // ADV_TIMER3 channel 2 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T3_TH_CHANNEL2_MODE_BIT 16 #define PWM_T3_TH_CHANNEL2_MODE_WIDTH 3 #define PWM_T3_TH_CHANNEL2_MODE_MASK 0x70000 // ADV_TIMER3 channel 3 threshold configuration bitfield. (access: R/W) #define PWM_T3_TH_CHANNEL3_TH_BIT 0 #define PWM_T3_TH_CHANNEL3_TH_WIDTH 16 #define PWM_T3_TH_CHANNEL3_TH_MASK 0xffff // ADV_TIMER3 channel 3 threshold match action on channel output signal configuration bitfield: - 3'h0: set. - 3'h1: toggle then next threshold match action is clear. - 3'h2: set then next threshold match action is clear. - 3'h3: toggle. - 3'h4: clear. - 3'h5: toggle then next threshold match action is set. - 3'h6: clear then next threshold match action is set. (access: R/W) #define PWM_T3_TH_CHANNEL3_MODE_BIT 16 #define PWM_T3_TH_CHANNEL3_MODE_WIDTH 3 #define PWM_T3_TH_CHANNEL3_MODE_MASK 0x70000 // ADV_TIMER output event 0 source configuration bitfiled: - 4'h0: ADV_TIMER0 channel 0. - 4'h1: ADV_TIMER0 channel 1. - 4'h2: ADV_TIMER0 channel 2. - 4'h3: ADV_TIMER0 channel 3. - 4'h4: ADV_TIMER1 channel 0. - 4'h5: ADV_TIMER1 channel 1. - 4'h6: ADV_TIMER1 channel 2. - 4'h7: ADV_TIMER1 channel 3. - 4'h8: ADV_TIMER2 channel 0. - 4'h9: ADV_TIMER2 channel 1. - 4'hA: ADV_TIMER2 channel 2. - 4'hB: ADV_TIMER2 channel 3. - 4'hC: ADV_TIMER3 channel 0. - 4'hD: ADV_TIMER3 channel 1. - 4'hE: ADV_TIMER3 channel 2. - 4'hF: ADV_TIMER3 channel 3. (access: R/W) #define PWM_EVENT_CFG_SEL0_BIT 0 #define PWM_EVENT_CFG_SEL0_WIDTH 4 #define PWM_EVENT_CFG_SEL0_MASK 0xf // ADV_TIMER output event 1 source configuration bitfiled: - 4'h0: ADV_TIMER0 channel 0. - 4'h1: ADV_TIMER0 channel 1. - 4'h2: ADV_TIMER0 channel 2. - 4'h3: ADV_TIMER0 channel 3. - 4'h4: ADV_TIMER1 channel 0. - 4'h5: ADV_TIMER1 channel 1. - 4'h6: ADV_TIMER1 channel 2. - 4'h7: ADV_TIMER1 channel 3. - 4'h8: ADV_TIMER2 channel 0. - 4'h9: ADV_TIMER2 channel 1. - 4'hA: ADV_TIMER2 channel 2. - 4'hB: ADV_TIMER2 channel 3. - 4'hC: ADV_TIMER3 channel 0. - 4'hD: ADV_TIMER3 channel 1. - 4'hE: ADV_TIMER3 channel 2. - 4'hF: ADV_TIMER3 channel 3. (access: R/W) #define PWM_EVENT_CFG_SEL1_BIT 4 #define PWM_EVENT_CFG_SEL1_WIDTH 4 #define PWM_EVENT_CFG_SEL1_MASK 0xf0 // ADV_TIMER output event 2 source configuration bitfiled: - 4'h0: ADV_TIMER0 channel 0. - 4'h1: ADV_TIMER0 channel 1. - 4'h2: ADV_TIMER0 channel 2. - 4'h3: ADV_TIMER0 channel 3. - 4'h4: ADV_TIMER1 channel 0. - 4'h5: ADV_TIMER1 channel 1. - 4'h6: ADV_TIMER1 channel 2. - 4'h7: ADV_TIMER1 channel 3. - 4'h8: ADV_TIMER2 channel 0. - 4'h9: ADV_TIMER2 channel 1. - 4'hA: ADV_TIMER2 channel 2. - 4'hB: ADV_TIMER2 channel 3. - 4'hC: ADV_TIMER3 channel 0. - 4'hD: ADV_TIMER3 channel 1. - 4'hE: ADV_TIMER3 channel 2. - 4'hF: ADV_TIMER3 channel 3. (access: R/W) #define PWM_EVENT_CFG_SEL2_BIT 8 #define PWM_EVENT_CFG_SEL2_WIDTH 4 #define PWM_EVENT_CFG_SEL2_MASK 0xf00 // ADV_TIMER output event 3 source configuration bitfiled: - 4'h0: ADV_TIMER0 channel 0. - 4'h1: ADV_TIMER0 channel 1. - 4'h2: ADV_TIMER0 channel 2. - 4'h3: ADV_TIMER0 channel 3. - 4'h4: ADV_TIMER1 channel 0. - 4'h5: ADV_TIMER1 channel 1. - 4'h6: ADV_TIMER1 channel 2. - 4'h7: ADV_TIMER1 channel 3. - 4'h8: ADV_TIMER2 channel 0. - 4'h9: ADV_TIMER2 channel 1. - 4'hA: ADV_TIMER2 channel 2. - 4'hB: ADV_TIMER2 channel 3. - 4'hC: ADV_TIMER3 channel 0. - 4'hD: ADV_TIMER3 channel 1. - 4'hE: ADV_TIMER3 channel 2. - 4'hF: ADV_TIMER3 channel 3. (access: R/W) #define PWM_EVENT_CFG_SEL3_BIT 12 #define PWM_EVENT_CFG_SEL3_WIDTH 4 #define PWM_EVENT_CFG_SEL3_MASK 0xf000 // ADV_TIMER output event enable configuration bitfield. ENA[i]=1 enables output event i generation. (access: R/W) #define PWM_EVENT_CFG_ENA_BIT 16 #define PWM_EVENT_CFG_ENA_WIDTH 4 #define PWM_EVENT_CFG_ENA_MASK 0xf0000 // ADV_TIMER clock gating configuration bitfield. - ENA[i]=0: clock gate ADV_TIMERi. - ENA[i]=1: enable ADV_TIMERi. (access: R/W) #define PWM_CG_ENA_BIT 0 #define PWM_CG_ENA_WIDTH 16 #define PWM_CG_ENA_MASK 0xffff #endif
/*++ Copyright (C) Microsoft. All rights reserved. Module Name: privdefs.h Abstract: This header file contains prototypes for routines that call into kernel exports or use definitions that are not exposed to regular drivers via WDM headers. Environment: Kernel mode --*/ // // Prototype declarations for various NT wrappers. // ULONG GpiopGetBaseRegistrationBufferSize ( VOID ); VOID GpiopInitializeIdleStateBufferAndCount ( __inout PVOID PowerRegistrationBuffer, __in ULONG ComponentId, __in PVOID IdleStateBuffer, __in ULONG IdleStateCount ); VOID GpiopInitializePrimaryDevice ( __inout PVOID PowerRegistrationBuffer, __in ULONG ComponentCount, __in PPO_FX_COMPONENT_ACTIVE_CONDITION_CALLBACK ComponentActiveCallback, __in PPO_FX_COMPONENT_IDLE_CONDITION_CALLBACK ComponentIdleCallback, __in PPO_FX_COMPONENT_IDLE_STATE_CALLBACK ComponentIdleStateCallback, __in PPO_FX_DEVICE_POWER_REQUIRED_CALLBACK DevicePowerRequiredCallback, __in PPO_FX_DEVICE_POWER_NOT_REQUIRED_CALLBACK DevicePowerNotRequiredCallback, __in PPO_FX_POWER_CONTROL_CALLBACK PowerControlCallback, __in PVOID DeviceContext, __in PPO_FX_COMPONENT_CRITICAL_TRANSITION_CALLBACK CriticalTransitionCallback ); NTSTATUS GpiopRegisterPrimaryDeviceInternal ( __in PDEVICE_OBJECT WdmDevice, __in PVOID RuntimePower, __out POHANDLE *PowerHandle ); NTSTATUS GpioHalEnableInterrupt ( __in ULONG Gsiv, __in KINTERRUPT_MODE InterruptMode, __in KINTERRUPT_POLARITY Polarity ); NTSTATUS GpioHalDisableInterrupt ( __in ULONG Gsiv, __in KINTERRUPT_MODE InterruptMode, __in KINTERRUPT_POLARITY Polarity ); NTSTATUS GpioHalMaskInterrupt ( __in ULONG Gsiv, __in ULONG Flags ); NTSTATUS GpioHalUnmaskInterrupt ( __in ULONG Gsiv, __in ULONG Flags ); VOID GpiopInvokeIsrForGsiv ( __in ULONG Gsiv, __in ULONG_PTR Context, __out PBOOLEAN IsrWasDispatched ); BOOLEAN GpiopExTryQueueWorkItem ( __inout PWORK_QUEUE_ITEM WorkItem, __in WORK_QUEUE_TYPE QueueType ); PVOID GpiopExAllocateTimerInternal ( _In_ PEXT_CALLBACK Callback, _In_opt_ PVOID Context );
#include<stdio.h> # define max 20 void freq(int [],int); int main() { int n,i,a[max]; printf("Enter the Size of Array:\t"); scanf("%d",&n); printf("Enter %d integers:\t",n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } freq(a,n); return 0; } void freq(int a[],int n) { int i,j,k,c=0,num; for(i=0;i<n;i++) { num=a[i]; c=1; for(j=i+1;j<n;j++) { if(a[j]==num) { c++; for(k=0;k<n;k++) { a[k]=a[k+1]; } n--; j--; } } printf("The Frequency element is %d and %d:\n",a[i],c); } }
#include "genresult.cuh" #include <sys/time.h> /* Put your own kernel(s) here*/ __device__ float segmented_scan_design(const int lane,const int* rows, float* ptrs){ if(lane>=1 && rows[threadIdx.x] == rows[threadIdx.x-1]) ptrs[threadIdx.x]+=ptrs[threadIdx.x-1]; if(lane>=2 && rows[threadIdx.x] == rows[threadIdx.x-2]) ptrs[threadIdx.x]+=ptrs[threadIdx.x-2]; if(lane>=4 && rows[threadIdx.x] == rows[threadIdx.x-4]) ptrs[threadIdx.x]+=ptrs[threadIdx.x-4]; if(lane>=8 && rows[threadIdx.x] == rows[threadIdx.x-8]) ptrs[threadIdx.x]+=ptrs[threadIdx.x-8]; if(lane>=16 && rows[threadIdx.x] == rows[threadIdx.x-16]) ptrs[threadIdx.x]+=ptrs[threadIdx.x-16]; return ptrs[threadIdx.x]; } __global__ void putProduct_kernel_design(int nz, int *rIndices, int *cIndices, float *values, int M, int N, float *vector, float *result){ /*Put your kernel(s) implementation here, you don't have to use exactly the * same kernel name */ //create a shared memory; __shared__ int rows[1024]; __shared__ float ptrs[1024]; int thread_id = threadIdx.x + (blockIdx.x *blockDim.x); int total_number_of_threads = blockDim.x * gridDim.x; int iteration = nz % total_number_of_threads ? nz/total_number_of_threads + 1 : nz/total_number_of_threads; for( int i = 0 ; i < iteration ; i++ ) { int data_id = thread_id + i* total_number_of_threads; if( data_id < nz ) { float data = values[data_id]; int row = rIndices[data_id]; int column = cIndices[data_id]; float multiplication_value = data * vector[column]; //copy values into the shared memory; ptrs[threadIdx.x] = multiplication_value; rows[threadIdx.x] = row; //atomicAdd(&result[row],multiplication_value); __syncthreads(); //warp details of the thread; unsigned int warpid = threadIdx.x>>5; unsigned int warp_first_threadId = warpid<<5; unsigned int warp_last_threadId = warp_first_threadId+31; const unsigned int lane = threadIdx.x%32; float val = segmented_scan_design(lane,rows,ptrs); row = rows[threadIdx.x]; __syncthreads(); /*if the next value of the row different from this index row value, then need to copy in the result matrix;*/ if((threadIdx.x == warp_last_threadId) || (rows[threadIdx.x] != rows[threadIdx.x+1])){ //do an atomic add; atomicAdd(&result[rows[threadIdx.x]],ptrs[threadIdx.x]); } } } } typedef struct cFormat{ int row; int col; float val; }cFormat; int comparisonFunction(const void* a, const void* b){ int l = ((cFormat*)a)->row; int r = ((cFormat*)b)->row; return (l-r); } void getMulDesign(MatrixInfo * mat, MatrixInfo * vec, MatrixInfo * res, int blockSize, int blockNum){ /*Allocate*/ int number_of_non_zeros = mat->nz; int *row_indices = mat->rIndex; int *column_indices = mat->cIndex; float *values = mat->val; int M = mat->M; int N = mat->N; float *vector = vec->val; float *result = res->val; /*Sorting the rows in the order*/ cFormat* arrayOfCoordinates = (cFormat*)malloc(sizeof(cFormat)*mat->nz); for(int i=0;i<mat->nz;i++){ arrayOfCoordinates[i].row = row_indices[i]; arrayOfCoordinates[i].col = column_indices[i]; arrayOfCoordinates[i].val = values[i]; } //apply the inbuilt quicksort function; qsort(arrayOfCoordinates,mat->nz,sizeof(cFormat),comparisonFunction); //get the sorted rows back into the row_indices and column indices and values; for(int i=0;i<mat->nz;i++){ row_indices[i] = arrayOfCoordinates[i].row; column_indices[i] = arrayOfCoordinates[i].col; values[i] = arrayOfCoordinates[i].val; } printf("\nGPU Code"); printf("\nBlock Size : %lu, Number of Blocks : %lu, nz : %lu\n",blockSize,blockNum,number_of_non_zeros); /* Device copies of the required values */ int * d_rIndices; int * d_cIndices; float *d_values; float *d_vector; float *d_result; /* Allocate values for the device copies */ cudaMalloc((void**)&d_rIndices, sizeof(int)*number_of_non_zeros); cudaMalloc((void**)&d_cIndices, sizeof(int)*number_of_non_zeros); cudaMalloc((void**)&d_values, sizeof(float)*number_of_non_zeros); cudaMalloc((void**)&d_vector, sizeof(float)*N); cudaMalloc((void**)&d_result, sizeof(float)*M); /* Set all the result values to be zeros */ cudaMemset(d_result, 0, sizeof(float)*M); /* Copying values from host to device */ cudaMemcpy(d_rIndices,row_indices,sizeof(int)*number_of_non_zeros, cudaMemcpyHostToDevice); cudaMemcpy(d_cIndices,column_indices, sizeof(int)*number_of_non_zeros , cudaMemcpyHostToDevice); cudaMemcpy(d_values,values, sizeof(float)*number_of_non_zeros,cudaMemcpyHostToDevice); cudaMemcpy(d_vector,vector, sizeof(float)*N, cudaMemcpyHostToDevice); //int *numberLeftForEachRow = (int*)malloc(sizeof(int)*M); //memset(numberLeftForEachRow,0,sizeof(int)*M); //int index =0; struct timespec start, end; cudaDeviceSynchronize(); clock_gettime(CLOCK_MONOTONIC_RAW, &start); /*Your own magic here!*/ putProduct_kernel_design<<<blockSize,blockNum>>>(number_of_non_zeros,d_rIndices,d_cIndices,d_values,M,N,d_vector,d_result); cudaDeviceSynchronize(); clock_gettime(CLOCK_MONOTONIC_RAW, &end); printf("Your Own Kernel Time: %lu micro-seconds\n", 1000000 * (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000); /*Deallocate*/ cudaMemcpy(result,d_result,sizeof(float)*M, cudaMemcpyDeviceToHost); res->val = result; /*Deallocate, please*/ cudaFree(d_rIndices); cudaFree(d_cIndices); cudaFree(d_values); cudaFree(d_vector); cudaFree(d_result); }
#include "petiga.h" #include "petigagrid.h" #include <petscblaslapack.h> #include <petsc/private/pcimpl.h> typedef struct { PetscInt dim,dof; PetscInt overlap[3]; PetscInt ghost_start[3]; PetscInt ghost_width[3]; LGMap lgmap; Mat mat; } PC_BBB; static inline PetscInt Index3D(const PetscInt start[3],const PetscInt width[3], PetscInt i,PetscInt j,PetscInt k) { if (start) { i -= start[0]; j -= start[1]; k -= start[2]; } return i + j * width[0] + k * width[0] * width[1]; } static PetscInt ComputeOverlap(const PetscInt lgmap[],PetscInt bs, PetscInt Astart,PetscInt Aend, const PetscInt gstart[3],const PetscInt gwidth[3], const PetscInt overlap[3], PetscInt iA,PetscInt jA,PetscInt kA, PetscInt indices[]) { PetscInt igs = gstart[0], ige = gstart[0]+gwidth[0], iov = overlap[0]; PetscInt jgs = gstart[1], jge = gstart[1]+gwidth[1], jov = overlap[1]; PetscInt kgs = gstart[2], kge = gstart[2]+gwidth[2], kov = overlap[2]; PetscInt i, iL = PetscMax(iA-iov,igs), iR = PetscMin(iA+iov,ige-1); PetscInt j, jL = PetscMax(jA-jov,jgs), jR = PetscMin(jA+jov,jge-1); PetscInt k, kL = PetscMax(kA-kov,kgs), kR = PetscMin(kA+kov,kge-1); PetscInt c, pos = 0; for (i=iL; i<=iR; i++) for (j=jL; j<=jR; j++) for (k=kL; k<=kR; k++) { PetscInt Alocal = Index3D(gstart,gwidth,i,j,k); PetscInt Aglobal = lgmap[Alocal]; if (PetscUnlikely(Aglobal < Astart || Aglobal >= Aend)) continue; for (c=0; c<bs; c++) indices[pos++] = c + bs*Aglobal; } return pos; } static inline PetscErrorCode InferMatrixType(Mat A,PetscBool *aij,PetscBool *baij,PetscBool *sbaij) { void (*f)(void) = NULL; PetscErrorCode ierr; PetscFunctionBegin; *aij = *baij = *sbaij = PETSC_FALSE; if (!f) {ierr = PetscObjectQueryFunction((PetscObject)A,"MatMPIAIJSetPreallocation_C",&f);CHKERRQ(ierr);} if (!f) {ierr = PetscObjectQueryFunction((PetscObject)A,"MatSeqAIJSetPreallocation_C",&f);CHKERRQ(ierr);} if (f) {*aij = PETSC_TRUE; goto done;}; if (!f) {ierr = PetscObjectQueryFunction((PetscObject)A,"MatMPIBAIJSetPreallocation_C",&f);CHKERRQ(ierr);} if (!f) {ierr = PetscObjectQueryFunction((PetscObject)A,"MatSeqBAIJSetPreallocation_C",&f);CHKERRQ(ierr);} if (f) {*baij = PETSC_TRUE; goto done;}; if (!f) {ierr = PetscObjectQueryFunction((PetscObject)A,"MatMPISBAIJSetPreallocation_C",&f);CHKERRQ(ierr);} if (!f) {ierr = PetscObjectQueryFunction((PetscObject)A,"MatSeqSBAIJSetPreallocation_C",&f);CHKERRQ(ierr);} if (f) {*sbaij = PETSC_TRUE; goto done;}; done: PetscFunctionReturn(0); } static PetscErrorCode PCSetUp_BBB_CreateMatrix(PC_BBB *bbb,Mat A,Mat *B) { MPI_Comm comm = ((PetscObject)A)->comm; PetscBool aij,baij,sbaij; PetscInt m,n,M,N,bs; MatType mtype; Mat mat; PetscErrorCode ierr; PetscFunctionBegin; ierr = PetscObjectGetComm((PetscObject)A,&comm);CHKERRQ(ierr); ierr = MatGetType(A,&mtype);CHKERRQ(ierr); ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr); ierr = MatGetLocalSize(A,&m,&n);CHKERRQ(ierr); ierr = MatGetBlockSize(A,&bs);CHKERRQ(ierr); ierr = MatCreate(comm,&mat);CHKERRQ(ierr); ierr = MatSetSizes(mat,m,n,M,N);CHKERRQ(ierr); ierr = MatSetBlockSize(mat,bs);CHKERRQ(ierr); ierr = MatSetType(mat,mtype);CHKERRQ(ierr); ierr = InferMatrixType(mat,&aij,&baij,&sbaij);CHKERRQ(ierr); if (aij || baij || sbaij) { PetscInt i, dim = bbb->dim, dof = bbb->dof; PetscInt *overlap = bbb->overlap; PetscInt dnnz=1, onnz=0; for (i=0; i<dim; i++) dnnz *= (4*overlap[i] + 1); if (aij) { dnnz *= dof; onnz *= dof; ierr = MatSeqAIJSetPreallocation(mat,dnnz,0);CHKERRQ(ierr); ierr = MatMPIAIJSetPreallocation(mat,dnnz,0,onnz,0);CHKERRQ(ierr); } else if (baij) { ierr = MatSeqBAIJSetPreallocation(mat,dof,dnnz,0);CHKERRQ(ierr); ierr = MatMPIBAIJSetPreallocation(mat,dof,dnnz,0,onnz,0);CHKERRQ(ierr); } else if (sbaij) { ierr = MatSeqSBAIJSetPreallocation(mat,dof,dnnz,0);CHKERRQ(ierr); ierr = MatMPISBAIJSetPreallocation(mat,dof,dnnz,0,onnz,0);CHKERRQ(ierr); } ierr = MatSetOption(mat,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);CHKERRQ(ierr); } else { ierr = MatSetUp(mat);CHKERRQ(ierr); } *B = mat; PetscFunctionReturn(0); } static PetscErrorCode PCSetUp_BBB(PC pc) { PC_BBB *bbb = (PC_BBB*)pc->data; IGA iga = 0; Mat A,B; PetscErrorCode ierr; PetscFunctionBegin; A = pc->pmat; ierr = PetscObjectQuery((PetscObject)A,"IGA",(PetscObject*)&iga);CHKERRQ(ierr); if (!iga) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Matrix is missing the IGA context"); PetscValidHeaderSpecific(iga,IGA_CLASSID,0); if (!pc->setupcalled) { MPI_Comm comm; IGA_Grid grid; PetscInt i, dim = iga->dim; const PetscInt *sizes = iga->node_sizes; const PetscInt *lstart = iga->node_lstart; const PetscInt *lwidth = iga->node_lwidth; PetscInt *overlap = bbb->overlap; PetscInt *gstart = bbb->ghost_start; PetscInt *gwidth = bbb->ghost_width; bbb->dim = iga->dim; bbb->dof = iga->dof; for (i=0; i<dim; i++) { PetscInt p = iga->axis[i]->p; if (overlap[i] < 0) { overlap[i] = p/2; } else { overlap[i] = PetscMin(overlap[i], p); } } for (i=0; i<dim; i++) { gstart[i] = lstart[i] - overlap[i]; gwidth[i] = lwidth[i] + overlap[i]; if (gstart[i] < 0) gstart[i] = iga->node_gstart[i]; if (gstart[i]+gwidth[i] >= sizes[i]) gwidth[i] = iga->node_gwidth[i]; } for (i=dim; i<3; i++) { overlap[i] = 0; gstart[i] = 0; gwidth[i] = 1; } ierr = IGAGetComm(iga,&comm);CHKERRQ(ierr); ierr = IGA_Grid_Create(comm,&grid);CHKERRQ(ierr); ierr = IGA_Grid_Init(grid,iga->dim,1,sizes,lstart,lwidth,gstart,gwidth);CHKERRQ(ierr); ierr = IGA_Grid_SetAO(grid,iga->ao);CHKERRQ(ierr); ierr = IGA_Grid_GetLGMap(grid,&bbb->lgmap);CHKERRQ(ierr); ierr = PetscObjectReference((PetscObject)bbb->lgmap);CHKERRQ(ierr); ierr = IGA_Grid_Destroy(&grid);CHKERRQ(ierr); } if (pc->flag != SAME_NONZERO_PATTERN) { ierr = MatDestroy(&bbb->mat);CHKERRQ(ierr); } if (!bbb->mat) { ierr = PCSetUp_BBB_CreateMatrix(bbb,A,&bbb->mat);CHKERRQ(ierr); } B = bbb->mat; ierr = MatZeroEntries(B);CHKERRQ(ierr); { PetscInt i,j,k,dim,dof; const PetscInt *start,*width; const PetscInt *gstart,*gwidth; const PetscInt *overlap; const PetscInt *ltogmap; PetscInt rstart,rend; PetscInt n,*indices; PetscBLASInt m,*ipiv,info,lwork; PetscScalar *values,*work,lwkopt; ierr = IGAGetDim(iga,&dim);CHKERRQ(ierr); ierr = IGAGetDof(iga,&dof);CHKERRQ(ierr); start = iga->node_lstart; width = iga->node_lwidth; gstart = bbb->ghost_start; gwidth = bbb->ghost_width; overlap = bbb->overlap; ierr = ISLocalToGlobalMappingGetBlockIndices(bbb->lgmap,&ltogmap);CHKERRQ(ierr); ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr); rstart /= dof; rend /= dof; for (n=dof, i=0; i<dim; n *= (2*overlap[i++] + 1)); ierr = PetscBLASIntCast(n,&m);CHKERRQ(ierr); ierr = PetscMalloc1((size_t)n,&indices);CHKERRQ(ierr); ierr = PetscMalloc1((size_t)n*(size_t)n,&values);CHKERRQ(ierr); ierr = PetscMalloc1((size_t)m,&ipiv);CHKERRQ(ierr); lwork = -1; work = &lwkopt; LAPACKgetri_(&m,values,&m,ipiv,work,&lwork,&info); lwork = (info==0) ? (PetscBLASInt)PetscRealPart(work[0]) : m*128; ierr = PetscMalloc1((size_t)lwork,&work);CHKERRQ(ierr); for (k=start[2]; k<start[2]+width[2]; k++) for (j=start[1]; j<start[1]+width[1]; j++) for (i=start[0]; i<start[0]+width[0]; i++) { n = ComputeOverlap(ltogmap,dof,rstart,rend,gstart,gwidth,overlap,i,j,k,indices);CHKERRQ(ierr); /* get element matrix from global matrix */ ierr = MatGetValues(A,n,indices,n,indices,values);CHKERRQ(ierr); /* compute inverse of element matrix */ if (PetscLikely(n > 1)) { ierr = PetscBLASIntCast(n,&m);CHKERRQ(ierr); LAPACKgetrf_(&m,&m,values,&m,ipiv,&info); if (info<0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Bad argument to LAPACKgetrf_"); if (info>0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_MAT_LU_ZRPVT,"Zero-pivot in LU factorization"); ierr = PetscLogFlops((PetscLogDouble)(1*n*n*n +2*n)/3);CHKERRQ(ierr); /* multiplications */ ierr = PetscLogFlops((PetscLogDouble)(2*n*n*n-3*n*n+1*n)/6);CHKERRQ(ierr); /* additions */ LAPACKgetri_(&m,values,&m,ipiv,work,&lwork,&info); if (info<0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Bad argument to LAPACKgetri_"); if (info>0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_MAT_LU_ZRPVT,"Zero-pivot in LU factorization"); ierr = PetscLogFlops((PetscLogDouble)(4*n*n*n+3*n*n+5*n)/6);CHKERRQ(ierr); /* multiplications */ ierr = PetscLogFlops((PetscLogDouble)(4*n*n*n-9*n*n+5*n)/6);CHKERRQ(ierr); /* additions */ } else if (PetscLikely(n == 1)) { if (PetscAbsScalar(values[0]) > 0) values[0] = (PetscScalar)1.0/values[0]; ierr = PetscLogFlops(1);CHKERRQ(ierr); } /* add values back into preconditioner matrix */ ierr = MatSetValues(B,n,indices,n,indices,values,ADD_VALUES);CHKERRQ(ierr); ierr = PetscLogFlops((PetscLogDouble)(n*n));CHKERRQ(ierr); } ierr = ISLocalToGlobalMappingRestoreBlockIndices(bbb->lgmap,&ltogmap);CHKERRQ(ierr); ierr = PetscFree2(indices,values);CHKERRQ(ierr); ierr = PetscFree(ipiv);CHKERRQ(ierr); ierr = PetscFree(work);CHKERRQ(ierr); } ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd (B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); PetscFunctionReturn(0); } #if PETSC_VERSION_LT(3,18,0) static PetscErrorCode PCSetFromOptions_BBB(PetscOptionItems *PetscOptionsObject,PC pc) #else static PetscErrorCode PCSetFromOptions_BBB(PC pc,PetscOptionItems *PetscOptionsObject) #endif { PC_BBB *bbb = (PC_BBB*)pc->data; PetscBool flg; PetscInt i,no=3,overlap[3]; PetscErrorCode ierr; PetscFunctionBegin; for (i=0; i<3; i++) overlap[i] = bbb->overlap[i]; ierr = PetscOptionsIntArray("-pc_bbb_overlap","Overlap","",overlap,&no,&flg);CHKERRQ(ierr); if (flg) for (i=0; i<3; i++) { PetscInt ov = (i<no) ? overlap[i] : overlap[0]; bbb->overlap[i] = ov; } PetscFunctionReturn(0); } static PetscErrorCode PCApply_BBB(PC pc,Vec x,Vec y) { PC_BBB *bbb = (PC_BBB*)pc->data; PetscErrorCode ierr; PetscFunctionBegin; ierr = MatMult(bbb->mat,x,y);CHKERRQ(ierr); PetscFunctionReturn(0); } static PetscErrorCode PCApplyTranspose_BBB(PC pc,Vec x,Vec y) { PC_BBB *bbb = (PC_BBB*)pc->data; PetscErrorCode ierr; PetscFunctionBegin; ierr = MatMultTranspose(bbb->mat,x,y);CHKERRQ(ierr); PetscFunctionReturn(0); } static PetscErrorCode PCView_BBB(PC pc,PetscViewer viewer) { PC_BBB *bbb = (PC_BBB*)pc->data; PetscInt *ov = bbb->overlap; PetscBool isascii; PetscErrorCode ierr; PetscFunctionBegin; ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);CHKERRQ(ierr); if (!isascii) PetscFunctionReturn(0); if (!bbb->mat) PetscFunctionReturn(0); ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr); ierr = PetscViewerASCIIPrintf(viewer,"overlap: %D,%D,%D\n",ov[0],ov[1],ov[2]);CHKERRQ(ierr); ierr = PetscViewerASCIIPrintf(viewer,"basis-by-basis matrix:\n");CHKERRQ(ierr); ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_INFO);CHKERRQ(ierr); ierr = MatView(bbb->mat,viewer);CHKERRQ(ierr); ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr); ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr); PetscFunctionReturn(0); } static PetscErrorCode PCReset_BBB(PC pc) { PC_BBB *bbb = (PC_BBB*)pc->data; PetscErrorCode ierr; PetscFunctionBegin; ierr = ISLocalToGlobalMappingDestroy(&bbb->lgmap);CHKERRQ(ierr); ierr = MatDestroy(&bbb->mat);CHKERRQ(ierr); PetscFunctionReturn(0); } static PetscErrorCode PCDestroy_BBB(PC pc) { PetscErrorCode ierr; PetscFunctionBegin; ierr = PCReset_BBB(pc);CHKERRQ(ierr); ierr = PetscFree(pc->data);CHKERRQ(ierr); PetscFunctionReturn(0); } EXTERN_C_BEGIN PetscErrorCode PCCreate_IGABBB(PC pc); PetscErrorCode PCCreate_IGABBB(PC pc) { PC_BBB *bbb = NULL; PetscErrorCode ierr; PetscFunctionBegin; ierr = PetscNew(&bbb);CHKERRQ(ierr); pc->data = (void*)bbb; bbb->overlap[0] = PETSC_DECIDE; bbb->overlap[1] = PETSC_DECIDE; bbb->overlap[2] = PETSC_DECIDE; bbb->mat = NULL; pc->ops->setup = PCSetUp_BBB; pc->ops->reset = PCReset_BBB; pc->ops->destroy = PCDestroy_BBB; pc->ops->setfromoptions = PCSetFromOptions_BBB; pc->ops->view = PCView_BBB; pc->ops->apply = PCApply_BBB; pc->ops->applytranspose = PCApplyTranspose_BBB; PetscFunctionReturn(0); } EXTERN_C_END
#include "server.h" // static char* mx_delete_slesh_n(char *str) { // *(str + mx_strlen(str) - 1) = '\0'; // return str; // } static void mx_add_last_message(int chat_id, char *message, char *time, char *sender, char* msg_type) { char *message_error; int check; int message_id = mx_get_last_message_id(chat_id); char *chat_id_str = mx_itoa(chat_id); char *message_id_str = mx_itoa(message_id); char sql[500]; message_id++; sqlite3 *db = mx_opening_db(); sprintf(sql ,"INSERT INTO MESSAGES (CHATID, MSGTYPE, MESSAGEID, SENDER, TIME, MESSAGE) VALUES(%d, '%s', %d, '%s', '%s', '%s');", chat_id, msg_type, message_id, sender, time, message); check = sqlite3_exec(db, sql, NULL, 0, &message_error); mx_dberror(db, check, "Error inserting to table"); sqlite3_close(db); free(chat_id_str); free(message_id_str); } static void mx_add_message_with_id(int message_id, int chat_id, char *message) { sqlite3 *db = mx_opening_db(); char *message_error; char sql[500]; bzero(sql, 500); int check; sprintf(sql, "BEGIN; UPDATE MESSAGES SET MESSAGE = '%s' WHERE MESSAGEID = %d; COMMIT;", message ,message_id); check = sqlite3_exec(db, sql, NULL, 0, &message_error); sqlite3_close(db); } static char *mx_json_packet_former_from_list(char* message, char* time, char* sender, int chat_id, char *all_users, char* msg_type) { cJSON *packet = cJSON_CreateObject(); char* packet_str = NULL; cJSON *json_value = cJSON_CreateString("add_msg_s"); char *last_msg_id_str = mx_itoa(mx_get_last_message_id(chat_id)); char packet_former[100]; bzero(packet_former, 100); cJSON_AddItemToObject(packet, "TYPE", json_value); json_value = cJSON_CreateString(all_users); cJSON_AddItemToObject(packet, "TO", json_value); sprintf(packet_former, "ID0"); json_value = cJSON_CreateString(last_msg_id_str); cJSON_AddItemToObject(packet, packet_former, json_value); json_value = cJSON_CreateString("1"); cJSON_AddItemToObject(packet, "MSGLEN", json_value); json_value = cJSON_CreateString(all_users); cJSON_AddItemToObject(packet, "ALLUSERS", json_value); json_value = cJSON_CreateString(sender); sprintf(packet_former, "SENDER0"); cJSON_AddItemToObject(packet, packet_former, json_value); json_value = cJSON_CreateString(time); sprintf(packet_former, "TIME0"); cJSON_AddItemToObject(packet, packet_former, json_value); json_value = cJSON_CreateString(msg_type); sprintf(packet_former, "MSGTYPE0"); cJSON_AddItemToObject(packet, packet_former, json_value); json_value = cJSON_CreateString(message); sprintf(packet_former, "MESSAGE0"); cJSON_AddItemToObject(packet, packet_former, json_value); json_value = cJSON_CreateString(mx_itoa(chat_id)); cJSON_AddItemToObject(packet, "CHATID", json_value); packet_str = cJSON_Print(packet); free(last_msg_id_str); return packet_str; } char* mx_add_message_by_id(char *packet) { char *message_id_str = get_value_by_key(packet, "MESSAGEID"); char *time = get_value_by_key(packet, "TIME"); char *message = get_value_by_key(packet, "MESSAGE"); char *chat_id_str = get_value_by_key(packet, "CHATID"); char *sender = get_value_by_key(packet, "SENDER"); char *to = get_value_by_key(packet, "TO"); char *msg_type = get_value_by_key(packet, "TYPE2"); int message_id = atoi(message_id_str); int chat_id = atoi(chat_id_str); if(message_id == 0) mx_add_last_message(chat_id, message, time, sender, msg_type); else mx_add_message_with_id(message_id, chat_id, message); char *return_packet = mx_json_packet_former_from_list(message, time, sender, chat_id, to, msg_type); return return_packet; }
#include <stdio.h> #include <stdint.h> #include <stdbool.h> struct _func_para { int32_t x; int32_t y; int32_t z; void (*toString)(struct _func_para *this ) }; struct _func_res { bool isRun; }; int main(void) { return 0; }
// SD -- square dance caller's helper. // // Copyright (C) 1990-2004 William B. Ackerman. // // This file is part of "Sd". // // Sd is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Sd 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, // in the file COPYING.txt, along with Sd. See // http://www.gnu.org/licenses/ // // =================================================================== /* The Sd program reads this binary file for its calls database */ #ifndef DATABASE_FILENAME #define DATABASE_FILENAME "sd_calls.dat" #endif /* The source form of the calls database. The mkcalls program compiles it. */ #ifndef CALLS_FILENAME #define CALLS_FILENAME "sd_calls.txt" #endif /* The output filename prefix. ".level" is added to the name. */ #ifndef SEQUENCE_FILENAME #define SEQUENCE_FILENAME "sequence" #endif /* The file containing the user's current working sessions. */ #ifndef SESSION_FILENAME #define SESSION_FILENAME "sd.ini" #endif /* The temporary file used when rewriting the above. */ #ifndef SESSION2_FILENAME #define SESSION2_FILENAME "sd2.ini" #endif
/* ******************************************************** * Tabela Para Debug (?) * ******************************************************** */ #define N_SLINE 1 #define N_PSYM 2 #define N_LSYM 3 #define N_GSYM 4 #define N_STSYM 5 #define N_RSYM 6 #define N_SYM 7 #define N_LENG 8 #define N_SOL 9 #define N_LBRAC 10 #define N_RBRAC 11 #define N_NFUN 12 #define N_SO 13 #define N_SSYM 14 #define N_FUN 15 #define N_LCSYM 16
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: haitao@openailab.com * Revised: lswang@openailab.com */ #pragma once #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "defines.h" #include <stdint.h> struct node; struct graph; /*! * @struct ir_tensor_t * @brief Abstract tensor intermediate representation */ typedef struct tensor { uint16_t index; //!< the index of a tensor int16_t producer; //!< node id, '-1' means no producer int16_t* consumer; //!< consumer nodes array uint8_t reshaped; //!< the tensor's shape has changed uint8_t consumer_num; //!< count of consumer nodes uint8_t tensor_type; //!< tensor_type: { const, input, var, dep } uint8_t data_type; //!< data_type: { int8, uint8, fp32, fp16, int32 } uint8_t dim_num; //!< count of dimensions uint8_t elem_size; //!< size of single element uint8_t subgraph_num; //!< count of all subgraphs which will wait for this tensor to be ready uint8_t free_host_mem; //!< should free host memory? uint8_t internal_allocated; //!< how memory is allocated? uint8_t layout; //!< tensor layout: { TENGINE_LAYOUT_NCHW, TENGINE_LAYOUT_NHWC } uint16_t quant_param_num; //!< quantization dimension uint32_t elem_num; //!< count of total elements int dims[TE_MAX_SHAPE_DIM_NUM]; //!< shape dimensions /*! * @union anonymity data pointer * @brief give useful pointer pointer */ union { void* data; int8_t* i8; uint8_t* u8; float* f32; uint16_t* f16; int32_t* i32; }; char* name; //!< tensor name /*! * @union anonymity quantization scale union * @brief scale or its array */ union { float* scale_list; float scale; }; /*! * @union anonymity quantization zero point union * @brief zero point or its array */ union { int zero_point; int* zp_list; }; struct dev_mem* dev_mem; uint8_t* subgraph_list; //!< subgraph index list of those subgraphs will wait for this tensor to be ready } ir_tensor_t; /*! * @brief Create a tensor for a graph. * * @param [in] graph: specific graph. * @param [in] tensor_name: tensor name. * @param [in] data_type: tensor data type(not tensor type). * * @return The pointer of the tensor. */ ir_tensor_t* create_ir_tensor(struct graph* graph, const char* tensor_name, int data_type); /*! * @brief Destroy a tensor. * * User should deal with other destroy works, such as ir_graph and ir_node. * * @param [in] ir_graph: specific graph. * @param [in] ir_tensor: the tensor pointer. */ void destroy_ir_tensor(struct graph* ir_graph, ir_tensor_t* ir_tensor); /*! * @brief Set shape for a tensor. * * @param [in] ir_tensor: specific tensor. * @param [in] dims: shape array. * @param [in] dim_number: shape dimensions. * * @return statue value, 0 success, other value failure. */ int set_ir_tensor_shape(ir_tensor_t* ir_tensor, const int dims[], int dim_number); /*! * @brief Set tensor name from id, for anonymity ones. * * @param [in] index: reference id. * * @return char array of the name. */ char* create_ir_tensor_name_from_index(int index); /*! * @brief Get tensor id from name, for anonymity ones. * * @param [in] ir_graph: specific graph. * @param [in] tensor_name: reference name. * * @return tensor id. */ int get_ir_tensor_index_from_name(struct graph* ir_graph, const char* tensor_name); /*! * @brief Set tensor quantization parameter. * * @param [in] ir_tensor: specific tensor. * @param [in] scale: scale pointer. * @param [in] zero_point: zero_point pointer. * @param [in] number: quantization parameter dimensions. * * @return statue value, 0 success, other value failure. */ int set_ir_tensor_quantization_parameter(ir_tensor_t* ir_tensor, const float* scale, const int* zero_point, int number); /*! * @brief Get tensor quantization parameter. * * @param [in] ir_tensor: specific tensor. * @param [in] scale: scale pointer. * @param [in] zero_point: zero_point pointer. * @param [in] number: quantization parameter dimensions. * * @return statue value, 0 success, other value failure. */ int get_ir_tensor_quantization_parameter(ir_tensor_t* ir_tensor, float* scale, int* zero_point, int number); /*! * @brief Dump the tensor. * * @param [in] ir_graph: specific graph. * @param [in] ir_tensor: specific tensor. */ void dump_ir_tensor(struct graph* ir_graph, ir_tensor_t* ir_tensor); /*! * @brief Set consumer node for a tensor. * * @param [in] ir_tensor: specific tensor. * @param [in] index: node index. * * @return statue value, 0 success, other value failure. */ int set_ir_tensor_consumer(ir_tensor_t* ir_tensor, const int index); #ifdef __cplusplus } #endif /* __cplusplus */
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <malloc.h> #include <string.h> #include <fcntl.h> struct treasure_map { int a; int b; }; int test_calloc(){ int *x,*y; y = calloc(50,sizeof(int)); if(!y){ perror("calloc"); return -1; } else{ printf("calloc success\n"); return 0; } } int test_malloc(){ struct treasure_map *map; map = malloc(sizeof(struct treasure_map)); if(!map){ perror("malloc"); return -1; } else{ printf("malloc success\n"); return 0; } } int test_realloc(){ int *x,*y; y = calloc(50,sizeof(int)); x = realloc(y,25*sizeof(int)); if(!x){ perror("realloc"); return -1; } else{ printf("ralloc success\n"); return 0; } } void print_chars(int n,char c){ int i; for(i = 0;i<n;i++){ char *s; int j; s = calloc(i+2,1); if(!s){ perror("calloc"); break; } for(j = 0;j<i+1;j++){ s[j] = c; } printf("%s\n", s); free(s); } } int test_mmap(){ return 0; } int test_posix(){ char *buf; int ret; ret = posix_memalign(&buf,256,1024); if(ret){ fprintf(stderr, "posix_memalign: %s\n",strerror(ret)); return -1; } else{ printf("posix_memalign success\n"); free(buf); return 0; } } int test_break(){ printf("the current break point is %p\n", sbrk(0)); return 0; } int test_mallopt(){ int ret = 0; ret = mallopt(M_MMAP_THRESHOLD, 64* 1024); if(!ret){ fprintf(stderr, "mallopt,M_MMAP_THRESHOLD,err\n"); } else{ printf("mallopt,M_MMAP_THRESHOLD success,%lf,\n",M_MMAP_THRESHOLD); return 0; } return 0; } int test_usable_size(){ size_t len = 21; size_t size; char *buf; buf = malloc(len); if(!buf){ perror("malloc"); return -1; } size = malloc_usable_size(buf); printf("%d\n", size); return 0; } int test_mallinfo(){ struct mallinfo m; m = mallinfo(); printf("free chunk: %d\n", m.ordblks); return 0; } int open_sysconf(const char *file,int flags,int mode){ const char *etc = "/etc/"; char *name; name = alloca(strlen(etc)+strlen(file)+1); strcpy(name,etc); strcpy(name,file); return open(name,flags,mode); } int test_alloca(){ char *song = "songs"; char *dup; dup = alloca(strlen(song)+1); strcpy(dup,song); printf("%s\n", dup); return 0; } int main() { test_malloc(); test_calloc(); test_realloc(); print_chars(3,'x'); test_posix(); test_break(); test_mmap(); test_mallopt(); test_usable_size(); test_mallinfo(); test_alloca(); return 0; }
#include <stdint.h> int spin_workload(void* input) { unsigned count = (unsigned)(uintptr_t)input, i = 0; for (i = 0; i < count; i++) { __asm__ __volatile__ (""); } return (int)i; } int empty_workload(void* nonce) { return 0; } int add_workload(void* input) { unsigned i = 0, sum = 0, max = (unsigned)(uintptr_t)input; for (i = 0; i < max; i++) { sum += i; } return (int)sum; }
/** * @file cmp_icu.c * @author Dominik Loidolt (dominik.loidolt@univie.ac.at) * @date 2020 * * @copyright GPLv2 * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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. * * @brief software compression library * @see Data Compression User Manual PLATO-UVIE-PL-UM-0001 * * To compress data, first create a compression configuration with the * cmp_cfg_icu_create() function. * Then set the different data buffers with the data to compressed, the model * data and the compressed data with the cmp_cfg_icu_buffers() function. * Then set the compression data type specific compression parameters. For * imagette data use the cmp_cfg_icu_imagette() function. For flux and center of * brightness data use the cmp_cfg_fx_cob() function. And for background, offset * and smearing data use the cmp_cfg_aux() function. * Finally, you can compress the data with the icu_compress_data() function. */ #include <stdint.h> #include <string.h> #include <limits.h> #include <byteorder.h> #include <cmp_debug.h> #include <cmp_data_types.h> #include <cmp_support.h> #include <cmp_icu.h> #include <cmp_entity.h> /* maximum used bits registry */ extern struct cmp_max_used_bits max_used_bits; /** * @brief pointer to a code word generation function */ typedef uint32_t (*generate_cw_f_pt)(uint32_t value, uint32_t encoder_par1, uint32_t encoder_par2, uint32_t *cw); /** * @brief structure to hold a setup to encode a value */ struct encoder_setupt { generate_cw_f_pt generate_cw_f; /**< function pointer to a code word encoder */ int (*encode_method_f)(uint32_t data, uint32_t model, int stream_len, const struct encoder_setupt *setup); /**< pointer to the encoding function */ uint32_t *bitstream_adr; /**< start address of the compressed data bitstream */ uint32_t max_stream_len; /**< maximum length of the bitstream/icu_output_buf in bits */ uint32_t encoder_par1; /**< encoding parameter 1 */ uint32_t encoder_par2; /**< encoding parameter 2 */ uint32_t spillover_par; /**< outlier parameter */ uint32_t lossy_par; /**< lossy compression parameter */ uint32_t max_data_bits; /**< how many bits are needed to represent the highest possible value */ }; /** * @brief create an ICU compression configuration * * @param data_type compression data product type * @param cmp_mode compression mode * @param model_value model weighting parameter (only needed for model compression mode) * @param lossy_par lossy rounding parameter (use CMP_LOSSLESS for lossless compression) * * @returns a compression configuration containing the chosen parameters; * on error the data_type record is set to DATA_TYPE_UNKNOWN */ struct cmp_cfg cmp_cfg_icu_create(enum cmp_data_type data_type, enum cmp_mode cmp_mode, uint32_t model_value, uint32_t lossy_par) { struct cmp_cfg cfg; memset(&cfg, 0, sizeof(cfg)); cfg.data_type = data_type; cfg.cmp_mode = cmp_mode; cfg.model_value = model_value; cfg.round = lossy_par; if (cmp_cfg_gen_par_is_invalid(&cfg, ICU_CHECK)) cfg.data_type = DATA_TYPE_UNKNOWN; return cfg; } /** * @brief setup the different data buffers for an ICU compression * * @param cfg pointer to a compression configuration (created * with the cmp_cfg_icu_create() function) * @param data_to_compress pointer to the data to be compressed * @param data_samples length of the data to be compressed measured in * data samples/entitys (collection header not * included by imagette data) * @param model_of_data pointer to model data buffer (can be NULL if no * model compression mode is used) * @param updated_model pointer to store the updated model for the next * model mode compression (can be the same as the model_of_data * buffer for in-place update or NULL if updated model is not needed) * @param compressed_data pointer to the compressed data buffer (can be NULL) * @param compressed_data_len_samples length of the compressed_data buffer in * measured in the same units as the data_samples * * @returns the size of the compressed_data buffer on success; 0 if the * parameters are invalid */ uint32_t cmp_cfg_icu_buffers(struct cmp_cfg *cfg, void *data_to_compress, uint32_t data_samples, void *model_of_data, void *updated_model, uint32_t *compressed_data, uint32_t compressed_data_len_samples) { uint32_t cmp_data_size, hdr_size; if (!cfg) { debug_print("Error: pointer to the compression configuration structure is NULL.\n"); return 0; } cfg->input_buf = data_to_compress; cfg->model_buf = model_of_data; cfg->samples = data_samples; cfg->icu_new_model_buf = updated_model; cfg->icu_output_buf = compressed_data; cfg->buffer_length = compressed_data_len_samples; if (cmp_cfg_icu_buffers_is_invalid(cfg)) return 0; cmp_data_size = cmp_cal_size_of_data(compressed_data_len_samples, cfg->data_type); hdr_size = cmp_ent_cal_hdr_size(cfg->data_type, cfg->cmp_mode == CMP_MODE_RAW); if ((cmp_data_size + hdr_size) > CMP_ENTITY_MAX_SIZE || cmp_data_size > CMP_ENTITY_MAX_SIZE) { debug_print("Error: The buffer for the compressed data is too large to fit in a compression entity.\n"); return 0; } return cmp_data_size; } /** * @brief set up the configuration parameters for an ICU imagette compression * * @param cfg pointer to a compression configuration (created * by the cmp_cfg_icu_create() function) * @param cmp_par imagette compression parameter (Golomb parameter) * @param spillover_par imagette spillover threshold parameter * * @returns 0 if parameters are valid, non-zero if parameters are invalid */ int cmp_cfg_icu_imagette(struct cmp_cfg *cfg, uint32_t cmp_par, uint32_t spillover_par) { if (!cfg) return -1; cfg->golomb_par = cmp_par; cfg->spill = spillover_par; return cmp_cfg_imagette_is_invalid(cfg, ICU_CHECK); } /** * @brief set up the configuration parameters for a flux/COB compression * @note not all parameters are needed for every flux/COB compression data type * * @param cfg pointer to a compression configuration (created * by the cmp_cfg_icu_create() function) * @param cmp_par_exp_flags exposure flags compression parameter * @param spillover_exp_flags exposure flags spillover threshold parameter * @param cmp_par_fx normal flux compression parameter * @param spillover_fx normal flux spillover threshold parameter * @param cmp_par_ncob normal center of brightness compression parameter * @param spillover_ncob normal center of brightness spillover threshold parameter * @param cmp_par_efx extended flux compression parameter * @param spillover_efx extended flux spillover threshold parameter * @param cmp_par_ecob extended center of brightness compression parameter * @param spillover_ecob extended center of brightness spillover threshold parameter * @param cmp_par_fx_cob_variance flux/COB variance compression parameter * @param spillover_fx_cob_variance flux/COB variance spillover threshold parameter * * @returns 0 if parameters are valid, non-zero if parameters are invalid */ int cmp_cfg_fx_cob(struct cmp_cfg *cfg, uint32_t cmp_par_exp_flags, uint32_t spillover_exp_flags, uint32_t cmp_par_fx, uint32_t spillover_fx, uint32_t cmp_par_ncob, uint32_t spillover_ncob, uint32_t cmp_par_efx, uint32_t spillover_efx, uint32_t cmp_par_ecob, uint32_t spillover_ecob, uint32_t cmp_par_fx_cob_variance, uint32_t spillover_fx_cob_variance) { if (!cfg) return -1; cfg->cmp_par_exp_flags = cmp_par_exp_flags; cfg->cmp_par_fx = cmp_par_fx; cfg->cmp_par_ncob = cmp_par_ncob; cfg->cmp_par_efx = cmp_par_efx; cfg->cmp_par_ecob = cmp_par_ecob; cfg->cmp_par_fx_cob_variance = cmp_par_fx_cob_variance; cfg->spill_exp_flags = spillover_exp_flags; cfg->spill_fx = spillover_fx; cfg->spill_ncob = spillover_ncob; cfg->spill_efx = spillover_efx; cfg->spill_ecob = spillover_ecob; cfg->spill_fx_cob_variance = spillover_fx_cob_variance; return cmp_cfg_fx_cob_is_invalid(cfg); } /** * @brief set up the configuration parameters for an auxiliary science data compression * @note auxiliary compression data types are: DATA_TYPE_OFFSET, DATA_TYPE_BACKGROUND, DATA_TYPE_SMEARING, DATA_TYPE_F_CAM_OFFSET, DATA_TYPE_F_CAM_BACKGROUND * @note not all parameters are needed for the every auxiliary compression data type * * @param cfg pointer to a compression configuration (created * with the cmp_cfg_icu_create() function) * @param cmp_par_mean mean compression parameter * @param spillover_mean mean spillover threshold parameter * @param cmp_par_variance variance compression parameter * @param spillover_variance variance spillover threshold parameter * @param cmp_par_pixels_error outlier pixels number compression parameter * @param spillover_pixels_error outlier pixels number spillover threshold parameter * * @returns 0 if parameters are valid, non-zero if parameters are invalid */ int cmp_cfg_aux(struct cmp_cfg *cfg, uint32_t cmp_par_mean, uint32_t spillover_mean, uint32_t cmp_par_variance, uint32_t spillover_variance, uint32_t cmp_par_pixels_error, uint32_t spillover_pixels_error) { if (!cfg) return -1; cfg->cmp_par_mean = cmp_par_mean; cfg->cmp_par_variance = cmp_par_variance; cfg->cmp_par_pixels_error = cmp_par_pixels_error; cfg->spill_mean = spillover_mean; cfg->spill_variance = spillover_variance; cfg->spill_pixels_error = spillover_pixels_error; return cmp_cfg_aux_is_invalid(cfg); } /** * @brief map a signed value into a positive value range * * @param value_to_map signed value to map * @param max_data_bits how many bits are needed to represent the * highest possible value * * @returns the positive mapped value */ static uint32_t map_to_pos(uint32_t value_to_map, unsigned int max_data_bits) { uint32_t result; uint32_t mask = (~0U >> (32 - max_data_bits)); /* mask the used bits */ value_to_map &= mask; if (value_to_map >> (max_data_bits - 1)) { /* check the leading signed bit */ value_to_map |= ~mask; /* convert to 32-bit signed integer */ /* map negative values to uneven numbers */ result = (-value_to_map) * 2 - 1; /* possible integer overflow is intended */ } else { /* map positive values to even numbers */ result = value_to_map * 2; /* possible integer overflow is intended */ } return result; } /** * @brief put the value of up to 32 bits into a bitstream * * @param value the value to put * @param n_bits number of bits to put in the bitstream * @param bit_offset bit index where the bits will be put, seen from * the very beginning of the bitstream * @param bitstream_adr this is the pointer to the beginning of the * bitstream (can be NULL) * @param max_stream_len maximum length of the bitstream in bits; is * ignored if bitstream_adr is NULL * * @returns length in bits of the generated bitstream on success; returns * negative in case of erroneous input; returns CMP_ERROR_SMALL_BUF if * the bitstream buffer is too small to put the value in the bitstream */ static int put_n_bits32(uint32_t value, unsigned int n_bits, int bit_offset, uint32_t *bitstream_adr, unsigned int max_stream_len) { uint32_t *local_adr; uint32_t mask; unsigned int shiftRight, shiftLeft, bitsLeft, bitsRight; int stream_len = (int)(n_bits + (unsigned int)bit_offset); /* overflow results in a negative return value */ /* Leave in case of erroneous input */ if (bit_offset < 0) return -1; if (n_bits == 0) return stream_len; if (n_bits > 32) return -1; /* Do we need to write data to the bitstream? */ if (!bitstream_adr) return stream_len; /* Check if bitstream buffer is large enough */ if ((unsigned int)stream_len > max_stream_len) { debug_print("Error: The buffer for the compressed data is too small to hold the compressed data. Try a larger buffer_length parameter.\n"); return CMP_ERROR_SMALL_BUF; } /* (M) is the n_bits parameter large enough to cover all value bits; the * calculations can be re-used in the unsegmented code, so we have no overhead */ shiftRight = 32 - n_bits; mask = 0xFFFFFFFFU >> shiftRight; value &= mask; /* Separate the bit_offset into word offset (set local_adr pointer) and local bit offset (bitsLeft) */ local_adr = bitstream_adr + (bit_offset >> 5); bitsLeft = bit_offset & 0x1F; /* Calculate the bitsRight for the unsegmented case. If bitsRight is * negative we need to split the value over two words */ bitsRight = shiftRight - bitsLeft; if ((int)bitsRight >= 0) { /* UNSEGMENTED * *|-----------|XXXXX|----------------| * bitsLeft n bitsRight * * -> to get the mask: * shiftRight = bitsLeft + bitsRight = 32 - n * shiftLeft = bitsRight = 32 - n - bitsLeft = shiftRight - bitsLeft */ shiftLeft = bitsRight; /* generate the mask, the bits for the values will be true * shiftRight = 32 - n_bits; see (M) above! * mask = (0XFFFFFFFF >> shiftRight) << shiftLeft; see (M) above! */ mask <<= shiftLeft; value <<= shiftLeft; /* clear the destination with inverse mask */ *(local_adr) &= ~mask; /* assign the value */ *(local_adr) |= value; } else { /* SEGMENTED * *|-----------------------------|XXX| |XX|------------------------------| * bitsLeft n1 n2 bitsRight * * -> to get the mask part 1: * shiftRight = bitsLeft * n1 = n - (bitsLeft + n - 32) = 32 - bitsLeft * * -> to get the mask part 2: * n2 = bitsLeft + n - 32 = -(32 - n - bitsLeft) = -(bitsRight_UNSEGMENTED) * shiftLeft = 32 - n2 = 32 - (bitsLeft + n - 32) = 64 - bitsLeft - n * */ unsigned int n2 = -bitsRight; /* part 1: */ shiftRight = bitsLeft; mask = 0XFFFFFFFFU >> shiftRight; /* clear the destination with inverse mask */ *(local_adr) &= ~mask; /* assign the value part 1 */ *(local_adr) |= (value >> n2); /* part 2: */ /* adjust address */ local_adr += 1; shiftLeft = 32 - n2; mask = 0XFFFFFFFFU >> n2; /* clear the destination */ *(local_adr) &= mask; /* assign the value part 2 */ *(local_adr) |= (value << shiftLeft); } return stream_len; } /** * @brief forms the codeword according to the Rice code * * @param value value to be encoded * @param m Golomb parameter, only m's which are power of 2 are allowed * @param log2_m Rice parameter, is log_2(m) calculate outside function * for better performance * @param cw address were the encode code word is stored * * @returns the length of the formed code word in bits * @note no check if the generated code word is not longer than 32 bits! */ static uint32_t rice_encoder(uint32_t value, uint32_t m, uint32_t log2_m, uint32_t *cw) { uint32_t g; /* quotient of value/m */ uint32_t q; /* quotient code without ending zero */ uint32_t r; /* remainder of value/m */ uint32_t rl; /* remainder length */ g = value >> log2_m; /* quotient, number of leading bits */ q = (1U << g) - 1; /* prepare the quotient code without ending zero */ r = value & (m-1); /* calculate the remainder */ rl = log2_m + 1; /* length of the remainder (+1 for the 0 in the quotient code) */ *cw = (q << rl) | r; /* put the quotient and remainder code together */ /* * NOTE: If log2_m = 31 -> rl = 32, (q << rl) leads to an undefined * behavior. However, in this case, a valid code with a maximum of 32 * bits can only be formed if q = 0. Any shift with 0 << x always * results in 0, which forms the correct codeword in this case. For * performance reasons, this undefined behaviour is not caught. */ return rl + g; /* calculate the length of the code word */ } /** * @brief forms a codeword according to the Golomb code * * @param value value to be encoded * @param m Golomb parameter (have to be bigger than 0) * @param log2_m is log_2(m) calculate outside function for better * performance * @param cw address were the formed code word is stored * * @returns the length of the formed code word in bits * @note no check if the generated code word is not longer than 32 bits! */ static uint32_t golomb_encoder(uint32_t value, uint32_t m, uint32_t log2_m, uint32_t *cw) { uint32_t len0, b, g, q, lg; uint32_t len; uint32_t cutoff; len0 = log2_m + 1; /* codeword length in group 0 */ cutoff = (1U << (log2_m + 1)) - m; /* members in group 0 */ if (value < cutoff) { /* group 0 */ *cw = value; len = len0; } else { /* other groups */ g = (value-cutoff) / m; /* this group is which one */ b = cutoff << 1; /* form the base codeword */ lg = len0 + g; /* it has lg remainder bits */ q = (1U << g) - 1; /* prepare the left side in unary */ *cw = (q << (len0+1)) + b + (value-cutoff) - g*m; /* composed codeword */ len = lg + 1; /* length of the codeword */ } return len; } /** * @brief generate a code word without an outlier mechanism and put in the * bitstream * * @param value value to encode in the bitstream * @param stream_len length of the bitstream in bits * @param setup pointer to the encoder setup * * @returns the bit length of the bitstream with the added encoded value on * success; negative on error, CMP_ERROR_SMALL_BUF if the bitstream buffer * is too small to put the value in the bitstream */ static int encode_normal(uint32_t value, int stream_len, const struct encoder_setupt *setup) { uint32_t code_word, cw_len; cw_len = setup->generate_cw_f(value, setup->encoder_par1, setup->encoder_par2, &code_word); return put_n_bits32(code_word, cw_len, stream_len, setup->bitstream_adr, setup->max_stream_len); } /** * @brief subtract the model from the data, encode the result and put it into * bitstream, for encoding outlier use the zero escape symbol mechanism * * @param data data to encode * @param model model of the data (0 if not used) * @param stream_len length of the bitstream in bits * @param setup pointer to the encoder setup * * @returns the bit length of the bitstream with the added encoded value on * success; negative on error, CMP_ERROR_SMALL_BUF if the bitstream buffer * is too small to put the value in the bitstream * * @note no check if the data or model are in the allowed range * @note no check if the setup->spillover_par is in the allowed range */ static int encode_value_zero(uint32_t data, uint32_t model, int stream_len, const struct encoder_setupt *setup) { data -= model; /* possible underflow is intended */ data = map_to_pos(data, setup->max_data_bits); /* For performance reasons, we check to see if there is an outlier * before adding one, rather than the other way around: * data++; * if (data < setup->spillover_par && data != 0) * return ... */ if (data < (setup->spillover_par - 1)) { /* detect non-outlier */ data++; /* add 1 to every value so we can use 0 as escape symbol */ return encode_normal(data, stream_len, setup); } data++; /* add 1 to every value so we can use 0 as escape symbol */ /* use zero as escape symbol */ stream_len = encode_normal(0, stream_len, setup); if (stream_len <= 0) return stream_len; /* put the data unencoded in the bitstream */ stream_len = put_n_bits32(data, setup->max_data_bits, stream_len, setup->bitstream_adr, setup->max_stream_len); return stream_len; } /** * @brief subtract the model from the data, encode the result and put it into * bitstream, for encoding outlier use the multi escape symbol mechanism * * @param data data to encode * @param model model of the data (0 if not used) * @param stream_len length of the bitstream in bits * @param setup pointer to the encoder setup * * @returns the bit length of the bitstream with the added encoded value on * success; negative on error, CMP_ERROR_SMALL_BUF if the bitstream buffer * is too small to put the value in the bitstream * * @note no check if the data or model are in the allowed range * @note no check if the setup->spillover_par is in the allowed range */ static int encode_value_multi(uint32_t data, uint32_t model, int stream_len, const struct encoder_setupt *setup) { uint32_t unencoded_data; unsigned int unencoded_data_len; uint32_t escape_sym, escape_sym_offset; data -= model; /* possible underflow is intended */ data = map_to_pos(data, setup->max_data_bits); if (data < setup->spillover_par) /* detect non-outlier */ return encode_normal(data, stream_len, setup); /* * In this mode we put the difference between the data and the spillover * threshold value (unencoded_data) after an encoded escape symbol, which * indicate that the next codeword is unencoded. * We use different escape symbol depended on the size the needed bit of * unencoded data: * 0, 1, 2 bits needed for unencoded data -> escape symbol is spillover_par + 0 * 3, 4 bits needed for unencoded data -> escape symbol is spillover_par + 1 * 5, 6 bits needed for unencoded data -> escape symbol is spillover_par + 2 * and so on */ unencoded_data = data - setup->spillover_par; if (!unencoded_data) /* catch __builtin_clz(0) because the result is undefined.*/ escape_sym_offset = 0; else escape_sym_offset = (31U - (uint32_t)__builtin_clz(unencoded_data)) >> 1; escape_sym = setup->spillover_par + escape_sym_offset; unencoded_data_len = (escape_sym_offset + 1U) << 1; /* put the escape symbol in the bitstream */ stream_len = encode_normal(escape_sym, stream_len, setup); if (stream_len <= 0) return stream_len; /* put the unencoded data in the bitstream */ stream_len = put_n_bits32(unencoded_data, unencoded_data_len, stream_len, setup->bitstream_adr, setup->max_stream_len); return stream_len; } /** * @brief put the value unencoded with setup->cmp_par_1 bits without any changes * in the bitstream * * @param value value to put unchanged in the bitstream * (setup->cmp_par_1 how many bits of the value are used) * @param unused this parameter is ignored * @param stream_len length of the bitstream in bits * @param setup pointer to the encoder setup * * @returns the bit length of the bitstream with the added unencoded value on * success; negative on error, CMP_ERROR_SMALL_BUF if the bitstream buffer * is too small to put the value in the bitstream * */ static int encode_value_none(uint32_t value, uint32_t unused, int stream_len, const struct encoder_setupt *setup) { (void)(unused); return put_n_bits32(value, setup->encoder_par1, stream_len, setup->bitstream_adr, setup->max_stream_len); } /** * @brief encodes the data with the model and the given setup and put it into * the bitstream * * @param data data to encode * @param model model of the data (0 if not used) * @param stream_len length of the bitstream in bits * @param setup pointer to the encoder setup * * @returns the bit length of the bitstream with the added encoded value on * success; negative on error, CMP_ERROR_SMALL_BUF if the bitstream buffer * is too small to put the value in the bitstream, CMP_ERROR_HIGH_VALUE if * the value or the model is bigger than the max_used_bits parameter allows */ static int encode_value(uint32_t data, uint32_t model, int stream_len, const struct encoder_setupt *setup) { uint32_t mask = ~(0xFFFFFFFFU >> (32-setup->max_data_bits)); /* lossy rounding of the data if lossy_par > 0 */ data = round_fwd(data, setup->lossy_par); model = round_fwd(model, setup->lossy_par); if (data & mask || model & mask) { debug_print("Error: The data or the model of the data are bigger than expected.\n"); return CMP_ERROR_HIGH_VALUE; } return setup->encode_method_f(data, model, stream_len, setup); } /** * @brief calculate the maximum length of the bitstream/icu_output_buf in bits * @note we round down to the next 4-byte allied address because we access the * cmp_buffer in uint32_t words * * @param buffer_length length of the icu_output_buf in samples * @param data_type used compression data type * * @returns buffer size in bits * */ static uint32_t cmp_buffer_length_to_bits(uint32_t buffer_length, enum cmp_data_type data_type) { return (cmp_cal_size_of_data(buffer_length, data_type) & ~0x3U) * CHAR_BIT; } /** * @brief configure an encoder setup structure to have a setup to encode a vale * * @param setup pointer to the encoder setup * @param cmp_par compression parameter * @param spillover spillover_par parameter * @param lossy_par lossy compression parameter * @param max_data_bits how many bits are needed to represent the highest possible value * @param cfg pointer to the compression configuration structure * * @returns 0 on success; otherwise error */ static int configure_encoder_setup(struct encoder_setupt *setup, uint32_t cmp_par, uint32_t spillover, uint32_t lossy_par, uint32_t max_data_bits, const struct cmp_cfg *cfg) { if (!setup) return -1; if (!cfg) return -1; if (max_data_bits > 32) { debug_print("Error: max_data_bits parameter is bigger than 32 bits.\n"); return -1; } memset(setup, 0, sizeof(*setup)); setup->encoder_par1 = cmp_par; setup->max_data_bits = max_data_bits; setup->lossy_par = lossy_par; setup->bitstream_adr = cfg->icu_output_buf; setup->max_stream_len = cmp_buffer_length_to_bits(cfg->buffer_length, cfg->data_type); if (cfg->cmp_mode != CMP_MODE_STUFF) { if (ilog_2(cmp_par) < 0) return -1; setup->encoder_par2 = (uint32_t)ilog_2(cmp_par); setup->spillover_par = spillover; /* for encoder_par1 which are a power of two we can use the faster rice_encoder */ if (is_a_pow_of_2(setup->encoder_par1)) setup->generate_cw_f = &rice_encoder; else setup->generate_cw_f = &golomb_encoder; } switch (cfg->cmp_mode) { case CMP_MODE_MODEL_ZERO: case CMP_MODE_DIFF_ZERO: setup->encode_method_f = &encode_value_zero; break; case CMP_MODE_MODEL_MULTI: case CMP_MODE_DIFF_MULTI: setup->encode_method_f = &encode_value_multi; break; case CMP_MODE_STUFF: setup->encode_method_f = &encode_value_none; setup->max_data_bits = cmp_par; break; case CMP_MODE_RAW: default: return -1; } return 0; } /** * @brief compress imagette data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream, CMP_ERROR_HIGH_VALUE if the value or the model is * bigger than the max_used_bits parameter allows */ static int compress_imagette(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct encoder_setupt setup; uint16_t *data_buf = cfg->input_buf; uint16_t *model_buf = cfg->model_buf; uint16_t model = 0; uint16_t *next_model_p = data_buf; uint16_t *up_model_buf = NULL; if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; up_model_buf = cfg->icu_new_model_buf; } err = configure_encoder_setup(&setup, cfg->golomb_par, cfg->spill, cfg->round, max_used_bits.nc_imagette, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i], model, stream_len, &setup); if (stream_len <= 0) break; if (up_model_buf) up_model_buf[i] = cmp_up_model(data_buf[i], model, cfg->model_value, setup.lossy_par); if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress the multi-entry packet header structure and sets the data, * model and up_model pointers to the data after the header * * @param data pointer to a pointer pointing to the data to be compressed * @param model pointer to a pointer pointing to the model of the data * @param up_model pointer to a pointer pointing to the updated model buffer * @param compressed_data pointer to the compressed data buffer * * @returns the bit length of the bitstream on success; negative on error, * * @note the (void **) cast relies on all pointer types having the same internal * representation which is common, but not universal; http://www.c-faq.com/ptrs/genericpp.html */ static int compress_multi_entry_hdr(void **data, void **model, void **up_model, void *compressed_data) { if (*up_model) { if (*data) memcpy(*up_model, *data, MULTI_ENTRY_HDR_SIZE); *up_model = (uint8_t *)*up_model + MULTI_ENTRY_HDR_SIZE; } if (*data) { if (compressed_data) memcpy(compressed_data, *data, MULTI_ENTRY_HDR_SIZE); *data = (uint8_t *)*data + MULTI_ENTRY_HDR_SIZE; } if (*model) *model = (uint8_t *)*model + MULTI_ENTRY_HDR_SIZE; return MULTI_ENTRY_HDR_SIZE * CHAR_BIT; } /** * @brief compress short normal light flux (S_FX) data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_s_fx(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct s_fx *data_buf = cfg->input_buf; struct s_fx *model_buf = cfg->model_buf; struct s_fx *up_model_buf = NULL; struct s_fx *next_model_p; struct s_fx model; struct encoder_setupt setup_exp_flag, setup_fx; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_exp_flag, cfg->cmp_par_exp_flags, cfg->spill_exp_flags, cfg->round, max_used_bits.s_exp_flags, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.s_fx, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].exp_flags, model.exp_flags, stream_len, &setup_exp_flag); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].exp_flags = cmp_up_model(data_buf[i].exp_flags, model.exp_flags, cfg->model_value, setup_exp_flag.lossy_par); up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress S_FX_EFX data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_s_fx_efx(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct s_fx_efx *data_buf = cfg->input_buf; struct s_fx_efx *model_buf = cfg->model_buf; struct s_fx_efx *up_model_buf = NULL; struct s_fx_efx *next_model_p; struct s_fx_efx model; struct encoder_setupt setup_exp_flag, setup_fx, setup_efx; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_exp_flag, cfg->cmp_par_exp_flags, cfg->spill_exp_flags, cfg->round, max_used_bits.s_exp_flags, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.s_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_efx, cfg->cmp_par_efx, cfg->spill_efx, cfg->round, max_used_bits.s_efx, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].exp_flags, model.exp_flags, stream_len, &setup_exp_flag); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].efx, model.efx, stream_len, &setup_efx); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].exp_flags = cmp_up_model(data_buf[i].exp_flags, model.exp_flags, cfg->model_value, setup_exp_flag.lossy_par); up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].efx = cmp_up_model(data_buf[i].efx, model.efx, cfg->model_value, setup_efx.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress S_FX_NCOB data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_s_fx_ncob(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct s_fx_ncob *data_buf = cfg->input_buf; struct s_fx_ncob *model_buf = cfg->model_buf; struct s_fx_ncob *up_model_buf = NULL; struct s_fx_ncob *next_model_p; struct s_fx_ncob model; struct encoder_setupt setup_exp_flag, setup_fx, setup_ncob; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_exp_flag, cfg->cmp_par_exp_flags, cfg->spill_exp_flags, cfg->round, max_used_bits.s_exp_flags, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.s_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ncob, cfg->cmp_par_ncob, cfg->spill_ncob, cfg->round, max_used_bits.s_ncob, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].exp_flags, model.exp_flags, stream_len, &setup_exp_flag); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_x, model.ncob_x, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_y, model.ncob_y, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].exp_flags = cmp_up_model(data_buf[i].exp_flags, model.exp_flags, cfg->model_value, setup_exp_flag.lossy_par); up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].ncob_x = cmp_up_model(data_buf[i].ncob_x, model.ncob_x, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].ncob_y = cmp_up_model(data_buf[i].ncob_y, model.ncob_y, cfg->model_value, setup_ncob.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress S_FX_EFX_NCOB_ECOB data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_s_fx_efx_ncob_ecob(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct s_fx_efx_ncob_ecob *data_buf = cfg->input_buf; struct s_fx_efx_ncob_ecob *model_buf = cfg->model_buf; struct s_fx_efx_ncob_ecob *up_model_buf = NULL; struct s_fx_efx_ncob_ecob *next_model_p; struct s_fx_efx_ncob_ecob model; struct encoder_setupt setup_exp_flag, setup_fx, setup_ncob, setup_efx, setup_ecob; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_exp_flag, cfg->cmp_par_exp_flags, cfg->spill_exp_flags, cfg->round, max_used_bits.s_exp_flags, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.s_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ncob, cfg->cmp_par_ncob, cfg->spill_ncob, cfg->round, max_used_bits.s_ncob, cfg); if (err) return -1; err = configure_encoder_setup(&setup_efx, cfg->cmp_par_efx, cfg->spill_efx, cfg->round, max_used_bits.s_efx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ecob, cfg->cmp_par_ecob, cfg->spill_ecob, cfg->round, max_used_bits.s_ecob, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].exp_flags, model.exp_flags, stream_len, &setup_exp_flag); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_x, model.ncob_x, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_y, model.ncob_y, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].efx, model.efx, stream_len, &setup_efx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ecob_x, model.ecob_x, stream_len, &setup_ecob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ecob_y, model.ecob_y, stream_len, &setup_ecob); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].exp_flags = cmp_up_model(data_buf[i].exp_flags, model.exp_flags, cfg->model_value, setup_exp_flag.lossy_par); up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].ncob_x = cmp_up_model(data_buf[i].ncob_x, model.ncob_x, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].ncob_y = cmp_up_model(data_buf[i].ncob_y, model.ncob_y, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].efx = cmp_up_model(data_buf[i].efx, model.efx, cfg->model_value, setup_efx.lossy_par); up_model_buf[i].ecob_x = cmp_up_model(data_buf[i].ecob_x, model.ecob_x, cfg->model_value, setup_ecob.lossy_par); up_model_buf[i].ecob_y = cmp_up_model(data_buf[i].ecob_y, model.ecob_y, cfg->model_value, setup_ecob.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress F_FX data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_f_fx(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct f_fx *data_buf = cfg->input_buf; struct f_fx *model_buf = cfg->model_buf; struct f_fx *up_model_buf = NULL; struct f_fx *next_model_p; struct f_fx model; struct encoder_setupt setup_fx; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.f_fx, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress F_FX_EFX data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_f_fx_efx(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct f_fx_efx *data_buf = cfg->input_buf; struct f_fx_efx *model_buf = cfg->model_buf; struct f_fx_efx *up_model_buf = NULL; struct f_fx_efx *next_model_p; struct f_fx_efx model; struct encoder_setupt setup_fx, setup_efx; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.f_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_efx, cfg->cmp_par_efx, cfg->spill_efx, cfg->round, max_used_bits.f_efx, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].efx, model.efx, stream_len, &setup_efx); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].efx = cmp_up_model(data_buf[i].efx, model.efx, cfg->model_value, setup_efx.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress F_FX_NCOB data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_f_fx_ncob(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct f_fx_ncob *data_buf = cfg->input_buf; struct f_fx_ncob *model_buf = cfg->model_buf; struct f_fx_ncob *up_model_buf = NULL; struct f_fx_ncob *next_model_p; struct f_fx_ncob model; struct encoder_setupt setup_fx, setup_ncob; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.f_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ncob, cfg->cmp_par_ncob, cfg->spill_ncob, cfg->round, max_used_bits.f_ncob, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_x, model.ncob_x, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_y, model.ncob_y, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].ncob_x = cmp_up_model(data_buf[i].ncob_x, model.ncob_x, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].ncob_y = cmp_up_model(data_buf[i].ncob_y, model.ncob_y, cfg->model_value, setup_ncob.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress F_FX_EFX_NCOB_ECOB data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_f_fx_efx_ncob_ecob(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct f_fx_efx_ncob_ecob *data_buf = cfg->input_buf; struct f_fx_efx_ncob_ecob *model_buf = cfg->model_buf; struct f_fx_efx_ncob_ecob *up_model_buf = NULL; struct f_fx_efx_ncob_ecob *next_model_p; struct f_fx_efx_ncob_ecob model; struct encoder_setupt setup_fx, setup_ncob, setup_efx, setup_ecob; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.f_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ncob, cfg->cmp_par_ncob, cfg->spill_ncob, cfg->round, max_used_bits.f_ncob, cfg); if (err) return -1; err = configure_encoder_setup(&setup_efx, cfg->cmp_par_efx, cfg->spill_efx, cfg->round, max_used_bits.f_efx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ecob, cfg->cmp_par_ecob, cfg->spill_ecob, cfg->round, max_used_bits.f_ecob, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_x, model.ncob_x, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_y, model.ncob_y, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].efx, model.efx, stream_len, &setup_efx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ecob_x, model.ecob_x, stream_len, &setup_ecob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ecob_y, model.ecob_y, stream_len, &setup_ecob); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].ncob_x = cmp_up_model(data_buf[i].ncob_x, model.ncob_x, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].ncob_y = cmp_up_model(data_buf[i].ncob_y, model.ncob_y, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].efx = cmp_up_model(data_buf[i].efx, model.efx, cfg->model_value, setup_efx.lossy_par); up_model_buf[i].ecob_x = cmp_up_model(data_buf[i].ecob_x, model.ecob_x, cfg->model_value, setup_ecob.lossy_par); up_model_buf[i].ecob_y = cmp_up_model(data_buf[i].ecob_y, model.ecob_y, cfg->model_value, setup_ecob.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress L_FX data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_l_fx(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct l_fx *data_buf = cfg->input_buf; struct l_fx *model_buf = cfg->model_buf; struct l_fx *up_model_buf = NULL; struct l_fx *next_model_p; struct l_fx model; struct encoder_setupt setup_exp_flag, setup_fx, setup_fx_var; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_exp_flag, cfg->cmp_par_exp_flags, cfg->spill_exp_flags, cfg->round, max_used_bits.l_exp_flags, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.l_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx_var, cfg->cmp_par_fx_cob_variance, cfg->spill_fx_cob_variance, cfg->round, max_used_bits.l_fx_variance, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].exp_flags, model.exp_flags, stream_len, &setup_exp_flag); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx_variance, model.fx_variance, stream_len, &setup_fx_var); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].exp_flags = cmp_up_model(data_buf[i].exp_flags, model.exp_flags, cfg->model_value, setup_exp_flag.lossy_par); up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].fx_variance = cmp_up_model(data_buf[i].fx_variance, model.fx_variance, cfg->model_value, setup_fx_var.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress L_FX_EFX data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_l_fx_efx(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct l_fx_efx *data_buf = cfg->input_buf; struct l_fx_efx *model_buf = cfg->model_buf; struct l_fx_efx *up_model_buf = NULL; struct l_fx_efx *next_model_p; struct l_fx_efx model; struct encoder_setupt setup_exp_flag, setup_fx, setup_efx, setup_fx_var; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_exp_flag, cfg->cmp_par_exp_flags, cfg->spill_exp_flags, cfg->round, max_used_bits.l_exp_flags, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.l_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_efx, cfg->cmp_par_efx, cfg->spill_efx, cfg->round, max_used_bits.l_efx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx_var, cfg->cmp_par_fx_cob_variance, cfg->spill_fx_cob_variance, cfg->round, max_used_bits.l_fx_variance, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].exp_flags, model.exp_flags, stream_len, &setup_exp_flag); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].efx, model.efx, stream_len, &setup_efx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx_variance, model.fx_variance, stream_len, &setup_fx_var); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].exp_flags = cmp_up_model(data_buf[i].exp_flags, model.exp_flags, cfg->model_value, setup_exp_flag.lossy_par); up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].efx = cmp_up_model(data_buf[i].efx, model.efx, cfg->model_value, setup_efx.lossy_par); up_model_buf[i].fx_variance = cmp_up_model(data_buf[i].fx_variance, model.fx_variance, cfg->model_value, setup_fx_var.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress L_FX_NCOB data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_l_fx_ncob(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct l_fx_ncob *data_buf = cfg->input_buf; struct l_fx_ncob *model_buf = cfg->model_buf; struct l_fx_ncob *up_model_buf = NULL; struct l_fx_ncob *next_model_p; struct l_fx_ncob model; struct encoder_setupt setup_exp_flag, setup_fx, setup_ncob, setup_fx_var, setup_cob_var; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_exp_flag, cfg->cmp_par_exp_flags, cfg->spill_exp_flags, cfg->round, max_used_bits.l_exp_flags, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.l_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ncob, cfg->cmp_par_ncob, cfg->spill_ncob, cfg->round, max_used_bits.l_ncob, cfg); if (err) return -1; /* we use compression parameter for both variance data fields */ err = configure_encoder_setup(&setup_fx_var, cfg->cmp_par_fx_cob_variance, cfg->spill_fx_cob_variance, cfg->round, max_used_bits.l_fx_variance, cfg); if (err) return -1; err = configure_encoder_setup(&setup_cob_var, cfg->cmp_par_fx_cob_variance, cfg->spill_fx_cob_variance, cfg->round, max_used_bits.l_cob_variance, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].exp_flags, model.exp_flags, stream_len, &setup_exp_flag); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_x, model.ncob_x, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_y, model.ncob_y, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx_variance, model.fx_variance, stream_len, &setup_fx_var); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].cob_x_variance, model.cob_x_variance, stream_len, &setup_cob_var); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].cob_y_variance, model.cob_y_variance, stream_len, &setup_cob_var); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].exp_flags = cmp_up_model(data_buf[i].exp_flags, model.exp_flags, cfg->model_value, setup_exp_flag.lossy_par); up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].ncob_x = cmp_up_model(data_buf[i].ncob_x, model.ncob_x, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].ncob_y = cmp_up_model(data_buf[i].ncob_y, model.ncob_y, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].fx_variance = cmp_up_model(data_buf[i].fx_variance, model.fx_variance, cfg->model_value, setup_fx_var.lossy_par); up_model_buf[i].cob_x_variance = cmp_up_model(data_buf[i].cob_x_variance, model.cob_x_variance, cfg->model_value, setup_cob_var.lossy_par); up_model_buf[i].cob_y_variance = cmp_up_model(data_buf[i].cob_y_variance, model.cob_y_variance, cfg->model_value, setup_cob_var.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress L_FX_EFX_NCOB_ECOB data * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_l_fx_efx_ncob_ecob(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct l_fx_efx_ncob_ecob *data_buf = cfg->input_buf; struct l_fx_efx_ncob_ecob *model_buf = cfg->model_buf; struct l_fx_efx_ncob_ecob *up_model_buf = NULL; struct l_fx_efx_ncob_ecob *next_model_p; struct l_fx_efx_ncob_ecob model; struct encoder_setupt setup_exp_flag, setup_fx, setup_ncob, setup_efx, setup_ecob, setup_fx_var, setup_cob_var; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_exp_flag, cfg->cmp_par_exp_flags, cfg->spill_exp_flags, cfg->round, max_used_bits.l_exp_flags, cfg); if (err) return -1; err = configure_encoder_setup(&setup_fx, cfg->cmp_par_fx, cfg->spill_fx, cfg->round, max_used_bits.l_fx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ncob, cfg->cmp_par_ncob, cfg->spill_ncob, cfg->round, max_used_bits.l_ncob, cfg); if (err) return -1; err = configure_encoder_setup(&setup_efx, cfg->cmp_par_efx, cfg->spill_efx, cfg->round, max_used_bits.l_efx, cfg); if (err) return -1; err = configure_encoder_setup(&setup_ecob, cfg->cmp_par_ecob, cfg->spill_ecob, cfg->round, max_used_bits.l_ecob, cfg); if (err) return -1; /* we use compression parameter for both variance data fields */ err = configure_encoder_setup(&setup_fx_var, cfg->cmp_par_fx_cob_variance, cfg->spill_fx_cob_variance, cfg->round, max_used_bits.l_fx_variance, cfg); if (err) return -1; err = configure_encoder_setup(&setup_cob_var, cfg->cmp_par_fx_cob_variance, cfg->spill_fx_cob_variance, cfg->round, max_used_bits.l_cob_variance, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].exp_flags, model.exp_flags, stream_len, &setup_exp_flag); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx, model.fx, stream_len, &setup_fx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_x, model.ncob_x, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ncob_y, model.ncob_y, stream_len, &setup_ncob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].efx, model.efx, stream_len, &setup_efx); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ecob_x, model.ecob_x, stream_len, &setup_ecob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].ecob_y, model.ecob_y, stream_len, &setup_ecob); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].fx_variance, model.fx_variance, stream_len, &setup_fx_var); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].cob_x_variance, model.cob_x_variance, stream_len, &setup_cob_var); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].cob_y_variance, model.cob_y_variance, stream_len, &setup_cob_var); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].exp_flags = cmp_up_model(data_buf[i].exp_flags, model.exp_flags, cfg->model_value, setup_exp_flag.lossy_par); up_model_buf[i].fx = cmp_up_model(data_buf[i].fx, model.fx, cfg->model_value, setup_fx.lossy_par); up_model_buf[i].ncob_x = cmp_up_model(data_buf[i].ncob_x, model.ncob_x, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].ncob_y = cmp_up_model(data_buf[i].ncob_y, model.ncob_y, cfg->model_value, setup_ncob.lossy_par); up_model_buf[i].efx = cmp_up_model(data_buf[i].efx, model.efx, cfg->model_value, setup_efx.lossy_par); up_model_buf[i].ecob_x = cmp_up_model(data_buf[i].ecob_x, model.ecob_x, cfg->model_value, setup_ecob.lossy_par); up_model_buf[i].ecob_y = cmp_up_model(data_buf[i].ecob_y, model.ecob_y, cfg->model_value, setup_ecob.lossy_par); up_model_buf[i].fx_variance = cmp_up_model(data_buf[i].fx_variance, model.fx_variance, cfg->model_value, setup_fx_var.lossy_par); up_model_buf[i].cob_x_variance = cmp_up_model(data_buf[i].cob_x_variance, model.cob_x_variance, cfg->model_value, setup_cob_var.lossy_par); up_model_buf[i].cob_y_variance = cmp_up_model(data_buf[i].cob_y_variance, model.cob_y_variance, cfg->model_value, setup_cob_var.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress offset data from the normal cameras * * @param cfg pointer to the compression configuration structure * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_nc_offset(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct nc_offset *data_buf = cfg->input_buf; struct nc_offset *model_buf = cfg->model_buf; struct nc_offset *up_model_buf = NULL; struct nc_offset *next_model_p; struct nc_offset model; struct encoder_setupt setup_mean, setup_var; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_mean, cfg->cmp_par_mean, cfg->spill_mean, cfg->round, max_used_bits.nc_offset_mean, cfg); if (err) return -1; err = configure_encoder_setup(&setup_var, cfg->cmp_par_variance, cfg->spill_variance, cfg->round, max_used_bits.nc_offset_variance, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].mean, model.mean, stream_len, &setup_mean); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].variance, model.variance, stream_len, &setup_var); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].mean = cmp_up_model(data_buf[i].mean, model.mean, cfg->model_value, setup_mean.lossy_par); up_model_buf[i].variance = cmp_up_model(data_buf[i].variance, model.variance, cfg->model_value, setup_var.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress background data from the normal cameras * * @param cfg pointer to the compression configuration structure * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_nc_background(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct nc_background *data_buf = cfg->input_buf; struct nc_background *model_buf = cfg->model_buf; struct nc_background *up_model_buf = NULL; struct nc_background *next_model_p; struct nc_background model; struct encoder_setupt setup_mean, setup_var, setup_pix; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_mean, cfg->cmp_par_mean, cfg->spill_mean, cfg->round, max_used_bits.nc_background_mean, cfg); if (err) return -1; err = configure_encoder_setup(&setup_var, cfg->cmp_par_variance, cfg->spill_variance, cfg->round, max_used_bits.nc_background_variance, cfg); if (err) return -1; err = configure_encoder_setup(&setup_pix, cfg->cmp_par_pixels_error, cfg->spill_pixels_error, cfg->round, max_used_bits.nc_background_outlier_pixels, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].mean, model.mean, stream_len, &setup_mean); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].variance, model.variance, stream_len, &setup_var); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].outlier_pixels, model.outlier_pixels, stream_len, &setup_pix); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].mean = cmp_up_model(data_buf[i].mean, model.mean, cfg->model_value, setup_mean.lossy_par); up_model_buf[i].variance = cmp_up_model(data_buf[i].variance, model.variance, cfg->model_value, setup_var.lossy_par); up_model_buf[i].outlier_pixels = cmp_up_model(data_buf[i].outlier_pixels, model.outlier_pixels, cfg->model_value, setup_pix.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief compress smearing data from the normal cameras * * @param cfg pointer to the compression configuration structure * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int compress_smearing(const struct cmp_cfg *cfg) { int err; int stream_len = 0; size_t i; struct smearing *data_buf = cfg->input_buf; struct smearing *model_buf = cfg->model_buf; struct smearing *up_model_buf = NULL; struct smearing *next_model_p; struct smearing model; struct encoder_setupt setup_mean, setup_var_mean, setup_pix; if (model_mode_is_used(cfg->cmp_mode)) up_model_buf = cfg->icu_new_model_buf; stream_len = compress_multi_entry_hdr((void **)&data_buf, (void **)&model_buf, (void **)&up_model_buf, cfg->icu_output_buf); if (model_mode_is_used(cfg->cmp_mode)) { model = model_buf[0]; next_model_p = &model_buf[1]; } else { memset(&model, 0, sizeof(model)); next_model_p = data_buf; } err = configure_encoder_setup(&setup_mean, cfg->cmp_par_mean, cfg->spill_mean, cfg->round, max_used_bits.smearing_mean, cfg); if (err) return -1; err = configure_encoder_setup(&setup_var_mean, cfg->cmp_par_variance, cfg->spill_variance, cfg->round, max_used_bits.smearing_variance_mean, cfg); if (err) return -1; err = configure_encoder_setup(&setup_pix, cfg->cmp_par_pixels_error, cfg->spill_pixels_error, cfg->round, max_used_bits.smearing_outlier_pixels, cfg); if (err) return -1; for (i = 0;; i++) { stream_len = encode_value(data_buf[i].mean, model.mean, stream_len, &setup_mean); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].variance_mean, model.variance_mean, stream_len, &setup_var_mean); if (stream_len <= 0) return stream_len; stream_len = encode_value(data_buf[i].outlier_pixels, model.outlier_pixels, stream_len, &setup_pix); if (stream_len <= 0) return stream_len; if (up_model_buf) { up_model_buf[i].mean = cmp_up_model(data_buf[i].mean, model.mean, cfg->model_value, setup_mean.lossy_par); up_model_buf[i].variance_mean = cmp_up_model(data_buf[i].variance_mean, model.variance_mean, cfg->model_value, setup_var_mean.lossy_par); up_model_buf[i].outlier_pixels = cmp_up_model(data_buf[i].outlier_pixels, model.outlier_pixels, cfg->model_value, setup_pix.lossy_par); } if (i >= cfg->samples-1) break; model = next_model_p[i]; } return stream_len; } /** * @brief fill the last part of the bitstream with zeros * * @param cfg pointer to the compression configuration structure * @param cmp_size length of the bitstream in bits * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF if the bitstream buffer is too small to put the * value in the bitstream */ static int pad_bitstream(const struct cmp_cfg *cfg, int cmp_size) { unsigned int output_buf_len_bits, n_pad_bits; if (cmp_size < 0) return cmp_size; if (!cfg->icu_output_buf) return cmp_size; /* no padding in RAW mode; ALWAYS BIG-ENDIAN */ if (cfg->cmp_mode == CMP_MODE_RAW) return cmp_size; /* maximum length of the bitstream/icu_output_buf in bits */ output_buf_len_bits = cmp_buffer_length_to_bits(cfg->buffer_length, cfg->data_type); n_pad_bits = 32 - ((unsigned int)cmp_size & 0x1FU); if (n_pad_bits < 32) { int n_bits = put_n_bits32(0, n_pad_bits, cmp_size, cfg->icu_output_buf, output_buf_len_bits); if (n_bits < 0) return n_bits; } return cmp_size; } /** * @brief change the endianness of the compressed data to big-endian * * @param cfg pointer to the compression configuration structure * @param cmp_size length of the bitstream in bits * * @returns 0 on success; non-zero on failure */ static int cmp_data_to_big_endian(const struct cmp_cfg *cfg, int cmp_size) { #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) size_t i; uint32_t *p; uint32_t s = (uint32_t)cmp_size; if (cmp_size < 0) return cmp_size; if (!cfg->icu_output_buf) return cmp_size; if (cfg->cmp_mode == CMP_MODE_RAW) { if (s & 0x7) /* size must be a multiple of 8 in RAW mode */ return -1; if (cmp_input_big_to_cpu_endianness(cfg->icu_output_buf, s/CHAR_BIT, cfg->data_type)) cmp_size = -1; } else { if (rdcu_supported_data_type_is_used(cfg->data_type)) { p = cfg->icu_output_buf; } else { p = &cfg->icu_output_buf[MULTI_ENTRY_HDR_SIZE/sizeof(uint32_t)]; s -= MULTI_ENTRY_HDR_SIZE * CHAR_BIT; } for (i = 0; i < cmp_bit_to_4byte(s)/sizeof(uint32_t); i++) cpu_to_be32s(&p[i]); } #else /* do nothing data are already in big-endian */ (void)cfg; #endif /*__BYTE_ORDER__ */ return cmp_size; } /** * @brief compress data on the ICU in software * * @param cfg pointer to a compression configuration (created with the * cmp_cfg_icu_create() function, setup with the cmp_cfg_xxx() functions) * * @note the validity of the cfg structure is checked before the compression is * started * * @returns the bit length of the bitstream on success; negative on error, * CMP_ERROR_SMALL_BUF (-2) if the compressed data buffer is too small to * hold the whole compressed data, CMP_ERROR_HIGH_VALUE (-3) if a data or * model value is bigger than the max_used_bits parameter allows (set with * the cmp_set_max_used_bits() function) */ int icu_compress_data(const struct cmp_cfg *cfg) { int cmp_size = 0; if (!cfg) return -1; if (cfg->samples == 0) /* nothing to compress we are done*/ return 0; if (raw_mode_is_used(cfg->cmp_mode)) if (cfg->samples > cfg->buffer_length) return CMP_ERROR_SMALL_BUF; if (cmp_cfg_icu_is_invalid(cfg)) return -1; if (raw_mode_is_used(cfg->cmp_mode)) { cmp_size = cmp_cal_size_of_data(cfg->samples, cfg->data_type); if (cfg->icu_output_buf) memcpy(cfg->icu_output_buf, cfg->input_buf, cmp_size); cmp_size *= CHAR_BIT; /* convert to bits */ } else { if (cfg->icu_output_buf && cfg->samples/3 > cfg->buffer_length) debug_print("Warning: The size of the compressed_data buffer is 3 times smaller than the data_to_compress. This is probably unintended.\n"); switch (cfg->data_type) { case DATA_TYPE_IMAGETTE: case DATA_TYPE_IMAGETTE_ADAPTIVE: case DATA_TYPE_SAT_IMAGETTE: case DATA_TYPE_SAT_IMAGETTE_ADAPTIVE: case DATA_TYPE_F_CAM_IMAGETTE: case DATA_TYPE_F_CAM_IMAGETTE_ADAPTIVE: cmp_size = compress_imagette(cfg); break; case DATA_TYPE_S_FX: cmp_size = compress_s_fx(cfg); break; case DATA_TYPE_S_FX_EFX: cmp_size = compress_s_fx_efx(cfg); break; case DATA_TYPE_S_FX_NCOB: cmp_size = compress_s_fx_ncob(cfg); break; case DATA_TYPE_S_FX_EFX_NCOB_ECOB: cmp_size = compress_s_fx_efx_ncob_ecob(cfg); break; case DATA_TYPE_F_FX: cmp_size = compress_f_fx(cfg); break; case DATA_TYPE_F_FX_EFX: cmp_size = compress_f_fx_efx(cfg); break; case DATA_TYPE_F_FX_NCOB: cmp_size = compress_f_fx_ncob(cfg); break; case DATA_TYPE_F_FX_EFX_NCOB_ECOB: cmp_size = compress_f_fx_efx_ncob_ecob(cfg); break; case DATA_TYPE_L_FX: cmp_size = compress_l_fx(cfg); break; case DATA_TYPE_L_FX_EFX: cmp_size = compress_l_fx_efx(cfg); break; case DATA_TYPE_L_FX_NCOB: cmp_size = compress_l_fx_ncob(cfg); break; case DATA_TYPE_L_FX_EFX_NCOB_ECOB: cmp_size = compress_l_fx_efx_ncob_ecob(cfg); break; case DATA_TYPE_OFFSET: cmp_size = compress_nc_offset(cfg); break; case DATA_TYPE_BACKGROUND: cmp_size = compress_nc_background(cfg); break; case DATA_TYPE_SMEARING: cmp_size = compress_smearing(cfg); break; case DATA_TYPE_F_CAM_OFFSET: case DATA_TYPE_F_CAM_BACKGROUND: /* LCOV_EXCL_START */ case DATA_TYPE_UNKNOWN: default: debug_print("Error: Data type not supported.\n"); cmp_size = -1; } /* LCOV_EXCL_STOP */ } cmp_size = pad_bitstream(cfg, cmp_size); cmp_size = cmp_data_to_big_endian(cfg, cmp_size); return cmp_size; }
// repeated.cpp : Defines the entry point for the console application. // #include<malloc.h> #include "stdafx.h" char* readinput1(); int _tmain(int argc, _TCHAR* argv[]) { char* s; int a[62]={0},i=0,j=0; s=readinput1(); while(*s){ //just considered alpha numeric values. if(*s>='a' && *s<='z'){ //this condition is to store low case letters in even number positions like a[0],a[2],a[4] a[2*((*s)-'a')]=*s; } else if(*s>='A' && *s<='Z'){ //this condition is to store uppercase in odd number positions lke a[1],a[3],a[5] a[(2*(*s-'A'))+1]=*s; } else if(*s>='0' && *s<='9'){ //this condition is to store numbers after storing upper and lower cases a[((*s-'0')+52)]=*s; } s++; //all other symbols are ignored } i=0; j=0; while(i<62){ /// this loop is to store all the sorted values in given input array if(a[i]!=0){ s[j]=a[i]; j++; } i++; } s[j]=0; printf("\n%s",s); return 0; } char* readinput1() { char* c; int n; printf("enter the maximum length"); scanf_s("%d",&n); printf("enter the string"); c=(char *)malloc(n); fflush(stdin); gets_s(c,n); return c; }
/** * Simple viewer for RLE images using mmap() and then memory buffer. * * Note that this is super-simple and omit some required checks, resulting * in buffer overflow! Don't use this for untrusted data! */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdint.h> #include "sdl-viewer.h" typedef int (*unit_processor_t)(const void **mem, void **buffer); struct rle_handle { const void *p; const void *mem; int fd; size_t size; }; static void mem_read(const void **buffer, void *dst, unsigned int size) { memcpy(dst, *buffer, size); *buffer = (char *)*buffer + size; } #define mem_read_autosize(b, d) mem_read(b, d, sizeof(*(d))) static void draw_scanline(void **buffer, unsigned length, uint32_t pixel) { uint32_t *p; unsigned int i; for (i = 0, p = *buffer; i < length; i++, p++) *p = pixel; *buffer = p; } static int unit_processor_color_rgb888(const void **mem, void **buffer) { struct rle_color_rgb888 v; uint32_t pixel; mem_read_autosize(mem, &v); pixel = v.color; draw_scanline(buffer, v.length, pixel); return 0; } static int unit_processor_color_rgb565(const void **mem, void **buffer) { struct rle_color_rgb565 v; uint32_t pixel; mem_read_autosize(mem, &v); if (v.color == 0xffff) pixel = 0xffffffff; else if (v.color == 0x0000) pixel = 0xff000000; else { uint32_t r, g, b; r = (v.color >> 11) & 0x1f; g = (v.color >> 5) & 0x3f; b = v.color & 0x1f; pixel = 0xff000000 | (r << (16 + 3)) | (g << (8 + 2)) | (b << 3); } draw_scanline(buffer, v.length, pixel); return 0; } static int unit_processor_grayscale(const void **mem, void **buffer) { struct rle_grayscale v; uint32_t pixel; mem_read_autosize(mem, &v); pixel = 0xff000000 | (v.level << 16) | (v.level << 8) | v.level; draw_scanline(buffer, v.length, pixel); return 0; } static int unit_processor_bitmask(const void **mem, void **buffer) { struct rle_bitmask v; uint32_t pixel; mem_read_autosize(mem, &v); pixel = v.bit ? 0xffffffff : 0xff000000; draw_scanline(buffer, v.length, pixel); return 0; } static int unit_processor_tinybitmask(const void **mem, void **buffer) { struct rle_tinybitmask v; uint32_t pixel; mem_read_autosize(mem, &v); pixel = v.bit ? 0xffffffff : 0xff000000; draw_scanline(buffer, v.length, pixel); return 0; } static int decode_line(const void **mem, unit_processor_t unit_processor, void *buffer) { unsigned short n; unsigned int i; mem_read_autosize(mem, &n); for (i = 0; i < n; i++) if (unit_processor(mem, &buffer) != 0) { fprintf(stderr, "Could not process unit %d\n", i); return -1; } return 0; } int rle_decode(rle_handle_t *handle, unsigned short h, rle_unit_type_t unit_type, void *buffer, unsigned short pitch) { unsigned int i; unit_processor_t unit_processor; const unit_processor_t unit_processors[] = { unit_processor_color_rgb888, unit_processor_color_rgb565, unit_processor_grayscale, unit_processor_bitmask, unit_processor_tinybitmask }; unit_processor = unit_processors[unit_type]; for (i = 0; i < h; i++) { if (decode_line(&handle->p, unit_processor, buffer) != 0) { fprintf(stderr, "Problems decoding line %d\n", i); return -1; } buffer = (char *)buffer + pitch; } return 0; } int rle_parse_header(rle_handle_t *handle, unsigned short *w, unsigned short *h, rle_unit_type_t *unit_type) { unsigned short v[4] = {0, 0, 0, 0}; mem_read(&handle->p, v, sizeof(v)); *w = v[0]; *h = v[1]; *unit_type = v[2]; return 0; } rle_handle_t * rle_open(const char *filename) { rle_handle_t *h; struct stat st; h = malloc(sizeof(*h)); if (!h) { perror("malloc"); return NULL; } h->fd = open(filename, O_RDONLY); if (h->fd < 0) { perror("open"); goto free_and_exit; } if (fstat(h->fd, &st) != 0) { perror("fstat"); goto close_file_free_and_exit; } h->size = st.st_size; h->mem = mmap(NULL, h->size, PROT_READ, MAP_SHARED | MAP_POPULATE, h->fd, 0); if (h->mem == MAP_FAILED) { perror("mmap"); goto close_file_free_and_exit; } h->p = h->mem; return h; close_file_free_and_exit: close(h->fd); free_and_exit: free(h); return NULL; } void rle_close(rle_handle_t *handle) { munmap((void *)handle->mem, handle->size); close(handle->fd); free(handle); }
/****************************************************************************** 版权所有 (C), 2015-2025, 网络科技有限公司 ****************************************************************************** 文 件 名 : rct_epr.h 版 本 号 : 初稿 作 者 : jimk 生成日期 : 2016年5月26日 最近修改 : 功能描述 : 函数列表 : 修改历史 : 1.日 期 : 2016年5月26日 作 者 : jimk 修改内容 : 创建文件 ******************************************************************************/ /*接收缓存*/ #define RCT_EXPIRE_RECVBUF_SIZE 256 /***************[Expire Ops]*************************/ /*老化事件*/ typedef struct tagRctReactorExpireHandler RCT_REACTOR_EXPIREHANDLER_S; typedef struct tagRctReactorExpireOpts RCT_REACTOR_EXPIRE_OPT_S; typedef VOID (*rtm_reactor_expireops_cb)(VOID *pvhandler); /*单个老化节点: 老化链表挂载以及处理老化回调函数*/ struct tagRctReactorExpireOpts { VOS_DLIST_NODE_S stNode; VOS_CALLBACK_S stExpirecb; ULONG ulExpireConfirm; }; /*老化处理器: 老化链表*/ struct tagRctReactorExpireHandler { RCT_EVTREACTOR_S *pstRctEvtReactor; /*Current Max ssl connect node num is 200 for one epollReactor, if >200, change to the hash table instand of the expirelist.*/ VOS_DLIST_NODE_S stExpireList; /*也是基于网络事件*/ RCT_REACTOR_NETEVT_OPT_S stNetEvtOps; /*老化处理器的Socketfd*/ LONG lExprEventfd; }; VOID RCT_Expire_EventHandlerCb(VOID *pvHandler); LONG RCT_Expire_EventHandlerCreate(RCT_EVTREACTOR_S *pstRctReactor); LONG RCT_Expire_EventHandlerRelease(RCT_REACTOR_EXPIREHANDLER_S *pstExpireHandler); LONG RCT_Expire_EventOptsRegister(RCT_EVTREACTOR_S *pstRctReactor, RCT_REACTOR_EXPIRE_OPT_S *pstExpireOps); LONG RCT_Expire_EventOptsUnRegister(RCT_EVTREACTOR_S *pstRctReactor, RCT_REACTOR_EXPIRE_OPT_S *pstExpireOps);
#include<stdio.h> #include<stdbool.h> #include<ctype.h> #define Num 5 //count from 0 int rool_dice(void); bool play_game(void); int main(void) { bool flag; int win=0; int lose=0; char c; flag = play_game(); if(flag) { win++; printf("\nYou win!"); } else{ lose++; printf("\nYou lose!"); } printf("\n\nPlay again?"); c = toupper(getchar()); getchar();//remember to drop the enter printf("\n"); while(c=='Y') { flag = play_game(); if(flag) { win++; printf("\nYou win!"); } else{ lose++; printf("\nYou lose!"); } printf("\n\nPlay again?"); c = toupper(getchar()); getchar(); printf("\n"); } if (c=='N') { printf("\nWins:%d\tLosses:%d",win,lose); } return 0; } int rool_dice(void) { int point1=0; int point2=0; int pointSum=0; point1=(rand()%Num); point2=(rand()%Num); pointSum = point1+point2+2; return pointSum; } bool play_game(void) { int point=0; int pointB=0; point = rool_dice(); printf("You rolled:%d",point); if ((point==7)||(point==11)) return true; else if((point==2)||(point==3)||(point==11)) return false; else { printf("\nYour point is:%d",point); pointB = point; point = rool_dice(); while((point!=7)&&(point!=pointB)) { printf("\nYou rolled:%d",point); point = rool_dice(); } printf("\nYou rolled:%d",point); if(point==7) return false; else if(point == pointB)return true; } }
#include "main.h" // ---------------------- // Tokenizer // ---------------------- //represent Inputed Token type typedef enum { tk_reserved, // symbol tk_num, //integer number tk_eof, //end of token } TokenKind; typedef struct Token Token; char *user_input; // declare Token practical used Token *token; // Func of report error void error_at(char *loc, char *fmt, ...) { va_list ap; va_start(ap, fmt); int pol = loc - user_input; fprintf(stderr, "%s\n", user_input); fprintf(stderr, "%*s", pol, ""); fprintf(stderr, "^ "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); exit(1); } // Check of whether token is equal with op args // if it was equal, token value was changed to Next token value and return true // if not, return false bool consume(char *op) { if (token->kind != TK_RESERVED || strlen(op) != token->len || memcmp(token->str, op, token->len)) return false; token = token->next; return true; } // Check of whether token is equal with op args // if it was equal, token value was changed to Next token value void expect(char *op) { if (token->kind != TK_RESERVED || strlen(op) != token->len || memcmp(token->str, op, token->len)) error_at(token->str, "Token is NOT '%c'", op); token = token->next; } // Check of whether token value is integer // if so, store the integer value to token val value and return it // if so, token value was changed to Next token value int expect_number() { if (token->kind != TK_NUM) error_at(token->str, "Not integer value"); int val = token->val; token = token->next; return val; } // Check of whether token value is EOF bool at_eof(){ return token->kind == TK_EOF; } // Create New Token and bind Next linked List Token *new_token(enum TokenKind kind, struct Token *cur, char *str, int len) { Token *tok = calloc(1, sizeof(Token)); tok->kind = kind; tok->str = str; tok->len = len; cur->next = tok; return tok; } // check strings on Tokenize bool startswitch(char *p, char *q) { return memcmp(p, q, strlen(q)) == 0; } // Tokenize inputed string p // if p is space, skip // if p is symbol, create new token and consume configured process // if p is integer or digit, create new token and store value // if p is EOF, return last Linked list head Token *tokenize() { char *p = user_input; Token head; head.next = NULL; Token *cur = &head; while (*p) { // space is Skip if (isspace(*p)) { p++; continue; } // Token is 2 digits operater, create New Token if (startswitch(p, "==") || startswitch(p, "!=") || startswitch(p, "<=") || startswitch(p, ">=")) { cur = new_token(TK_RESERVED, cur, p, 2); p += 2; continue; } // Token is single digit operater, create New Token if (strchr("+-*/()<>", *p)){ cur = new_token(TK_RESERVED, cur, p++, 1); continue; } //strtol : convert input to value //p -> Decimal number value (10) //if strtol couldn't convert input, return position of unconvert value //&p -> '+' or '-' or etc //arg is 0, that's why digits values length is unknown, so calculate and store it if (isdigit(*p)) { cur = new_token(TK_NUM, cur, p, 0); char *q = p; cur->val = strtol(p, &p, 10); cur->len = p - q; continue; } error_at(p, "Unable to tokenize"); } new_token(TK_EOF, cur, p, 0); return head.next; }
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> // Funcion auxiliar para obtener el nombre del // fichero incluido en un path. char *get_file_from_path(char *path) { for (size_t i = strlen(path) - 1; i; i--) { if (path[i] == '/') { return &path[i + 1]; } } return path; } // Funcion auxiliar para obtener hex de un char. uint8_t get_hex(char c) { uint8_t ret; switch (c) { case '0': ret = 0x00; break; case '1': ret = 0x01; break; case '2': ret = 0x02; break; case '3': ret = 0x03; break; case '4': ret = 0x04; break; case '5': ret = 0x05; break; case '6': ret = 0x06; break; case '7': ret = 0x07; break; case '8': ret = 0x08; break; case '9': ret = 0x09; break; case 'A': ret = 0x0A; break; case 'B': ret = 0x0B; break; case 'C': ret = 0x0C; break; case 'D': ret = 0x0D; break; case 'E': ret = 0x0E; break; case 'F': ret = 0x0F; break; } return ret; } int main(int argc, char *argv[]) { int i; if (argc == 1) { printf("=> Error: no hay fichero de entrada! \n"); return 0; } FILE *pf = fopen(argv[1], "r"); if (NULL != pf) { // Calculamos size del fichero, lo leemos y cerramos. fseek(pf, 0, SEEK_END); int f_size = ftell(pf); char *code = malloc(sizeof(char) * f_size); fseek(pf, 0, SEEK_SET); fread(code, f_size, 1, pf); fclose(pf); // Nombre del nuevo fichero binario. char *bin_filename = get_file_from_path(argv[1]); FILE *f_bin = fopen(bin_filename, "wb"); // nuevo fichero binario. uint8_t datum; // 0 - 5 => .text 2E74657874 datum = 0x2E; fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x74; fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x65; fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x78; fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x74; fwrite(&datum, 1, sizeof(uint8_t), f_bin); // 6 - 11 => code[i] for (i = 6; i < 12; i += 2) { datum = get_hex(code[i]); datum <<= 4; datum += get_hex(code[i + 1]); fwrite(&datum, 1, sizeof(uint8_t), f_bin); } // 7 - 7 => \n // 8 - 13 => .data 2E64617661 datum = 0x2E; fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x64; fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x61; fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x74; fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x61; fwrite(&datum, 1, sizeof(uint8_t), f_bin); // 18 - 14 => code[i] for (i = 19; i < 25; i += 2) { datum = get_hex(code[i]); datum <<= 4; datum += get_hex(code[i + 1]); fwrite(&datum, 1, sizeof(uint8_t), f_bin); } datum = 0; int par = 1; for (i = 25; i < f_size; i++) { if (code[i] != '\n') { datum += get_hex(code[i]); if (par % 2 == 0) { fwrite(&datum, 1, sizeof(uint8_t), f_bin); datum = 0x00; } else { datum <<= 4; } par++; } } if (par % 2 != 0) { datum <<= 4; // datum = datum << 1; datum += 0x00; } fclose(f_bin); } return 1; }
#include <stdio.h> #include <limits.h> unsigned srl(unsigned x, int k) { /* Perform shift arithmetically */ unsigned xsra = (int) x >> k; return(xsra & (MAX_INT >> (k-1))); } int sra(int x, int k) { /* Perform shift logically */ int xsrl = (unsigned) x >> k; return(xsrl | ~(MAX_INT >> (k-1))); } int main(int argc){ printf("srl: %d\n", srl(-1,5) printf("sra: %d\n", sra(-1,5))); }
// 示例:5.7.4.2 string s2 = "我在示例 5.7.4.2 中!"; void test2() { cecho(s2); }
#ifndef __KERN_MM_DEFAULT_PMM_H__ #define __KERN_MM_DEFAULT_PMM_H__ #include "mm/pmm.h" #include "mm/memlayout.h" extern const struct pmm_manager default_pmm_manager; #endif /* ! __KERN_MM_DEFAULT_PMM_H__ */
#ifndef _TINYLIBC_UNISTD_H #define _TINYLIBC_UNISTD_H #include <bits/tlibc_config.h> #include <sys/types.h> char **environ; #define STDERR_FILENO 2 #define STDOUT_FILENO 1 #define STDIN_FILENO 0 #define PROT_READ 0x1 /* page can be read */ #define PROT_WRITE 0x2 /* page can be written */ #define PROT_EXEC 0x4 /* page can be executed */ #define PROT_SEM 0x8 /* page may be used for atomic ops */ #define PROT_NONE 0x0 /* page can not be accessed */ #define PROT_GROWSDOWN 0x01000000 /* mprotect flag: extend change to start of growsdown vma */ #define PROT_GROWSUP 0x02000000 /* mprotect flag: extend change to end of growsup vma */ #define MAP_SHARED 0x01 /* Share changes */ #define MAP_PRIVATE 0x02 /* Changes are private */ #define MAP_TYPE 0x0f /* Mask for type of mapping */ #define MAP_FIXED 0x10 /* Interpret addr exactly */ #define MAP_ANONYMOUS 0x20 /* don't use a file */ #ifndef FASYNC #define FASYNC 00020000 /* fcntl, for BSD compatibility */ #endif #ifndef O_DIRECT #define O_DIRECT 00040000 /* direct disk access hint */ #endif #ifndef O_LARGEFILE #define O_LARGEFILE 00100000 #endif #ifndef O_NOATIME #define O_NOATIME 01000000 #endif #define __S_ISUID 04000 /* Set user ID on execution. */ #define __S_ISGID 02000 /* Set group ID on execution. */ #define __S_ISVTX 01000 /* Save swapped text after use (sticky). */ #define __S_IREAD 0400 /* Read by owner. */ #define __S_IWRITE 0200 /* Write by owner. */ #define __S_IEXEC 0100 /* Execute by owner. */ # define S_ISUID __S_ISUID /* Set user ID on execution. */ # define S_ISGID __S_ISGID /* Set group ID on execution. */ # define S_IRUSR __S_IREAD /* Read by owner. */ # define S_IWUSR __S_IWRITE /* Write by owner. */ # define S_IXUSR __S_IEXEC /* Execute by owner. */ /* Read, write, and execute by owner. */ # define S_IRWXU (__S_IREAD|__S_IWRITE|__S_IEXEC) # define S_IRGRP (S_IRUSR >> 3) /* Read by group. */ # define S_IWGRP (S_IWUSR >> 3) /* Write by group. */ # define S_IXGRP (S_IXUSR >> 3) /* Execute by group. */ /* Read, write, and execute by group. */ # define S_IRWXG (S_IRWXU >> 3) # define S_IROTH (S_IRGRP >> 3) /* Read by others. */ # define S_IWOTH (S_IWGRP >> 3) /* Write by others. */ # define S_IXOTH (S_IXGRP >> 3) /* Execute by others. */ /* Read, write, and execute by others. */ # define S_IRWXO (S_IRWXG >> 3) TLIBC_FN int close(int); TLIBC_FN void _exit(int); TLIBC_FN ssize_t read(int, void*, size_t); TLIBC_FN ssize_t write(int, const void*, size_t); TLIBC_FN off_t lseek(int, off_t, int); TLIBC_FN int execve(const char *, char * const[], char * const[]); #endif /* _TINYLIBC_UNISTD_H */ #define _TINYLIBC_IN_USE
#include "header.h" /*pontlista kezelo fuggvenyek*/ int pont_beolvas(FILE *f,char *nev,int *p) { char s[50]; int c,i; c=fgetc(f); if(c==EOF || c=='\n')return 0; for(i=0;c!=EOF && c!='\n' && i<=48;i++) { s[i]=c; c=fgetc(f); }s[i]='\0'; for(i=i-1;i>=0 && (s[i]>'9' || s[i]<'0');i--); while(i>=0 && s[i]!=' ')i--; sscanf(s+i,"%d",p); s[i]=0; strcpy(nev,s); return 1; } pontlista *pontlista_init(pontlista *lis) { FILE *f; pontlista *uj; char s[50]; int psz; f=fopen("high_score.txt","rt"); lis=NULL; while(pont_beolvas(f,s,&psz)==1) { uj=(pontlista*)malloc(sizeof(pontlista)); uj->nev=(char*)malloc(sizeof(char)*strlen(s)+1); strcpy(uj->nev,s); uj->psz=psz; uj->kov=lis; lis=uj; } fclose(f); return lis; } void pontlista_felszab(pontlista *lis) { pontlista*tmp; while(lis!=NULL) { tmp=lis->kov; free(lis->nev); free(lis); lis=tmp; } }
#include <std.h> inherit ROOM; void create() { ::create(); set_name("Drow Camp"); set_items((["snow" : "A deep white snow", "dirt" : "A dark brown mixture"])); set_properties((["light":2, "night light":3])); set_short("camp"); set_long("This is the drow encampment, where the drows are waiting to " "attack roston, the town to the south. There are tents layed out " "all around as far as you can see. The drows seem to be very " "relaxed and calm. There seems to be a giant gold tent to " "the north west. Tons of tracks can be seen to the north."); set_exits( ([ "south" : "/wizards/detach/roston/drow/room85", "north" : "/wizards/detach/roston/drow/room88", "east" : "/wizards/detach/roston/drow/room83" ])); }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #define INPUT_FILE1 "input1.dat" #define INPUT_FILE2 "input2.dat" #define OUTPUT_FILE "output.dat" #define MAX_NR_LENGTH 10 typedef struct st_BTree BTree; struct st_BTree { BTree* left; BTree* right; //Max depth of subtrees int Lweight; int Rweight; void* data; };
#ifndef LIB_COS_AUTH_H #define LIB_COS_AUTH_H #include "aos_util.h" #include "aos_string.h" #include "aos_http_io.h" #include "cos_define.h" COS_CPP_START /** * @brief sign cos headers **/ void cos_sign_headers(aos_pool_t *p, const aos_string_t *signstr, const aos_string_t *access_key_id, const aos_string_t *access_key_secret, aos_table_t *headers); /** * @brief get string to signature **/ int cos_get_string_to_sign(aos_pool_t *p, http_method_e method, const aos_string_t *canon_res, const aos_table_t *headers, const aos_table_t *params, aos_string_t *signstr); /** * @brief get signed cos request headers **/ int cos_get_signed_headers(aos_pool_t *p, const aos_string_t *access_key_id, const aos_string_t *access_key_secret, const aos_string_t* canon_res, aos_http_request_t *req); /** * @brief sign cos request **/ int cos_sign_request(aos_http_request_t *req, const cos_config_t *config); /** * @brief generate cos request Signature **/ int get_cos_request_signature(const cos_request_options_t *options, aos_http_request_t *req, const aos_string_t *expires, aos_string_t *signature); /** * @brief get cos signed url **/ int cos_get_signed_url(const cos_request_options_t *options, aos_http_request_t *req, const aos_string_t *expires, aos_string_t *auth_url); COS_CPP_END #endif
#include "lista_enc.h" #include <stdio.h> #include <stdlib.h> #include "no.h" #define FALSE 0 #define TRUE 1 //#define DEBUG struct listas_enc { no_t *cabeca; /*!< Referência da cabeça da lista encadeada: primeiro elemento. */ no_t *cauda; /*!< Referência da cauda da lista encadeada: último elemento. */ int tamanho; /*!< Tamanho atual da lista. */ }; int lista_tamanho(lista_enc_t * lista){ return lista->tamanho; } /** * @brief Cria uma nova lista encadeada vazia. * @param Nenhum * * @retval lista_enc_t *: ponteiro (referência) da nova lista encadeada. */ lista_enc_t *cria_lista_enc (void) { lista_enc_t *p = malloc(sizeof(lista_enc_t)); if (p == NULL){ perror("cria_lista_enc:"); exit(EXIT_FAILURE); } p->cabeca = NULL; p->cauda = NULL; p->tamanho = 0; return p; } /** * @brief Adiciona um nó de lista no final. * @param lista: lista encadeada que se deseja adicionar. * @param elemento: nó que será adicionado na cauda. * * @retval Nenhum */ void add_cauda(lista_enc_t *lista, no_t* elemento) { if (lista == NULL || elemento == NULL){ fprintf(stderr,"add_cauda: ponteiros invalidos"); exit(EXIT_FAILURE); } #ifdef DEBUG printf("Adicionando %p --- tamanho: %d\n", elemento, lista->tamanho); #endif // DEBUG //lista vazia if (lista->tamanho == 0) { #ifdef DEBUG printf("add_cauda: add primeiro elemento: %p\n", elemento); #endif // DEBUG lista->cauda = elemento; lista->cabeca = elemento; lista->tamanho++; desliga_no(elemento); } else { // Remove qualquer ligacao antiga desliga_no(elemento); // Liga cauda da lista com novo elemento liga_nos(lista->cauda, elemento); lista->cauda = elemento; lista->tamanho++; } } /** * @brief Imprime os ponteiros de dados adicionados na lista. * @param lista: lista encadeada * * @retval Nenhum */ void imprimi_lista (lista_enc_t *lista) { no_t *no = NULL; if (lista == NULL){ fprintf(stderr,"imprimi_lista: ponteiros invalidos"); exit(EXIT_FAILURE); } no = lista->cabeca; while (no){ printf("Dados: %p\n", obter_dado(no)); no = obtem_proximo(no); } } /** * @brief Imprime os ponteiros de dados adicionados na lista. Ordem reversa. * @param lista: lista encadeada * * @retval Nenhum */ void imprimi_lista_tras (lista_enc_t *lista) { no_t *no = NULL; if (lista == NULL){ fprintf(stderr,"imprimi_lista: ponteiros invalidos"); exit(EXIT_FAILURE); } no = lista->cauda; while (no){ printf("Dados: %p\n", obter_dado(no)); no = obtem_anterior(no); } } /** * @brief Retorna se a lista está vazia. * @param lista: lista encadeada. * * @retval Nenhum */ int lista_vazia(lista_enc_t *lista) { int ret; (lista->tamanho == 0) ? (ret = TRUE) : (ret = FALSE); return ret; } /** * @brief Obtém a referência do início (cabeça) da lista encadeada. * @param lista: lista que se deseja obter o início. * * @retval no_t *: nó inicial (cabeça) da lista. */ no_t *obter_cabeca(lista_enc_t *lista){ if (lista == NULL){ fprintf(stderr,"obter_cabeca: ponteiros invalidos"); exit(EXIT_FAILURE); } return lista->cabeca; } /** * @brief Obtém a referência do final (cauda) da lista encadeada. * @param lista: lista que se deseja obter a cauda * * @retval no_t *: nó final (cauda) da lista. */ no_t *obter_cauda(lista_enc_t *lista){ if (lista == NULL){ fprintf(stderr,"obter_cabeca: ponteiros invalidos"); exit(EXIT_FAILURE); } return lista->cauda; } /** * @brief Remove um dado do final (cauda) da lista encadeada. * @param lista: lista que se deseja remover da cauda * * @retval no_t *: nó removido da lista. */ no_t *remover_cauda(lista_enc_t *lista) { no_t *anterior; no_t *removido; if (lista == NULL){ fprintf(stderr,"remover_cauda: ponteiro invalido"); exit(EXIT_FAILURE); } if (lista->cauda == NULL) return NULL; removido = lista->cauda; if (lista->cauda == lista->cabeca) { lista->tamanho = 0; lista->cauda = NULL; lista->cabeca = NULL; return removido; } anterior = obtem_anterior(lista->cauda); desliga_no(removido); lista->cauda = anterior; desliga_no_proximo(anterior); lista->tamanho--; return removido; } /** * @brief Remove um dado do início (cabeça) da lista encadeada. * @param lista: lista que se deseja remover da cauda * * @retval no_t *: nó removido da lista. */ no_t *remover_cabeca(lista_enc_t *lista) { no_t *proximo; no_t *removido; if (lista == NULL){ fprintf(stderr,"remover_cauda: ponteiro invalido"); exit(EXIT_FAILURE); } if (lista->cabeca == NULL) return NULL; removido = lista->cabeca; if (lista->cauda == lista->cabeca) { lista->tamanho = 0; lista->cauda = NULL; lista->cabeca = NULL; return removido; } proximo = obtem_proximo(lista->cabeca); desliga_no(removido); lista->cabeca = proximo; desliga_no_anterior(proximo); lista->tamanho--; return removido; } /** * @brief Remove um nó da lista encadeada * @param lista: lista que se deseja remover da cauda * @param no_removido: nó que se deseja remover da lista * * @retval no_t *: nó removido da lista. */ void *remover_no(lista_enc_t *lista, no_t *no_removido) { no_t *meu_no; void *dado; no_t *proximo; no_t *anterior; if (lista == NULL || no_removido == NULL){ fprintf(stderr,"remover_no: ponteiro invalido"); exit(EXIT_FAILURE); } //Varre lista até encontrar nó meu_no = obter_cabeca(lista); while (meu_no){ dado = obter_dado(meu_no); if (meu_no == no_removido){ if (meu_no == lista->cabeca) remover_cabeca(lista); else if (meu_no == lista->cauda) remover_cauda(lista); else { proximo = obtem_proximo(meu_no); anterior = obtem_anterior(meu_no); liga_nos(anterior, proximo); lista->tamanho--; } free(meu_no); break; } meu_no = obtem_proximo(meu_no); } return dado; }
#include <stdio.h> int main() { /* vars */ int n, i, j; printf("\tPASCAL'S TRIANGLE\n"); /* input */ printf("Insert a number N: "); scanf("%d", &n); int m[n][n]; /* initializing matrix */ for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { m[i][j] = 0; } } /* calculating triangle */ for (i = 0; i < n; i++) { for (j = 0; j <= i; j++) { /* calculating each element */ if (j == 0) { m[i][j] = 1; } else { m[i][j] = m[i-1][j-1] + m[i-1][j]; } } } /* printing triangle */ for (i = 0; i < n; i++) { for (j = n-1; j >= 0; j--) { if (m[i][j] == 0) { printf(" "); } else { printf("%d ", m[i][j]); } } printf("\n"); } return 0; }
#ifndef DIRECCION_H_INCLUDED #define DIRECCION_H_INCLUDED #endif // DIRECCION_H_INCLUDED
/* * Copyright (c) 2014-2015 André Erdmann <dywi@mailerd.de> * * Distributed under the terms of the MIT license. * (See LICENSE.MIT or http://opensource.org/licenses/MIT) */ #ifndef _ZRAM_DEVFS_H_ #define _ZRAM_DEVFS_H_ #include "data_types.h" int zram_mknod ( const struct zram_dev_info* const p_dev ); int zram_make_devfs_symlink ( struct zram_dev_info* const p_dev ); #endif
#include <stdio.h> #include <stdlib.h> #include <pthread.h> long thread_count,n=800,flag=0; double sum=0; void* suma_thread(void* rank); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; thread_count = strtol(argv[1],NULL,10); thread_handles = malloc(thread_count*sizeof(pthread_t)); for(thread=0; thread<thread_count;thread++) pthread_create(&thread_handles[thread],NULL,suma_thread,(void*)thread); for(thread=0;thread<thread_count;thread++) pthread_join(thread_handles[thread],NULL); printf("%d\n",sum); free(thread_handles); return 0; } void* suma_thread(void* rank){ long my_rank = (long) rank; double factor,my_sum = 0.0; long long i; long long my_n = n/thread_count; long long my_first_i = my_n * my_rank; long long my_last_i = my_first_i * my_n; if(my_first_i % 2 == 0) factor = 1.0; else factor = -1.0; for(i = my_first_i ; i < my_last_i ; i++ , factor = -factor) my_sum += factor / (2*i+1); while(flag!=my_rank); sum += my_sum; flag = (flag+1)%thread_count; //printf("El thread %ld conto\n",(long)rank); }
#ifndef HOME_H #define HOME_H STATE homeMode(Nunchuk input, LiquidCrystal lcd); #endif
/**CFile********************************************************************** FileName [dddmpNodeBdd.c] PackageName [dddmp] Synopsis [Functions to handle BDD node infos and numbering] Description [Functions to handle BDD node infos and numbering. ] Author [Gianpiero Cabodi and Stefano Quer] Copyright [ Copyright (c) 2004 by Politecnico di Torino. All Rights Reserved. This software is for educational purposes only. Permission is given to academic institutions to use, copy, and modify this software and its documentation provided that this introductory message is not removed, that this software and its documentation is used for the institutions' internal research and educational purposes, and that no monies are exchanged. No guarantee is expressed or implied by the distribution of this code. Send bug-reports and/or questions to: {gianpiero.cabodi,stefano.quer}@polito.it. ] ******************************************************************************/ #include "dddmpInt.h" /*---------------------------------------------------------------------------*/ /* Stucture declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Type declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Variable declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Macro declarations */ /*---------------------------------------------------------------------------*/ /**AutomaticStart*************************************************************/ /*---------------------------------------------------------------------------*/ /* Static function prototypes */ /*---------------------------------------------------------------------------*/ static int NumberNodeRecurBdd(DdNode *f, int id); static void RemoveFromUniqueRecurBdd(DdManager *ddMgr, DdNode *f); static void RestoreInUniqueRecurBdd(DdManager *ddMgr, DdNode *f); /**AutomaticEnd***************************************************************/ /*---------------------------------------------------------------------------*/ /* Definition of exported functions */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Definition of internal functions */ /*---------------------------------------------------------------------------*/ /**Function******************************************************************** Synopsis [Removes nodes from unique table and number them] Description [Node numbering is required to convert pointers to integers. Since nodes are removed from unique table, no new nodes should be generated before re-inserting nodes in the unique table (DddmpUnnumberBddNodes ()). ] SideEffects [Nodes are temporarily removed from unique table] SeeAlso [RemoveFromUniqueRecur(), NumberNodeRecur(), DddmpUnnumberBddNodes ()] ******************************************************************************/ int DddmpNumberBddNodes ( DdManager *ddMgr /* IN: DD Manager */, DdNode **f /* IN: array of BDDs */, int n /* IN: number of BDD roots in the array of BDDs */ ) { int id=0, i; for (i=0; i<n; i++) { RemoveFromUniqueRecurBdd (ddMgr, f[i]); } for (i=0; i<n; i++) { id = NumberNodeRecurBdd (f[i], id); } return (id); } /**Function******************************************************************** Synopsis [Restores nodes in unique table, loosing numbering] Description [Node indexes are no more needed. Nodes are re-linked in the unique table. ] SideEffects [None] SeeAlso [DddmpNumberBddNode ()] ******************************************************************************/ void DddmpUnnumberBddNodes( DdManager *ddMgr /* IN: DD Manager */, DdNode **f /* IN: array of BDDs */, int n /* IN: number of BDD roots in the array of BDDs */ ) { int i; for (i=0; i<n; i++) { RestoreInUniqueRecurBdd (ddMgr, f[i]); } return; } /**Function******************************************************************** Synopsis [Write index to node] Description [The index of the node is written in the "next" field of a DdNode struct. LSB is not used (set to 0). It is used as "visited" flag in DD traversals. ] SideEffects [None] SeeAlso [DddmpReadNodeIndexBdd(), DddmpSetVisitedBdd (), DddmpVisitedBdd ()] ******************************************************************************/ void DddmpWriteNodeIndexBdd ( DdNode *f /* IN: BDD node */, int id /* IN: index to be written */ ) { if (!Cudd_IsConstant (f)) { f->next = (struct DdNode *)((ptruint)id<<1); } return; } /**Function******************************************************************** Synopsis [Reads the index of a node] Description [Reads the index of a node. LSB is skipped (used as visited flag). ] SideEffects [None] SeeAlso [DddmpWriteNodeIndexBdd (), DddmpSetVisitedBdd (), DddmpVisitedBdd ()] ******************************************************************************/ int DddmpReadNodeIndexBdd ( DdNode *f /* IN: BDD node */ ) { if (!Cudd_IsConstant (f)) { return ((int)(((ptruint)(f->next))>>1)); } else { return (1); } } /**Function******************************************************************** Synopsis [Returns true if node is visited] Description [Returns true if node is visited] SideEffects [None] SeeAlso [DddmpSetVisitedBdd (), DddmpClearVisitedBdd ()] ******************************************************************************/ int DddmpVisitedBdd ( DdNode *f /* IN: BDD node to be tested */ ) { f = Cudd_Regular(f); return ((int)((ptruint)(f->next)) & (01)); } /**Function******************************************************************** Synopsis [Marks a node as visited] Description [Marks a node as visited] SideEffects [None] SeeAlso [DddmpVisitedBdd (), DddmpClearVisitedBdd ()] ******************************************************************************/ void DddmpSetVisitedBdd ( DdNode *f /* IN: BDD node to be marked (as visited) */ ) { f = Cudd_Regular(f); f->next = (DdNode *)(ptruint)((int)((ptruint)(f->next))|01); return; } /**Function******************************************************************** Synopsis [Marks a node as not visited] Description [Marks a node as not visited] SideEffects [None] SeeAlso [DddmpVisited (), DddmpSetVisited ()] ******************************************************************************/ void DddmpClearVisitedBdd ( DdNode *f /* IN: BDD node to be marked (as not visited) */ ) { f = Cudd_Regular (f); f->next = (DdNode *)(ptruint)((int)((ptruint)(f->next)) & (~01)); return; } /*---------------------------------------------------------------------------*/ /* Definition of static functions */ /*---------------------------------------------------------------------------*/ /**Function******************************************************************** Synopsis [Number nodes recursively in post-order] Description [Number nodes recursively in post-order. The "visited" flag is used with inverse polarity, because all nodes were set "visited" when removing them from unique. ] SideEffects ["visited" flags are reset.] SeeAlso [] ******************************************************************************/ static int NumberNodeRecurBdd ( DdNode *f /* IN: root of the BDD to be numbered */, int id /* IN/OUT: index to be assigned to the node */ ) { f = Cudd_Regular (f); if (!DddmpVisitedBdd (f)) { return (id); } if (!cuddIsConstant (f)) { id = NumberNodeRecurBdd (cuddT (f), id); id = NumberNodeRecurBdd (cuddE (f), id); } DddmpWriteNodeIndexBdd (f, ++id); DddmpClearVisitedBdd (f); return (id); } /**Function******************************************************************** Synopsis [Removes a node from unique table] Description [Removes a node from the unique table by locating the proper subtable and unlinking the node from it. It recurs on the children of the node. Constants remain untouched. ] SideEffects [Nodes are left with the "visited" flag true.] SeeAlso [RestoreInUniqueRecurBdd ()] ******************************************************************************/ static void RemoveFromUniqueRecurBdd ( DdManager *ddMgr /* IN: DD Manager */, DdNode *f /* IN: root of the BDD to be extracted */ ) { DdNode *node, *last, *next; DdNode *sentinel = &(ddMgr->sentinel); DdNodePtr *nodelist; DdSubtable *subtable; int pos, level; f = Cudd_Regular (f); if (DddmpVisitedBdd (f)) { return; } if (!cuddIsConstant (f)) { RemoveFromUniqueRecurBdd (ddMgr, cuddT (f)); RemoveFromUniqueRecurBdd (ddMgr, cuddE (f)); level = ddMgr->perm[f->index]; subtable = &(ddMgr->subtables[level]); nodelist = subtable->nodelist; pos = ddHash (cuddT (f), cuddE (f), subtable->shift); node = nodelist[pos]; last = NULL; while (node != sentinel) { next = node->next; if (node == f) { if (last != NULL) last->next = next; else nodelist[pos] = next; break; } else { last = node; node = next; } } f->next = NULL; } DddmpSetVisitedBdd (f); return; } /**Function******************************************************************** Synopsis [Restores a node in unique table] Description [Restores a node in unique table (recursively)] SideEffects [Nodes are not restored in the same order as before removal] SeeAlso [RemoveFromUnique()] ******************************************************************************/ static void RestoreInUniqueRecurBdd ( DdManager *ddMgr /* IN: DD Manager */, DdNode *f /* IN: root of the BDD to be restored */ ) { DdNodePtr *nodelist; DdNode *T, *E, *looking; DdNodePtr *previousP; DdSubtable *subtable; int pos, level; #ifdef DDDMP_DEBUG DdNode *node; DdNode *sentinel = &(ddMgr->sentinel); #endif f = Cudd_Regular(f); if (!Cudd_IsComplement (f->next)) { return; } if (cuddIsConstant (f)) { /* StQ 11.02.2004: Bug fixed --> restore NULL within the next field */ /*DddmpClearVisitedBdd (f);*/ f->next = NULL; return; } RestoreInUniqueRecurBdd (ddMgr, cuddT (f)); RestoreInUniqueRecurBdd (ddMgr, cuddE (f)); level = ddMgr->perm[f->index]; subtable = &(ddMgr->subtables[level]); nodelist = subtable->nodelist; pos = ddHash (cuddT (f), cuddE (f), subtable->shift); #ifdef DDDMP_DEBUG /* verify uniqueness to avoid duplicate nodes in unique table */ for (node=nodelist[pos]; node != sentinel; node=node->next) assert(node!=f); #endif T = cuddT (f); E = cuddE (f); previousP = &(nodelist[pos]); looking = *previousP; while (T < cuddT (looking)) { previousP = &(looking->next); looking = *previousP; } while (T == cuddT (looking) && E < cuddE (looking)) { previousP = &(looking->next); looking = *previousP; } f->next = *previousP; *previousP = f; return; }
/* THIS FILE HAS BEEN GENERATED, DO NOT MODIFY IT. */ /* * Copyright (C) 2019 GreenWaves Technologies * * 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 __INCLUDE_ARCHI_RTC_V1_RTC_V1_ACCESSORS_H__ #define __INCLUDE_ARCHI_RTC_V1_RTC_V1_ACCESSORS_H__ #if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__) #include <stdint.h> #include "archi/utils.h" #endif // // REGISTERS ACCESS FUNCTIONS // #if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__) static inline uint32_t rtc_apb_sr_get(uint32_t base) { return ARCHI_READ(base, RTC_APB_SR_OFFSET); } static inline void rtc_apb_sr_set(uint32_t base, uint32_t value) { ARCHI_WRITE(base, RTC_APB_SR_OFFSET, value); } static inline uint32_t rtc_apb_cr_get(uint32_t base) { return ARCHI_READ(base, RTC_APB_CR_OFFSET); } static inline void rtc_apb_cr_set(uint32_t base, uint32_t value) { ARCHI_WRITE(base, RTC_APB_CR_OFFSET, value); } static inline uint32_t rtc_apb_dr_get(uint32_t base) { return ARCHI_READ(base, RTC_APB_DR_OFFSET); } static inline void rtc_apb_dr_set(uint32_t base, uint32_t value) { ARCHI_WRITE(base, RTC_APB_DR_OFFSET, value); } static inline uint32_t rtc_reserved_get(uint32_t base) { return ARCHI_READ(base, RTC_RESERVED_OFFSET); } static inline void rtc_reserved_set(uint32_t base, uint32_t value) { ARCHI_WRITE(base, RTC_RESERVED_OFFSET, value); } static inline uint32_t rtc_apb_icr_get(uint32_t base) { return ARCHI_READ(base, RTC_APB_ICR_OFFSET); } static inline void rtc_apb_icr_set(uint32_t base, uint32_t value) { ARCHI_WRITE(base, RTC_APB_ICR_OFFSET, value); } static inline uint32_t rtc_apb_imr_get(uint32_t base) { return ARCHI_READ(base, RTC_APB_IMR_OFFSET); } static inline void rtc_apb_imr_set(uint32_t base, uint32_t value) { ARCHI_WRITE(base, RTC_APB_IMR_OFFSET, value); } static inline uint32_t rtc_apb_ifr_get(uint32_t base) { return ARCHI_READ(base, RTC_APB_IFR_OFFSET); } static inline void rtc_apb_ifr_set(uint32_t base, uint32_t value) { ARCHI_WRITE(base, RTC_APB_IFR_OFFSET, value); } #endif #endif
#include <std.h> inherit MONSTER; void create() { ::create(); set_name("patron"); set("short", "A cheerful patron"); set("long", "This friendly and cheerful patron in habits the Mad Cow Inn."); set("id", ({"patron", "monster"}) ); set_level(20 + random(7)); set("race", "human"); set_body_type("human"); set_gender("male"); }
/** * This is template for main module created by MCUXpresso Project Generator. Enjoy! **/ #include <string.h> #include "board.h" #include "pin_mux.h" #include "clock_config.h" /*#include "fsl_debug_console.h"*/ #include "fsl_gpio.h" /* FreeRTOS kernel includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "timers.h" /* Defines & Functions */ #define N 4 static const gpio_pin_config_t led_conf = { kGPIO_DigitalOutput, // OUTPUT 1, // HIGH INITIAL VALUE }; GPIO_Type *led_gpio[N] = { GPIOA, GPIOA, GPIOC, GPIOB }; uint32_t led_pins[N] = { 18, 19, 1, 0 }; void GPIO_Init() { uint8_t i; for(i=0; i<N; i++) GPIO_PinInit(led_gpio[i], led_pins[i], &led_conf); } portTickType Ticks(const float s) { return (portTickType) (s * (const float) configTICK_RATE_HZ); } /* Task priorities. */ #define led_task1_PRIORITY (configMAX_PRIORITIES - 1) #define led_task2_PRIORITY (configMAX_PRIORITIES - 2) /*! * @brief Task responsible for printing of "Hello world." message. */ static void led_task1(void *pv) { uint8_t i; for(i=0;;i++) { GPIO_WritePinOutput(led_gpio[i%3], led_pins[i%3], 0); vTaskDelay( Ticks(0.1) ); GPIO_WritePinOutput(led_gpio[i%3], led_pins[i%3], 1); vTaskDelay( Ticks(0.9) ); } } static void led_task2(void *pv) { for(;;) { GPIO_WritePinOutput(led_gpio[3], led_pins[3], 0); vTaskDelay( Ticks(1.1) ); GPIO_WritePinOutput(led_gpio[3], led_pins[3], 1); vTaskDelay( Ticks(0.9) ); } } /*! * @brief Application entry point. */ int main(void) { /* Init board hardware. */ BOARD_InitBootPins(); BOARD_InitBootClocks(); BOARD_InitDebugConsole(); /* Add your code here */ GPIO_Init(); /* Create RTOS task */ xTaskCreate( led_task1, "led_task1", configMINIMAL_STACK_SIZE, NULL, led_task1_PRIORITY, NULL ); xTaskCreate( led_task2, "led_task2", configMINIMAL_STACK_SIZE, NULL, led_task2_PRIORITY, NULL ); vTaskStartScheduler(); for(;;) { __asm("NOP"); } }
#ifndef __SYS_H #define __SYS_H /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx.h" #include "stdlib.h" #include <stdio.h> #include "deca_types.h" #include "deca_regs.h" #include "deca_device_api.h" #include "list.h" typedef unsigned long long uint64; /* Default antenna delay values for 64 MHz PRF. See NOTE 2 below. */ #define TX_ANT_DLY 16495 #define RX_ANT_DLY 16495 /* Index to access some of the fields in the frames involved in the process. */ #define ACK_FC_0 0x02 #define ACK_FC_1 0x00 #define ANCHTYPE 1 #define TAGTYPE 0 #define FRAME_SN_IDX 2 #define DESTADD 5 #define SOURADD 7 #define FUNCODE_IDX 9 #define TIMSTAMPS_OWNERID 10 #define RXBUFFTS_IDX 12 #define PAYLOADTS_IDX 2 #define TDOAMSGLEN 16 #define TDOAMSGSIZE 16 #define TDOAMPUMSGSIZE 16+4 #define UWBFREQ1 12 #define UWBFREQ2 13 #define WLIDX 10 #define WRIDX 11 #define ANCHORCNT 5 #define ANCHOR_NUM 1 #define TOA_MSG_LEN 10+2+2+4+4*ANCHORCNT+2 #define TOAMSGSIZE 10+2+2+4*ANCHORCNT+2 #define TOAMPUMSGSIZE 10+2+2+4+4*ANCHORCNT+2 #define TOA_DATA_IDX 14 #define TOAMPU_DATA_IDX 18 #define MPUFREQ1 14 #define MPUFREQ2 15 #define MPUCNT1 16 #define MPUCNT2 17 #define PAYLOOAD_WLIDX 7 #define PAYLOOAD_WRIDX 8 #define RXBUFF_WLIDX 17 #define RXBUFF_WRIDX 18 #define FCTRL_ACK_REQ_MASK 0x20 /* UWB microsecond (uus) to device time unit (dtu, around 15.65 ps) conversion factor. * 1 uus = 512 / 499.2 ? and 1 ? = 499.2 * 128 dtu. */ #define UUS_TO_DWT_TIME 65536 #define FINAL_MSG_POLL_TX_TS_IDX 10 #define FINAL_MSG_RESP_RX_TS_IDX 15 #define FINAL_MSG_FINAL_TX_TS_IDX 20 #define FINAL_MSG_TS_LEN 5 #define DWT_TIME_UNITS (1.0/499.2e6/128.0) #define INIT_TX_DELAYED_TIME_UUS 2000 /* Speed of light in air, in metres per second. */ #define SPEED_OF_LIGHT 299702547 /* Length of the common part of the message (up to and including the function code, see NOTE 3 below). */ #define ALL_MSG_COMMON_LEN 10 #define RX_BUF_LEN 127 #define USAMRTCMD 63//==/? #define TXDELAYTIME_US (ANCHOR_NUM-1)*1500UL //#define MPUUSING //#define TIMEBASE #ifndef TIMEBASE #if ANCHOR_NUM==1 #define MAIN_ANCHOR #else #define SLAVE_ANCHOR #endif #else #define SYNCIDX 6 #endif #define NRFQUELen 50 #define QUANTITY_ANCHOR 3 #define EASY_READ #define MAX_MPUDATA_CNT 800 #define WAIT_REC_ACK(t) {uint16 __t=t; \ while(!isreceive_To&&!istxframe_acked) \ {__t?__t--:isreceive_To++;}} #define WAIT_REC_TO(t) {uint16 __t=t; \ while(!isreceive_To&&!isframe_rec) \ {__t?__t--:isreceive_To++;}} #define WAIT_SENT(t) {uint32 __t=t; \ while(!isframe_sent&&__t) \ {__t--;}} extern __IO uint32_t msec; extern uint8_t nrf_Tx_Buffer[33] ; // 无线传输发送数据 extern uint8_t nrf_Rx_Buffer[33] ; // 无线传输接收数据 extern uint8 rx_buffer[RX_BUF_LEN]; extern uint8 frame_seq_nb; extern uint8 dw_payloadbuff[]; void reset_DW1000(void); void dw_setARER(int enable); extern volatile uint8 DMA_transing; extern uint8 ACKframe[]; typedef struct { uint8 timebase; uint8 ACtype; uint16 id; uint16 TBfreq; uint8 acnum; }sys_config_t; typedef struct tag_str { uint8 datatype; uint8 tagid; uint8 seqid; uint8 acnum; uint16 uwbfreq; void *puwbdata; uint8 mpu_use; uint16 mpufreq; uint8 mpudata_fault; uint16 mpudatacnt; float *pmpudata; struct list_head taglist; }TAGlist_t; #endif /* __MAIN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
#include"BinarySearchTree.h" //int allocation(BST **x, int key, BST *parent); void inorder_tree_walk(BST *x) { if(x != NULL) { inorder_tree_walk(x->left); printf("%d ",x->key); inorder_tree_walk(x->right); } } //程序能用,但是用了递归,且代码量也大。 //int allocation(BST **x, int key, BST *parent) //{ // *x = (BST *)malloc(sizeof(BST)); // if(*x == NULL) // { // printf("memory error"); // return -1; // } // // (*x)->key = key; // (*x)->left = NULL; // (*x)->right = NULL; // (*x)->parent = parent; // return 0; //} // //void insert_tree(BST **x, int key) //{ // if(*x == NULL) // { // allocation(x, key, NULL); // }else // { // if((*x)->key > key)//小于父节点的值放在左孩子节点 // { // if((*x)->left == NULL) // { // allocation(&(*x)->left,key,*x); // }else // { // insert_tree(&(*x)->left,key); // } // }else // { // if((*x)->right == NULL) // { // allocation(&(*x)->right,key,*x); // }else // { // insert_tree(&(*x)->right,key); // } // } // } //} BST *tree_search(BST *x, int key) { //使用递归方法来查询key的位置 if(x == NULL || key == x->key) { return x; }else if(key < x->key) { return tree_search(x->left,key); }else { return tree_search(x->right,key); } } BST *iterative_tree_search(BST *x, int key) { //使用迭代方法查询key的位置 while(x != NULL && key != x->key) { if(key < x->key) { x = x->left; }else { x = x->right; } } return x; } BST *tree_minimum(BST *x) { if(x == NULL)return NULL; while(x->left != NULL) { x = x->left; } return x; } BST *tree_maximum(BST *x) { if(x == NULL)return NULL; while(x->right != NULL) { x = x->right; } return x; } BST *tree_successor(BST *x) { //一个节点x的后继是大于x.key的最小关键字的节点。 if(x == NULL)return NULL; if(x->right != NULL) { return tree_minimum(x->right); } BST *y = x->parent; while(y != NULL && x == y->right) { x = y; y = y->parent; } return y; } BST *tree_predecessor(BST *x) { if(x == NULL)return NULL; if(x->left != NULL) { return tree_maximum(x->left); } BST *y = x->parent; while(y != NULL && x == y->left) { x = y; y = y->parent; } return y; } void tree_insert(TREE *T, BST *z) { //printf("z2 = %d\n",z); BST *y = NULL; BST *x = T->root; while(x != NULL) { y = x; if(z->key < x->key) { x = x->left; }else { x = x->right; } } z->parent = y; if(y == NULL) { T->root = z; }else if(z->key < y->key) { y->left = z; }else { y->right = z; } } void transplant(TREE *T, BST *u, BST *v) { //用另一颗子树v替换一棵子树u,并成为其双亲的孩子节点 if(u->parent == NULL) { T->root = v; }else if(u == u->parent->left) { u->parent->left = v; }else { u->parent->right = v; } if(v != NULL) { v->parent = u->parent; } } void tree_delete(TREE *T, BST *z) { //从二叉搜索树T中删除节点z. BST *y; if(z->left == NULL) { transplant(T,z,z->right); }else if(z->right == NULL) { transplant(T,z,z->left); }else { y = tree_minimum(z->right); if(y->parent != z) { transplant(T,y,y->right); y->right = z->right; y->right->parent = y; } transplant(T,z,y); y->left = z->left; y->left->parent = y; } free(z); } BST *bst_node_init(int key) { BST *z; z = (BST *)malloc(sizeof(BST)); z->key = key; z->left = NULL; z->right = NULL; z->parent = NULL; return z; } /**< 红黑树 */ RB_BST *rb_bst_node_init(RB_TREE *T,int key) { RB_BST *z; z = (RB_BST *)malloc(sizeof(RB_BST)); z->key = key; z->left = T->nil; z->right = T->nil; z->parent = T->nil; return z; } void left_rotate(RB_TREE *T, RB_BST *x) { //if(x == NULL)return; RB_BST *y = x->right; //set y x->right = y->left; //turn y's left subtree into x's right subtree if(y->left != T->nil) { y->left->parent = x; } y->parent = x->parent; //link x's parent to y if(x->parent == T->nil) { T->root = y; }else if(x == x->parent->left) { x->parent->left = y; }else { x->parent->right = y; } y->left = x; //put x on y's left x->parent = y; } void right_rotate(RB_TREE *T, RB_BST *y) { RB_BST *x = y->left; y->left = x->right; if(x->right != T->nil) { x->right->parent = y; } x->parent = y->parent; if(y->parent == T->nil) { T->root = x; }else if(y == y->parent->left) { y->parent->left = x; }else { y->parent->right = x; } x->right = y; y->parent = x; } void rb_insert(RB_TREE *T, RB_BST *z) { RB_BST *y = T->nil; RB_BST *x = T->root; while(x != T->nil) { y = x; if(z->key < x->key) { x = x->left; }else { x = x->right; } } z->parent = y; if(y == T->nil) { T->root = z; }else if(z->key < y->key) { y->left = z; }else { y->right = z; } z->left = T->nil; z->right = T->nil; z->color = RED; rb_insert_fixup(T,z); } void rb_insert_fixup(RB_TREE *T, RB_BST *z) { RB_BST *y; //if(z->parent == NULL)return; //if(z->parent->parent == NULL)return; while(z->parent->color == RED) { if(z->parent == z->parent->parent->left) { y = z->parent->parent->right; if(y->color == RED) { z->parent->color = BLACK; //case 1 y->color = BLACK; //case 1 z->parent->parent->color = RED; //case 1 z = z->parent->parent; //case 1 }else if(z == z->parent->right) { z = z->parent; //case 2 left_rotate(T, z); //case 2 }else { z->parent->color = BLACK; //case 3 z->parent->parent->color = RED; //case 3 right_rotate(T,z->parent->parent); //case 3 } }else { y = z->parent->parent->left; if(y->color == RED) { z->parent->color = BLACK; //case 1 y->color = BLACK; //case 1 z->parent->parent->color = RED; //case 1 z = z->parent->parent; //case 1 }else if(z == z->parent->left) { z = z->parent; //case 2 right_rotate(T, z); //case 2 }else { z->parent->color = BLACK; //case 3 z->parent->parent->color = RED; //case 3 left_rotate(T,z->parent->parent); //case 3 } } T->root->color = BLACK; } } void rb_inorder_tree_walk(RB_TREE *T, RB_BST *x) { if(x != T->nil) { rb_inorder_tree_walk(T, x->left); printf("%d ",x->key); rb_inorder_tree_walk(T, x->right); } } RB_TREE *rb_init_tree() { RB_TREE *T; T = (RB_TREE *)malloc(sizeof(RB_TREE)); T->nil = (RB_BST *)malloc(sizeof(RB_BST)); T->nil->left = T->nil; T->nil->right = T->nil; T->nil->parent = T->nil; T->nil->color = BLACK; T->root = T->nil; return T; } RB_BST *rb_tree_minimum(RB_TREE *T, RB_BST *x) { if(x == T->nil)return T->nil; while(x->left != T->nil) { x = x->left; } return x; } RB_BST *rb_tree_maximum(RB_TREE *T, RB_BST *x) { if(x == T->nil)return T->nil; while(x->right != T->nil) { x = x->right; } return x; } void rb_transplant(RB_TREE *T, RB_BST *u, RB_BST *v) { if(u->parent == T->nil) { T->root = v; }else if(u == u->parent->left) { u->parent->left = v; }else { u->parent->right = v; } v->parent = u->parent; } void rb_delete(RB_TREE *T, RB_BST *z) { RB_BST *y = z; RB_BST *x; int y_original_color = y->color; if(z->left == T->nil) { x = z->right; rb_transplant(T,z,z->right); }else if(z->right == T->nil) { x = z->left; rb_transplant(T,z,z->left); }else { y = rb_tree_minimum(T,z->right); y_original_color = y->color; x = y->right; if(y->parent == z) { x->parent = y; }else { rb_transplant(T,y,y->right); y->right = z->right; y->right->parent = y; } rb_transplant(T,z,y); y->left = z->left; y->left->parent = y; y->color = z->color; } if(y_original_color == BLACK) { rb_delete_fixup(T,x); } free(z); } void rb_delete_fixup(RB_TREE *T, RB_BST *x) { RB_BST *w; while(x != T->root && x->color == BLACK) { if(x == x->parent->left) { w = x->parent->right; if(w->color == RED) { /**< x的兄弟节点w是红色的 */ w->color = BLACK; //case 1 x->parent->color = RED; //case 1 left_rotate(T,x->parent); //case 1 w = x->parent->right; //case 1 }else if(w->left->color == BLACK && w->right->color == BLACK) { /**< x的兄弟节点w是黑色的,而且w的两个子节点都是黑色的 */ w->color = RED; //case 2 x = x->parent; //case 2 }else if(w->right->color == BLACK) { /**< x的兄弟节点w是黑色的,w的左孩子是红色的,w的右孩子是黑色的 */ w->right->color = BLACK; //case 3 w->color = RED; //case 3 right_rotate(T,w); //case 3 w = x->parent->right; //case 3 }else { /**< x的兄弟节点w是黑色的,且w的右孩子是红色的 */ w->color = x->parent->color; //case 4 x->parent->color = BLACK; //case 4 w->right->color = BLACK; //case 4 left_rotate(T,x->parent); //case 4 x = T->root; } }else { w = x->parent->left; if(w->color == RED) { w->color = BLACK; x->parent->color = RED; right_rotate(T,x->parent); w = x->parent->left; }else if(w->right->color == BLACK && w->left->color == BLACK) { w->color = RED; x = x->parent; }else if(w->left->color == BLACK) { w->left->color = BLACK; w->color = RED; left_rotate(T,w); w = x->parent->left; }else { w->color = x->parent->color; x->parent->color = BLACK; w->left->color = BLACK; right_rotate(T,x->parent); x = T->root; } } } x->color = BLACK; } RB_BST *iterative_rb_tree_search(RB_TREE *T, int key) { //使用迭代方法查询key的位置 RB_BST *x = T->root; while(x != T->nil && key != x->key) { if(key < x->key) { x = x->left; }else { x = x->right; } } return x; }
#define _BSD_SOURCE #define _XOPEN_SOURCE #include<unistd.h> #include<limits.h> #include<pwd.h> #include<shadow.h> #include"tlpi_hdr.h" //判断是否存在这个用户名 //判断是否存在shadow密码文件并且是否拥有访问权 //判断输入的密码是否一致 int main(int argc, char *argv[]){ char *username, *password, *encrypted, *p; struct passwd *pwd; struct spwd *spwd; Boolean authOk; size_t len; long lnmax; //获取用户名的最大长度 lnmax=sysconf(_SC_LOGIN_NAME_MAX); //如果没有定义,那么自己定义一个 if(lnmax==-1) lnmax=256; username=malloc(lnmax); if(username==NULL) errExit("malloc"); printf("Username: "); //确定屏幕已经打印处username: fflush(stdout); //fgets和snscanf差不多,只不过fgets有返回值方便判断 if(fgets(username, lnmax, stdin)==NULL) exit(EXIT_FAILURE); len=strlen(username); if(username[len-1]=='\n') username[len-1]='\0'; pwd=getpwnam(username); if(pwd==NULL) fatal("couldn't get password record"); spwd=getspnam(username); //如果存在shadow密码文件,那么获取这个密码 //否则按普通password文件里的密码来 if(spwd==NULL&&errno==EACCES) fatal("no permission to read shadow password file"); if(spwd!=NULL) pwd->pw_passwd=spwd->sp_pwdp; //getpass函数会在屏幕输出实参内的字符串 //然后暂时屏蔽屏幕回显,也就是你现在看不见你的输入 password=getpass("Password: "); //用crypt函数验证你输入的密码正不正确 //一般都用加密后的密码前两个字符作为salt参数 //要用这个函数编译时需要加上-lcrypt encrypted=crypt(password, pwd->pw_passwd); //销毁你输入的密码 for(p=password; *p!='\0'; ) *p++='\0'; if(encrypted==NULL) errExit("crypt"); authOk=strcmp(encrypted, pwd->pw_passwd)==0; if(!authOk){ printf("Incorrect password\n"); exit(EXIT_FAILURE); } printf("Successfully authenticated: UID=%ld\n", (long)pwd->pw_uid); //做一些成功登录后的事情 exit(EXIT_SUCCESS); }
#include <windows.h> #include <stdio.h> #include "../libs/handles.h" void main() { // переменная для записи char buffer[100] = "It was readed . . ."; // переменная для записи колличества записанных байт DWORD actlen; // HANDLE пременные для инициализации не буфферезиванного ввода вывода HANDLE hstdin, hstdout; // статус открытия BOOL rc; // инициализация HANDLE переменных hstdout = GetStdHandle(STD_OUTPUT_HANDLE); hstdin = GetStdHandle(STD_INPUT_HANDLE); // проверка инициализации if(check_handle(hstdin) == 0 || check_handle(hstdout) == 0) return ; // проверка на возможность чтения из консоли rc=ReadFile(hstdin, buffer+18, 80, &actlen, NULL); if (!rc) return; actlen += 18; // запись в консолт WriteFile(hstdout, buffer, actlen, &actlen, 0); WriteFile(hstdout, "Input handle value 0\n", actlen, &actlen, 0); WriteFile(hstdout, "Output handle value 1\n", actlen, &actlen, 0); getchar(); }
//refer from: https://www.cnblogs.com/ningci/p/5425771.html #include <reg52.h> #include <intrins.h> #include <string.h> #include "uart.h" #include "delay.h" #include "IR.h" #include "eeprom.h" IR_CODE read_ir_code(unsigned char); void save_block_ir_code(); void save_ir_code(IR_CODE ir_code,unsigned int addr); //全局接收红外线信号存放 IR_CODE global_ir_code; //从eeprom 中读取 按键值 IR_CODE k3_ir_code; IR_CODE k4_ir_code; IR_CODE k5_ir_code; IR_CODE k6_ir_code; //3个按键 sbit K3 = P3 ^ 5; sbit K4 = P3 ^ 4; sbit K5 = P3 ^ 3; #ifdef DEBUG //main 中 EX1 = 1; //外部中断1 按下时发送红外线信号 void infrared_led_int1() interrupt 2 { EX1 = 0; IR_launch(global_ir_code); EX1 = 1; } #endif void main() { IR_CODE tt; //总中断开关 EA = 1; init_uart(); init_IR(); //全局接收红外线清0 memset(&global_ir_code, 0, 4); //从eeprom 中读取 按键值 k3_ir_code = read_ir_code(0); k4_ir_code = read_ir_code(4); k5_ir_code = read_ir_code(8); while(1) { memset(&tt, 0xff, 4); send_code(tt); //按键按下 if(0 == K3) { //去抖动后 delayms(30); if(0 == K3) { //关中断 中断打开时,时钟可能不准 EA = 0; //如果有全局接收 则存入 eeprom if(global_ir_code.ir_code) { k3_ir_code = global_ir_code; save_block_ir_code(); memset(&global_ir_code, 0, 4); //闪灯2次表示 存入成功 P1 = 0x0; delayms(300); P1 = 0xff; delayms(300); P1 = 0x0; delayms(300); P1 = 0xff; } else { IR_launch(k3_ir_code); //闪灯1次表示 发射成功 P1 = 0x0; delayms(300); P1 = 0xff; } //开中断 EA = 1; } } //按键按下 if(0 == K4) { //去抖动后 delayms(30); if(0 == K4) { //关中断 中断打开时,时钟可能不准 EA = 0; //如果有全局接收 则存入 eeprom if(global_ir_code.ir_code) { k4_ir_code = global_ir_code; save_block_ir_code(); memset(&global_ir_code, 0, 4); //闪灯2次表示 存入成功 P1 = 0x0; delayms(300); P1 = 0xff; delayms(300); P1 = 0x0; delayms(300); P1 = 0xff; } else { IR_launch(k4_ir_code); //闪灯1次表示 发射成功 P1 = 0x0; delayms(300); P1 = 0xff; } //开中断 EA = 1; } } //按键按下 if(0 == K5) { //去抖动后 delayms(30); if(0 == K5) { //关中断 中断打开时,时钟可能不准 EA = 0; //如果有全局接收 则存入 eeprom if(global_ir_code.ir_code) { k5_ir_code = global_ir_code; save_block_ir_code(); memset(&global_ir_code, 0, 4); //闪灯2次表示 存入成功 P1 = 0x0; delayms(300); P1 = 0xff; delayms(300); P1 = 0x0; delayms(300); P1 = 0xff; } else { IR_launch(k5_ir_code); //闪灯1次表示 发射成功 P1 = 0x0; delayms(300); P1 = 0xff; } //开中断 EA = 1; } } } } void IR_int() interrupt 0 { IR_CODE ir_code; EX0 = 0;//处理过程中 关中断 ir_code = IR_recv(); if(ir_code.ir_code) { //点亮P1 显示收到了编码 P1 = 0x0; delayms(300); P1 = 0xff; //发送到串口 send_code(ir_code); //给全局编码赋值 global_ir_code = ir_code; } EX0 = 1;//处理结束后 开中断 } //读取 eeprom 中的值 IR_CODE read_ir_code(unsigned char addr) { IR_CODE ir_code; ir_code.custom_height = read(addr); ir_code.custom_lower = read(addr+1); ir_code.ir_code = read(addr+2); ir_code.re_ir_code = read(addr+3); return ir_code; } //保存所有编码 void save_block_ir_code() { erase(); save_ir_code(k3_ir_code, 0); save_ir_code(k4_ir_code, 4); save_ir_code(k5_ir_code, 8); } //保存一个编码 void save_ir_code(IR_CODE ir_code,unsigned int addr) { prog(addr, ir_code.custom_height); prog(addr+1, ir_code.custom_lower); prog(addr+2, ir_code.ir_code); prog(addr+3, ir_code.re_ir_code); }
$NetBSD: patch-libyara_re.c,v 1.1 2019/12/14 10:46:08 khorben Exp $ Ensure we adhere to valid value domain for isxxxx() function/macro. --- libyara/re.c.orig 2019-10-10 11:10:50.000000000 +0000 +++ libyara/re.c @@ -2063,14 +2063,14 @@ int yr_re_exec( case RE_OPCODE_DIGIT: prolog; - match = isdigit(*input); + match = isdigit((unsigned char)*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_DIGIT: prolog; - match = !isdigit(*input); + match = !isdigit((unsigned char)*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break;