repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMHTTPBasicAuthenticationService.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> #import "OMAuthenticationService.h" #import "OMHTTPBasicConfiguration.h" @interface OMHTTPBasicAuthenticationService : OMAuthenticationService <NSURLSessionDelegate, NSURLSessionTaskDelegate> @property(nonatomic, strong) NSString *userName; @property(nonatomic, strong) NSString *password; @property(nonatomic, strong) NSString *identityDomain; @property(nonatomic, strong) NSURLSessionDataTask *sessionDataTask; @property(nonatomic) BOOL authChallengeReceived; @property(nonatomic, weak) OMHTTPBasicConfiguration *configuration; @property(nonatomic) BOOL usePreviousCredential; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMOAMOAuthConfiguration.h
<gh_stars>10-100 /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import "OMOAuthConfiguration.h" #import "OMMobileSecurityService.h" #import "OMToken.h" @interface OMOAMOAuthConfiguration : OMOAuthConfiguration @property (nonatomic, strong) NSURL *oauthServiceEndpoint; @property (nonatomic, strong) NSURL *notificationEndpoint; @property (nonatomic, strong) NSMutableArray *userProfileEndpoints; @property (nonatomic, strong) NSString *deliveryMechanism; @property (nonatomic, weak) OMMobileSecurityService *mss; @property (nonatomic, strong) NSString *clientRegistrationType; @property (nonatomic, strong) NSString *deviceProfile; @property (nonatomic, strong) OMToken *preAuthzCode; @property (nonatomic, strong) OMToken *userAssertionToken; @property (nonatomic) BOOL ssoEnabled; @property (nonatomic, strong) NSArray *allowedGrants; @property (nonatomic, strong) NSArray *claimAttributes; - (NSURL*)discoveryUrl; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/SecureStorage/OMDataSerializationHelper.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @interface OMDataSerializationHelper : NSObject + (BOOL)serializeData:(id)data toFile:(NSString*)filePath; + (id)deserializeDataFromFile:(NSString*)filePath; + (id)serializeData:(id)data; + (id)deserializeData:(id)data; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMFedAuthAuthenticationService.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import "OMAuthenticationService.h" @class OMFedAuthConfiguration; @interface OMFedAuthAuthenticationService : OMAuthenticationService @property(nonatomic, weak) OMFedAuthConfiguration *configuration; @property(nonatomic, assign) BOOL authChallengeReceived; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/CredentialStoreService/OMCredential.h
<gh_stars>10-100 /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @interface OMCredential : NSObject @property (nonatomic, strong) NSString *userName; @property (nonatomic, strong) NSString *userPassword; @property (nonatomic, strong) NSString *tenantName; @property (nonatomic, strong) NSDictionary *properties; /** * Initializer method of OMCredential, which initializes * this object by taking username, password, tenantName * and custom user objects * * @param userName - Username * @param userPassword - <PASSWORD> * @param tenantName - Tenant name where the user belongs * @param properties - Custom user properties * * @return OMCredential object */ - (id) initWithUserName:(NSString*)userName password:(<PASSWORD> tenantName:(NSString*)tenantName properties:(NSDictionary*)properties; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/Common/OMJSONUtlity.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @interface OMJSONUtlity : NSObject + (NSString *)getJSONRepresentation:(id)jsonObj prettyPrint:(BOOL)prettyPrint ; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/KeyManager/OMKeyManager.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @class OMKeyStore; @interface OMKeyManager : NSObject + (OMKeyManager *)sharedManager; - (OMKeyStore*)createKeyStore:(NSString *)keyStoreId kek:(NSData*)kek overWrite:(BOOL)overWrite error:(NSError**)error; - (OMKeyStore*)updateKeyStore:(NSString *)keyStoreId kek:(NSData*)kek newKek:(NSData*)newKek error:(NSError**)error; - (void)deleteKeyStore:(NSString *)keyStoreId kek:(NSData*)kek error:(NSError**)error; - (OMKeyStore *)keyStore:(NSString *)keyStoreId kek:(NSData*)kek error:(NSError**)error; - (NSString*)hashFileNameForKeystore:(NSString *)keyStoreId kek:(NSData*)kek; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMServiceDiscoveryHandler.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import "OMAuthenticationService.h" typedef void (^OMServiceDiscoveryCallback)(NSDictionary * propertiesJSON, NSError * discoveryError); @interface OMServiceDiscoveryHandler : OMAuthenticationService + (OMServiceDiscoveryHandler *)sharedHandler; - (void)discoverConfigurationWithURL:(NSURL *)discoveryURL withMss:(OMMobileSecurityService*)mss completion:(OMServiceDiscoveryCallback )completion; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMOIDCAuthenticationService.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> #import "OMOAuthAuthenticationService.h" @interface OMOIDCAuthenticationService : OMOAuthAuthenticationService @property (nonatomic, strong) NSString *idToken; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/LocalAuthentication/OMAuthData.h
<gh_stars>10-100 /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @interface OMAuthData : NSObject - (instancetype)initWithData:(NSData*)data; - (NSData *)data; - (NSString*)authDataStr; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMIDCSClientRegistrationService.h
<filename>src/ios/sdk/IDMMobileSDKv2/OMIDCSClientRegistrationService.h /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import "OMOAuthAuthenticationService.h" @interface OMIDCSClientRegistrationService : OMOAuthAuthenticationService @property (nonatomic) BOOL backChannelRequestDone; @property (nonatomic, strong) NSString *tokenType; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/BaseClass/OMErrorCodes.h
<reponame>x-and/cordova-plugin-oracle-idm-auth /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ /////////////////////////////////////////////////////////////////////////////// // Define all error codes here. It shall be of the format given below. Assign // the error codes in sequence. Do not jump or start assign error codes in new // series. Number of digits shall not exceed five digits. For each error code, // make corresponding error message entry in resource bundle // OMLocalizable.strings file. Error look up key shall also be the same number // but in string format. When you add string look up key in // OMLocalizable.strings file, ensure that it is added in 5 digit format. For // example, if you are error code is 7, resource bundle look-up key is "00007". // // OMERR_ERROR_CODE_NAME ERROR // CODE //----- -------------------------------------------------------------- ----- -- /////////////////////////////////////////////////////////////////////////////// //#define OMERR_NOT_FOUND 132 //#define OMERR_UNSUPPORTED_URL 133 //#define OMERR_SERVER_UNREACHABLE 135 //#define OMERR_SERVER_ERROR 136 //#define OMERR_INVALID_LOGOUT_URL 137 //#define OMERR_USER_CANCELLED_IMPORT 140 //#define OMERR_OAUTH_GRANT_NOT_ALLOWED 141 //#define OMERR_OAUTH_SERVER_SSO_NOT_SUPPORTED 142 //#define OMERR_ACTION_NOT_ALLOWED 144 //#define OMERR_MAXIMUM_LOGIN_ATTEMPTS_EXCEEDED 145 #define OMERR_NETWORK_UNAVAILABLE 00134 #define OMERR_SUCCESS 10000 #define OMERR_COULD_NOT_CONNECT_TO_SERVER 10001 #define OMERR_INVALID_USERNAME_PASSWORD 10003 #define OMERR_OIC_SERVER_RETURNED_ERROR 10005 #define OMERR_INITIALIZATION_FAILED 10025 #define OMERR_LOGOUT_FAILED 10035 #define OMERR_USER_AUTHENTICATION_FAILED 10408 #define OMERR_INVALID_USERNAME_PASSWORD_IDENTITY 10011 #define OMERR_USER_CANCELED_AUTHENTICATION 10029 #define OMERR_DENIED_ACTION 10030 #define OMERR_NO_IDENTITY 10037 #define OMERR_INVALID_PASSWORD 10038 #define OMERR_AUTHENTICATION_TIMED_OUT 10042 #define OMERR_OUT_OF_RANGE 10403 #define OMERR_WEBVIEW_REQUIRED 10017 #define OMERR_INVALID_SEND_CUSTOM_HEADERS_LOGOUT 10018 #define OMERR_INVALID_SEND_AUTH_HEADER_LOGOUT 10019 #define OMERR_WKWEBVIEW_REQUIRED 10020 #define OMERR_INVALID_CUSTOM_HEADERS 10021 #define OMERR_KEY_IS_NIL 10501 #define OMERR_INVALID_INPUT 10502 #define OMERR_INVALID_CRYPTO_SCHEME 10503 /////////////////////////////////////////////////////////////////////////////// // OMCryptoService Messages /////////////////////////////////////////////////////////////////////////////// #define OMERR_MEMORY_ALLOCATION_FAILURE 10503 #define OMERR_RANDOM_GENERATOR_SYSTEM_ERROR 10504 #define OMERR_REQUESTED_LENGTH_TOO_SHORT 10505 #define OMERR_INPUT_TEXT_CANNOT_BE_EMPTY 10406 #define OMERR_MAX_RETRIES_REACHED 10418 #define OMERR_UNKNOWN_OR_UNSUPPORTED_ALGORITHM 10506 #define OMERR_KEY_SIZE_NOT_SUPPORTED_BY_ALGORITHM 10507 #define OMERR_IV_LENGTH_MUST_MATCH_ALGORITHM_BLOCK_SIZE 10508 #define OMERR_PADDING_REQUIRED 10509 #define OMERR_UNKNOWN_OR_UNSUPPORTED_PADDING 10510 #define OMERR_ENCRYPTION_SYSTEM_ERROR 10511 #define OMERR_REQUESTED_LENGTH_NOT_A_MULTIPLE_OF_4 10512 #define OMERR_SALT_REQUIRED_FOR_CHOSEN_ALGORITHM 10513 #define OMERR_SALT_NOT_SUPPORTED_FOR_CHOSEN_ALGORITHM 10514 #define OMERR_CANNOT_PREFIX_SALT_IN_NON_SALTED_ALGORITHM 10515 #define OMERR_INPUT_NOT_PREFIXED_WITH_ALGORITHM_NAME 10516 #define OMERR_INPUT_MUST_BE_NSSTRING_WHEN_BASE64_IS_ENABLED 10517 #define OMERR_UNKNOWN_INPUT_TYPE 10518 #define OMERR_INPUT_LENGTH_MUST_BE_LESS_THAN_OR_EQUAL_TO 10519 #define OMERR_KEYPAIR_GENERATION_SYSTEM_ERROR 10520 #define OMERR_TAG_REQUIRED_TO_IDENTIFY_KEY_IN_KEYCHAIN 10521 #define OMERR_KEYCHAIN_SYSTEM_ERROR 10522 #define OMERR_KEYCHAIN_ITEM_NOT_FOUND 10523 #define OMERR_SIGNING_SYSTEM_ERROR 10524 #define OMERR_INPUT_SIGN_CANNOT_BE_EMPTY 10525 #define OMERR_VERIFICATION_SYSTEM_ERROR 10526 #define OMERR_DECRYPTION_SYSTEM_ERROR 10527 #define OMERR_KEYCHAIN_ITEM_ALREADY_FOUND 10528 #define OMERR_UNKNOWN_OR_UNSUPPORTED_KEY_TYPE 10529 #define OMERR_INVALID_KEYCHAIN_DATA_PROTECTION_LEVEL 10530 #define OMERR_PBKDF2_KEY_GENERATION_ERROR 10531 #define OMERR_DELEGATE_NOT_SET 10532 #define OMERR_RESOURCE_FILE_PATH 10533 #define OMERR_LOGIN_IS_IN_PROGRESS 10534 #define OMERR_INVALID_APP_NAME 10100 #define OMERR_LOGIN_URL_IS_INVALID 10101 #define OMERR_LOGOUT_URL_IS_INVALID 10102 #define OMERR_INVALID_SESSION_TIMEOUT_TIME 10103 #define OMERR_INVALID_IDLE_TIMEOUT_TIME 10104 #define OMERR_INVALID_IDLE_DELTA 10105 #define OMERR_INVALID_RETRY_COUNTS 10106 #define OMERR_INVALID_REQUIRED_TOKENS 10107 #define OMERR_INVALID_IDENTITY_DOMAIN 10108 #define OMERR_INVALID_COLLECT_IDENTITY_DOMAIN 10109 #define OMERR_INVALID_REMEMBER_CREDENTAILS_ENABLED 10110 #define OMERR_INVALID_REMEMBER_USERNAME_DEFAULT 10111 #define OMERR_INVALID_AUTOLOGIN 10112 #define OMERR_INVALID_REMEMBER_CREDENTIALS 10113 #define OMERR_INVALID_REMEMBER_USERNAME 10114 #define OMERR_INVALID_AUTH_SERVER_TYPE 10115 #define OMERR_INVALID_OFFLINE_AUTH_ALLOWED 10116 #define OMERR_INVALID_CONNECTIVITY_MODE 10117 #define OMERR_INVALID_PRESENT_IDENTITY_ON_DEMAND 10118 #define OMERR_INVALID_BROWSERMODE 10119 #define OMERR_INVALID_CLIENT_CERTIFICATE 30004 #define OMERR_FEDAUTH_LOGIN_SUCCESS_URL_IS_INVALID 50001 #define OMERR_FEDAUTH_LOGIN_FAILURE_URL_IS_INVALID 50002 #define OMERR_PARSE_TOKEN_RELAY_RESPONSE_INVALID 50003 #define OMERR_IDCS_CLIENT_REGISTRATION_FAILED 50300 #define OMERR_IDCS_CLIENT_REGISTRATION_UNABLE_TO_OBTAIN_AT 50301 #define OMERR_IDCS_CLIENT_REGISTRATION_PARSING_FAILED 50302 #define OMERR_IDCS_CLIENT_REGISTRATION_INVALID_ENDPOINT 50303 #define OMERR_IDCS_CLIENT_REGISTRATION_TOKEN_EMPTY 50400 #define OMERR_OAUTH_UNSUPPORTED_RESPONSE_TYPE 40211 #define OMERR_OAUTH_UNAUTHORIZED_CLIENT 40214 #define OMERR_OAUTH_STATE_INVALID 40220 #define OMERR_OAUTH_INVALID_REQUEST 40230 #define OMERR_OAUTH_ACCESS_DENIED 40231 #define OMERR_OAUTH_INVALID_SCOPE 40232 #define OMERR_OAUTH_SERVER_ERROR 40233 #define OMERR_OAUTH_TEMPORARILY_UNAVAILABLE 40234 #define OMERR_OAUTH_OTHER_ERROR 40235 #define OMERR_OAUTH_BAD_REQUEST 40236 #define OMERR_OAUTH_CLIENT_ASSERTION_REVOKED 40237 #define OMERR_OAUTH_INVALID_CLIENT 40239 #define OMERR_OAUTH_INVALID_GRANT 40240 #define OMERR_OAUTH_CLIENT_SECRET_INVALID 40241 #define OMERR_OAUTH_CLIENT_ID_INVALID 40242 #define OMERR_OAUTH_TOKEN_ENDPOINT_INVALID 40243 #define OMERR_OAUTH_AUTHZ_ENDPOINT_INVALID 40244 #define OMERR_OAUTH_REDIRECT_ENDPOINT_INVALID 40245 #define OMERR_INVALID_APP_RESPONSE 40246 /////////////////////////////////////////////////////////////////////////////// // Open ID Error Codes /////////////////////////////////////////////////////////////////////////////// #define OMERR_OIDC10_UNAUTHORIZED_ISSUER 60001 #define OMERR_OIDC10_USERINFO_ENDPOINT_INVALID 60002 #define OMERR_OIDC10_REVOCATION_ENDPOINT_INVALID 60003 #define OMERR_OIDC10_INVALID_CLAIMS 60004 #define OMERR_OIDC10_UNKNOWN 60005 #define OMERR_OIDC10_INVALID_JSON 60007 #define OMERR_OIDC10_DISCOVERY_ENDPOINT_INVALID 60008 //secure #define OMERR_AUTHDATA_ALREADY_SET 70007 #define OMERR_AUTHDATA_NOT_SET 70008 #define OMERR_INCORRECT_CURRENT_AUTHDATA 70009 #define OMERR_FILE_NOT_FOUND 75001 #define OMERR_AUTHENTICATOR_NOT_REGISTERED 70001 #define OMERR_KEY_NOT_FOUND 75002 #define OM_KEYSTORE_EXIST 71000 #define OMERR_AUTHENTICATOR_ALREADY_REGISTERED 70012 #define OMERR_KEYSTORE_FILE_CREATION_FAILED 70013 #define OMERR_KEY_ALREADY_FOUND 70014 #define OMERR_PIN_CHANGE_FAILED 70015 #define OMERR_LOCAL_AUTH_NOT_AUTHENTICATED 70016 #define OMERR_KEYCHAIN_CANNOT_BE_NIL 70017 /////////////////////////////////////////////////////////////////////////////// // End of OMErrorCodes.h ///////////////////////////////////////////////////////////////////////////////
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/SecureStorage/OMSecureStorage.h
<filename>src/ios/sdk/IDMMobileSDKv2/SecureStorage/OMSecureStorage.h /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @class OMKeyStore; @interface OMSecureStorage : NSObject - (id)initWithKeyStore:(OMKeyStore*)keyStore keyId:(NSString*)keyId error:(NSError**)error; /** * This method retrieves the data from the secure storage and returns the same * @param dataid represents the id against which data has been saved in the storage * @param error Refrence to a NSError object that will contain any error * while retriving the data * @return data */ - (id)dataForId:(NSString *)dataId error:(NSError **)error; /** * This method encrypts the data and stores it in secure storage * @param dataid represents the id against which data has been saved in the storage * @param data represents the data to be saved in the storage * @param error Refrence to a NSError object that will contain any error * while retriving the data * @return BOOL Yes if saved no if its not */ - (BOOL)saveDataForId:(NSString *)dataId data:(id)data error:(NSError **)error; /** * This method deletes the data against given dataid * @param dataid represents the id against which data has been saved in the storage * @param error Refrence to a NSError object that will contain any error * while retriving the data * @return BOOL Yes if date deleted no if its not */ - (BOOL)deleteDataForId:(NSString *)dataId error:(NSError **)error; - (NSString *)fileNameForDataId:(NSString *)dataId; - (NSString *)filePathForDataId:(NSString*)dataId; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/IDMMobileSDKv2.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <UIKit/UIKit.h> //! Project version number for IDMMobileSDKv2. FOUNDATION_EXPORT double IDMMobileSDKv2VersionNumber; //! Project version string for IDMMobileSDKv2. FOUNDATION_EXPORT const unsigned char IDMMobileSDKv2VersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <IDMMobileSDKv2/PublicHeader.h> #import <IDMMobileSDKv2/OMAuthenticationRequest.h> #import <IDMMobileSDKv2/OMCredential.h> #import <IDMMobileSDKv2/OMMobileSecurityConfiguration.h> #import <IDMMobileSDKv2/OMAuthenticationChallenge.h> #import <IDMMobileSDKv2/OMCertInfo.h> #import <IDMMobileSDKv2/OMDefinitions.h> #import <IDMMobileSDKv2/OMMobileSecurityService.h> #import <IDMMobileSDKv2/OMAuthenticationContext.h> #import <IDMMobileSDKv2/OMCertService.h> #import <IDMMobileSDKv2/OMErrorCodes.h> #import <IDMMobileSDKv2/OMObject.h> #import <IDMMobileSDKv2/OMToken.h> #import <IDMMobileSDKv2/OMCredentialStore.h> #import <IDMMobileSDKv2/NSData+OMBase64.h> #import <IDMMobileSDKv2/NSData+OMBase32.h> #import <IDMMobileSDKv2/OMAuthenticator.h> #import <IDMMobileSDKv2/OMPinauthenticator.h> #import <IDMMobileSDKv2/OMTouchIDAuthenticator.h> #import <IDMMobileSDKv2/OMDefaultAuthenticator.h> #import <IDMMobileSDKv2/OMAuthData.h> #import <IDMMobileSDKv2/OMLocalAuthenticationManager.h> #import <IDMMobileSDKv2/OMKeyStore.h> #import <IDMMobileSDKv2/OMKeyManager.h> #import <IDMMobileSDKv2/OMSecureStorage.h> #import <IDMMobileSDKv2/OMAuthenticationDelegate.h> #import <IDMMobileSDKv2/OMCryptoService.h> #import <IDMMobileSDKv2/OMOTPService.h> #import <IDMMobileSDKv2/OMBiometricAuthenticator.h> #import <IDMMobileSDKv2/OMClassicCredential.h>
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMOAMUserAssertionService.h
<reponame>x-and/cordova-plugin-oracle-idm-auth /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import "OMAuthenticationService.h" @interface OMOAMUserAssertionService : OMAuthenticationService @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMAuthorizationCodeGrant.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import "OMAuthorizationGrant.h" #import "OMOAuthWebViewHandler.h" @interface OMAuthorizationCodeGrant : OMAuthorizationGrant @property (nonatomic, strong) NSString *authCode; @property (nonatomic) volatile int32_t finished; @property (nonatomic, strong) OMOAuthWebViewHandler *handler; @property (nonatomic, strong) NSString *codeChallenge; @property (nonatomic, strong) NSString *codeVerifier; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/Common/OMASN1Node.h
<gh_stars>10-100 /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @interface OMASN1Node : NSObject { @private NSMutableArray *_childList; NSString *_tag; NSString *_value; } @property(nonatomic, retain) NSMutableArray *childList; @property(nonatomic, retain) NSString *tag; @property(nonatomic, retain) NSString *value; -(id)initWithHexString:(NSString *)string; -(id)init; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/LocalAuthentication/OMLocalAuthenticationManager.h
<reponame>x-and/cordova-plugin-oracle-idm-auth /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @class OMAuthenticator; @interface OMLocalAuthenticationManager : NSObject + (OMLocalAuthenticationManager *)sharedManager; -(void)useBiometricInsteadOfTouchID:(BOOL)useBiometric; - (BOOL)registerAuthenticator:(NSString*)authenticatorName className:(NSString*)className error:(NSError **)error; - (BOOL)unRegisterAuthenticator:(NSString*)authenticatorName error:(NSError **)error; - (BOOL)enableAuthentication:(NSString*)authenticatorName instanceId:(NSString*)instanceId error:(NSError **)error; - (BOOL)disableAuthentication:(NSString*)instanceId error:(NSError **)error; - (OMAuthenticator*)authenticatorForInstanceId:(NSString*)instanceId error:(NSError **)error; - (NSString *)authenticationTypeForInstanceId:(NSString*)instanceId; - (BOOL)isAuthenticatorClassRegistered:(NSString*)className; - (BOOL)isAuthenticatorRegistered:(NSString*)authenticatorName; - (BOOL)isAuthKeyEnabled:(NSString*)key; - (void)addAuthKeyToList:(NSString*)key; - (void)removeAuthKeyFromList:(NSString*)key; @end @interface AuthenticatorInstanceIdInfo : NSObject<NSCoding> @property (nonatomic, strong) NSString * authenticatorName; @property (nonatomic, assign) BOOL isEnabled; - (instancetype)initWithAuthenticatorName:(NSString *)authenticatorName enable:(BOOL)enable; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMOpenIDCServiceDiscovery.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> #import "OMDefinitions.h" #import "OMErrorCodes.h" typedef void (^OMOpenIDCDiscoveryCallback)(NSMutableDictionary *_Nullable propertiesJSON, NSError *_Nullable discoveryError); @interface OMOpenIDCServiceDiscovery : NSObject + (void)discoverConfigurationWithURL:(NSURL * _Nonnull)discoveryURL completion:(OMOpenIDCDiscoveryCallback _Null_unspecified)completion; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/CredentialStoreService/OMClassicCredential.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface OMClassicCredential : NSObject - (id)getCredentialForKey:(NSString*)key; @end NS_ASSUME_NONNULL_END
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMCertInfo.h
<reponame>x-and/cordova-plugin-oracle-idm-auth<filename>src/ios/sdk/IDMMobileSDKv2/OMCertInfo.h /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @interface OMCertInfo : NSObject { @private NSString *_commonName; NSString *_organizationalUnit; NSString *_location; NSString *_organization; NSString *_state; NSString *_country; NSString *_serialNumber; NSDate *_issuedOn; NSDate *_expiresOn; NSString *_issuer; } @property(nonatomic, retain) NSString *commonName; @property(nonatomic, retain) NSString *organizationalUnit; @property(nonatomic, retain) NSString *organization; @property(nonatomic, retain) NSString *location; @property(nonatomic, retain) NSString *state; @property(nonatomic, retain) NSString *country; @property(nonatomic, retain) NSString *serialNumber; @property(nonatomic, retain) NSDate *issuedOn; @property(nonatomic, retain) NSDate *expiresOn; @property(nonatomic, retain) NSString *issuer; -(id)initWithCertHex:(NSString *)hexString; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMAuthenticationContext.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> #import "OMCredential.h" enum { OMLocal = 1, OMRemote = 2 }; typedef NSUInteger OMAuthenticationMode; enum { OMSessionTimer, OMIdleTimer }; typedef NSUInteger OMTimerType; typedef enum : NSUInteger { eAlive, eUseRefreshToken, eExpired, } OMTokenStatus; @class OMMobileSecurityService; @class OMAuthenticationContext; @protocol OMAuthenticationContextDelegate<NSObject> -(void)authContext:(OMAuthenticationContext *)context timeoutOccuredForTimer:(OMTimerType)timerType remainingTime:(NSTimeInterval)duration; @end @interface OMAuthenticationContext : NSObject @property (nonatomic, strong) NSString *userName; @property (nonatomic, strong) NSMutableArray *visitedHosts; @property (nonatomic) OMAuthenticationMode authMode; @property (nonatomic, weak) id delegate; @property (nonatomic, strong) NSMutableDictionary *accessTokens; @property (nonatomic, strong) NSString *tokenValue; @property (nonatomic, strong) NSString *identityDomain; @property (nonatomic, strong) NSMutableArray *tokens; @property (nonatomic, strong) NSString *idToken; @property (nonatomic, strong) NSString *offlineCredentialKey; @property (nonatomic) BOOL isLogoutFalseCalled; @property (nonatomic, strong) NSDictionary *userInfo; @property (nonatomic, strong) NSDate *sessionExpiryDate; @property (nonatomic, strong) NSDate *idleTimeExpiryDate; @property (nonatomic, weak) OMMobileSecurityService *mss; -(id)initWithMss:(OMMobileSecurityService*)inObj; /** * Clear all cookies of URLs visited during login operation from cookie store */ -(void)clearCookies:(BOOL)clearPersistentCookies; - (NSArray *)cookies; - (void)startTimers; - (void)stopTimers; - (BOOL)resetTimer:(OMTimerType)timerType; - (BOOL)isValid:(BOOL)validateOnline; - (NSDictionary *)requestParametersForURL:(NSString *)theURL includeHeaders:(BOOL)includeHeaders; -(void)setCredentialInformation:(NSDictionary *)credInfo; - (NSDictionary *)credentialInformationForKeys:(NSArray *)keys; - (BOOL)isValidForScopes:(NSSet *)scopes refreshExpiredToken:(BOOL)refresh; - (BOOL)isValid; - (NSString *)passwordForCredential:(OMCredential *)cred outError:(NSError **)error; - (NSDictionary *)customHeaders; - (NSArray *)tokensForScopes:(NSSet *)scopes; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMAuthenticationDelegate.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @protocol OMAuthenticationDelegate <NSObject> - (void)didFinishCurrentStep: (id)object nextStep: (NSUInteger)nextStep authResponse: (NSDictionary *)data error: (NSError *)error; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMClientCertConfiguration.h
/** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> #import "OMMobileSecurityConfiguration.h" @interface OMClientCertConfiguration : OMMobileSecurityConfiguration @property (nonatomic, retain) NSSet *requiredTokens; @property (nonatomic, strong) NSURL *loginURL; @property (nonatomic, strong) NSURL *logoutURL; -(id)initWithProperties:(NSDictionary *)properties error:(NSError **)error; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/CredentialStoreService/OMKeyChain.h
<filename>src/ios/sdk/IDMMobileSDKv2/CredentialStoreService/OMKeyChain.h /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> @interface OMKeyChain : NSObject + (void)setItem:(id)item forKey:(NSString*)key accessGroup:(NSString *)accessGroup; + (void)setItem:(id)item forKey:(NSString*)key accessGroup:(NSString *)accessGroup dataAccessibleLevel:(CFTypeRef)protectionLevel; + (id)itemForKey:(NSString*)key accessGroup:(NSString *)accessGroup; + (void)deleteItemForKey:(NSString*)key accessGroup:(NSString *)accessGroup; @end
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMCSRFRequestHandler.h
// // OMCSRFRequestHandler.h // IDMMobileSDKv2 // // Created by <NAME> on 17/02/20. // Copyright © 2020 Oracle. All rights reserved. // #import <Foundation/Foundation.h> #import "OMFedAuthConfiguration.h" NS_ASSUME_NONNULL_BEGIN typedef void (^TokenRelayHandler)(id response, NSError *error); @interface OMCSRFRequestHandler : NSObject - (NSDictionary*)extractTokenRelayTokensWithConfig:(OMFedAuthConfiguration*)config error:(NSError**)error; @end NS_ASSUME_NONNULL_END
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/Common/OMOTPService.h
<reponame>x-and/cordova-plugin-oracle-idm-auth<filename>src/ios/sdk/IDMMobileSDKv2/Common/OMOTPService.h /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import <Foundation/Foundation.h> #import "OMObject.h" #import "OMCryptoService.h" @interface OMOTPService : NSObject { @private NSData *_sharedSecret; uint64_t _counter; uint64_t _incrementBy; uint64_t _baseTime; uint64_t _timeSteps; uint64_t _numDigitsInOTP; BOOL _addCheckSum; BOOL _isHOTP; OMCryptoAlgorithm _algorithm; } /** * Initializer method for Hash MAC based One-Time Password (OTP) generation as * per RFC 4226. This initializer method uses SHA1 algorithm for hashing. * * @param key Shared secret that is used for generating Hashed * Message Authentication Code (HMAC) * @param counter Starting counter value * @param incrementBy Counter incremented by this value after * generating OTP * @param requiredDigitsInOTP Number of digits required in OTP * @param addCheckSumToOTP Flag that indicates whether check sum shall be * calculated for OTP and added to OTP * @return OMOTPService object, if initialization is successful. */ - (id) initForHOTPWithSharedKey: (NSData *)key andStartingCounter: (uint64_t)counter incrementBy: (long)incrementValue requiredDigitsInOTP: (unsigned long)numDigits addCheckSumToOTP: (BOOL)addCheckSum; /** * Initializer method for Hash MAC based One-Time Password generation as per * RFC 4226. This initializer method allows the app to specify required * hashing algorithm. * * @param key Shared secret that is used for generating Hashed * Message Authentication Code (HMAC) * @param counter Starting counter value * @param incrementBy Counter incremented by this value after * generating OTP * @param hashingAlgorithm Hashing algorithm that has to be used for * generating OTP. Refer OMCryptoAlgorithm for more * details. Supported hashing algorithms are * OMAlgorithmMD5,OMAlgorithmSHA1,OMAlgorithmSHA224, * OMAlgorithmSHA256,OMAlgorithmSHA384, and * OMAlgorithmSHA512 * @param requiredDigitsInOTP Number of digits required in OTP * @param addCheckSumToOTP Flag that indicates whether check sum shall be * calculated for OTP and added to OTP * @return OMOTPService object, if initialization is successful. */ - (id) initForHOTPWithSharedKey: (NSData *)key andStartingCounter: (uint64_t)counter incrementBy: (long)incrementValue hashingAlgorithm: (OMCryptoAlgorithm)algorithm requiredDigitsInOTP: (unsigned long)numDigits addCheckSumToOTP: (BOOL)addCheckSum; /** * Initializer method for Time based One-Time Password (OTP) generation as * per RFC 6238. This initializer method allows the app to specify required * hashing algorithm. * * @param key Shared secret that is used for generating Hashed * Message Authentication Code (HMAC) * @param referenceTime Base Time - number of seconds elapse since 1st * Jan 1970 UTC time zone - to be used for * calculating OTP * @param timeStepInSeconds Time step in seconds. If this value is zero, * it will be set to 30 seconds. * @param hashingAlgorithm Hashing algorithm that has to be used for * computing HMAC. Refer OMCryptoAlgorithm for more * details. Supported hashing algorithms are * OMAlgorithmMD5,OMAlgorithmSHA1,OMAlgorithmSHA224, * OMAlgorithmSHA256,OMAlgorithmSHA384, and * OMAlgorithmSHA512 * @param requiredDigitsInOTP Number of digits required in OTP * @param addCheckSumToOTP Flag that indicates whether check sum shall be * calculated for OTP and added to OTP * @return OMOTPService object, if initialization is successful. */ - (id) initForTOTPWithSharedKey: (NSData *)key baseTimeInSeconds: (uint64_t)referenceTime timeStepInSeconds: (NSUInteger)timeSteps hashingAlgorithm: (OMCryptoAlgorithm)algorithm requiredDigitsInOTP: (NSUInteger)numDigits useCheckSum: (BOOL)addCheckSum; /** * Returns next One-Time Password as NSString object. * * @param error If OTP generation has failed, error message is returned * through this parameter * @return One-Time Password in NSString Object */ - (NSString *) OTPAsStringReturningError: (NSError **)error; /** * Returns next One-Time Password * * @param error If OTP generation has failed, error message is returned * through this parameter * @return One-Time Password */ - (uint64_t) OTPAsIntReturningError: (NSError **)error; /** * Class method to compute Hash Based Message Authentication Code (HMAC) as * per RFC 2104 given the data, key, and hashing algorithm. * * @param data Text for computing Hash Based Message Authentication * Code (HMAC) * @param algorithm Hashing algorithm that has to be used for computing * HMAC. Refer OMCryptoAlgorithm for more details. * Supported hashing algorithms are * OMAlgorithmMD5,OMAlgorithmSHA1,OMAlgorithmSHA224, * OMAlgorithmSHA256,OMAlgorithmSHA384, and * OMAlgorithmSHA512 * @param key Secret to compute HMAC * @param encode Identifies whether HMAC has to be base64 encoded or not * @param outError Returns NSError object in case of any error while * computing HMAC * @return HMAC as NSData object */ + (id) computeHashMACForData: (NSData *)data usingHashingAlgoritm: (OMCryptoAlgorithm)algorithm andKey: (NSData *)key base64EncodeHMAC: (BOOL)encode outError: (NSError **)error; /** * Class method to compute One-Time Password given counter, secret, and hashing * algorithm. * * @param counter counter value using OTP has to be computed * @param algorithm Hashing algorithm that has to be used for * computing HMAC. Refer OMCryptoAlgorithm for * more details. Supported hashing algorithms are * OMAlgorithmMD5, OMAlgorithmSHA1, * OMAlgorithmSHA224, OMAlgorithmSHA256, * OMAlgorithmSHA384, and OMAlgorithmSHA512 * @param key Secret to compute OTP * @param requiredDigitsInOTP Number of digits required in OTP * @param addCheckSumToOTP Flag that indicates whether check sum shall be * calculated for OTP and added to OTP * @param outError Returns NSError object in case of any error while * computing HMAC * @return One-Time Password */ + (uint64_t) OTPForCounter: (uint64_t)counter usingHashingAlgorithm: (OMCryptoAlgorithm)algorithm andKey: (NSData *)secret requiredDigitsInOTP: (NSUInteger)numberOfDigits addCheckSum: (BOOL)useCheckSum outError: (NSError **)error; /** * Class method to compute One-Time Password given text as NSData, secret, * and hashing algorithm. * * @param data Text for computing HMAC and OTP * @param algorithm Hashing algorithm that has to be used for * computing HMAC. Refer OMCryptoAlgorithm for * more details. Supported hashing algorithms are * OMAlgorithmMD5, OMAlgorithmSHA1, * OMAlgorithmSHA224, OMAlgorithmSHA256, * OMAlgorithmSHA384, and OMAlgorithmSHA512 * @param key Secret to compute OTP * @param requiredDigitsInOTP Number of digits required in OTP * @param addCheckSum Flag that indicates whether check sum shall be * calculated for OTP and added to OTP * @param outError Returns NSError object in case of any error * while computing OTP * @return One-Time Password */ + (uint64_t) OTPForData: (NSData *)data usingHashingAlgorithm: (OMCryptoAlgorithm)algorithm andKey: (NSData *)secret requiredDigitsInOTP: (NSUInteger)numberOfDigits addCheckSum: (BOOL)useCheckSum outError: (NSError **)error; /** * Class method to compute One-Time Password given text as NSString object, * secret, and hashing algorithm. * * @param text Text for computing HMAC and OTP * @param algorithm Hashing algorithm that has to be used for * computing HMAC. Refer OMCryptoAlgorithm for * more details. Supported hashing algorithms are * OMAlgorithmMD5, OMAlgorithmSHA1, * OMAlgorithmSHA224, OMAlgorithmSHA256, * OMAlgorithmSHA384, and OMAlgorithmSHA512 * @param key Secret to compute OTP * @param requiredDigitsInOTP Number of digits required in OTP * @param addCheckSum Flag that indicates whether check sum shall be * calculated for OTP and added to OTP * @param outError Returns NSError object in case of any error * while computing OTP * @return One-Time Password */ + (uint64_t) OTPForText: (NSString *)text usingHashingAlgorithm: (OMCryptoAlgorithm)algorithm andKey: (NSData *)secret requiredDigitsInOTP: (NSUInteger)numberOfDigits addCheckSum: (BOOL)useCheckSum outError: (NSError **)error; /** * Class method to compute Time based One-Time Password given time, secret, * and hashing algorithm. * * @param currentElpasedTimeSince1970 Time elapsed in seconds since 1st * Jan 1970 * @param algorithm Hashing algorithm that has to be used * for computing HMAC. Refer * OMCryptoAlgorithm for more details. * Supported hashing algorithms are * OMAlgorithmMD5, OMAlgorithmSHA1, * OMAlgorithmSHA224, OMAlgorithmSHA256, * OMAlgorithmSHA384, and * OMAlgorithmSHA512 * @param baseTime Base time to compute TOTP * @param timeStep Time steps used to compute TOTP * @param key Secret to compute OTP * @param numberOfDigits Number of digits required in OTP * @param useCheckSum Flag that indicates whether check sum * shall be calculated for OTP and added * to OTP * @param error Returns NSError object in case of any * error while computing TOTP * @return One-Time Password */ + (uint64_t) TOTPForTime: (uint64_t)currentElapsedTimeSince1970 usingHashingAlgorithm: (OMCryptoAlgorithm)algorithm baseTime: (uint64_t)baseTime timeStep: (uint64_t)timeStep andKey: (NSData *)key requiredDigitsInOTP: (NSUInteger)numberOfDigits addCheckSum: (BOOL)useCheckSum outError: (NSError **)error; /** * Class method to compute Time based One-Time Password given time step, * secret, and hashing algorithm. It uses 1st Jan 1970 0000 hrs as base * time. * * @param algorithm Hashing algorithm that has to be used * for computing HMAC. Refer * OMCryptoAlgorithm for more details. * Supported hashing algorithms are * OMAlgorithmMD5, OMAlgorithmSHA1, * OMAlgorithmSHA224, OMAlgorithmSHA256, * OMAlgorithmSHA384, and * OMAlgorithmSHA512 * @param timeStep Time steps used to compute TOTP * @param key Secret to compute OTP * @param numberOfDigits Number of digits required in OTP * @param useCheckSum Flag that indicates whether check sum * shall be calculated for OTP and added * to OTP * @param error Returns NSError object in case of any * error while computing TOTP * @param validity Returns how long this OTP is valid in * seconds * @return One-Time Password */ + (uint64_t) TOTPusingHashingAlgorithm: (OMCryptoAlgorithm)algorithm timeStep: (uint64_t)timeStep andKey: (NSData *)key requiredDigitsInOTP: (NSUInteger)numberOfDigits addCheckSum: (BOOL)useCheckSum outError: (NSError **)error expiresIn: (uint64_t *)validity; /** * Class method to convert uint64_t data to Byte array. * * Note: The caller of the application has to free memory allocated to Byte * array after its usage. * * @param number Number that has to be converted as Byte array * @return Byte array */ + (Byte *)convertInt64ToByte: (uint64_t)number; /** * Class method to convert uint64_t data to NSData object * * @param number Number that has to be converted as NSData object * @return NSData object containing bytes of passed uint64_t integer */ + (NSData *)convertInt64ToNSData: (uint64_t)number; /** * Class method to convert Byte array as hex formatted string. * * @param byteData Byte array that has to be converted * @return NSString object containing hex formatted string. Return value does * contain "0x" prefix. */ + (NSString *)convertByteAsHexFormattedString: (Byte *)byteData length: (NSUInteger)length; /** * Class method to convert NSData object as hex formatted string. * * @param data NSData object that has to be converted * @return NSString object containing hex formatted string. Return value does * contain "0x" prefix. */ + (NSString *)convertDataAsHexFormattedString: (NSData *)data; /** * Class method to convert NSString object as hex formatted string. NSString * is converted to Byte array using NSUTF8StringEncoding always. * * @param string NSString object that has to be converted * @return NSString object containing hex formatted string. Return value does * contain "0x" prefix. */ + (NSString *)convertStringAsHexFormattedString: (NSString *)string; /** * Class method to convert byte to binary format * * @param val Byte value * @return NSString object containing binary representation of byte */ + (NSString *)convertByteToBinaryString: (Byte)val; @end /////////////////////////////////////////////////////////////////////////////// // End ///////////////////////////////////////////////////////////////////////////////
x-and/cordova-plugin-oracle-idm-auth
src/ios/sdk/IDMMobileSDKv2/OMIDCSClientRegistrationToken.h
<gh_stars>10-100 /** * Copyright (c) 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ #import "OMToken.h" @interface OMIDCSClientRegistrationToken : OMToken @property (nonatomic, strong) NSString *clientID; @property (nonatomic, strong) NSString *clientName; @property (nonatomic, strong) NSString *clientSecret; @property (nonatomic, strong) NSArray *redirectUris; @property (nonatomic, strong) NSArray *grantTypes; @property (nonatomic, strong) NSString *scope; @property (nonatomic, strong) NSString *deviceID; @property (nonatomic, strong) NSString *appBundleID; @property (nonatomic, strong) NSDate *clientSecretExpiryDate; - (id)initWithInfo:(NSDictionary*)info; - (NSDictionary*)jsonInfo; @end //
JasonDeras/Proyecto2_CTJ_EDD1
Arista.h
#ifndef ARISTA_H #define ARISTA_H #include "Object.h" #include <string> using namespace std; class Arista : public Object{ public: Arista(); Arista(int, int, int); ~Arista(); int getOrigen(); int getDireccion(); int getPeso(); void setOrigen(int); void setDireccion(int); void setPeso(int); string toString(); private: int origen; int direccion; int peso; }; #endif
JasonDeras/Proyecto2_CTJ_EDD1
TDA_Tree.h
<reponame>JasonDeras/Proyecto2_CTJ_EDD1 #ifndef TDA_TREE_H #define TDA_TREE_H #include <vector> #include "Tree_Node.h" using std::vector; class TDA_Tree{ public: TDA_Tree(int n_Nodos); TDA_Tree(vector<Tree_Node*> arbol); Tree_Node* Padre(Tree_Node* t_Node); Tree_Node* Hijo_Izquierdo(Tree_Node* t_Node); Tree_Node* Hijo_Derecho(Tree_Node* t_Node); Tree_Node* Crear(string etiqueta, int nodo = -1 ,int izquierdo = -1, int derecho = -1); Tree_Node* Raiz(); void Anula(); static TDA_Tree* leerDeArchivo(string nombre); void PreOrder(Tree_Node* t_Node); void InOrder(Tree_Node* A); void PostOrder(Tree_Node* raiz); string Ruta(string etiqueta); ~TDA_Tree(); protected: vector<Tree_Node*> nodes; int root; }; #endif
JasonDeras/Proyecto2_CTJ_EDD1
Grafo.h
<gh_stars>0 #ifndef GRAFO_H #define GRAFO_H #include <vector> #include <iostream> #include <climits> using namespace std; class Grafo { public: Grafo(string nombrearchivo); Grafo(int nodos); void Crear_Aristas(int origen, int destino, int peso); vector<string> Split(string linea, char deliminator); vector< vector<int> > prim(); vector< vector<int> > kruskal(); vector< vector<int> > floyd(); void imprimir(vector< vector<int> >); private: int cn; //cantidad de nodos const int INF = INT_MAX; vector< vector<int> > ady; //matriz de adyacencia }; #endif
JasonDeras/Proyecto2_CTJ_EDD1
Object.h
#ifndef OBJECT_H #define OBJECT_H #include <string> using std::string; class Object{ public: Object(); virtual int Comparar(Object*) = 0; virtual string toString() = 0; virtual ~Object() {} }; #endif
JasonDeras/Proyecto2_CTJ_EDD1
Tree_Node.h
<gh_stars>0 #ifndef TREE_NODE_H #define TREE_NODE_H #include "Object.h" class Tree_Node : public Object{ public: Tree_Node(Tree_Node* padre, Tree_Node* hijo_izquierdo, Tree_Node* hijo_derecho, string etiqueta); Tree_Node* getPadre(); void setPadre(Tree_Node* padre); Tree_Node* getIzquierdo(); void setIzquierdo(Tree_Node* hijo_izquierdo); Tree_Node* getDerecho(); void setDerecho(Tree_Node* hijo_derecho); string getEtiqueta(); void setEtiqueta(string etiqueta); virtual int Comparar(Object*); virtual string toString(); ~Tree_Node(); protected: Tree_Node *padre; Tree_Node *hijo_izquierdo; Tree_Node *hijo_derecho; string etiqueta; }; #endif
cogniteam/cogniteam_ros2
include/cognitao_ros2/runner/Ros2Runner.h
/** * @brief ROS 2 cognitao runner * * @file Ros2Runner.h * * @author <NAME> (<EMAIL>) * @date 2020-03-15 * @copyright Cogniteam (c) 2020 * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the 'Software'), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef INCLUDE_ROS2_RUNNER_H_ #define INCLUDE_ROS2_RUNNER_H_ #include <string> #include <map> #include <future> #include <iostream> #include <rclcpp/rclcpp.hpp> #include <rclcpp_action/rclcpp_action.hpp> #include <cognitao/CogniTao.h> #include <cognitao_ros2/action/action.hpp> #include <cognitao_ros2/msg/event.hpp> using actionType =cognitao_ros2:: action::Action; using GoalHandleActionType = rclcpp_action::ClientGoalHandle<actionType>; using namespace std::placeholders; using namespace std; /** * Allows to receive data, manage callback and publish da */ class Ros2Runner : public Runner { public: /** * @brief Construct a new Ros 2 Runner object */ Ros2Runner(); /** * @brief Destroys the Ros 2 Runner object */ ~Ros2Runner(); public: /** * @brief execute task * @return bool */ virtual bool run() override; /** * @brief Gets the Type * @return std::string */ virtual std::string getType() override; /** * @brief stop executing task */ virtual void stop() override; private: atomic<bool> stopRequested_; rclcpp::Node::SharedPtr nodeHandle_; rclcpp_action::Client<actionType>::SharedPtr client_; rclcpp_action::ClientGoalHandle<actionType>::SharedPtr goalHandle_; }; #endif /* INCLUDE_ROS2_RUNNER_H_ */
cogniteam/cogniteam_ros2
include/cognitao_ros2/server/Ros2ActionContext.h
<reponame>cogniteam/cogniteam_ros2 /** * @brief ROS 2Action Wait Server * * @file Ros2ActionContext.h * * @author <NAME> (<EMAIL>) * @date 2020-03-15 * @copyright Cogniteam (c) 2020 * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the 'Software'), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef INCLUDE_ROS2_ACTION_CONTEXT_H_ #define INCLUDE_ROS2_ACTION_CONTEXT_H_ #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" using namespace std; using actionType=cognitao_ros2::action::Action; using GoalHandleActionType = rclcpp_action::ServerGoalHandle<actionType>; using namespace std::placeholders; class Ros2ActionContext { public: /** * @brief Construct a new Ros 2 Action Context object * @param goal_handle */ Ros2ActionContext(const std::shared_ptr<GoalHandleActionType> goal_handle = nullptr){ goal_handle_ = goal_handle; std::shared_ptr<const actionType::Goal> goal = goal_handle_->get_goal(); for (auto const& param : goal->goal.parameters){ parameters_[param.key] = param.val; } } /** * @brief Gets the Parameters * @return std::map<std::string, std::string> */ std::map<std::string, std::string> getParameters() const{ return parameters_; } /** * @brief Gets the Goal Handle * @return std::shared_ptr<GoalHandleActionType> */ std::shared_ptr<GoalHandleActionType> getGoalHandle() const{ return goal_handle_; } /** * @brief Sets the Result * @param resultVal */ void setResult(bool resultVal) { auto result = std::make_shared<actionType::Result>(); result->resultvalue = resultVal; goal_handle_->succeed(result); } /** * @brief set result false and cancel goal * */ void cancelGoal(){ auto result = std::make_shared<actionType::Result>(); result->resultvalue = false; goal_handle_->canceled(result); } /** * @brief goal is preempted * * @return true * @return false */ bool isPreemptRequested() { return getGoalHandle()->is_canceling(); } private: std::shared_ptr<GoalHandleActionType> goal_handle_; std::map<std::string, std::string> parameters_; }; #endif /* INCLUDE_ROS2_ACTION_CONTEXT_H_ */
cogniteam/cogniteam_ros2
include/cognitao_ros2/data_source/Ros2DataSource.h
/* * RosDataSource.h * @author <NAME> (<EMAIL>) * @date 2020-03-15 * @copyright Cogniteam (c) 2020 * * * Cogniteam LTD CONFIDENTIAL * * Unpublished Copyright (c) 2010-2020 Cogniteam, All Rights Reserved. * * NOTICE: All information contained herein is, and remains the property * of Cogniteam. The intellectual and technical concepts contained * herein are proprietary to Cogniteam and may be covered by Israeli and * Foreign Patents, patents in process, and are protected by trade secret * or copyright law. Dissemination of this information or reproduction of * this material is strictly forbidden unless prior written permission is * obtained from Cogniteam. Access to the source code contained herein * is hereby forbidden to anyone except current Cogniteam employees, * managers or contractors who have executed Confidentiality and * Non-disclosure agreements explicitly covering such access * * The copyright notice above does not evidence any actual or intended * publication or disclosure of this source code, which includes * information that is confidential and/or proprietary, and is a trade * secret, of Cogniteam. ANY REPRODUCTION, MODIFICATION, DISTRIBUTION, * PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR THROUGH USE OF THIS * SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF Cogniteam IS * STRICTLY PROHIBITED, AND IN VIOLATION OF APPLICABLE LAWS AND INTERNATIONAL * TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE CODE AND/OR RELATED * INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS TO REPRODUCE, DISCLOSE * OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE, USE, OR SELL ANYTHING * THAT IT MAY DESCRIBE, IN WHOLE OR IN PART * */ #ifndef ROS2_DATA_SOURCE_H_ #define ROS2_DATA_SOURCE_H_ #include <cognitao/CogniTao.h> #include <rclcpp/rclcpp.hpp> #include <cognitao_ros2/msg/event.hpp> #include <cognitao/data_sources/DataSource.h> #include "std_msgs/msg/string.hpp" // #include <cognitao/CogniTao.h> using namespace std; /** * manage the WM */ class Ros2DataSource :public DataSource{ public: /** * @brief Construct a new Ros 2 Data Source object */ Ros2DataSource(); /** * @brief Destroys the Ros 2 Data Source object */ virtual ~Ros2DataSource(){}; public: /** * @brief create ros2 data source * @return DataSource::Ptr */ static DataSource::Ptr create(){ return DataSource::Ptr(new Ros2DataSource()); } protected: /** * @brief publish events * @return bool */ virtual bool publishUpdateEvent(const string &name, const string &value); /** * @brief updates the world model * @return bool */ void onDataSourceEvent(const cognitao_ros2::msg::Event::SharedPtr msg); void doSpin(); private: rclcpp::Subscription<cognitao_ros2::msg::Event>::SharedPtr event_sub_; rclcpp::Publisher<cognitao_ros2::msg::Event>::SharedPtr event_pub_; std::thread spinThread_; rclcpp::Node::SharedPtr g_node_ = nullptr; }; #endif /* ROS2_DATA_SOURCE_H_ */
cogniteam/cogniteam_ros2
include/cognitao_ros2/server/Ros2ActionServer.h
<filename>include/cognitao_ros2/server/Ros2ActionServer.h /** * @brief ROS 2 Action Server * * @file Ros2ActionServer.h * * @author <NAME> (<EMAIL>) * @date 2020-03-15 * @copyright Cogniteam (c) 2020 * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the 'Software'), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef INCLUDE_ROS2_ACTION_SERVER_H_ #define INCLUDE_ROS2_ACTION_SERVER_H_ #include <inttypes.h> #include <memory> #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" #include "Ros2ActionContext.h" using namespace std; using actionType=cognitao_ros2::action::Action; using GoalHandleActionType = rclcpp_action::ServerGoalHandle<actionType>; using namespace std::placeholders; class Ros2ActionServer { public: /** * @brief Construct a new Ros 2 Action Server object * @param node * @param action */ Ros2ActionServer(rclcpp::Node::SharedPtr node, const std::string action) { g_node_ = node; this->server_ = rclcpp_action::create_server<actionType>( g_node_, action, std::bind(&Ros2ActionServer::handleGoal, this, std::placeholders::_1, std::placeholders::_2), std::bind(&Ros2ActionServer::handleCancel, this, std::placeholders::_1), std::bind(&Ros2ActionServer::onStart, this, std::placeholders::_1) ); } /** * @brief Destroys the Ros 2 Action Server object */ virtual ~Ros2ActionServer(){}; private: rclcpp_action::GoalResponse handleGoal( const std::array<uint8_t, 16> &, std::shared_ptr<const actionType::Goal> ) { return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE; } rclcpp_action::CancelResponse handleCancel( const std::shared_ptr<GoalHandleActionType> ) { return rclcpp_action::CancelResponse::ACCEPT; } void onStart(const std::shared_ptr<GoalHandleActionType> goal_handle) { Ros2ActionContext ros2ActionContext(goal_handle); std::thread{std::bind(&Ros2ActionServer::execute, this, _1), ros2ActionContext}.detach(); } virtual void execute(Ros2ActionContext ros2ActionContext) = 0; private: rclcpp::Node::SharedPtr g_node_ = nullptr; rclcpp_action::Server<actionType>::SharedPtr server_; }; #endif /* INCLUDE_ROS2_ACTION_SERVER_H_ */
graphicsfuzz/get-image-hlsl
get-image-hlsl/stdafx.h
<gh_stars>0 // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #define _WIN32_WINNT 0x600 #undef NDEBUG #define DEBUG #define NOMINMAX #include <Windows.h> #include "targetver.h" #include <iostream> #include <stdio.h> #include <tchar.h> #include <d3dcompiler.h> #include <DirectXColors.h> #include <DirectXMath.h> #include <concrt.h> #include <d2d1_3.h> #include <d2d1effects_2.h> #include <d3d11_3.h> #include <dwrite_3.h> #include <memory> #include <wincodec.h> #include <wrl/client.h> #include <sstream> #include <fstream> #include <codecvt> #include <string> // " to simplify the tutorial we will go ahead and add them all to your new // project's pch.h header" lol #include "CommonStates.h" #include "DDSTextureLoader.h" #include "DirectXHelpers.h" #include "Effects.h" #include "GamePad.h" #include "GeometricPrimitive.h" #include "GraphicsMemory.h" #include "Keyboard.h" #include "Model.h" #include "Mouse.h" #include "PrimitiveBatch.h" #include "ScreenGrab.h" #include "SimpleMath.h" #include "SpriteBatch.h" #include "SpriteFont.h" #include "VertexTypes.h" #include "WICTextureLoader.h" #include <comdef.h> #pragma comment(lib, "d3dcompiler.lib") #pragma comment(lib, "d3d11.lib")
renatoferrarezi/keyboard_isr_routine
keyboard.h
<gh_stars>0 #ifndef KEYBOARD_h #define KEYBOARD_h #include <avr/interrupt.h> #include <Arduino.h> #define KBD_BUFFER_SIZE 0x14 class keyboard { public: keyboard(uint8_t kbl1, uint8_t kbl2, uint8_t kbl3, uint8_t kbl4, uint8_t kbr1, uint8_t kbr2, uint8_t kbr3, uint8_t kbr4); void timer_set(unsigned long debounce_time, unsigned long repeat_time); void start(); void stop(); uint8_t available(void); uint8_t getkey(void); private: unsigned long _interval; }; #endif
orrinjelo/AdventOfCode2019
cpp/include/utils.h
<reponame>orrinjelo/AdventOfCode2019 #pragma once #include <vector> #include <sstream> template<class T> std::string vectorToString(std::vector<T> v) { bool first = true; std::stringstream ss; for (auto x: v) { if (!first) { ss << ", "; } ss << x; first = false; } return ss.str(); }
orrinjelo/AdventOfCode2019
cpp/include/operators.h
#pragma once #include <vector> #include <functional> typedef int64_t big_int; typedef std::vector<big_int> vector_big_int; class Operators { public: Operators() {}; ~Operators() {}; void add( vector_big_int &program, int &pc, int offset=0 ); void mul( vector_big_int &program, int &pc, int offset=0 ); void inp( vector_big_int &program, int &pc, int offset, std::function<big_int(std::string)> inputCallback ); void prt( vector_big_int &program, int &pc, int offset, std::function<void(big_int&)> outputCallback ); void jmp( vector_big_int &program, int &pc, int offset=0 ); void jmf( vector_big_int &program, int &pc, int offset=0 ); void ltn( vector_big_int &program, int &pc, int offset=0 ); void eql( vector_big_int &program, int &pc, int offset=0 ); void rel( vector_big_int &program, int &pc, int &offset ); private: void scrapeOp( int x, int &A, int &B, int &C, int &DE ); void interpretOperand( vector_big_int &program, big_int &o, int O, int offset ); void interpretOperandAndSet( vector_big_int &program, big_int value, big_int &c, int C, int &offset ); };
orrinjelo/AdventOfCode2019
cpp/include/vm.h
<gh_stars>1-10 #pragma once #include <functional> #include <string> #include <vector> #include <fstream> #include "operators.h" class VM { public: enum OpCode { ADD = 1, MUL = 2, INP = 3, PRT = 4, JMP = 5, JMF = 6, LTN = 7, EQL = 8, REL = 9, HALT = 99 }; VM( int memSize=4096 ); VM( std::function<big_int(std::string)> inputCB, std::function<void(big_int&)> ouputCB, int memSize=4096 ); ~VM() {} void loadIntCode(std::ifstream &in); void loadIntCode(std::string &s); void loadIntCode(vector_big_int &v); void execute(); void reset(); void terminate(); vector_big_int& memory() { return memory_; } private: bool running_; vector_big_int memory_; Operators operators_; int pc_; int relativeBase_; std::function<int(std::string)> inputCB_; std::function<void(big_int&)> outputCB_; void stringToVector(std::string s); };
toiletsnakes/DATReaderC
C/fileheader.c
<filename>C/fileheader.c<gh_stars>0 #include <inttypes.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include "fileheader.h" #include "byteswap.h" #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" struct FileHeader *FileHeader_create(void) { FileHeader *fileHeader = malloc(sizeof(struct FileHeader)); assert(fileHeader != NULL); return fileHeader; }; void getFileHeader(FileHeader *header, FILE *datFile) { assert(datFile != NULL); fseek(datFile, 0, SEEK_SET); fread(&header->fileSize, sizeof(header->fileSize), 1, datFile); fread(&header->pointerTableOffset, sizeof(header->pointerTableOffset), 1, datFile); fread(&header->pointerCount, sizeof(header->pointerCount), 1, datFile); fread(&header->rootNodeCount, sizeof(header->rootNodeCount), 1, datFile); fread(&header->referenceNodeCount, sizeof(header->referenceNodeCount), 1, datFile); fread(&header->unknownString, sizeof(header->unknownString), 1, datFile); fread(&header->unknownPadding1, sizeof(header->unknownPadding1), 1, datFile); fread(&header->unknownPadding2, sizeof(header->unknownPadding2), 1, datFile); header->fileSize = byteswap32(header->fileSize); header->pointerTableOffset = byteswap32(header->pointerTableOffset); header->pointerCount = byteswap32(header->pointerCount); header->rootNodeCount = byteswap32(header->rootNodeCount); header->referenceNodeCount = byteswap32(header->referenceNodeCount); header->unknownPadding1 = byteswap32(header->unknownPadding1); header->unknownPadding2 = byteswap32(header->unknownPadding2); } void FileHeader_destroy(FileHeader *fileHeader) { assert(fileHeader != NULL); free(fileHeader); } void FileHeader_print(FileHeader *fileHeader) { printf("\nfileHeader->fileSize: "KRED"%"PRIu32"\n"KNRM,fileHeader->fileSize); printf("fileHeader->pointerTableOffset: "KRED"%#.08x\n"KNRM,fileHeader->pointerTableOffset); printf("fileHeader->pointerCount: "KRED"%"PRIu32"\n"KNRM,fileHeader->pointerCount); printf("fileHeader->rootNodeCount: "KRED"%"PRIu32"\n"KNRM,fileHeader->rootNodeCount); printf("fileHeader->referenceNodeCount: "KRED"%"PRIu32"\n"KNRM,fileHeader->referenceNodeCount); printf("fileHeader->unknownString: "KRED"%s\n"KNRM,fileHeader->unknownString); printf("fileHeader->unknownPadding1: "KRED"%"PRIu32"\n"KNRM,fileHeader->unknownPadding1); printf("fileHeader->unknownPadding2: "KRED"%"PRIu32"\n"KNRM,fileHeader->unknownPadding2); }
toiletsnakes/DATReaderC
C/byteswap.c
<reponame>toiletsnakes/DATReaderC #include <inttypes.h> #include "byteswap.h" #include <stdio.h> // int main(int argc, char const *argv[]) // { // littleEndian(); // return 0; // } uint32_t byteswap32(uint32_t num32) { if (littleEndian()) { return ((num32>>3*8)&0x000000ff)| // move byte 3 to byte 0 ((num32<<1*8)&0x00ff0000)| // move byte 1 to byte 2 ((num32>>1*8)&0x0000ff00)| // move byte 2 to byte 1 ((num32<<3*8)&0xff000000); // byte 0 to byte 3 } else { return num32; } } uint16_t byteswap16(uint16_t num16) { if (littleEndian()) { return ((num16 & 0xff00) >> 8)| ((num16 & 0x00ff) << 8); } else { return num16; } } float floatSwap(float floatIn) { if (littleEndian()) { uint32_t num32 = *(uint32_t *)&floatIn; num32 = ((num32>>3*8)&0x000000ff)| // move byte 3 to byte 0 ((num32<<1*8)&0x00ff0000)| // move byte 1 to byte 2 ((num32>>1*8)&0x0000ff00)| // move byte 2 to byte 1 ((num32<<3*8)&0xff000000); // byte 0 to byte 3 floatIn = *(float *)&num32; return floatIn; } else { return floatIn; } } int littleEndian(void) { FILE *fp = fopen("endian", "rb"); uint32_t bigHex[1]; bigHex[0] = 0x3f800000; fseek(fp, 0, SEEK_SET); uint32_t readHex[1]; float readFloat[1]; fread(readFloat, sizeof(uint32_t), 1, fp); readHex[0] = *(uint32_t *)&readFloat[0]; fclose(fp); int little = 0; if (*(uint32_t*)&readFloat[0] == bigHex[0]) { //printf("%f, %f\n", readFloat[0], *(float *)& bigHex[0]); //printf("BIG ENDIAN: %#.08x is %#.08x\n", bigHex[0], readHex[0]); little = 1; } else if (*(uint32_t*)&readFloat[0] != bigHex[0]){ //printf("%f, %f\n", readFloat[0], *(float *)& bigHex[0]); //printf("LITTLE ENDIAN: %#.08x is not %#.08x\n", bigHex[0], readHex[0]); little = -1; } return little; }
toiletsnakes/DATReaderC
C/fileheader.h
struct FileHeader { uint32_t fileSize; uint32_t pointerTableOffset; uint32_t pointerCount; uint32_t rootNodeCount; uint32_t referenceNodeCount; char unknownString[4]; uint32_t unknownPadding1; uint32_t unknownPadding2; }; typedef struct FileHeader FileHeader; struct FileHeader *FileHeader_create(void); void getFileHeader(FileHeader *header, FILE *fp); void FileHeader_destroy(FileHeader *fileHeader); void FileHeader_print(FileHeader *fileHeader);
toiletsnakes/DATReaderC
C/bonestructure.c
#include <inttypes.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include "byteswap.h" #include "inttypes.h" #include "rootnodes.h" #include "bonestructure.h" #define DATA_BLOCK 0x20 #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" struct BoneStructureRoot *BoneStructureRoots_create(uint32_t count) { BoneStructureRoot *boneStructureRoots = malloc(sizeof(struct BoneStructureRoot) * count); assert(boneStructureRoots != NULL); return boneStructureRoots; } void GetBoneStructureRoots(RootNode *rootNodes, uint32_t count, BoneStructureRoot *boneStructureRoots, FILE *datFile) { assert(datFile != NULL); for (int i = 0; i < count; ++i) { RootNode *rootNode = &rootNodes[i]; fseek(datFile, rootNode->dataOffset+DATA_BLOCK, SEEK_SET); BoneStructureRoot *boneStructureRoot = &boneStructureRoots[i]; fread(&boneStructureRoot->stringOffset, sizeof(boneStructureRoot->stringOffset), 1, datFile); fread(&boneStructureRoot->unknownFlags, sizeof(boneStructureRoot->unknownFlags), 1, datFile); fread(&boneStructureRoot->childBoneStructOffset, sizeof(boneStructureRoot->childBoneStructOffset), 1, datFile); fread(&boneStructureRoot->nextBoneStructOffset, sizeof(boneStructureRoot->nextBoneStructOffset), 1, datFile); fread(&boneStructureRoot->objectStructOffset, sizeof(boneStructureRoot->objectStructOffset), 1, datFile); fread(&boneStructureRoot->rotation_x, sizeof(boneStructureRoot->rotation_x), 1, datFile); fread(&boneStructureRoot->rotation_y, sizeof(boneStructureRoot->rotation_y), 1, datFile); fread(&boneStructureRoot->rotation_z, sizeof(boneStructureRoot->rotation_z), 1, datFile); fread(&boneStructureRoot->scale_x, sizeof(boneStructureRoot->scale_x), 1, datFile); fread(&boneStructureRoot->scale_y, sizeof(boneStructureRoot->scale_y), 1, datFile); fread(&boneStructureRoot->scale_z, sizeof(boneStructureRoot->scale_z), 1, datFile); fread(&boneStructureRoot->location_x, sizeof(boneStructureRoot->location_x), 1, datFile); fread(&boneStructureRoot->location_y, sizeof(boneStructureRoot->location_y), 1, datFile); fread(&boneStructureRoot->location_z, sizeof(boneStructureRoot->location_z), 1, datFile); fread(&boneStructureRoot->inverseBindMatrixOffset, sizeof(boneStructureRoot->inverseBindMatrixOffset), 1, datFile); fread(&boneStructureRoot->pointerUnknown, sizeof(boneStructureRoot->pointerUnknown), 1, datFile); boneStructureRoot->stringOffset=byteswap32(boneStructureRoot->stringOffset); boneStructureRoot->unknownFlags=byteswap32(boneStructureRoot->unknownFlags); boneStructureRoot->childBoneStructOffset=byteswap32(boneStructureRoot->childBoneStructOffset); boneStructureRoot->nextBoneStructOffset=byteswap32(boneStructureRoot->nextBoneStructOffset); boneStructureRoot->objectStructOffset=byteswap32(boneStructureRoot->objectStructOffset); float tempFloat; tempFloat = boneStructureRoot->rotation_x; boneStructureRoot->rotation_x = floatSwap(tempFloat); tempFloat = boneStructureRoot->rotation_y; boneStructureRoot->rotation_y = floatSwap(tempFloat); tempFloat = boneStructureRoot->rotation_z; boneStructureRoot->rotation_z = floatSwap(tempFloat); tempFloat = boneStructureRoot->scale_x; boneStructureRoot->scale_x = floatSwap(tempFloat); tempFloat = boneStructureRoot->scale_y; boneStructureRoot->scale_y = floatSwap(tempFloat); tempFloat = boneStructureRoot->scale_z; boneStructureRoot->scale_z = floatSwap(tempFloat); tempFloat = boneStructureRoot->location_x; boneStructureRoot->location_x = floatSwap(tempFloat); tempFloat = boneStructureRoot->location_y; boneStructureRoot->location_y = floatSwap(tempFloat); tempFloat = boneStructureRoot->location_z; boneStructureRoot->location_z = floatSwap(tempFloat); boneStructureRoot->inverseBindMatrixOffset=byteswap32(boneStructureRoot->inverseBindMatrixOffset); boneStructureRoot->pointerUnknown=byteswap32(boneStructureRoot->pointerUnknown); } } void BoneStructureRoots_print(BoneStructureRoot *boneStructureRoots, uint32_t count) { for (int i = 0; i < count; ++i) { BoneStructureRoot *boneStructureRoot = &boneStructureRoots[i]; printf("\nstringOffset: "KRED"%#.08x"KNRM, boneStructureRoot->stringOffset); printf("\nunknownFlags: "KRED"%#.08x"KNRM, boneStructureRoot->unknownFlags); printf("\nchildBoneStructOffset: "KRED"%#.08x"KNRM, boneStructureRoot->childBoneStructOffset); printf("\nnextBoneStructOffset: "KRED"%#.08x"KNRM, boneStructureRoot->nextBoneStructOffset); printf("\nobjectStructOffset: "KRED"%#.08x"KNRM, boneStructureRoot->objectStructOffset); printf("\nrotation_x: "KRED"%#.08f"KNRM, boneStructureRoot->rotation_x); printf("\nrotation_y: "KRED"%#.08f"KNRM, boneStructureRoot->rotation_y); printf("\nrotation_z: "KRED"%#.08f"KNRM, boneStructureRoot->rotation_z); printf("\nscale_x: "KRED"%#.08f"KNRM, boneStructureRoot->scale_x); printf("\nscale_y: "KRED"%#.08f"KNRM, boneStructureRoot->scale_y); printf("\nscale_z: "KRED"%#.08f"KNRM, boneStructureRoot->scale_z); printf("\nlocation_x: "KRED"%#.08f"KNRM, boneStructureRoot->location_x); printf("\nlocation_y: "KRED"%#.08f"KNRM, boneStructureRoot->location_y); printf("\nlocation_z: "KRED"%#.08f"KNRM, boneStructureRoot->location_z); printf("\ninverseBindMatrixOffset: "KRED"%#.08x"KNRM, boneStructureRoot->inverseBindMatrixOffset); printf("\npointerUnknown: "KRED"%#.08x\n"KNRM, boneStructureRoot->pointerUnknown); } } void BoneStructureRoots_destroy(BoneStructureRoot *boneStructureRoots) { assert(boneStructureRoots != NULL); free(boneStructureRoots); }
toiletsnakes/DATReaderC
C/pointertable.h
typedef uint32_t PointerTable; PointerTable* GetPointersFromPointerTable(FILE *datFile, uint32_t pointerTableOffset, uint32_t count); void PointerTable_print(PointerTable *pointerTable, uint32_t count); void PointerTable_destroy(PointerTable *pointerTable);
toiletsnakes/DATReaderC
C/rootnodes.c
<reponame>toiletsnakes/DATReaderC<filename>C/rootnodes.c<gh_stars>0 #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include "rootnodes.h" #include "byteswap.h" #define DATA_BLOCK 0x20 struct RootNode *RootNodes_create (uint32_t count) { RootNode *rootNodes = malloc(sizeof(struct RootNode) * count); assert(rootNodes != NULL); return rootNodes; }; void GetRootNodes(RootNode *rootNodes, FILE *datFile, uint32_t offset, uint32_t count) { assert(datFile != NULL); fseek(datFile, offset, SEEK_SET); for (int i = 0; i < count; i++) { RootNode *rootNode = &rootNodes[i]; fread(&rootNode->dataOffset, sizeof(rootNode->dataOffset), 1, datFile); fread(&rootNode->stringOffset, sizeof(rootNode->stringOffset), 1, datFile); rootNode->dataOffset = byteswap32(rootNode->dataOffset); rootNode->stringOffset = byteswap32(rootNode->stringOffset); } for (int i = 0; i < count; i++) { long startingOffset = ftell(datFile); int length = 0; do { length++; } while (fgetc(datFile)!= 0x00); RootNode *rootNode = &rootNodes[i]; rootNode->string = malloc(length); fseek(datFile, startingOffset, SEEK_SET); fgets(rootNode->string, length, datFile); fseek(datFile, 1, SEEK_CUR); } } void RootNodes_destroy(RootNode *rootNodes) { assert(rootNodes != NULL); free(rootNodes); } void RootNodes_print(RootNode *rootNodes, uint32_t count) { for (int i = 0; i < count; i++) { RootNode *rootNode = &rootNodes[i]; printf("\nrootNode[%d]->dataOffset: %#.08x\n", i+1, (rootNode->dataOffset)); printf("rootNode[%d]->stringOffset: %#.08x\n", i+1, (rootNode->stringOffset)); printf("rootNode[%d]->string: %s\n", i+1, (rootNode->string)); } }
toiletsnakes/DATReaderC
C/galereader.c
#include <stdio.h> #include <inttypes.h> #include <stdlib.h> #include "fileheader.h" #include "rootnodes.h" #include "pointertable.h" #include "byteswap.h" #include "bonestructure.h" #include "object.h" #define DATA_BLOCK 0x20 int main(int argc, char const *argv[]) { FILE *datFile = fopen("PlFcGr.dat", "rb"); if (datFile) { printf("opened file\n"); } else { printf("there was an error!\007\n"); return -1; } FileHeader *fileHeader = FileHeader_create(); getFileHeader(fileHeader, datFile); FileHeader_print(fileHeader); PointerTable *pointerTable = GetPointersFromPointerTable(datFile, fileHeader->pointerTableOffset, fileHeader->pointerCount); PointerTable_print(pointerTable, fileHeader->pointerCount); RootNode *rootNodes = RootNodes_create(fileHeader->rootNodeCount); GetRootNodes(rootNodes, datFile, ftell(datFile), fileHeader->rootNodeCount); RootNodes_print(rootNodes, fileHeader->rootNodeCount); BoneStructureRoot *boneStructureRoots = BoneStructureRoots_create(fileHeader->rootNodeCount); GetBoneStructureRoots(rootNodes, fileHeader->rootNodeCount,boneStructureRoots, datFile); BoneStructureRoots_print(boneStructureRoots, fileHeader->rootNodeCount); ObjectStruct *objectStruct = ObjectStruct_create();; long offset = boneStructureRoots[0].objectStructOffset; do { GetObjectStruct(objectStruct, offset ,datFile); offset = objectStruct->nextObjectOffset; ObjectStruct_print(objectStruct); } while (offset != 0x0000); fclose(datFile); FileHeader_destroy(fileHeader); RootNodes_destroy(rootNodes); PointerTable_destroy(pointerTable); BoneStructureRoots_destroy(boneStructureRoots); ObjectStruct_destroy(objectStruct); printf("\nclosed file\n"); return 0; }
toiletsnakes/DATReaderC
C/rgba565.c
<reponame>toiletsnakes/DATReaderC<gh_stars>0 #include <stdio.h> #include <inttypes.h> #include <stdlib.h> void printRBGFromRGB365(uint16_t color); struct Pixel { uint8_t red; uint8_t green; uint8_t blue; }; typedef struct Pixel Pixel; int main(int argc, char const *argv[]) { /* code */ printRBGFromRGB365(0b1111100000000000); printRBGFromRGB365(0x0000); printRBGFromRGB365(0x40B0); printRBGFromRGB365(0x0078); return 0; } void printRBGFromRGB365(uint16_t color) { int red; int green; int blue; red = (color>>11)&0b0000000000011111; green = (color>>05)&0b0000000000111111; blue = (color>>00)&0b0000000000011111; Pixel *pixel = malloc(sizeof(struct Pixel)); red *=0x08; green *=0x04; blue *=0x08; pixel->red = red; pixel->green = green; pixel->blue = blue; printf("R: %"PRIu8"\nG: %"PRIu8"\nB: %"PRIu8"\n\n", pixel->red, pixel->green, pixel->blue); free(pixel); } uint8_t lerp (uint8_t a, uint8_t b, uint8_t t) { float T = (float)t / 255.0f; return (b-a)*t + b; }
toiletsnakes/DATReaderC
C/rootnodes.h
struct RootNode { uint32_t dataOffset; uint32_t stringOffset; char *string; }; typedef struct RootNode RootNode; struct RootNode *RootNodes_create (uint32_t count); void GetRootNodes(RootNode *rootNodes, FILE *fp, uint32_t offset, uint32_t count); void RootNodes_destroy(RootNode *rootNodes); void RootNodes_print(RootNode *rootNodes, uint32_t count);
toiletsnakes/DATReaderC
C/byteswap.h
uint32_t byteswap32(uint32_t num32); uint16_t byteswap16(uint16_t num16); float floatSwap(float floatIn); int littleEndian(void);
toiletsnakes/DATReaderC
C/bonestructure.h
struct BoneStructureRoot { //http://wiki.tockdom.com/wiki/HAL_DAT_(File_Format)#Bone_Structures_.28Root_Structure.29 uint32_t stringOffset; uint32_t unknownFlags; uint32_t childBoneStructOffset; uint32_t nextBoneStructOffset; uint32_t objectStructOffset; float rotation_x; float rotation_y; float rotation_z; float scale_x; float scale_y; float scale_z; float location_x; float location_y; float location_z; uint32_t inverseBindMatrixOffset; uint32_t pointerUnknown; }; typedef struct BoneStructureRoot BoneStructureRoot; struct BoneStructureRoot *BoneStructureRoots_create(uint32_t offset); void GetBoneStructureRoots(RootNode *rootNodes, uint32_t count, BoneStructureRoot *boneStructureRoots, FILE *datFile); void BoneStructureRoots_destroy(BoneStructureRoot *boneStructureRoots); void BoneStructureRoots_print(BoneStructureRoot *boneStructureRoots, uint32_t count);
toiletsnakes/DATReaderC
C/pointertable.c
#include <stdio.h> #include <assert.h> #include <stdlib.h> #include <inttypes.h> #include "byteswap.h" #include "pointertable.h" #define DATA_BLOCK 0x20 #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" PointerTable* GetPointersFromPointerTable(FILE *datFile, uint32_t pointerTableOffset, uint32_t count) { assert(datFile != NULL); fseek(datFile, pointerTableOffset+DATA_BLOCK, SEEK_SET); PointerTable *pointers = malloc(sizeof(uint32_t) * count); fread(pointers, sizeof(uint32_t), count, datFile); for (int i = 0; i < count; i++) { pointers[i] = byteswap32(pointers[i]); } return pointers; } void PointerTable_print(PointerTable *pointerTable, uint32_t count) { for (int i = 0; i < count; i++) { printf(""KGRN"%#.8lx "KNRM, (unsigned long) pointerTable[i]); if (i % 9 == 8) { printf("\n"); } } } void PointerTable_destroy(PointerTable *pointerTable) { assert(pointerTable != NULL); free(pointerTable); }
toiletsnakes/DATReaderC
C/object.h
<reponame>toiletsnakes/DATReaderC struct ObjectStruct { uint32_t stringOffset; uint32_t nextObjectOffset; uint32_t materialStructOffset; uint32_t meshStructOffset; }; typedef struct ObjectStruct ObjectStruct; struct ObjectStruct *ObjectStruct_create(void); void GetObjectStruct(ObjectStruct *objectStruct, uint32_t offset, FILE *datFile); void ObjectStruct_print (ObjectStruct *objectStruct); void ObjectStruct_destroy(ObjectStruct *objectStruct);
toiletsnakes/DATReaderC
C/object.c
<reponame>toiletsnakes/DATReaderC<gh_stars>0 #include <inttypes.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include "byteswap.h" #include "inttypes.h" #include "rootnodes.h" #include "bonestructure.h" #include "object.h" #define DATA_BLOCK 0x20 #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" struct ObjectStruct *ObjectStruct_create(void) { ObjectStruct *objectStruct = malloc(sizeof(struct ObjectStruct)); assert(objectStruct != NULL); return objectStruct; } void GetObjectStruct(ObjectStruct *objectStruct, uint32_t offset, FILE *datFile) { fseek(datFile, offset+DATA_BLOCK, SEEK_SET); printf("\nbefore getting object, file is at "KRED"%#.08lx"KNRM, ftell(datFile)); assert(objectStruct != NULL); assert(datFile != NULL); fread(&objectStruct->stringOffset, sizeof(objectStruct->stringOffset), 1, datFile); fread(&objectStruct->nextObjectOffset, sizeof(objectStruct->nextObjectOffset), 1, datFile); fread(&objectStruct->materialStructOffset, sizeof(objectStruct->materialStructOffset), 1, datFile); fread(&objectStruct->meshStructOffset, sizeof(objectStruct->meshStructOffset), 1, datFile); objectStruct->stringOffset=byteswap32(objectStruct->stringOffset); objectStruct->nextObjectOffset=byteswap32(objectStruct->nextObjectOffset); objectStruct->materialStructOffset=byteswap32(objectStruct->materialStructOffset); objectStruct->meshStructOffset=byteswap32(objectStruct->meshStructOffset); } void ObjectStruct_print (ObjectStruct *objectStruct) { assert(objectStruct != NULL); printf("\nobjectStruct->stringOffset "KRED"%#.08x"KNRM, objectStruct->stringOffset); printf("\nobjectStruct->nextObjectOffset "KRED"%#.08x"KNRM, objectStruct->nextObjectOffset); printf("\nobjectStruct->materialStructOffset "KRED"%#.08x"KNRM, objectStruct->materialStructOffset); printf("\nobjectStruct->meshStructOffset "KRED"%#.08x\n"KNRM, objectStruct->meshStructOffset); } void ObjectStruct_destroy(ObjectStruct *objectStruct) { assert(objectStruct != NULL); free(objectStruct); }
NJasp/netwerkmesh
sniffer/main.c
/* * Copyright (C) 2015-18 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @defgroup app_sniffer * @brief Sniffer application based on the new network stack * @{ * * @file * @brief Sniffer application for RIOT * * @author <NAME> <hauke.petersen@fu-berlin.de> * @author <NAME> <m.lenders@fu-berlin.de> * * @} */ #include <stdio.h> #include "fmt.h" #include "thread.h" #include "xtimer.h" #include "shell.h" #include "shell_commands.h" #include "net/gnrc.h" /** * @brief Buffer size used by the shell */ #define SHELL_BUFSIZE (64U) /** * @brief Priority of the RAW dump thread */ #define RAWDUMP_PRIO (THREAD_PRIORITY_MAIN - 1) /** * @brief Message queue size of the RAW dump thread */ #define RAWDUMP_MSG_Q_SIZE (32U) /** * @brief Stack for the raw dump thread */ static char rawdmp_stack[THREAD_STACKSIZE_SMALL]; /** * @brief Make a raw dump of the given packet contents */ void dump_pkt(gnrc_pktsnip_t *pkt) { gnrc_pktsnip_t *snip = pkt; uint8_t lqi = 0; if (pkt->next) { if (pkt->next->type == GNRC_NETTYPE_NETIF) { gnrc_netif_hdr_t *netif_hdr = pkt->next->data; lqi = netif_hdr->lqi; pkt = gnrc_pktbuf_remove_snip(pkt, pkt->next); } } uint64_t now_us = xtimer_usec_from_ticks64(xtimer_now64()); print_str("rftest-rx --- len "); print_u32_hex((uint32_t)gnrc_pkt_len(pkt)); print_str(" lqi "); print_byte_hex(lqi); print_str(" rx_time "); print_u64_hex(now_us); print_str("\n"); while (snip) { for (size_t i = 0; i < snip->size; i++) { print_byte_hex(((uint8_t *)(snip->data))[i]); print_str(" "); } snip = snip->next; } print_str("\n\n"); gnrc_pktbuf_release(pkt); } /** * @brief Event loop of the RAW dump thread * * @param[in] arg unused parameter */ void *rawdump(void *arg) { msg_t msg_q[RAWDUMP_MSG_Q_SIZE]; (void)arg; msg_init_queue(msg_q, RAWDUMP_MSG_Q_SIZE); while (1) { msg_t msg; msg_receive(&msg); switch (msg.type) { case GNRC_NETAPI_MSG_TYPE_RCV: dump_pkt((gnrc_pktsnip_t *)msg.content.ptr); break; default: /* do nothing */ break; } } /* never reached */ return NULL; } /** * @brief Maybe you are a golfer?! */ int main(void) { gnrc_netreg_entry_t dump; puts("RIOT sniffer application"); /* start and register rawdump thread */ puts("Run the rawdump thread and register it"); dump.target.pid = thread_create(rawdmp_stack, sizeof(rawdmp_stack), RAWDUMP_PRIO, THREAD_CREATE_STACKTEST, rawdump, NULL, "rawdump"); dump.demux_ctx = GNRC_NETREG_DEMUX_CTX_ALL; gnrc_netreg_register(GNRC_NETTYPE_UNDEF, &dump); /* start the shell */ puts("All ok, starting the shell now"); char line_buf[SHELL_DEFAULT_BUFSIZE]; shell_run(NULL, line_buf, SHELL_DEFAULT_BUFSIZE); return 0; }
NJasp/netwerkmesh
meshdemo/main.c
#define Q_SZ 64 #include <stdio.h> #include "shell.h" #include "msg.h" #include "thread.h" #include "net/gnrc.h" #include "net/gnrc/netif.h" #include "net/gnrc/netreg.h" #include "net/gnrc/ipv6.h" #define MAIN_QUEUE_SIZE (8) extern int udp_cmd(int argc, char **argv); extern void start_server(char *port_str); static kernel_pid_t led_pid; static msg_t main_msg_q[Q_SZ]; static char _ledstack[THREAD_STACKSIZE_SMALL]; // No large stack size neccesary, so using small stack static kernel_pid_t udp_pid; static char _udp_receive_stack[THREAD_STACKSIZE_MAIN]; static char _stack[THREAD_STACKSIZE_MAIN]; static const shell_command_t shell_commands[] = { { "udp", "send data over UDP and listen on UDP ports", udp_cmd }, { NULL, NULL, NULL } }; // Give LED thread a kernel pid and a stack // Function containing the code to be exectued in the LED thread static void *_led_fwd_eventloop(void *arg) { while(1) { // Write LED high, wait 1 second and write LED low gpio_write(GPIO4, 1); xtimer_sleep(1); gpio_write(GPIO4, 0); // Set thread to sleeping, when new message arrives the thread will be waken up thread_sleep(); } /* never reached */ return NULL; } //Scheduled task to receive udp packets void *_udp_receive_loop(void *arg) { //Variable for message queue used by application layer static msg_t _msg_q[Q_SZ]; //Create a message to reply with msg_t msg, reply; reply.type = GNRC_NETAPI_MSG_TYPE_ACK; reply.content.value = -ENOTSUP; //Initialize the message queue with the static queue size msg_init_queue(_msg_q, Q_SZ); //Create a empty UDP packet pointer that will be used to point to the data of the udp packet gnrc_pktsnip_t *pkt = NULL; gnrc_netreg_entry_t me_reg; //Setup the thread and port number that is used me_reg.demux_ctx = 88; me_reg.target.pid = thread_getpid(); //Register this thread to be used as udp receive thread gnrc_netreg_register(GNRC_NETTYPE_UDP, &me_reg); while (1) { //Listen on incoming messages msg_receive(&msg); //If a message is received, lookup the type of message switch (msg.type) { //Message is a incoming message case GNRC_NETAPI_MSG_TYPE_RCV: //Set the packet pointer to the data of the message pkt = msg.content.ptr; //Print the data of the packet printf("UDP message received: %s\n", (char*)pkt->data); break; //Message is a outgoing message case GNRC_NETAPI_MSG_TYPE_SND: //Set the packet pointer to the data of the message pkt = msg.content.ptr; //Print the data of the packet printf("UDP message send: %s\n", (char*)pkt->data); break; case GNRC_NETAPI_MSG_TYPE_SET: case GNRC_NETAPI_MSG_TYPE_GET: msg_reply(&msg, &reply); break; default: break; } } return NULL; } #ifdef MODULE_GNRC_SIXLOWPAN static void *_ipv6_fwd_eventloop(void *arg) { (void)arg; msg_t msg, msg_q[8]; gnrc_netreg_entry_t me_reg = GNRC_NETREG_ENTRY_INIT_PID(GNRC_NETREG_DEMUX_CTX_ALL, thread_getpid()); msg_init_queue(msg_q, 8); gnrc_netreg_register(GNRC_NETTYPE_SIXLOWPAN, &me_reg); while(1) { msg_receive(&msg); gnrc_pktsnip_t *pkt = msg.content.ptr; if(msg.type == GNRC_NETAPI_MSG_TYPE_SND) { gnrc_pktsnip_t *ipv6 = gnrc_pktsnip_search_type(pkt, GNRC_NETTYPE_IPV6); ipv6_addr_t addrs[GNRC_NETIF_IPV6_ADDRS_NUMOF]; int res; ipv6 = ipv6->data; ipv6_hdr_t *ipv6_hdr =(ipv6_hdr_t *)ipv6; /* get the first IPv6 interface and prints its address */ gnrc_netif_t *netif = gnrc_netif_iter(NULL); res = gnrc_netif_ipv6_addrs_get(netif, addrs, sizeof(addrs)); if (res < 0) { /* an error occurred, just continue */ continue; } for (unsigned i = 0; i < (res / sizeof(ipv6_addr_t)); i++) { if ((!ipv6_addr_is_link_local(&addrs[i])) && (!ipv6_addr_is_link_local(&ipv6_hdr->src)) && (!ipv6_addr_is_link_local(&ipv6_hdr->dst)) && (!ipv6_addr_equal(&addrs[i], &(ipv6_hdr->src)))) { thread_wakeup(led_pid); // Wake up the LED thread, indicating a routing message has been received char addr_str[IPV6_ADDR_MAX_STR_LEN]; printf("IPv6 ROUTER: forward from src = %s ", ipv6_addr_to_str(addr_str, &(ipv6_hdr->src), sizeof(addr_str)) ); printf("to dst = %s\n", ipv6_addr_to_str(addr_str, &(ipv6_hdr->dst), sizeof(addr_str))); } } } gnrc_pktbuf_release(pkt); } /* never reached */ return NULL; } #endif int main(void) { msg_init_queue(main_msg_q, Q_SZ); gpio_init(GPIO4, GPIO_OUT); led_pid = thread_create(_ledstack, sizeof(_ledstack), (THREAD_PRIORITY_MAIN - 5), THREAD_CREATE_STACKTEST, _led_fwd_eventloop, NULL, "led_fwd"); udp_pid = thread_create(_udp_receive_stack, sizeof(_udp_receive_stack), (THREAD_PRIORITY_MAIN - 6), THREAD_CREATE_STACKTEST, _udp_receive_loop, NULL, "udp_receive"); start_server("88"); #ifdef MODULE_GNRC_SIXLOWPAN thread_create(_stack, sizeof(_stack), (THREAD_PRIORITY_MAIN - 4), THREAD_CREATE_STACKTEST, _ipv6_fwd_eventloop, NULL, "ipv6_fwd"); #endif /* start shell */ puts("All up, running the shell now"); char line_buf[SHELL_DEFAULT_BUFSIZE]; shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE); /* should be never reached */ return 0; }
NJasp/netwerkmesh
stm32_test/send_test/main.c
<gh_stars>0 #include <stdio.h> #include <mrf24j40.h> #include <mrf24j40_params.h> mrf24j40_t sender; uint8_t data = 8; int main(void) { /* init mrf24j40 */ mrf24j40_setup(&sender, mrf24j40_params); mrf24j40_reset(&sender); /* init for sending */ mrf24j40_tx_prepare(&sender); mrf24j40_tx_load(&sender, &data, 1, 0); while (1) { mrf24j40_tx_exec(&sender); } return 0; }
NJasp/netwerkmesh
stm32_test/recv_test/main.c
<filename>stm32_test/recv_test/main.c<gh_stars>0 #include <stdio.h> #include <mrf24j40.h> #include <mrf24j40_internal.h> #include <mrf24j40_params.h> int main(void) { /* init mrf24j40 */ mrf24j40_t dev; mrf24j40_setup(&dev, mrf24j40_params); mrf24j40_reset(&dev); while(1) { uint8_t buf; mrf24j40_rx_fifo_read(&dev, 0, &buf, 1); if (buf != 0) { printf("\rreceived: %d:\t'%c'\n", buf, buf); } } return 0; }
fpfis/vmod-drupal7
src/vmod_drupal7.c
#include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> //#include "vrt.h" #include "vsha256.h" #include "cache/cache.h" #include "vcc_if.h" int init_function(struct vmod_priv *priv, const struct VCL_conf *conf) { return 0; } /* * Given a HTTP Host and a base path, return the resulting Drupal session name. * Useful to compute the session cookie name of known Drupal sites. * This function is equivalent to suffixing SESS with the result of: * php -r 'echo substr(hash("sha256", "domain/base-path"), 0, 32);' */ VCL_STRING vmod_session_name(const struct vrt_ctx *ctx, VCL_STRING host, VCL_STRING base_path) { char *session_name; SHA256_CTX *sha256_ctx; unsigned char *digest; signed int format_result; // We need 4 characters for "SESS" + the first 32 characters of the SHA256 hash + \0. session_name = (char *)WS_Alloc(ctx->ws, 37); if (session_name == NULL) { VSL(SLT_Debug, 0, "drupal7-vmod: Unable to allocate return string to compute session name, abort"); return NULL; } sha256_ctx = (SHA256_CTX *)WS_Alloc(ctx->ws, sizeof(SHA256_CTX)); if (sha256_ctx == NULL) { VSL(SLT_Debug, 0, "drupal7-vmod: Unable to allocate SHA256 context to compute session name, abort"); return NULL; } digest = (unsigned char *)WS_Alloc(ctx->ws, 32); if (digest == NULL) { VSL(SLT_Debug, 0, "drupal7-vmod: Unable to allocate SHA256 digest to compute session name, abort"); return NULL; } // Initialize a SHA256 context. SHA256_Init(sha256_ctx); // Fill it with the host and base path. if (host != NULL) { SHA256_Update(sha256_ctx, host, strlen(host)); } if (base_path != NULL) { SHA256_Update(sha256_ctx, base_path, strlen(base_path)); } // Retrieve the resulting SHA256 digest... SHA256_Final(digest, sha256_ctx); // ... and express its first 128 bytes (Big Endian-wise) as 16 pairs of // hexadecimal digits. format_result = snprintf( session_name, 37, "SESS%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15] ); // We do not expect snprintf() to return anything else than "I have written 36 chars". if (format_result != 36) { VSL(SLT_Debug, 0, "drupal7-vmod: snprintf failed (returned %d) to format session name, abort", format_result); return NULL; } return session_name; }
SearyBlue/st
colors/base16-chalk-theme.h
<gh_stars>0 /* * base16-chalk-theme.h * * Base16: (https://github.com/chriskempson/base16) * * Authors: * * Scheme: <NAME> (http://chriskempson.com) * Template: <NAME> <<EMAIL>> * */ static const char *colorname[] = { "#202020", /* base00 */ "#fb9fb1", /* base08 */ "#acc267", /* base0B */ "#ddb26f", /* base0A */ "#6fc2ef", /* base0D */ "#e1a3ee", /* base0E */ "#12cfc0", /* base0C */ "#d0d0d0", /* base05 */ "#505050", /* base03 */ "#eda987", /* base09 */ "#202020", /* base01 */ "#303030", /* base02 */ "#b0b0b0", /* base04 */ "#e0e0e0", /* base06 */ "#deaf8f", /* base0F */ "#f5f5f5", /* base07 */ }; unsigned int defaultfg = 7; unsigned int defaultbg = 0; static unsigned int defaultcs = 13; static unsigned int defaultrcs = 0;
SearyBlue/st
colors/base16-zenburn-theme.h
/* * base16-zenburn-theme.h * * Base16: (https://github.com/chriskempson/base16) * * Authors: * * Scheme: elnawe * Template: <NAME> <<EMAIL>> * */ static const char *colorname[] = { "#3f3f3f", /* base00 */ "#dca3a3", /* base08 */ "#5f7f5f", /* base0B */ "#e0cf9f", /* base0A */ "#7cb8bb", /* base0D */ "#dc8cc3", /* base0E */ "#93e0e3", /* base0C */ "#dcdccc", /* base05 */ "#4f4f4f", /* base03 */ "#dfaf8f", /* base09 */ "#404040", /* base01 */ "#606060", /* base02 */ "#808080", /* base04 */ "#c0c0c0", /* base06 */ "#000000", /* base0F */ "#ffffff", /* base07 */ }; unsigned int defaultfg = 7; unsigned int defaultbg = 0; static unsigned int defaultcs = 13; static unsigned int defaultrcs = 0;
shaonianzhentan/raspberry-xunfei
include/msp_cmn.h
<reponame>shaonianzhentan/raspberry-xunfei /** * @file msp_cmn.h * @brief Mobile Speech Platform Common Interface Header File * * This file contains the quick common programming interface (API) declarations * of MSP. Developer can include this file in your project to build applications. * For more information, please read the developer guide. * Use of this software is subject to certain restrictions and limitations set * forth in a license agreement entered into between iFLYTEK, Co,LTD. * and the licensee of this software. Please refer to the license * agreement for license use rights and restrictions. * * Copyright (C) 1999 - 2015 by iFLYTEK, Co,LTD. * All rights reserved. * * @author MSC * @version 5.0 * @date 2015/03/19 * * @see * * <b>History:</b><br> * <table> * <tr> <th>Version <th>Date <th>Author <th>Notes</tr> * <tr> <td>5.0 <td> 2015/03/19 <td>MSC <td>Create this file</tr> *</table> */ #ifndef __MSP_CMN_H__ #define __MSP_CMN_H__ #include "msp_types.h" #ifdef __cplusplus extern "C" { #endif /* C++ */ /** * @fn MSPLogin * @brief user login interface * * User login. * * @return int MSPAPI - Return 0 in success, otherwise return error code. * @param const char* usr - [in] user name. * @param const char* pwd - [in] password. * @param const char* params - [in] parameters when user login. * @see */ int MSPAPI MSPLogin(const char* usr, const char* pwd, const char* params); typedef int (MSPAPI *Proc_MSPLogin)(const char* usr, const char* pwd, const char* params); /** * @fn MSPLogout * @brief user logout interface * * User logout * * @return int MSPAPI - Return 0 in success, otherwise return error code. * @see */ int MSPAPI MSPLogout(); typedef int (MSPAPI *Proc_MSPLogout)(); /** * @fn MSPGetResult * @brief Get Result * * Get result of uploading, downloading or searching, etc. * * @return const char* MSPAPI - Return result of uploading, downloading or searching, etc. * @param int* rsltLen - [out] Length of result returned. * @param int* rsltStatus - [out] Status of result returned. * @param int* errorCode - [out] Return 0 in success, otherwise return error code. * @see */ const char* MSPAPI MSPGetResult(unsigned int* rsltLen, int* rsltStatus, int *errorCode); typedef const char * (MSPAPI *Proc_MSPGetResult)(unsigned int* rsltLen, int* rsltStatus, int *errorCode); /** * @fn MSPSetParam * @brief set params of msc * * set param of msc * * @return int - Return 0 if success, otherwise return errcode. * @param const char* paramName - [in] param name. * @param const char* paramValue - [in] param value * @see */ int MSPAPI MSPSetParam( const char* paramName, const char* paramValue ); typedef int (MSPAPI *Proc_MSPSetParam)(const char* paramName, const char* paramValue); /** * @fn MSPGetParam * @brief get params of msc * * get param of msc * * @return int - Return 0 if success, otherwise return errcode. * @param const char* paramName - [in] param name. * @param const char* paramValue - [out] param value * @param const char* valueLen - [in/out] param value (buffer) length * @see */ int MSPAPI MSPGetParam( const char *paramName, char *paramValue, unsigned int *valueLen ); typedef int (MSPAPI *Proc_MSPGetParam)( const char *paramName, char *paramValue, unsigned int *valueLen ); /** * @fn MSPUploadData * @brief Upload User Specific Data * * Upload data such as user config, custom grammar, etc. * * @return const char* MSPAPI - data id returned by Server, used for special command. * @param const char* dataName - [in] data name, should be unique to diff other data. * @param void* data - [in] the data buffer pointer, data could be binary. * @param unsigned int dataLen - [in] length of data. * @param const char* params - [in] parameters about uploading data. * @param int* errorCode - [out] Return 0 in success, otherwise return error code. * @see */ const char* MSPAPI MSPUploadData(const char* dataName, void* data, unsigned int dataLen, const char* params, int* errorCode); typedef const char* (MSPAPI* Proc_MSPUploadData)(const char* dataName, void* data, unsigned int dataLen, const char* params, int* errorCode); /** * @fn MSPDownloadData * @brief Download User Specific Data * * Download data such as user config, etc. * * @return const void* MSPAPI - received data buffer pointer, data could be binary, NULL if failed or data does not exsit. * @param const char* params - [in] parameters about data to be downloaded. * @param unsigned int* dataLen - [out] length of received data. * @param int* errorCode - [out] Return 0 in success, otherwise return error code. * @see */ const void* MSPAPI MSPDownloadData(const char* params, unsigned int* dataLen, int* errorCode); typedef const void* (MSPAPI* Proc_MSPDownloadData)(const char* params, unsigned int* dataLen, int* errorCode); /** * @fn MSPSearch * @brief Search text for result * * Search text content, and got text result * * @return const void* MSPAPI - received data buffer pointer, data could be binary, NULL if failed or data does not exsit. * @param const char* params - [in] parameters about data to be downloaded. * @param unsigned int* dataLen - [out] length of received data. * @param int* errorCode - [out] Return 0 in success, otherwise return error code. * @see */ const char* MSPAPI MSPSearch(const char* params, const char* text, unsigned int* dataLen, int* errorCode); typedef const char* (MSPAPI* Proc_MSPSearch)(const char* params, const char* text, unsigned int* dataLen, int* errorCode); typedef int (*NLPSearchCB)(const char *sessionID, int errorCode, int status, const void* result, long rsltLen, void *userData); const char* MSPAPI MSPNlpSearch(const char* params, const char* text, unsigned int textLen, int *errorCode, NLPSearchCB callback, void *userData); typedef const char* (MSPAPI* Proc_MSPNlpSearch)(const char* params, const char* text, unsigned int textLen, int *errorCode, NLPSearchCB callback, void *userData); int MSPAPI MSPNlpSchCancel(const char *sessionID, const char *hints); /** * @fn MSPRegisterNotify * @brief Register a Callback * * Register a Callback * * @return int - * @param msp_status_ntf_handler statusCb - [in] notify handler * @param void *userData - [in] userData * @see */ typedef void ( *msp_status_ntf_handler)( int type, int status, int param1, const void *param2, void *userData ); int MSPAPI MSPRegisterNotify( msp_status_ntf_handler statusCb, void *userData ); typedef const char* (MSPAPI* Proc_MSPRegisterNotify)( msp_status_ntf_handler statusCb, void *userData ); #ifdef __cplusplus } /* extern "C" */ #endif /* C++ */ #endif /* __MSP_CMN_H__ */
shaonianzhentan/raspberry-xunfei
include/msp_types.h
<reponame>shaonianzhentan/raspberry-xunfei #ifndef __MSP_TYPES_H__ #define __MSP_TYPES_H__ #if !defined(MSPAPI) #if defined(WIN32) #define MSPAPI __stdcall #else #define MSPAPI #endif /* WIN32 */ #endif /* MSPAPI */ /** * MSPSampleStatus indicates how the sample buffer should be handled * MSP_AUDIO_SAMPLE_FIRST - The sample buffer is the start of audio * If recognizer was already recognizing, it will discard * audio received to date and re-start the recognition * MSP_AUDIO_SAMPLE_CONTINUE - The sample buffer is continuing audio * MSP_AUDIO_SAMPLE_LAST - The sample buffer is the end of audio * The recognizer will cease processing audio and * return results * Note that sample statii can be combined; for example, for file-based input * the entire file can be written with SAMPLE_FIRST | SAMPLE_LAST as the * status. * Other flags may be added in future to indicate other special audio * conditions such as the presence of AGC */ enum { MSP_AUDIO_SAMPLE_INIT = 0x00, MSP_AUDIO_SAMPLE_FIRST = 0x01, MSP_AUDIO_SAMPLE_CONTINUE = 0x02, MSP_AUDIO_SAMPLE_LAST = 0x04, }; /* * The enumeration MSPRecognizerStatus contains the recognition status * MSP_REC_STATUS_SUCCESS - successful recognition with partial results * MSP_REC_STATUS_NO_MATCH - recognition rejected * MSP_REC_STATUS_INCOMPLETE - recognizer needs more time to compute results * MSP_REC_STATUS_NON_SPEECH_DETECTED - discard status, no more in use * MSP_REC_STATUS_SPEECH_DETECTED - recognizer has detected audio, this is delayed status * MSP_REC_STATUS_COMPLETE - recognizer has return all result * MSP_REC_STATUS_MAX_CPU_TIME - CPU time limit exceeded * MSP_REC_STATUS_MAX_SPEECH - maximum speech length exceeded, partial results may be returned * MSP_REC_STATUS_STOPPED - recognition was stopped * MSP_REC_STATUS_REJECTED - recognizer rejected due to low confidence * MSP_REC_STATUS_NO_SPEECH_FOUND - recognizer still found no audio, this is delayed status */ enum { MSP_REC_STATUS_SUCCESS = 0, MSP_REC_STATUS_NO_MATCH = 1, MSP_REC_STATUS_INCOMPLETE = 2, MSP_REC_STATUS_NON_SPEECH_DETECTED = 3, MSP_REC_STATUS_SPEECH_DETECTED = 4, MSP_REC_STATUS_COMPLETE = 5, MSP_REC_STATUS_MAX_CPU_TIME = 6, MSP_REC_STATUS_MAX_SPEECH = 7, MSP_REC_STATUS_STOPPED = 8, MSP_REC_STATUS_REJECTED = 9, MSP_REC_STATUS_NO_SPEECH_FOUND = 10, MSP_REC_STATUS_FAILURE = MSP_REC_STATUS_NO_MATCH, }; /** * The enumeration MSPepState contains the current endpointer state * MSP_EP_LOOKING_FOR_SPEECH - Have not yet found the beginning of speech * MSP_EP_IN_SPEECH - Have found the beginning, but not the end of speech * MSP_EP_AFTER_SPEECH - Have found the beginning and end of speech * MSP_EP_TIMEOUT - Have not found any audio till timeout * MSP_EP_ERROR - The endpointer has encountered a serious error * MSP_EP_MAX_SPEECH - Have arrive the max size of speech */ enum { MSP_EP_LOOKING_FOR_SPEECH = 0, MSP_EP_IN_SPEECH = 1, MSP_EP_AFTER_SPEECH = 3, MSP_EP_TIMEOUT = 4, MSP_EP_ERROR = 5, MSP_EP_MAX_SPEECH = 6, MSP_EP_IDLE = 7 // internal state after stop and before start }; /* Synthesizing process flags */ enum { MSP_TTS_FLAG_STILL_HAVE_DATA = 1, MSP_TTS_FLAG_DATA_END = 2, MSP_TTS_FLAG_CMD_CANCELED = 4, }; /* Handwriting process flags */ enum { MSP_HCR_DATA_FIRST = 1, MSP_HCR_DATA_CONTINUE = 2, MSP_HCR_DATA_END = 4, }; /*ivw message type */ enum { MSP_IVW_MSG_WAKEUP = 1, MSP_IVW_MSG_ERROR = 2, MSP_IVW_MSG_ISR_RESULT = 3, MSP_IVW_MSG_ISR_EPS = 4, MSP_IVW_MSG_VOLUME = 5, MSP_IVW_MSG_ENROLL = 6 }; /* Upload data process flags */ enum { MSP_DATA_SAMPLE_INIT = 0x00, MSP_DATA_SAMPLE_FIRST = 0x01, MSP_DATA_SAMPLE_CONTINUE = 0x02, MSP_DATA_SAMPLE_LAST = 0x04, }; #endif /* __MSP_TYPES_H__ */
rcr/libgrapheme
data/grapheme_boundary.c
<reponame>rcr/libgrapheme /* See LICENSE file for copyright and license details. */ #include <stddef.h> #include <stdio.h> #include <string.h> #include "datautil.h" static struct { char *enumname; char *identifier; struct range *table; size_t tablelen; } properties[] = { { /* carriage return */ .enumname = "GB_PROP_CR", .identifier = "CR", }, { /* line feed */ .enumname = "GB_PROP_LF", .identifier = "LF", }, { /* control character */ .enumname = "GB_PROP_CONTROL", .identifier = "Control", }, { /* grapheme extender */ .enumname = "GB_PROP_EXTEND", .identifier = "Extend", }, { /* zero width joiner */ .enumname = "GB_PROP_ZWJ", .identifier = "ZWJ", }, { /* regional indicator */ .enumname = "GB_PROP_REGIONAL_INDICATOR", .identifier = "Regional_Indicator", }, { /* prepend character */ .enumname = "GB_PROP_PREPEND", .identifier = "Prepend", }, { /* spacing mark */ .enumname = "GB_PROP_SPACINGMARK", .identifier = "SpacingMark", }, { /* hangul syllable type L */ .enumname = "GB_PROP_L", .identifier = "L", }, { /* hangul syllable type V */ .enumname = "GB_PROP_V", .identifier = "V", }, { /* hangul syllable type T */ .enumname = "GB_PROP_T", .identifier = "T", }, { /* hangul syllable type LV */ .enumname = "GB_PROP_LV", .identifier = "LV", }, { /* hangul syllable type LVT */ .enumname = "GB_PROP_LVT", .identifier = "LVT", }, }; int process_line(char **field, size_t nfields, char *comment) { size_t i; struct range r; (void)comment; if (nfields < 2) { return 1; } for (i = 0; i < LEN(properties); i++) { if (!strcmp(field[1], properties[i].identifier)) { if (range_parse(field[0], &r)) { return 1; } range_list_append(&(properties[i].table), &(properties[i].tablelen), &r); break; } } return 0; } int main(void) { size_t i, j; printf("/* Automatically generated by data/gbp */\n" "#include <stdint.h>\n\n#include \"../src/util.h\"\n\n"); parse_input(process_line); /* output enum */ printf("enum gb_prop {\n"); for (i = 0; i < LEN(properties); i++) { printf("\t%s,\n", properties[i].enumname); } printf("};\n\n"); /* output table */ printf("static const struct range_list gb_prop[] = {\n"); for (i = 0; i < LEN(properties); i++) { printf("\t[%s] = {\n\t\t.data = (struct range[]){\n", properties[i].enumname); for (j = 0; j < properties[i].tablelen; j++) { printf("\t\t\t{ UINT32_C(0x%06X), UINT32_C(0x%06X) },\n", properties[i].table[j].lower, properties[i].table[j].upper); } printf("\t\t},\n\t\t.len = %zu,\n\t},\n", properties[i].tablelen); } printf("};\n"); return 0; }
rcr/libgrapheme
src/grapheme.c
/* See LICENSE file for copyright and license details. */ #include <stddef.h> #include <stdlib.h> #include "../grapheme.h" size_t grapheme_bytelen(const char *str) { uint32_t cp0, cp1; size_t ret, len = 0; int state = 0; if (str == NULL) { return 0; } /* * grapheme_cp_decode, when it encounters an unexpected byte, * does not count it to the error and instead assumes that the * unexpected byte is the beginning of a new sequence. * This way, when the string ends with a null byte, we never * miss it, even if the previous UTF-8 sequence terminates * unexpectedly, as it would either act as an unexpected byte, * saved for later, or as a null byte itself, that we can catch. * We pass 5 to the length, as we will never read beyond * the null byte for the reasons given above. */ /* get first code point */ len += grapheme_cp_decode(&cp0, (uint8_t *)str, 5); if (cp0 == GRAPHEME_CP_INVALID) { return len; } while (cp0 != 0) { /* get next code point */ ret = grapheme_cp_decode(&cp1, (uint8_t *)(str + len), 5); if (cp1 == GRAPHEME_CP_INVALID || grapheme_boundary(cp0, cp1, &state)) { /* we read an invalid cp or have a breakpoint */ break; } else { /* we don't have a breakpoint, continue */ len += ret; } /* prepare next round */ cp0 = cp1; } return len; }
rcr/libgrapheme
test/utf8-encode.c
<reponame>rcr/libgrapheme /* See LICENSE file for copyright and license details. */ #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "../grapheme.h" #define LEN(x) (sizeof(x) / sizeof(*x)) static const struct { uint32_t cp; /* input code point */ uint8_t *exp_arr; /* expected UTF-8 byte sequence */ size_t exp_len; /* expected length of UTF-8 sequence */ } enc_test[] = { { /* invalid code point (UTF-16 surrogate half) */ .cp = UINT32_C(0xD800), .exp_arr = (uint8_t[]){ 0xEF, 0xBF, 0xBD }, .exp_len = 3, }, { /* invalid code point (UTF-16-unrepresentable) */ .cp = UINT32_C(0x110000), .exp_arr = (uint8_t[]){ 0xEF, 0xBF, 0xBD }, .exp_len = 3, }, { /* code point encoded to a 1-byte sequence */ .cp = 0x01, .exp_arr = (uint8_t[]){ 0x01 }, .exp_len = 1, }, { /* code point encoded to a 2-byte sequence */ .cp = 0xFF, .exp_arr = (uint8_t[]){ 0xC3, 0xBF }, .exp_len = 2, }, { /* code point encoded to a 3-byte sequence */ .cp = 0xFFF, .exp_arr = (uint8_t[]){ 0xE0, 0xBF, 0xBF }, .exp_len = 3, }, { /* code point encoded to a 4-byte sequence */ .cp = UINT32_C(0xFFFFF), .exp_arr = (uint8_t[]){ 0xF3, 0xBF, 0xBF, 0xBF }, .exp_len = 4, }, }; int main(void) { size_t i, j, failed; /* UTF-8 encoder test */ for (i = 0, failed = 0; i < LEN(enc_test); i++) { uint8_t arr[4]; size_t len; len = grapheme_cp_encode(enc_test[i].cp, arr, LEN(arr)); if (len != enc_test[i].exp_len || memcmp(arr, enc_test[i].exp_arr, len)) { fprintf(stderr, "Failed UTF-8-encoder test %zu: " "Expected (", i); for (j = 0; j < enc_test[i].exp_len; j++) { fprintf(stderr, "0x%x", enc_test[i].exp_arr[j]); if (j + 1 < enc_test[i].exp_len) { fprintf(stderr, " "); } } fprintf(stderr, "), but got ("); for (j = 0; j < len; j++) { fprintf(stderr, "0x%x", arr[j]); if (j + 1 < len) { fprintf(stderr, " "); } } fprintf(stderr, ")\n"); failed++; } } printf("UTF-8 encoder test: Passed %zu out of %zu tests.\n", LEN(enc_test) - failed, LEN(enc_test)); return (failed > 0) ? 1 : 0; }
rcr/libgrapheme
grapheme.h
/* See LICENSE file for copyright and license details. */ #ifndef GRAPHEME_H #define GRAPHEME_H #include <stddef.h> #include <stdint.h> #define GRAPHEME_CP_INVALID UINT32_C(0xFFFD) int grapheme_boundary(uint32_t, uint32_t, int *); size_t grapheme_bytelen(const char *); size_t grapheme_cp_decode(uint32_t *, const uint8_t *, size_t); size_t grapheme_cp_encode(uint32_t, uint8_t *, size_t); #endif /* GRAPHEME_H */
rcr/libgrapheme
data/emoji.c
<filename>data/emoji.c /* See LICENSE file for copyright and license details. */ #include <stddef.h> #include <stdio.h> #include <string.h> #include "datautil.h" static struct { char *enumname; char *identifier; struct range *table; size_t tablelen; } properties[] = { { /* extended pictographic */ .enumname = "EMOJI_PROP_EXTPICT", .identifier = "Extended_Pictographic", }, }; int process_line(char **field, size_t nfields, char *comment) { size_t i; struct range r; (void)comment; if (nfields < 2) { return 1; } for (i = 0; i < LEN(properties); i++) { if (!strcmp(field[1], properties[i].identifier)) { if (range_parse(field[0], &r)) { return 1; } range_list_append(&(properties[i].table), &(properties[i].tablelen), &r); break; } } return 0; } int main(void) { size_t i, j; printf("/* Automatically generated by data/emo */\n" "#include <stdint.h>\n\n#include \"../src/util.h\"\n\n"); parse_input(process_line); /* output enum */ printf("enum emoji_prop {\n"); for (i = 0; i < LEN(properties); i++) { printf("\t%s,\n", properties[i].enumname); } printf("};\n\n"); /* output table */ printf("static const struct range_list emoji_prop[] = {\n"); for (i = 0; i < LEN(properties); i++) { printf("\t[%s] = {\n\t\t.data = (struct range[]){\n", properties[i].enumname); for (j = 0; j < properties[i].tablelen; j++) { printf("\t\t\t{ UINT32_C(0x%06X), UINT32_C(0x%06X) },\n", properties[i].table[j].lower, properties[i].table[j].upper); } printf("\t\t},\n\t\t.len = %zu,\n\t},\n", properties[i].tablelen); } printf("};\n"); return 0; }
rcr/libgrapheme
src/codepoint.c
/* See LICENSE file for copyright and license details. */ #include "../grapheme.h" #include <stdio.h> #define BETWEEN(c, l, u) (c >= l && c <= u) #define LEN(x) (sizeof(x) / sizeof(*x)) /* lookup-table for the types of sequence first bytes */ static const struct { uint8_t lower; /* lower bound of sequence first byte */ uint8_t upper; /* upper bound of sequence first byte */ uint32_t mincp; /* smallest non-overlong encoded code point */ uint32_t maxcp; /* largest encodable code point */ /* * implicit: table-offset represents the number of following * bytes of the form 10xxxxxx (6 bits capacity each) */ } lut[] = { [0] = { /* 0xxxxxxx */ .lower = 0x00, /* 00000000 */ .upper = 0x7F, /* 01111111 */ .mincp = (uint32_t)0, .maxcp = ((uint32_t)1 << 7) - 1, /* 7 bits capacity */ }, [1] = { /* 110xxxxx */ .lower = 0xC0, /* 11000000 */ .upper = 0xDF, /* 11011111 */ .mincp = (uint32_t)1 << 7, .maxcp = ((uint32_t)1 << 11) - 1, /* 5+6=11 bits capacity */ }, [2] = { /* 1110xxxx */ .lower = 0xE0, /* 11100000 */ .upper = 0xEF, /* 11101111 */ .mincp = (uint32_t)1 << 11, .maxcp = ((uint32_t)1 << 16) - 1, /* 4+6+6=16 bits capacity */ }, [3] = { /* 11110xxx */ .lower = 0xF0, /* 11110000 */ .upper = 0xF7, /* 11110111 */ .mincp = (uint32_t)1 << 16, .maxcp = ((uint32_t)1 << 21) - 1, /* 3+6+6+6=21 bits capacity */ }, }; size_t grapheme_cp_decode(uint32_t *cp, const uint8_t *s, size_t n) { size_t off, i; if (n == 0) { /* a sequence must be at least 1 byte long */ *cp = GRAPHEME_CP_INVALID; return 1; } /* identify sequence type with the first byte */ for (off = 0; off < LEN(lut); off++) { if (BETWEEN(s[0], lut[off].lower, lut[off].upper)) { /* * first byte is within the bounds; fill * p with the the first bits contained in * the first byte (by subtracting the high bits) */ *cp = s[0] - lut[off].lower; break; } } if (off == LEN(lut)) { /* * first byte does not match a sequence type; * set cp as invalid and return 1 byte processed */ *cp = GRAPHEME_CP_INVALID; return 1; } if (1 + off > n) { /* * input is not long enough, set cp as invalid and * return number of bytes needed */ *cp = GRAPHEME_CP_INVALID; return 1 + off; } /* * process 'off' following bytes, each of the form 10xxxxxx * (i.e. between 0x80 (10000000) and 0xBF (10111111)) */ for (i = 1; i <= off; i++) { if(!BETWEEN(s[i], 0x80, 0xBF)) { /* * byte does not match format; return * number of bytes processed excluding the * unexpected character as recommended since * Unicode 6 (chapter 3) */ *cp = GRAPHEME_CP_INVALID; return 1 + (i - 1); } /* * shift code point by 6 bits and add the 6 stored bits * in s[i] to it using the bitmask 0x3F (00111111) */ *cp = (*cp << 6) | (s[i] & 0x3F); } if (*cp < lut[off].mincp || BETWEEN(*cp, UINT32_C(0xD800), UINT32_C(0xDFFF)) || *cp > UINT32_C(0x10FFFF)) { /* * code point is overlong encoded in the sequence, is a * high or low UTF-16 surrogate half (0xD800..0xDFFF) or * not representable in UTF-16 (>0x10FFFF) (RFC-3629 * specifies the latter two conditions) */ *cp = GRAPHEME_CP_INVALID; } return 1 + off; } size_t grapheme_cp_encode(uint32_t cp, uint8_t *s, size_t n) { size_t off, i; if (BETWEEN(cp, UINT32_C(0xD800), UINT32_C(0xDFFF)) || cp > UINT32_C(0x10FFFF)) { /* * code point is a high or low UTF-16 surrogate half * (0xD800..0xDFFF) or not representable in UTF-16 * (>0x10FFFF), which RFC-3629 deems invalid for UTF-8. */ cp = GRAPHEME_CP_INVALID; } /* determine necessary sequence type */ for (off = 0; off < LEN(lut); off++) { if (cp <= lut[off].maxcp) { break; } } if (1 + off > n) { /* specified buffer is too small to store sequence */ return 1 + off; } /* build sequence by filling cp-bits into each byte */ /* * lut[off].lower is the bit-format for the first byte and * the bits to fill into it are determined by shifting the * cp 6 times the number of following bytes, as each * following byte stores 6 bits, yielding the wanted bits. * * We do not overwrite the mask because we guaranteed earlier * that there are no bits higher than the mask allows. */ s[0] = lut[off].lower | (cp >> (6 * off)); for (i = 1; i <= off; i++) { /* * the bit-format for following bytes is 10000000 (0x80) * and it each stores 6 bits in the 6 low bits that we * extract from the properly-shifted value using the * mask 00111111 (0x3F) */ s[i] = 0x80 | ((cp >> (6 * (off - i))) & 0x3F); } return 1 + off; }
rcr/libgrapheme
data/datautil.h
/* See LICENSE file for copyright and license details. */ #ifndef DATAUTIL_H #define DATAUTIL_H #include <stddef.h> #include <stdint.h> #define LEN(x) (sizeof (x) / sizeof *(x)) struct range { uint32_t lower; uint32_t upper; }; void parse_input(int (*process_line)(char **, size_t, char *)); int cp_parse(const char *, uint32_t *); int range_parse(const char *, struct range *); void range_list_append(struct range **, size_t *, const struct range *); #endif /* DATAUTIL_H */
rcr/libgrapheme
data/datautil.c
<reponame>rcr/libgrapheme<filename>data/datautil.c<gh_stars>0 /* See LICENSE file for copyright and license details. */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include "datautil.h" void parse_input(int (*process_line)(char **, size_t, char *)) { char *line = NULL, **field = NULL, *comment; size_t linebufsize = 0, i, fieldbufsize = 0, j, nfields; ssize_t len; while ((len = getline(&line, &linebufsize, stdin)) >= 0) { /* remove trailing newline */ if (len > 0 && line[len - 1] == '\n') { line[len - 1] = '\0'; len--; } /* skip empty lines and comment lines */ if (len == 0 || line[0] == '#') { continue; } /* tokenize line into fields */ for (i = 0, nfields = 0, comment = NULL; i < (size_t)len; i++) { /* extend field buffer, if necessary */ if (++nfields > fieldbufsize) { if ((field = realloc(field, nfields * sizeof(*field))) == NULL) { fprintf(stderr, "realloc: %s\n", strerror(errno)); exit(1); } fieldbufsize = nfields; } /* skip leading whitespace */ while (line[i] == ' ') { i++; } /* set current position as field start */ field[nfields - 1] = &line[i]; /* continue until we reach ';' or '#' or end */ while (line[i] != ';' && line[i] != '#' && line[i] != '\0') { i++; } if (line [i] == '#') { /* set comment-variable for later */ comment = &line[i + 1]; } /* go back whitespace and terminate field there */ if (i > 0) { for (j = i - 1; line[j] == ' '; j--) ; line[j + 1] = '\0'; } else { line[i] = '\0'; } /* if comment is set, we are done */ if (comment != NULL) { break; } } /* skip leading whitespace in comment */ while (comment != NULL && comment[0] == ' ') { comment++; } /* call line processing function */ if (process_line(field, nfields, comment)) { exit(1); } } free(line); free(field); } static int valid_hexstring(const char *str) { const char *p = str; while ((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F')) { p++; } if (*p != '\0') { fprintf(stderr, "invalid code point range '%s'\n", str); return 0; } return 1; } int cp_parse(const char *str, uint32_t *cp) { if (!valid_hexstring(str)) { return 1; } *cp = strtol(str, NULL, 16); return 0; } int range_parse(const char *str, struct range *range) { char *p; if ((p = strstr(str, "..")) == NULL) { /* input has the form "XXXXXX" */ if (!valid_hexstring(str)) { return 1; } range->lower = range->upper = strtol(str, NULL, 16); } else { /* input has the form "XXXXXX..XXXXXX" */ *p = '\0'; p += 2; if (!valid_hexstring(str) || !valid_hexstring(p)) { return 1; } range->lower = strtol(str, NULL, 16); range->upper = strtol(p, NULL, 16); } return 0; } void range_list_append(struct range **range, size_t *nranges, const struct range *new) { if (*nranges > 0 && (*range)[*nranges - 1].upper == new->lower) { /* we can merge with previous entry */ (*range)[*nranges - 1].upper = new->upper; } else { /* need to append new entry */ if ((*range = realloc(*range, (++(*nranges)) * sizeof(**range))) == NULL) { fprintf(stderr, "realloc: %s\n", strerror(errno)); exit(1); } (*range)[*nranges - 1].lower = new->lower; (*range)[*nranges - 1].upper = new->upper; } }
rcr/libgrapheme
src/util.h
<gh_stars>0 /* See LICENSE file for copyright and license details. */ #ifndef UTIL_H #define UTIL_H #include <stddef.h> #include <stdint.h> #define LEN(x) (sizeof (x) / sizeof *(x)) struct range { uint32_t lower; uint32_t upper; }; struct range_list { struct range *data; size_t len; }; /* 16-slot (0,...,15) optionally undetermined binary state */ struct heisenstate { uint_least16_t determined; uint_least16_t state; }; int heisenstate_get(struct heisenstate *, int); int heisenstate_set(struct heisenstate *, int, int); #endif /* UTIL_H */
rcr/libgrapheme
test/grapheme_boundary.c
/* See LICENSE file for copyright and license details. */ #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "../grapheme.h" #include "../data/grapheme_boundary_test.h" #define LEN(x) (sizeof(x) / sizeof(*x)) int main(void) { int state; size_t i, j, k, len, failed; /* grapheme break test */ for (i = 0, failed = 0; i < LEN(t); i++) { for (j = 0, k = 0, state = 0, len = 1; j < t[i].cplen; j++) { if ((j + 1) == t[i].cplen || grapheme_boundary(t[i].cp[j], t[i].cp[j + 1], &state)) { /* check if our resulting length matches */ if (k == t[i].lenlen || len != t[i].len[k++]) { fprintf(stderr, "Failed \"%s\"\n", t[i].descr); failed++; break; } len = 1; } else { len++; } } } printf("Grapheme break test: Passed %zu out of %zu tests.\n", LEN(t) - failed, LEN(t)); return (failed > 0) ? 1 : 0; }
rcr/libgrapheme
test/utf8-decode.c
/* See LICENSE file for copyright and license details. */ #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "../grapheme.h" #define LEN(x) (sizeof(x) / sizeof(*x)) static const struct { uint8_t *arr; /* UTF-8 byte sequence */ size_t len; /* length of UTF-8 byte sequence */ size_t exp_len; /* expected length returned */ uint32_t exp_cp; /* expected code point returned */ } dec_test[] = { { /* empty sequence * [ ] -> * INVALID */ .arr = NULL, .len = 0, .exp_len = 1, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid lead byte * [ 11111101 ] -> * INVALID */ .arr = (uint8_t[]){ 0xFD }, .len = 1, .exp_len = 1, .exp_cp = GRAPHEME_CP_INVALID, }, { /* valid 1-byte sequence * [ 00000001 ] -> * 0000001 */ .arr = (uint8_t[]){ 0x01 }, .len = 1, .exp_len = 1, .exp_cp = 0x1, }, { /* valid 2-byte sequence * [ 11000011 10111111 ] -> * 00011111111 */ .arr = (uint8_t[]){ 0xC3, 0xBF }, .len = 2, .exp_len = 2, .exp_cp = 0xFF, }, { /* invalid 2-byte sequence (second byte missing) * [ 11000011 ] -> * INVALID */ .arr = (uint8_t[]){ 0xC3 }, .len = 1, .exp_len = 2, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 2-byte sequence (second byte malformed) * [ 11000011 11111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xC3, 0xFF }, .len = 2, .exp_len = 1, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 2-byte sequence (overlong encoded) * [ 11000001 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xC1, 0xBF }, .len = 2, .exp_len = 2, .exp_cp = GRAPHEME_CP_INVALID, }, { /* valid 3-byte sequence * [ 11100000 10111111 10111111 ] -> * 0000111111111111 */ .arr = (uint8_t[]){ 0xE0, 0xBF, 0xBF }, .len = 3, .exp_len = 3, .exp_cp = 0xFFF, }, { /* invalid 3-byte sequence (second byte missing) * [ 11100000 ] -> * INVALID */ .arr = (uint8_t[]){ 0xE0 }, .len = 1, .exp_len = 3, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 3-byte sequence (second byte malformed) * [ 11100000 01111111 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xE0, 0x7F, 0xBF }, .len = 3, .exp_len = 1, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 3-byte sequence (third byte missing) * [ 11100000 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xE0, 0xBF }, .len = 2, .exp_len = 3, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 3-byte sequence (third byte malformed) * [ 11100000 10111111 01111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xE0, 0xBF, 0x7F }, .len = 3, .exp_len = 2, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 3-byte sequence (overlong encoded) * [ 11100000 10011111 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xE0, 0x9F, 0xBF }, .len = 3, .exp_len = 3, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 3-byte sequence (UTF-16 surrogate half) * [ 11101101 10100000 10000000 ] -> * INVALID */ .arr = (uint8_t[]){ 0xED, 0xA0, 0x80 }, .len = 3, .exp_len = 3, .exp_cp = GRAPHEME_CP_INVALID, }, { /* valid 4-byte sequence * [ 11110011 10111111 10111111 10111111 ] -> * 011111111111111111111 */ .arr = (uint8_t[]){ 0xF3, 0xBF, 0xBF, 0xBF }, .len = 4, .exp_len = 4, .exp_cp = UINT32_C(0xFFFFF), }, { /* invalid 4-byte sequence (second byte missing) * [ 11110011 ] -> * INVALID */ .arr = (uint8_t[]){ 0xF3 }, .len = 1, .exp_len = 4, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 4-byte sequence (second byte malformed) * [ 11110011 01111111 10111111 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xF3, 0x7F, 0xBF, 0xBF }, .len = 4, .exp_len = 1, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 4-byte sequence (third byte missing) * [ 11110011 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xF3, 0xBF }, .len = 2, .exp_len = 4, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 4-byte sequence (third byte malformed) * [ 11110011 10111111 01111111 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xF3, 0xBF, 0x7F, 0xBF }, .len = 4, .exp_len = 2, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 4-byte sequence (fourth byte missing) * [ 11110011 10111111 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xF3, 0xBF, 0xBF }, .len = 3, .exp_len = 4, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 4-byte sequence (fourth byte malformed) * [ 11110011 10111111 10111111 01111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xF3, 0xBF, 0xBF, 0x7F }, .len = 4, .exp_len = 3, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 4-byte sequence (overlong encoded) * [ 11110000 10000000 10000001 10111111 ] -> * INVALID */ .arr = (uint8_t[]){ 0xF0, 0x80, 0x81, 0xBF }, .len = 4, .exp_len = 4, .exp_cp = GRAPHEME_CP_INVALID, }, { /* invalid 4-byte sequence (UTF-16-unrepresentable) * [ 11110100 10010000 10000000 10000000 ] -> * INVALID */ .arr = (uint8_t[]){ 0xF4, 0x90, 0x80, 0x80 }, .len = 4, .exp_len = 4, .exp_cp = GRAPHEME_CP_INVALID, }, }; int main(void) { size_t i, failed; /* UTF-8 decoder test */ for (i = 0, failed = 0; i < LEN(dec_test); i++) { size_t len; uint32_t cp; len = grapheme_cp_decode(&cp, dec_test[i].arr, dec_test[i].len); if (len != dec_test[i].exp_len || cp != dec_test[i].exp_cp) { fprintf(stderr, "Failed UTF-8-decoder test %zu: " "Expected (%zx,%u), but got (%zx,%u)\n", i, dec_test[i].exp_len, dec_test[i].exp_cp, len, cp); failed++; } } printf("UTF-8 decoder test: Passed %zu out of %zu tests.\n", LEN(dec_test) - failed, LEN(dec_test)); return (failed > 0) ? 1 : 0; }
rcr/libgrapheme
src/util.c
<filename>src/util.c /* See LICENSE file for copyright and license details. */ #include "util.h" int heisenstate_get(struct heisenstate *h, int slot) { if (h == NULL || slot >= 16 || slot < 0 || !(h->determined & (1 << slot))) { /* no state given, slot out of range or undetermined */ return -1; } else { /* slot determined, return state (0 or 1) */ return (h->state & (1 << slot)) ? 1 : 0; } } int heisenstate_set(struct heisenstate *h, int slot, int state) { if (h == NULL || slot >= 16 || slot < 0) { /* no state given or slot out of range */ return 1; } else { h->determined |= (1 << slot); if (state) { h->state |= (1 << slot); } else { h->state &= ~(1 << slot); } } return 0; }
rcr/libgrapheme
src/boundary.c
<reponame>rcr/libgrapheme /* See LICENSE file for copyright and license details. */ #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include "../data/emoji.h" #include "../data/grapheme_boundary.h" enum { GRAPHEME_STATE_RI_ODD = 1 << 0, /* odd number of RI's before the seam */ GRAPHEME_STATE_EMOJI = 1 << 1, /* within emoji modifier or zwj sequence */ }; static int cp_cmp(const void *a, const void *b) { uint32_t cp = *(uint32_t *)a; uint32_t *range = (uint32_t *)b; return (cp >= range[0] && cp <= range[1]) ? 0 : (cp - range[0]); } static int has_property(uint32_t cp, struct heisenstate *cpstate, const struct range_list *proptable, int property) { if (heisenstate_get(cpstate, property) == -1) { /* state undetermined, make a lookup and set it */ heisenstate_set(cpstate, property, bsearch(&cp, proptable[property].data, proptable[property].len, sizeof(*proptable[property].data), cp_cmp) ? 1 : 0); } return heisenstate_get(cpstate, property); } int grapheme_boundary(uint32_t a, uint32_t b, int *state) { struct heisenstate gb[2] = { 0 }, emoji[2] = { 0 }; int s; /* skip printable ASCII */ if ((a >= 0x20 && a <= 0x7E) && (b >= 0x20 && b <= 0x7E)) { return 1; } /* set internal state based on given state-pointer */ s = (state != NULL) ? *state : 0; /* * Apply grapheme cluster breaking algorithm (UAX #29), see * http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules */ /* * update state */ if (has_property(b, &gb[1], gb_prop, GB_PROP_REGIONAL_INDICATOR)) { if (has_property(a, &gb[0], gb_prop, GB_PROP_REGIONAL_INDICATOR)) { /* one more RI is on the left side of the seam */ s ^= GRAPHEME_STATE_RI_ODD; } else { /* an RI appeared on the right side but the left side is not an RI, reset state (0 is even) */ s &= ~GRAPHEME_STATE_RI_ODD; } } if (!(*state & GRAPHEME_STATE_EMOJI) && ((has_property(a, &emoji[0], emoji_prop, EMOJI_PROP_EXTPICT) && has_property(b, &gb[1], gb_prop, GB_PROP_ZWJ)) || (has_property(a, &emoji[0], emoji_prop, EMOJI_PROP_EXTPICT) && has_property(b, &gb[1], gb_prop, GB_PROP_EXTEND)))) { s |= GRAPHEME_STATE_EMOJI; } else if ((*state & GRAPHEME_STATE_EMOJI) && ((has_property(a, &gb[0], gb_prop, GB_PROP_ZWJ) && has_property(b, &emoji[1], emoji_prop, EMOJI_PROP_EXTPICT)) || (has_property(a, &gb[0], gb_prop, GB_PROP_EXTEND) && has_property(b, &gb[1], gb_prop, GB_PROP_EXTEND)) || (has_property(a, &gb[0], gb_prop, GB_PROP_EXTEND) && has_property(b, &gb[1], gb_prop, GB_PROP_ZWJ)) || (has_property(a, &emoji[0], emoji_prop, EMOJI_PROP_EXTPICT) && has_property(b, &gb[1], gb_prop, GB_PROP_ZWJ)) || (has_property(a, &emoji[0], emoji_prop, EMOJI_PROP_EXTPICT) && has_property(b, &gb[1], gb_prop, GB_PROP_EXTEND)))) { /* GRAPHEME_STATE_EMOJI remains */ } else { s &= ~GRAPHEME_STATE_EMOJI; } /* write updated state to state-pointer, if given */ if (state != NULL) { *state = s; } /* * apply rules */ /* skip GB1 and GB2, as they are never satisfied here */ /* GB3 */ if (has_property(a, &gb[0], gb_prop, GB_PROP_CR) && has_property(b, &gb[1], gb_prop, GB_PROP_LF)) { return 0; } /* GB4 */ if (has_property(a, &gb[0], gb_prop, GB_PROP_CONTROL) || has_property(a, &gb[0], gb_prop, GB_PROP_CR) || has_property(a, &gb[0], gb_prop, GB_PROP_LF)) { return 1; } /* GB5 */ if (has_property(b, &gb[1], gb_prop, GB_PROP_CONTROL) || has_property(b, &gb[1], gb_prop, GB_PROP_CR) || has_property(b, &gb[1], gb_prop, GB_PROP_LF)) { return 1; } /* GB6 */ if (has_property(a, &gb[0], gb_prop, GB_PROP_L) && (has_property(b, &gb[1], gb_prop, GB_PROP_L) || has_property(b, &gb[1], gb_prop, GB_PROP_V) || has_property(b, &gb[1], gb_prop, GB_PROP_LV) || has_property(b, &gb[1], gb_prop, GB_PROP_LVT))) { return 0; } /* GB7 */ if ((has_property(a, &gb[0], gb_prop, GB_PROP_LV) || has_property(a, &gb[0], gb_prop, GB_PROP_V)) && (has_property(b, &gb[1], gb_prop, GB_PROP_V) || has_property(b, &gb[1], gb_prop, GB_PROP_T))) { return 0; } /* GB8 */ if ((has_property(a, &gb[0], gb_prop, GB_PROP_LVT) || has_property(a, &gb[0], gb_prop, GB_PROP_T)) && has_property(b, &gb[1], gb_prop, GB_PROP_T)) { return 0; } /* GB9 */ if (has_property(b, &gb[1], gb_prop, GB_PROP_EXTEND) || has_property(b, &gb[1], gb_prop, GB_PROP_ZWJ)) { return 0; } /* GB9a */ if (has_property(b, &gb[1], gb_prop, GB_PROP_SPACINGMARK)) { return 0; } /* GB9b */ if (has_property(a, &gb[0], gb_prop, GB_PROP_PREPEND)) { return 0; } /* GB11 */ if ((s & GRAPHEME_STATE_EMOJI) && has_property(a, &gb[0], gb_prop, GB_PROP_ZWJ) && has_property(b, &emoji[1], emoji_prop, EMOJI_PROP_EXTPICT)) { return 0; } /* GB12/GB13 */ if (has_property(a, &gb[0], gb_prop, GB_PROP_REGIONAL_INDICATOR) && has_property(b, &gb[1], gb_prop, GB_PROP_REGIONAL_INDICATOR) && (s & GRAPHEME_STATE_RI_ODD)) { return 0; } /* GB999 */ return 1; }
rcr/libgrapheme
data/grapheme_boundary_test.c
<reponame>rcr/libgrapheme /* See LICENSE file for copyright and license details. */ #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "datautil.h" struct break_test { uint32_t *cp; size_t cplen; size_t *len; size_t lenlen; char *descr; }; static struct break_test *test = NULL; static size_t ntests = 0; int process_line(char **field, size_t nfields, char *comment) { struct break_test *t; size_t i; char *token; if (nfields < 1) { return 1; } /* append new testcase and initialize with zeroes */ if ((test = realloc(test, ++ntests * sizeof(*test))) == NULL) { fprintf(stderr, "realloc: %s\n", strerror(errno)); return 1; } t = &test[ntests - 1]; memset(t, 0, sizeof(*t)); /* parse testcase "<÷|×> <cp> <÷|×> ... <cp> <÷|×>" */ for (token = strtok(field[0], " "), i = 0; token != NULL; i++, token = strtok(NULL, " ")) { if (i % 2 == 0) { /* delimiter */ if (!strncmp(token, "\xC3\xB7", 2)) { /* UTF-8 */ /* * '÷' indicates a breakpoint, * the current length is done; allocate * a new length field and set it to 0 */ if ((t->len = realloc(t->len, ++t->lenlen * sizeof(*t->len))) == NULL) { fprintf(stderr, "realloc: %s\n", strerror(errno)); return 1; } t->len[t->lenlen - 1] = 0; } else if (!strncmp(token, "\xC3\x97", 2)) { /* UTF-8 */ /* * '×' indicates a non-breakpoint, do nothing */ } else { fprintf(stderr, "malformed delimiter '%s'\n", token); return 1; } } else { /* add code point to cp-array */ if ((t->cp = realloc(t->cp, ++t->cplen * sizeof(*t->cp))) == NULL) { fprintf(stderr, "realloc: %s\n", strerror(errno)); return 1; } if (cp_parse(token, &t->cp[t->cplen - 1])) { return 1; } if (t->lenlen > 0) { t->len[t->lenlen - 1]++; } } } if (t->len[t->lenlen - 1] == 0) { /* we allocated one more length than we needed */ t->lenlen--; } /* store comment */ if ((test[ntests - 1].descr = strdup(comment)) == NULL) { fprintf(stderr, "strdup: %s\n", strerror(errno)); return 1; } return 0; } int main(void) { size_t i, j; printf("/* Automatically generated by data/gbt */\n" "#include <stdint.h>\n#include <stddef.h>\n\n"); parse_input(process_line); printf("static const struct break_test {\n\tuint32_t *cp;\n" "\tsize_t cplen;\n\tsize_t *len;\n\tsize_t lenlen;\n" "\tchar *descr;\n} t[] = {\n"); for (i = 0; i < ntests; i++) { printf("\t{\n"); printf("\t\t.cp = (uint32_t[]){"); for (j = 0; j < test[i].cplen; j++) { printf(" UINT32_C(0x%06X)", test[i].cp[j]); if (j + 1 < test[i].cplen) { putchar(','); } } printf(" },\n"); printf("\t\t.cplen = %zu,\n", test[i].cplen); printf("\t\t.len = (size_t[]){"); for (j = 0; j < test[i].lenlen; j++) { printf(" %zu", test[i].len[j]); if (j + 1 < test[i].lenlen) { putchar(','); } } printf(" },\n"); printf("\t\t.lenlen = %zu,\n", test[i].lenlen); printf("\t\t.descr = \"%s\",\n", test[i].descr); printf("\t},\n"); } printf("};\n"); return 0; }
zclfly/radhat-trie
src/hat-trie/misc.c
<reponame>zclfly/radhat-trie /* Copyright (c) 2013 Hyperbotics, Inc. <http://www.hyperbotics.com> 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. This file is part of trie-collection Original Author : <NAME> <<EMAIL>> */ #include <stdlib.h> #include "misc.h" void* malloc_or_die(size_t n) { void* p = malloc(n); if (p == NULL && n != 0) { fprintf(stderr, "Cannot allocate %zu bytes.\n", n); exit(EXIT_FAILURE); } return p; } void* realloc_or_die(void* ptr, size_t n) { void* p = realloc(ptr, n); if (p == NULL && n != 0) { fprintf(stderr, "Cannot allocate %zu bytes.\n", n); exit(EXIT_FAILURE); } return p; } FILE* fopen_or_die(const char* path, const char* mode) { FILE* f = fopen(path, mode); if (f == NULL) { fprintf(stderr, "Cannot open file %s with mode %s.\n", path, mode); exit(EXIT_FAILURE); } return f; }
zclfly/radhat-trie
src/hat-trie/murmurhash3.h
<gh_stars>1-10 #ifndef MURMURHASH3_H #define MURMURHASH3_H #include <stdlib.h> #ifndef _CONFIG_H #define _CONFIG_H #include "config.h" #endif #ifdef HAVE_STDINT_H #include <stdint.h> #else #include "pstdint.h" #endif uint32_t hash(const char* data, size_t len); #endif
zclfly/radhat-trie
src/trie/trie.c
/* Copyright (c) 2013 Hyperbotics, Inc. <http://www.hyperbotics.com> 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. Original Author: <NAME> <<EMAIL>> */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include "trie.h" /* * Initialize a new trie pointer * * @param - None * */ trie_t * trie_new () { trie_t *trie = NULL; trie = calloc (1, sizeof (*trie)); if (!trie) return NULL; trie->root.trie = trie; return trie; } /* * Add a subnode * * @param - node, id */ static trienode_t * trie_subnode (trienode_t *node, int id) { trienode_t *subnode = NULL; subnode = node->subnodes[id]; if (!subnode) { subnode = calloc (1, sizeof (*subnode)); if (!subnode) return NULL; subnode->id = id; subnode->depth = node->depth + 1; node->subnodes[id] = subnode; subnode->parent = node; subnode->trie = node->trie; node->trie->nodecnt++; } return subnode; } /* */ int trie_add (trie_t *trie, const char *dword) { trienode_t *node = NULL; int i = 0; char id = 0; trienode_t *subnode = NULL; node = &trie->root; for (i = 0; i < strlen (dword); i++) { id = dword[i]; subnode = trie_subnode (node, id); if (!subnode) return -1; node = subnode; } node->eow = 1; return 0; } /* */ static void trienode_free (trienode_t *node) { trienode_t *trav = NULL; int i = 0; for (i = 0; i < 255; i++) { trav = node->subnodes[i]; if (trav) trienode_free (trav); } free (node->data); free (node); } /* */ void trie_destroy (trie_t *trie) { trienode_free ((trienode_t *)trie); } /* */ void trie_destroy_bynode (trienode_t *node) { trie_destroy (node->trie); } /* */ static int trienode_walk (trienode_t *node, int (*fn)(trienode_t *node, void *data), void *data, int eowonly) { trienode_t *trav = NULL; int i = 0; int cret = 0; int ret = 0; if (!eowonly || node->eow) ret = fn (node, data); if (ret) goto out; for (i = 0; i < 255; i++) { trav = node->subnodes[i]; if (!trav) continue; cret = trienode_walk (trav, fn, data, eowonly); if (cret < 0) { ret = cret; goto out; } ret += cret; } out: return ret; } /* */ static int trie_walk (trie_t *trie, int (*fn)(trienode_t *node, void *data), void *data, int eowonly) { return trienode_walk (&trie->root, fn, data, eowonly); } /* */ static void print_node (trienode_t *node, char **buf) { if (!node->parent) return; if (node->parent) { print_node (node->parent, buf); *(*buf)++ = node->id; } } /* */ int trienode_get_word (trienode_t *node, char **bufp) { char *buf = NULL; buf = calloc (1, node->depth + 1); if (!buf) return -1; *bufp = buf; print_node (node, &buf); return 0; } /* */ static int trie_calc_dist (trienode_t *node, void *data) { const char *word = NULL; int i = 0; int *row = NULL; int *uprow = NULL; int distu = 0; int distl = 0; int distul = 0; word = data; node->data = calloc (node->trie->len, sizeof (int)); if (!node->data) return -1; row = node->data; if (!node->parent) { for (i = 0; i < node->trie->len; i++) row[i] = i+1; return 0; } uprow = node->parent->data; distu = node->depth; /* up node */ distul = node->parent->depth; /* up-left node */ for (i = 0; i < node->trie->len; i++) { distl = uprow[i]; /* left node */ if (word[i] == node->id) row[i] = distul; else row[i] = min ((distul + DISTANCE_EDIT), min ((distu + DISTANCE_DEL), (distl + DISTANCE_INS))); distu = row[i]; distul = distl; } return 0; } /* */ int trienode_get_dist (trienode_t *node) { int *row = NULL; row = node->data; return row[node->trie->len - 1]; } /* */ static void trienodevec_clear (struct trienodevec *nodevec) { memset(nodevec->nodes, 0, sizeof (*nodevec->nodes) * nodevec->cnt); } /* */ static int trie_collect_closest (trienode_t *node, void *data) { struct trienodevec_w *nodevec_w = NULL; struct trienodevec *nodevec = NULL; int dist = 0; int i = 0; nodevec_w = data; nodevec = nodevec_w->vec; if (trie_calc_dist (node, (void *)nodevec_w->word)) return -1; if (!node->eow || !nodevec->cnt) return 0; dist = trienode_get_dist (node); /* * I thought that when descending further after some dictionary word dw, * if we see that child's distance is bigger than it was for dw, then we * can prune this branch, as it can contain only worse nodes. * * This conjecture fails, see eg: * * d("AB", "B") = 1; * d("AB", "BA") = 2; * d("AB", "BAB") = 1; * * -- if both "B" and "BAB" are in dict., then pruning at "BA" would * miss "BAB". * * (example courtesy of <NAME> <<EMAIL> at g<EMAIL>>) if (node->parent->eow && dist > trienode_get_dist (node->parent)) return 1; */ if (nodevec->nodes[0] && dist < trienode_get_dist (nodevec->nodes[0])) { /* improving over the findings so far */ trienodevec_clear (nodevec); nodevec->nodes[0] = node; } else if (!nodevec->nodes[0] || dist == trienode_get_dist (nodevec->nodes[0])) { /* as good as the best so far, add if there is free space */ for (i = 0; i < nodevec->cnt; i++) { if (!nodevec->nodes[i]) { nodevec->nodes[i] = node; break; } } } return 0; } /* */ int trie_measure (trie_t *trie, const char *word, trienode_t **nodes, int nodecnt) { struct trienodevec nodevec = {0,}; nodevec.nodes = nodes; nodevec.cnt = nodecnt; return trie_measure_vec (trie, word, &nodevec); } /* */ int trie_measure_vec (trie_t *trie, const char *word, struct trienodevec *nodevec) { struct trienodevec_w nodevec_w = {0,}; int ret = 0; trie->len = strlen (word); trienodevec_clear (nodevec); nodevec_w.vec = nodevec; nodevec_w.word = word; ret = trie_walk (trie, trie_collect_closest, &nodevec_w, 0); if (ret > 0) ret = 0; return ret; } /* */ static int trienode_reset (trienode_t *node, void *data) { free (node->data); return 0; } /* */ void trie_reset_search (trie_t *trie) { trie->len = 0; trie_walk (trie, trienode_reset, NULL, 0); }
ddrown/asymmetric-ntp-client
shm_offsets.c
<reponame>ddrown/asymmetric-ntp-client #include <time.h> #include <stdio.h> // structure from ntp-4.2.6p5/ntpd/refclock_shm.c struct shmTime { int mode; /* 0 - if valid set * use values, * clear valid * 1 - if valid set * if count before and after read of values is equal, * use values * clear valid */ int count; time_t clockTimeStampSec; int clockTimeStampUSec; time_t receiveTimeStampSec; int receiveTimeStampUSec; int leap; int precision; int nsamples; int valid; int dummy[10]; } a; int main() { printf("sizeof = %d time_t = %d\n", sizeof(a), sizeof(time_t)); printf("r.s = %d r.us = %d\n", (void *)&a.clockTimeStampSec - (void *)&a, (void *)&a.clockTimeStampUSec - (void *)&a); printf("l.s = %d l.us = %d\n", (void *)&a.receiveTimeStampSec - (void *)&a, (void *)&a.receiveTimeStampUSec - (void *)&a); printf("leap = %d valid = %d\n", (void *)&a.leap - (void *)&a, (void *)&a.valid - (void *)&a); printf("lastdummy = %d\n", (void *)&a.dummy[9] - (void *)&a); /* Output x86_64, Linux: sizeof = 96 time_t = 8 r.s = 8 r.us = 16 l.s = 24 l.us = 32 leap = 36 valid = 48 lastdummy = 88 i686, Linux: sizeof = 80 time_t = 4 r.s = 8 r.us = 12 l.s = 16 l.us = 20 leap = 24 valid = 36 lastdummy = 76 */ }
GabrielAlva/Swift-Prompts
SwiftPrompts/SwiftPrompts.h
// // SwiftPrompts.h // SwiftPrompts // // Created by <NAME> on 23.03.16. // // #import <UIKit/UIKit.h> //! Project version number for SwiftPrompts. FOUNDATION_EXPORT double SwiftPromptsVersionNumber; //! Project version string for SwiftPrompts. FOUNDATION_EXPORT const unsigned char SwiftPromptsVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SwiftPrompts/PublicHeader.h>
h5tube/h5tube-kakasi-ruby
kakasi.c
/* * kakasi.c -- Kakasi module * Copyright (c) 1999-2002 <NAME> */ #include <string.h> #include "ruby.h" #include "libkakasi.h" #define OPTMAX 1024 #define min(x,y) ((x)<(y) ? (x) : (y)) static char const rcsid[] = "$kNotwork: kakasi.c,v 1.3 2002/09/28 05:21:37 gotoken Exp $"; static int dic_closed = 1, len = 0; static char prev_opt_ptr[OPTMAX]; static VALUE rb_kakasi_kakasi(obj, opt, src) VALUE obj, opt, src; { int argc = 0, i = 0; char **argv, **opts; char *buf, *opt_ptr, *t; VALUE dst; Check_Type(src, T_STRING); /* return "" immediately if source str is empty */ if (RSTRING(src)->len == 0) return rb_str_new2(""); Check_Type(opt, T_STRING); /* initialize kakasi iff opt != previous opt */ if (0 == len || 0 != strncmp(RSTRING(opt)->ptr, prev_opt_ptr, min(RSTRING(opt)->len, len))) { strncpy(prev_opt_ptr, RSTRING(opt)->ptr, RSTRING(opt)->len); len = RSTRING(opt)->len; if (len + 1 > OPTMAX) { rb_raise(rb_eArgError, "too long 1st arg (should be < 1023)"); } if (!dic_closed) { kakasi_close_kanwadict(); dic_closed = 1; } argv = opts = ALLOCA_N(char*, RSTRING(opt)->len); *opts++ = "kakasi"; argc++; opt_ptr = ALLOCA_N(char, 1 + RSTRING(opt)->len); strncpy(opt_ptr, RSTRING(opt)->ptr, RSTRING(opt)->len); opt_ptr[RSTRING(opt)->len] = '\0'; if (*opts++ = strtok(opt_ptr, " \t")) { argc++; while (t = strtok(NULL, " \t")) { *opts++ = t; argc++; } } if (0 != kakasi_getopt_argv(argc, argv)) rb_raise(rb_eRuntimeError, "failed to initialize kakasi"); dic_closed = 0; } dst = rb_str_new2(""); while (i < RSTRING(src)->len) { if (*(RSTRING(src)->ptr + i) != '\0') { buf = kakasi_do((RSTRING(src)->ptr + i)); rb_str_concat(dst, rb_str_new2(buf)); if (*buf) free(buf); while (*(RSTRING(src)->ptr + i) != '\0') { i++; } } if (i == RSTRING(src)->len) { break; } rb_str_concat(dst, rb_str_new("\0", 1)); i++; } return dst; } void Init_kakasi() { VALUE mKakasi = rb_define_module("Kakasi"); rb_define_module_function(mKakasi, "kakasi", rb_kakasi_kakasi, 2); rb_define_const(mKakasi, "KAKASI_VERSION", rb_str_new2("2002-09-28")); }
muukii/Realm-EasyBackground
Example/Pods/Target Support Files/Pods-Realm-EasyBackground_Tests/Pods-Realm-EasyBackground_Tests-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_Realm_EasyBackground_TestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Realm_EasyBackground_TestsVersionString[];
muukii/Realm-EasyBackground
Example/Pods/Target Support Files/Realm-EasyBackground/Realm-EasyBackground-umbrella.h
<reponame>muukii/Realm-EasyBackground #import <UIKit/UIKit.h> FOUNDATION_EXPORT double Realm_EasyBackgroundVersionNumber; FOUNDATION_EXPORT const unsigned char Realm_EasyBackgroundVersionString[];
eyantra/CS308_DRAWOID---Android-Touch-Controlled-Bot_2012
codes/Drawoid_firebird/drawoid/drawoid.c
<reponame>eyantra/CS308_DRAWOID---Android-Touch-Controlled-Bot_2012 /******************************************************************************** *! * Drawoid.c * * General Description: * * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * ********************************************************************************/ #ifndef F_CPU #define F_CPU 11059200UL #endif #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include <stdio.h> #include <stdlib.h> #include "Motion.c" #include "LCD.c" #include "servo.c" #include "globalVar.h" #include "bluetooth.c" //Initialize the devices and thier ports void init_devices(void){ cli(); //disable all interrupts timer1_init(); lcd_init(); uart3_init(); servo2_pin_config(); motion_port_init(); sei(); //re-enable interrupts } void turn_right(int degree){ pen_up(); _delay_ms(100); move_straight(245,1); right_degrees(degree); move_straight(255,0); pen_down(); } void turn_left(int degree){ pen_up(); _delay_ms(100); move_straight(245,1); left_degrees(degree); move_straight(245,0); _delay_ms(100); pen_down(); } //Main function int main(void) { //Initialize value array with 0 int i; for(i=0;i<1000;i++){ val_array[i] = 0; } data_pos = 0; bot_pos = 0; init_devices(); //LCD_Reset_4bit(); lcd_cursor(2,1); lcd_string("DRAWOID"); while(1){ if (bot_pos < data_pos){ lcd_print(1,9,val_array[bot_pos],3); lcd_cursor(1,1); if (mov_array[bot_pos] == 'F'){ lcd_string("F"); move_straight(val_array[bot_pos],1); } else if (mov_array[bot_pos] == 'B'){ lcd_string("B"); move_straight(val_array[bot_pos],0); } else if (mov_array[bot_pos] == 'R'){ lcd_string("R"); turn_right(val_array[bot_pos]); } else if (mov_array[bot_pos] == 'L'){ lcd_string("L"); turn_left(val_array[bot_pos]); } else if (mov_array[bot_pos] == 'U'){ lcd_string("U"); pen_up(); } else if (mov_array[bot_pos] == 'D'){ lcd_string("D"); pen_down(); } bot_pos++; _delay_ms(1000); } } return 0; }
eyantra/CS308_DRAWOID---Android-Touch-Controlled-Bot_2012
codes/Drawoid_firebird/drawoid/bluetooth.c
<gh_stars>0 /******************************************************************************** Written by: <NAME>, NEX Robotics Pvt. Ltd. Edited by: <NAME>, NEX Robotics Pvt. Ltd. AVR Studio Version 4.17, Build 666 Date: 26th December 2010 Application example: Robot control over serial port Concepts covered: serial communication Serial Port used: UART1 There are two components to the motion control: 1. Direction control using pins PORTA0 to PORTA3 2. Velocity control by PWM on pins PL3 and PL4 using OC5A and OC5B. In this experiment for the simplicity PL3 and PL4 are kept at logic 1. Pins for PWM are kept at logic 1. Connection Details: Motion control: L-1---->PA0; L-2---->PA1; R-1---->PA2; R-2---->PA3; PL3 (OC5A) ----> Logic 1; PL4 (OC5B) ----> Logic 1; Serial Communication: PORTD 2 --> RXD1 UART1 receive for RS232 serial communication PORTD 3 --> TXD1 UART1 transmit for RS232 serial communication PORTH 0 --> RXD2 UART 2 receive for USB - RS232 communication PORTH 1 --> TXD2 UART 2 transmit for USB - RS232 communication PORTE 0 --> RXD0 UART0 receive for ZigBee wireless communication PORTE 1 --> TXD0 UART0 transmit for ZigBee wireless communication PORTJ 0 --> RXD3 UART3 receive available on microcontroller expansion socket PORTJ 1 --> TXD3 UART3 transmit available on microcontroller expansion socket Serial communication baud rate: 9600bps To control robot use number pad of the keyboard which is located on the right hand side of the keyboard. Make sure that NUM lock is on. Commands: Keyboard Key HEX value Action 8 0x38 Forward 2 0x32 Backward 4 0x34 Left 6 0x36 Right 5 0x35 Stop 7 0x37 Buzzer on 9 0x39 Buzzer off Note: 1. Make sure that in the configuration options following settings are done for proper operation of the code Microcontroller: atmega2560 Frequency: 14745600 Optimization: -O0 (For more information read section: Selecting proper optimization options below figure 2.22 in the Software Manual) 2. Difference between the codes for RS232 serial, USB and wireless communication is only in the serial port number. Rest of the things are the same. 3. For USB communication check the Jumper 1 position on the ATMEGA2560 microcontroller adaptor board 4. Auxiliary power can supply current up to 1 Ampere while Battery can supply current up to 2 Ampere. When both motors of the robot changes direction suddenly without stopping, it produces large current surge. When robot is powered by Auxiliary power which can supply only 1 Ampere of current, sudden direction change in both the motors will cause current surge which can reset the microcontroller because of sudden fall in voltage. It is a good practice to stop the motors for at least 0.5seconds before changing the direction. This will also increase the useable time of the fully charged battery. the life of the motor. *********************************************************************************/ /******************************************************************************** Copyright (c) 2010, NEX Robotics Pvt. Ltd. -*- c -*- 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 copyright holders nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Source code can be used for academic purpose. For commercial use permission form the author needs to be taken. 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. Software released under Creative Commence cc by-nc-sa licence. For legal information refer to: http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode ********************************************************************************/ #include<avr/io.h> #include<avr/interrupt.h> #include<util/delay.h> #include "globalVar.h" void uart3_init(void) { UCSR3B = 0x00; //disable while setting baud rate UCSR3A = 0x00; UCSR3C = 0x06; UBRR3L = 0x5F; UBRR3H = 0x00; //set baud rate hi UCSR3B = 0x98; } SIGNAL(SIG_USART3_RECV) // ISR for receive complete interrupt { unsigned char data1 = UDR3; int i = data1 - '0'; if(data1 == 0x24){ data_pos++; } else if (data1 == 0x46){ mov_array[data_pos] = 'F'; flag = 1; } else if (data1 == 0x42){ mov_array[data_pos] = 'B'; //flag = 1; } else if (data1 == 0x52){ mov_array[data_pos] = 'R'; //flag = 1; } else if (data1 == 0x4C){ mov_array[data_pos] = 'L'; //flag = 1; } else if (data1 == 0x44){ mov_array[data_pos] = 'D'; //flag = 1; } else if (data1 == 0x55){ mov_array[data_pos] = 'U'; //flag = 1; } else if ( i <= 10 && i > -1 && flag == 1){ val_array[data_pos] = val_array[data_pos]*10 + i; } }
eyantra/CS308_DRAWOID---Android-Touch-Controlled-Bot_2012
codes/Drawoid_firebird/drawoid/Motion.c
/*! * @file * Drawoid - * * General Description: * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * */ #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "globalVar.h" /*! * Function to configure INT4 (PORTE 4) pin as input for the left position encoder */ void left_encoder_pin_config (void) { DDRE = DDRE & 0xEF; //Set the direction of the PORTE 4 pin as input PORTE = PORTE | 0x10; //Enable internal pullup for PORTE 4 pin } /*! * Function to configure INT5 (PORTE 5) pin as input for the right position encoder */ void right_encoder_pin_config (void) { DDRE = DDRE & 0xDF; //Set the direction of the PORTE 4 pin as input PORTE = PORTE | 0x20; //Enable internal pullup for PORTE 4 pin } /*! * This function enables interrupt 4 */ void left_position_encoder_interrupt_init (void) { //cli(); //Clears the global interrupt EICRB = EICRB | 0x02; // INT4 is set to trigger with falling edge EIMSK = EIMSK | 0x10; // Enable Interrupt INT4 for left position encoder //sei(); // Enables the global interrupt } /*! * This function enables interrupt 5 */ void right_position_encoder_interrupt_init (void) { //cli(); //Clears the global interrupt EICRB = EICRB | 0x08; // INT5 is set to trigger with falling edge EIMSK = EIMSK | 0x20; // Enable Interrupt INT5 for right position encoder //sei(); // Enables the global interrupt } /*! * Initialize the motor ports */ void motion_pin_config (void) { DDRA = DDRA | 0x0F; PORTA = PORTA & 0xF0; DDRL = DDRL | 0x18; // Setting PL3 and PL4 pins as output for PWM generation PORTL = PORTL | 0x18; // PL3 and PL4 pins are for velocity control using PWM. } /*! * Function to initialize all the devices */ void motion_port_init() { motion_pin_config(); //robot motion pins config left_encoder_pin_config(); //left encoder pin config right_encoder_pin_config(); //right encoder pin config left_position_encoder_interrupt_init(); right_position_encoder_interrupt_init(); } /*! * ISR for right position encoder */ ISR(INT5_vect) { ShaftCountRight++; //increment right shaft position count } /*! * ISR for left position encoder */ ISR(INT4_vect) { ShaftCountLeft++; //increment left shaft position count } /*! * This function moves the motor in the given direction * Direction --> 1 (forward) * Direction --> 0 (backward) */ void motion_set (unsigned char Direction) { unsigned char PortARestore = 0; Direction &= 0x0F; // removing upper nibbel for the protection PortARestore = PORTA; // reading the PORTA original status PortARestore &= 0xF0; // making lower direction nibbel to 0 PortARestore |= Direction; // adding lower nibbel for forward command and restoring the PORTA status PORTA = PortARestore; // executing the command } void forward (void) /*! both wheels forward */ { motion_set(0x06); } void back (void) /*! both wheels backward */ { motion_set(0x09); } void left (void) /*! Left wheel backward, Right wheel forward */ { motion_set(0x05); } void right (void) /*! Left wheel forward, Right wheel backward */ { motion_set(0x0A); } void soft_left (void) /*! Left wheel stationary, Right wheel forward */ { motion_set(0x04); } void soft_right (void) /*! Left wheel forward, Right wheel is stationary */ { motion_set(0x02); } void soft_left_2 (void) /*! Left wheel backward, right wheel stationary */ { motion_set(0x01); } void soft_right_2 (void) /*! Left wheel stationary, Right wheel backward */ { motion_set(0x08); } void stop (void) { motion_set(0x00); } /*! * This function turns the robot by specified degrees */ void angle_rotate(unsigned int Degrees) { float ReqdShaftCount = 0; unsigned long int ReqdShaftCountInt = 0; ReqdShaftCount = (float) Degrees/ 4.36; // division by resolution to get shaft count ReqdShaftCountInt = (unsigned int) ReqdShaftCount; ShaftCountRight = 0; ShaftCountLeft = 0; while (1) { if((ShaftCountRight >= ReqdShaftCountInt) || (ShaftCountLeft >= ReqdShaftCountInt)) //change break; } stop(); //Stop action } /*! * This function movs the * robot forward by specified distance */ void linear_distance_mm(unsigned int DistanceInMM) { float ReqdShaftCount = 0; unsigned long int ReqdShaftCountInt = 0; ReqdShaftCount = DistanceInMM / 13.58; // division by resolution to get shaft count ReqdShaftCountInt = (unsigned long int) ReqdShaftCount; ShaftCountRight = 0; while(1) { if(ShaftCountRight > ReqdShaftCountInt)//also adding count for left count { break; } } stop(); //Stop action } /*! * This function moves the robot forward * by DistanceInMM millimeters */ void forward_mm(unsigned int DistanceInMM) { forward(); linear_distance_mm(DistanceInMM); } /*! * This function moves the robot backward * by DistanceInMM millimeters */ void back_mm(unsigned int DistanceInMM) { back(); linear_distance_mm(DistanceInMM); } /*! * This function turns the robot to the left * by DistanceInMM millimeters */ void left_degrees(unsigned int Degrees) { // 80 pulses for 360 degrees rotation 4.510 degrees per count left(); //Turn left angle_rotate(Degrees); } /*! * This function turns the robot to the right * by DistanceInMM millimeters */ void right_degrees(unsigned int Degrees) { // 80 pulses for 360 degrees rotation 4.510 degrees per count right(); //Turn right angle_rotate(Degrees); } /*! * This function turns the robot to the left * softly by DistanceInMM millimeters */ void soft_left_degrees(unsigned int Degrees) { // 160 pulses for 360 degrees rotation 2.255 degrees per count soft_left(); //Turn soft left Degrees=Degrees*2; angle_rotate(Degrees); } /*! * This function turns the robot to the right * softly by DistanceInMM millimeters * Here it moves the left motor backwards * without moving the right motor to acheive * the desired movement */ void soft_right_degrees(unsigned int Degrees) { // 160 pulses for 360 degrees rotation 2.255 degrees per count soft_right_2(); //Turn soft right Degrees=Degrees*2; angle_rotate(Degrees); } /*! * This function turns the robot to the left * softly by DistanceInMM millimeters * The difference here is that is moves the right motor * forwards without moving the left motor */ void soft_left_2_degrees(unsigned int Degrees) { // 160 pulses for 360 degrees rotation 2.255 degrees per count soft_left_2(); //Turn reverse soft left Degrees=Degrees*2; angle_rotate(Degrees); } /*! * This function turns the robot to the left * softly by DistanceInMM millimeters * It acheives this move by moving the left motor * forwards without moving the left motor */ void soft_right_2_degrees(unsigned int Degrees) { // 160 pulses for 360 degrees rotation 2.255 degrees per count soft_right_2(); //Turn reverse soft right Degrees=Degrees*2; angle_rotate(Degrees); } /*! * This function moves the robot by dist mm according * to the direction, i.e. 1 -> forwards, * 0 -> backwards */ void move_straight(unsigned int dist,int direction) //moves the bot in the given direction { //1 - forward 0 - backward if(direction == 1) { forward_mm(dist); } else { back_mm(dist); } stop(); }
eyantra/CS308_DRAWOID---Android-Touch-Controlled-Bot_2012
codes/Drawoid_firebird/drawoid/servo.c
<filename>codes/Drawoid_firebird/drawoid/servo.c /******************************************************************************** Written by: <NAME>, NEX Robotics Pvt. Ltd. Edited by: <NAME>, NEX Robotics Pvt. Ltd. AVR Studio Version 4.17, Build 666 Date: 26th December 2010 This experiment demonstrates Servo motor control using 10 bit fast PWM mode. Concepts covered: Use of timer to generate PWM for servo motor control Fire Bird V ATMEGA2560 microcontroller board has connection for 3 servo motors (S1, S2, S3). Servo motors move between 0 to 180 degrees proportional to the pulse train with the on time of 0.6 to 2 ms with the frequency between 40 to 60 Hz. 50Hz is most recommended. We are using Timer 1 at 10 bit fast PWM mode to generate servo control waveform. In this mode servo motors can be controlled with the angular resolution of 1.86 degrees. Although angular resolution is less this is very simple method. There are better ways to produce very high resolution PWM but it involves interrupts at the frequency of the PWM. High resolution PWM is used for servo control in the Hexapod robot. Connection Details: PORTB 5 OC1A --> Servo 1: Camera pod pan servo PORTB 6 OC1B --> Servo 2: Camera pod tile servo PORTB 7 OC1C --> Servo 3: Reserved Note: 1. Make sure that in the configuration options following settings are done for proper operation of the code Microcontroller: atmega2560 Frequency: 14745600 Optimization: -O0 (For more information read section: Selecting proper optimization options below figure 2.22 in the Software Manual) 2. 5V supply to these motors is provided by separate low drop voltage regulator "5V Servo" which can supply maximum of 800mA current. It is a good practice to move one servo at a time to reduce power surge in the robot's supply lines. Also preferably take ADC readings while servo motor is not moving or stopped moving after giving desired position. *********************************************************************************/ /******************************************************************************** Copyright (c) 2010, NEX Robotics Pvt. Ltd. -*- c -*- 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 copyright holders nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Source code can be used for academic purpose. For commercial use permission form the author needs to be taken. 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. Software released under Creative Commence cc by-nc-sa licence. For legal information refer to: http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode ********************************************************************************/ #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "globalVar.h" //Configure PORTB 6 pin for servo motor 2 operation void servo2_pin_config (void) { DDRB = DDRB | 0x40; //making PORTB 6 pin output PORTB = PORTB | 0x40; //setting PORTB 6 pin to logic 1 } //TIMER1 initialization in 10 bit fast PWM mode //prescale:256 // WGM: 7) PWM 10bit fast, TOP=0x03FF // actual value: 52.25Hz void timer1_init(void) { TCCR1B = 0x00; //stop TCNT1H = 0xFC; //Counter high value to which OCR1xH value is to be compared with TCNT1L = 0x01; //Counter low value to which OCR1xH value is to be compared with OCR1BH = 0x03; //Output compare Register high value for servo 2 OCR1BL = 0xFF; //Output Compare Register low Value For servo 2 ICR1H = 0x03; ICR1L = 0xFF; TCCR1A = 0xAB; /*{COM1A1=1, COM1A0=0; COM1B1=1, COM1B0=0; COM1C1=1 COM1C0=0} For Overriding normal port functionality to OCRnA outputs. {WGM11=1, WGM10=1} Along With WGM12 in TCCR1B for Selecting FAST PWM Mode*/ TCCR1C = 0x00; TCCR1B = 0x0C; //WGM12=1; CS12=1, CS11=0, CS10=0 (Prescaler=256) } //Function to rotate Servo 2 by a specified angle in the multiples of 1.86 degrees void servo_2(float degrees) { float PositionTiltServo = 0; PositionTiltServo = ((float)degrees / 1.86) + 35.0; OCR1BH = 0x00; OCR1BL = (unsigned char) PositionTiltServo; } //servo_free functions unlocks the servo motors from the any angle //and make them free by giving 100% duty cycle at the PWM. This function can be used to //reduce the power consumption of the motor if it is holding load against the gravity. void servo_2_free (void) //makes servo 2 free rotating { OCR1BH = 0x03; OCR1BL = 0xFF; //Servo 2 off } void pen_up(void) { int degree = 72; servo_2(degree); _delay_ms(2000); servo_2_free(); } void pen_down(void) { int degree = 99; servo_2(degree); _delay_ms(2000); servo_2_free(); }
Liceti-Rapallo/ExBohLib
Motore.h
#ifndef LIB_MOTORE_H #define LIB_MOTORE_H #if defined(ARDUINO) && ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif #include <inttypes.h> #include "tools.h" class Motore { public: float x[5]; float v[4]; float a[3]; float t[5]; int pIN1; int pIN2; int pPWM; int pENC1; int pENC2; int pot; int corr; int pENC1Last; Motore(int pIN1, int pIN2, int pPWM, int pENC1, int pENC2); void loop(); void muovi(int pot); void stop(); void regola(); void letturaEncoder(); }; #endif //LIB_MOTORE_H
Liceti-Rapallo/ExBohLib
Motori.h
<reponame>Liceti-Rapallo/ExBohLib<filename>Motori.h #ifndef LIB_MOTORI_H #define LIB_MOTORI_H #if defined(ARDUINO) && ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif #include <inttypes.h> #include "Motore.h" class Motori { public: Motore *dx, *sx; int stby; //Il pin stby int pos; //Posizione attuale int stoppos; //Positione dove fermarsi Motori(Motore* dx, Motore* sx, int stby); void loop(); void avanti(int vel, int space); void indietro(int vel, int space); void muovi(int vel, int space); void stop(); void attiva(); void disattiva(); }; #endif //LIB_MOTORI_H
Liceti-Rapallo/ExBohLib
tools.h
<filename>tools.h // // Created by Giotino on 12/03/2016. // #ifndef LIB_TOOLS_H #define LIB_TOOLS_H extern int netxPos(int &pos, int a[]); extern void shiftArray(float *a); #endif //LIB_TOOLS_H
NEKERAFA/Advent-of-Code-2021
day-6/part-one.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define FILENAME "input.txt" unsigned long long* loadinput() { unsigned long long* lanternfish = (unsigned long long*)malloc(sizeof(unsigned long long) * 9); FILE* input = fopen(FILENAME, "r"); char* line = NULL; size_t len = 0; while (getline(&line, &len, input) != -1) { char* value = strtok(line, ","); while (value != NULL) { int age = atoi(value); lanternfish[age]++; value = strtok(NULL, ","); } } free(line); fclose(input); return lanternfish; } void startsim(unsigned long long* lanternfish, int days) { int day = 0; while (day < days) { unsigned long long newfishes = lanternfish[0]; int i; for (i = 0; i < 8; i++) { lanternfish[i] = lanternfish[i + 1]; } lanternfish[6] += newfishes; lanternfish[8] = newfishes; day++; } } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "part-one <days>\n"); exit(EXIT_FAILURE); } int days = atoi(argv[1]); unsigned long long* lanternfish = loadinput(); startsim(lanternfish, days); int i; unsigned long long total = 0; for (i = 0; i < 9; i++) { printf("Lanternfish with age %i: %llu\n", i, lanternfish[i]); total += lanternfish[i]; } printf("Total: %llu\n", total); free(lanternfish); return 0; }
xiaochonzi/amap-location-flutter
ios/Classes/AmapFlutterStreamManager.h
<gh_stars>100-1000 // // AmapFlutterStreamManager.h // amap_location_flutter_plugin // // Created by ldj on 2018/10/30. // #import <Foundation/Foundation.h> #import <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN @class AmapFlutterStreamHandler; @interface AmapFlutterStreamManager : NSObject + (instancetype)sharedInstance ; @property (nonatomic, strong) AmapFlutterStreamHandler* streamHandler; @end @interface AmapFlutterStreamHandler : NSObject<FlutterStreamHandler> @property (nonatomic, strong,nullable) FlutterEventSink eventSink; @end NS_ASSUME_NONNULL_END
leathalman/Sticky-Notes
Pods/Target Support Files/ChromaColorPicker/ChromaColorPicker-umbrella.h
<reponame>leathalman/Sticky-Notes #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double ChromaColorPickerVersionNumber; FOUNDATION_EXPORT const unsigned char ChromaColorPickerVersionString[];
leathalman/Sticky-Notes
Pods/Target Support Files/BottomPopup/BottomPopup-umbrella.h
<reponame>leathalman/Sticky-Notes<filename>Pods/Target Support Files/BottomPopup/BottomPopup-umbrella.h #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double BottomPopupVersionNumber; FOUNDATION_EXPORT const unsigned char BottomPopupVersionString[];
leathalman/Sticky-Notes
Jotify/Receipt/pkcs7_union_accessors.c
<gh_stars>100-1000 // // pkcs7_union_accessors.c // SwiftyReceiptValidatorDemo // // Created by <NAME> on 10/26/17. // Copyright © 2017 <NAME>. All rights reserved. // #include "pkcs7_union_accessors.h" inline char *pkcs7_d_char(PKCS7 *ptr) { return ptr->d.ptr; } inline ASN1_OCTET_STRING *pkcs7_d_data(PKCS7 *ptr) { return ptr->d.data; } inline PKCS7_SIGNED *pkcs7_d_sign(PKCS7 *ptr) { return ptr->d.sign; } inline PKCS7_ENVELOPE *pkcs7_d_enveloped(PKCS7 *ptr) { return ptr->d.enveloped; } inline PKCS7_SIGN_ENVELOPE *pkcs7_d_signed_and_enveloped(PKCS7 *ptr) { return ptr->d.signed_and_enveloped; } inline PKCS7_DIGEST *pkcs7_d_digest(PKCS7 *ptr) { return ptr->d.digest; } inline PKCS7_ENCRYPT *pkcs7_d_encrypted(PKCS7 *ptr) { return ptr->d.encrypted; } inline ASN1_TYPE *pkcs7_d_other(PKCS7 *ptr) { return ptr->d.other; }
leathalman/Sticky-Notes
Jotify/Jotify-Bridging-Header.h
// // Use this file to import your target's public headers that you would like to expose to Swift. // #include "pkcs7_union_accessors.h" #import <openssl/pkcs7.h> #import <openssl/objects.h> #import <openssl/sha.h> #import <openssl/x509.h>