added
stringdate
2024-11-18 17:54:19
2024-11-19 03:39:31
created
timestamp[s]date
1970-01-01 00:04:39
2023-09-06 04:41:57
id
stringlengths
40
40
metadata
dict
source
stringclasses
1 value
text
stringlengths
13
8.04M
score
float64
2
4.78
int_score
int64
2
5
2024-11-18T22:11:19.770076+00:00
2021-07-31T16:40:07
0c1d9bfa6ce6664dc18961df60a062af5697608e
{ "blob_id": "0c1d9bfa6ce6664dc18961df60a062af5697608e", "branch_name": "refs/heads/master", "committer_date": "2021-07-31T16:40:07", "content_id": "e4edea19fe7e3e0bc680109b30be4c382e1d4aaf", "detected_licenses": [ "MIT" ], "directory_id": "8a4f7a2118ea2fa79cc9bf30f11bf142f7a5f9ee", "extension": "c", "filename": "T101-symmetric-tree.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 257138678, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 467, "license": "MIT", "license_type": "permissive", "path": "/algorithm/algorithm/binary-tree/T101-symmetric-tree.c", "provenance": "stackv2-0072.json.gz:46275", "repo_name": "youshihou/leetcode-algorithm", "revision_date": "2021-07-31T16:40:07", "revision_id": "3f2c277b9d020a9c4dbd235caa26b6d0437c84aa", "snapshot_id": "b30ee9fa7fdf29b6b66f9aac86d3ec400aa9204e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/youshihou/leetcode-algorithm/3f2c277b9d020a9c4dbd235caa26b6d0437c84aa/algorithm/algorithm/binary-tree/T101-symmetric-tree.c", "visit_date": "2023-06-20T20:13:37.098293" }
stackv2
// // T101-symmetric-tree.c // algorithm // // Created by Ankui on 7/22/20. // Copyright © 2020 Ankui. All rights reserved. // // https://leetcode-cn.com/problems/symmetric-tree/ #include "T101-symmetric-tree.h" #include "algorithm-common.h" /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool isSymmetric(struct TreeNode* root) { return false; }
2.203125
2
2024-11-18T22:11:19.883364+00:00
2014-07-28T19:35:29
965de46e8ca94ff268e388b4cc71e50fe476672a
{ "blob_id": "965de46e8ca94ff268e388b4cc71e50fe476672a", "branch_name": "refs/heads/master", "committer_date": "2014-07-28T19:38:45", "content_id": "8c74a2d3c9fcda40f9e4dd80e6034fe46abef418", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c9f26c4e89ab32983416eb770d03d118eec776d2", "extension": "c", "filename": "keyset.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 53563, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/libelektra/keyset.c", "provenance": "stackv2-0072.json.gz:46532", "repo_name": "intfrr/libelektra", "revision_date": "2014-07-28T19:35:29", "revision_id": "c5e9aa050381606524a1dd44e27b7c3893856c7a", "snapshot_id": "5633f668acebb961370f5d126367ac6ebfaee0a1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/intfrr/libelektra/c5e9aa050381606524a1dd44e27b7c3893856c7a/src/libelektra/keyset.c", "visit_date": "2020-12-25T01:50:19.385043" }
stackv2
/*************************************************************************** keyset.c - Methods for KeySet manipulation ------------------- begin : Sun Oct 02 2005 copyright : (C) 2005 by Avi Alkalay email : avi@unix.sh ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the BSD License (revised). * * * ***************************************************************************/ /** @class doxygenFlatCopy * * @note Because the key is not copied, * also the pointer to the current metadata keyNextMeta() * will be shared. */ /** * @defgroup keyset KeySet * @brief Methods to manipulate KeySets. * * A KeySet is a sorted set of keys. * So the correct name actually would be KeyMap. * * With ksNew() you can create a new KeySet. * * You can add keys with ksAppendKey() in the keyset. * Using ksAppend() you can append a whole keyset. * * @copydoc doxygenFlatCopy * * ksGetSize() tells you the current size of the keyset. * * With ksRewind() and ksNext() you can navigate through the keyset. Don't * expect any particular order, but it is assured that you will get every * key of the set. * * KeySets have an @link ksCurrent() internal cursor @endlink. This is used * for ksLookup() and kdbSet(). * * KeySet has a fundamental meaning inside elektra. It makes it possible * to get and store many keys at once inside the database. In addition to * that the class can be used as high level datastructure in applications. * With ksLookupByName() it is possible to fetch easily specific keys * out of the list of keys. * * You can easily create and iterate keys: * @code #include <kdb.h> // create a new keyset with 3 keys // with a hint that about 20 keys will be inside KeySet *myConfig = ksNew(20, keyNew ("user/name1", 0), keyNew ("user/name2", 0), keyNew ("user/name3", 0), KS_END); // append a key in the keyset ksAppendKey(myConfig, keyNew("user/name4", 0)); Key *current; ksRewind(myConfig); while ((current=ksNext(myConfig))!=0) { printf("Key name is %s.\n", keyName (current)); } ksDel (myConfig); // delete keyset and all keys appended * @endcode * * @{ */ #ifdef HAVE_KDBCONFIG_H #include "kdbconfig.h" #endif #if DEBUG && HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STDARG_H #include <stdarg.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #include "kdbinternal.h" /** * Allocate, initialize and return a new KeySet object. * * Objects created with ksNew() must be destroyed with ksDel(). * * You can use a various long list of parameters to preload the keyset * with a list of keys. Either your first and only parameter is 0 or * your last parameter must be KEY_END. * * So, terminate with ksNew(0) or ksNew(20, ..., KS_END) * * For most uses * @code KeySet *keys = ksNew(0); // work with it ksDel (keys); * @endcode * goes ok, the alloc size will be 16, defined in kdbprivate.h. * The alloc size will be doubled whenever size reaches alloc size, * so it also performs out large keysets. * * But if you have any clue how large your keyset may be you should * read the next statements. * * If you want a keyset with length 15 (because you know of your * application that you normally need about 12 up to 15 keys), use: * @code KeySet * keys = ksNew (15, keyNew ("user/sw/app/fixedConfiguration/key01", KEY_SWITCH_VALUE, "value01", 0), keyNew ("user/sw/app/fixedConfiguration/key02", KEY_SWITCH_VALUE, "value02", 0), keyNew ("user/sw/app/fixedConfiguration/key03", KEY_SWITCH_VALUE, "value03", 0), // ... keyNew ("user/sw/app/fixedConfiguration/key15", KEY_SWITCH_VALUE, "value15", 0), KS_END); // work with it ksDel (keys); * @endcode * * If you start having 3 keys, and your application needs approximately * 200-500 keys, you can use: * @code KeySet * config = ksNew (500, keyNew ("user/sw/app/fixedConfiguration/key1", KEY_SWITCH_VALUE, "value1", 0), keyNew ("user/sw/app/fixedConfiguration/key2", KEY_SWITCH_VALUE, "value2", 0), keyNew ("user/sw/app/fixedConfiguration/key3", KEY_SWITCH_VALUE, "value3", 0), KS_END); // don't forget the KS_END at the end! // work with it ksDel (config); * @endcode * Alloc size is 500, the size of the keyset will be 3 after ksNew. * This means the keyset will reallocate when appending more than * 497 keys. * * The main benefit of taking a list of variant length parameters is to be able * to have one C-Statement for any possible KeySet. * * Due to ABI compatibility, the @p KeySet structure is only declared in kdb.h, * and not defined. So you can only declare @p pointers to @p KeySets in your * program. * See http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html#AEN135 * * @see ksDel() to free the keyset afterwards * @see ksDup() to duplicate an existing keyset * @param alloc gives a hint for the size how many Keys may be stored initially * @return a ready to use KeySet object * @return 0 on memory error */ KeySet *ksNew(size_t alloc, ...) { KeySet *ks; va_list va; va_start(va, alloc); ks = ksVNew (alloc, va); va_end (va); return ks; } /** * @copydoc ksNew * * @pre caller must call va_start and va_end * @par va the list of arguments **/ KeySet *ksVNew (size_t alloc, va_list va) { KeySet *keyset=0; Key *key = 0; keyset= (KeySet *)elektraMalloc(sizeof(KeySet)); if (!keyset) { /*errno = KDB_ERR_NOMEM;*/ return 0; } ksInit(keyset); alloc ++; /* for ending null byte */ if (alloc < KEYSET_SIZE) keyset->alloc=KEYSET_SIZE; else keyset->alloc=alloc; keyset->array = elektraMalloc (sizeof(struct _Key *) * keyset->alloc); if (!keyset->array) { /*errno = KDB_ERR_NOMEM;*/ return 0; } keyset->array[0] = 0; if (alloc != 1) { key = (struct _Key *) va_arg (va, struct _Key *); while (key) { ksAppendKey(keyset, key); key = (struct _Key *) va_arg (va, struct _Key *); } } return keyset; } /** * Return a duplicate of a keyset. * * Objects created with ksDup() must be destroyed with ksDel(). * * Memory will be allocated as needed for dynamic properties, * so you need to ksDel() the returned pointer. * * A flat copy is made, so the keys will not be duplicated, * but there reference counter is updated, so both keysets * need ksDel(). * * @param source has to be an initializised source KeySet * @return a flat copy of source on success * @return 0 on NULL pointer * @see ksNew(), ksDel() * @see keyDup() for key duplication */ KeySet *ksDup (const KeySet * source) { KeySet *keyset=0; if (!source) return 0; keyset = ksNew(source->alloc,KS_END); ksAppend (keyset, source); return keyset; } /** * Copy a keyset. * * Most often you may want a duplicate of a keyset, see * ksDup() or append keys, see ksAppend(). * But in some situations you need to copy a * keyset to a existing keyset, for that this function * exists. * * You can also use it to clear a keyset when you pass * a NULL pointer as @p source. * * Note that all keys in @p dest will be deleted. Afterwards * the content of the source will be added to the destination * and the ksCurrent() is set properly in @p dest. * * A flat copy is made, so the keys will not be duplicated, * but there reference counter is updated, so both keysets * need to be ksDel(). * * @copydoc doxygenFlatCopy * * @code int f (KeySet *ks) { KeySet *c = ksNew (20, ..., KS_END); // c receives keys ksCopy (ks, c); // pass the keyset to the caller ksDel (c); } // caller needs to ksDel (ks) * @endcode * * @param source has to be an initialized source KeySet or NULL * @param dest has to be an initialized KeySet where to write the keys * @return 1 on success * @return 0 if dest was cleared successfully (source is NULL) * @return -1 on NULL pointer * @see ksNew(), ksDel(), ksDup() * @see keyCopy() for copying keys */ int ksCopy (KeySet *dest, const KeySet *source) { if (!dest) return -1; ksClear (dest); if (!source) return 0; ksAppend (dest, source); ksSetCursor (dest, ksGetCursor (source)); return 1; } /** * A destructor for KeySet objects. * * Cleans all internal dynamic attributes, decrement all reference pointers * to all keys and then keyDel() all contained Keys, * and free()s the release the KeySet object memory (that was previously * allocated by ksNew()). * * @param ks the keyset object to work with * @return 0 when the keyset was freed * @return -1 on null pointer * @see ksNew() */ int ksDel(KeySet *ks) { int rc; if (!ks) return -1; rc=ksClose(ks); elektraFree(ks); return rc; } /** * @internal * * KeySet object cleaner. * * Will keyDel() all contained keys, reset internal pointers and counters. * * After this call you can use the empty keyset again. * * @param ks the keyset object to work with * @see ksAppendKey() for details on how keys are inserted in KeySets * @return 0 on sucess * @return -1 on failure */ int ksClear(KeySet *ks) { ksClose (ks); if (ks->array) { /* go back to standard size KEYSET_SIZE */ if (elektraRealloc ((void**) &ks->array, sizeof(struct _Key *) * KEYSET_SIZE) == -1) { /*errno = KDB_ERR_NOMEM;*/ elektraFree (ks->array); ks->array = 0; ks->size = 0; return -1; } } else { if ((ks->array = elektraMalloc (sizeof(struct _Key *) * KEYSET_SIZE)) == 0) { /*errno = KDB_ERR_NOMEM;*/ ks->size = 0; return -1; } } ks->alloc = KEYSET_SIZE; return 0; } /** * @internal * * Used as a callback by the qsort() function */ static int keyCmpInternal(const void *p1, const void *p2) { Key *key1=*(Key **)p1; Key *key2=*(Key **)p2; const char *name1 = keyName(key1); const char *name2 = keyName(key2); int ret = strcmp(name1, name2); /* sort by owner */ if (ret == 0) { const char *owner1 = keyOwner(key1); const char *owner2 = keyOwner(key2); if (!owner1 && !owner2) return 0; if (!owner1) return -1; if (!owner2) return 1; return strcmp(owner1, owner2); } return ret; } /** * Compare the name of two keys. * * @return a number less than, equal to or greater than zero if * k1 is found, respectively, to be less than, to match, or * be greater than k2. * * The comparison is based on a strcmp of the keynames, and iff * they match a strcmp of the owner will be used to distuingish. * If even this matches the keys are found to be exactly the * same and 0 is returned. These two keys can't be used in the same * KeySet. * * keyCmp() defines the sorting order for a KeySet. * * The following 3 points are the rules for null values. * They only take account when none of the preceding rules * matched. * * - A null pointer will be found to be smaller than every other * key. If both are null pointers, 0 is returned. * * - A null name will be found to be smaller than every other * name. If both are null names, 0 is returned. * * - No owner will be found to be smaller then every other owner. * If both don't have a owner, 0 is returned. * * @note the owner will only be used if the names are equal. * * Often is enough to know if the other key is * less then or greater then the other one. * But Sometimes you need more precise information, * see keyRel(). * * Given any Keys k1 and k2 constructed with keyNew(), following * equation hold true: * * @code // keyCmp(0,0) == 0 // keyCmp(k1,0) == 1 // keyCmp(0,k2) == -1 * @endcode * * You can write similar equation for the other rules. * * Here are some more examples with equation: * @code Key *k1 = keyNew("user/a", KEY_END); Key *k2 = keyNew("user/b", KEY_END); // keyCmp(k1,k2) < 0 // keyCmp(k2,k1) > 0 * @endcode * * @code Key *k1 = keyNew("user/a", KEY_OWNER, "markus", KEY_END); Key *k2 = keyNew("user/a", KEY_OWNER, "max", KEY_END); // keyCmp(k1,k2) < 0 // keyCmp(k2,k1) > 0 * @endcode * * @warning Do not try to strcmp the keyName() yourself because * the used strcmp implementation is allowed to differ from * simple ascii comparison. * * @param k1 the first key object to compare with * @param k2 the second key object to compare with * * @see ksAppendKey(), ksAppend() will compare keys when appending * @see ksLookup() will compare keys during searching * @ingroup keytest */ int keyCmp (const Key *k1, const Key *k2) { if (!k1 && !k2) return 0; if (!k1) return -1; if (!k2) return 1; if (!k1->key && !k2->key) return 0; if (!k1->key) return -1; if (!k2->key) return 1; return keyCmpInternal(&k1, &k2); } /** * Compare the order metadata of two keys. * * @return a number less than, equal to or greater than zero if * the order of k1 is found, respectively, to be less than, * to match, or be greater than the order of k2. If one key is * NULL, but the other isn't, the key which is not NULL is considered * to be greater. If both keys are NULL, they are * considered to be equal. If one key does have an order * metadata but the other has not, the key with the metadata * is considered greater. If no key has metadata, * they are considered to be equal. */ int elektraKeyCmpOrder(const Key *ka, const Key *kb) { if (!ka && !kb) return 0; if (ka && !kb) return 1; if (!ka && kb) return -1; int aorder = -1; int border = -1; const Key *kam = keyGetMeta (ka, "order"); const Key *kbm = keyGetMeta (kb, "order"); if (kam) aorder = atoi (keyString (kam)); if (kbm) border = atoi (keyString (kbm)); if (aorder > 0 && border > 0) return aorder - border; if (aorder < 0 && border < 0) return 0; if (aorder < 0 && border >= 0) return -1; if (aorder >= 0 && border < 0) return 1; /* cannot happen anyway */ return 0; } /** * @internal * * Checks if KeySet needs sync. * * When keys are changed this is reflected into keyNeedSync(). * * But when keys are popped from a keyset this can't be seen * by looking at the individual keys. * * ksNeedSync() allows the backends to know if a key was * popped from the keyset to know that this keyset needs * to be written out. * * @param ks the keyset to work with * @return -1 on null keyset * @return 0 if it does not need sync * @return 1 if it needs sync */ int ksNeedSync(const KeySet *ks) { if (!ks) return -1; return (ks->flags & KS_FLAG_SYNC) == KS_FLAG_SYNC; } /** * Return the number of keys that @p ks contains. * * @param ks the keyset object to work with * @return the number of keys that @p ks contains. * @return -1 on NULL pointer * @see ksNew(0), ksDel() */ ssize_t ksGetSize(const KeySet *ks) { if (!ks) return -1; return ks->size; } /******************************************* * Filling up KeySets * *******************************************/ /** * @internal * * Binary search in a keyset. * * @code ssize_t result = ksSearchInternal(ks, toAppend); if (result >= 0) { ssize_t position = result; // Seems like the key already exist. } else { ssize_t insertpos = -result-1; // Seems like the key does not exist. } * @endcode * * @param ks the keyset to work with * @param toAppend the key to check * @return position where the key is (>=0) if the key was found * @return -insertpos -1 (< 0) if the key was not found * so to get the insertpos simple do: -insertpos -1 */ ssize_t ksSearchInternal(const KeySet *ks, const Key *toAppend) { ssize_t left = 0; ssize_t right = ks->size-1; register int cmpresult = 1; ssize_t middle = -1; ssize_t insertpos = 0; #if DEBUG && VERBOSE int c=0; #endif while(1) { #if DEBUG && VERBOSE ++c; #endif if (right < left) { /* Nothing was found */ break; } middle = left + ((right-left)/2); cmpresult = keyCmpInternal(&toAppend, &ks->array[middle]); if (cmpresult > 0) { insertpos = left = middle + 1; } else if (cmpresult == 0) { /* We have found it */ break; } else { insertpos = middle; right = middle - 1; } #if DEBUG && VERBOSE /* This is even for verbose too verbose! printf ("bsearch -- c: %d res: %d left: %zd middle: %zd right: %zd insertpos: %zd\n", c, cmpresult, left, middle, right, insertpos); */ #endif } if (!cmpresult) { return middle; } else { return -insertpos - 1; } } /** * Appends a Key to the end of @p ks. * * A pointer to the key will * be stored, and not a private copy. So a future ksDel() on * @p ks may keyDel() the @p toAppend object, see keyGetRef(). * * The reference counter of the key will be incremented, and * thus toAppend is not const. * * @copydoc doxygenFlatCopy * * If the keyname already existed, it will be replaced with * the new key. * * The KeySet internal cursor will be set to the new key. * * It is save to use ksAppendKey(ks, keyNew(..)). * * * @return the size of the KeySet after insertion * @return -1 on NULL pointers * @return -1 if insertion failed, the key will be deleted then. * @param ks KeySet that will receive the key * @param toAppend Key that will be appended to ks or deleted * @see ksAppend(), keyNew(), ksDel() * @see keyIncRef() * */ ssize_t ksAppendKey(KeySet *ks, Key *toAppend) { ssize_t result = -1; if (!ks) return -1; if (!toAppend) return -1; if (!toAppend->key) { // needed for ksAppendKey(ks, keyNew(0)) keyDel (toAppend); return -1; } result = ksSearchInternal(ks, toAppend); if (result >= 0) { /* Seems like the key already exist. */ if (toAppend == ks->array[result]) { /* user tried to insert the same key again */ return ks->size; } /* Pop the key in the result */ keyDecRef (ks->array[result]); keyDel (ks->array[result]); /* And use the other one instead */ keyIncRef (toAppend); ks->array[result] = toAppend; ksSetCursor(ks, result); } else { ssize_t insertpos = -result-1; /* We want to append a new key in position insertpos */ ++ ks->size; if (ks->size >= ks->alloc) ksResize (ks, ks->alloc * 2-1); keyIncRef (toAppend); if (insertpos == (ssize_t)ks->size-1) { /* Append it to the very end */ ks->array[ks->size-1] = toAppend; ks->array[ks->size] = 0; ksSetCursor(ks, ks->size-1); } else { size_t n = ks->size-insertpos; memmove(ks->array+(insertpos+1), ks->array+insertpos, n*sizeof(struct Key*)); /* printf ("memmove -- ks->size: %zd insertpos: %zd n: %zd\n", ks->size, insertpos, n); */ ks->array[insertpos] = toAppend; ksSetCursor(ks, insertpos); } } return ks->size; } /** * Append all @p toAppend contained keys to the end of the @p ks. * * @p toAppend KeySet will be left unchanged. * * If a key is both in toAppend and ks, the Key in ks will be * overridden. * * @copydoc doxygenFlatCopy * * @post Sorted KeySet ks with all keys it had before and additionally * the keys from toAppend * @return the size of the KeySet after transfer * @return -1 on NULL pointers * @param ks the KeySet that will receive the keys * @param toAppend the KeySet that provides the keys that will be transferred * @see ksAppendKey() * */ ssize_t ksAppend(KeySet *ks, const KeySet *toAppend) { size_t toAlloc = 0; if (!ks) return -1; if (!toAppend) return -1; if (toAppend->size <= 0) return ks->size; /* Do only one resize in advance */ for (toAlloc = ks->alloc; ks->size+toAppend->size >= toAlloc; toAlloc *= 2); ksResize (ks, toAlloc-1); /* TODO: here is lots of room for optimizations */ for (size_t i=0; i<toAppend->size; ++i) { ksAppendKey (ks, toAppend->array[i]); } return ks->size; } static int keyCompareByNameOwner(const void *p1, const void *p2); /** * @internal * * Returns the previous Key in a KeySet. * * KeySets have an internal cursor that can be reset with ksRewind(). Every * time ksPrev() is called the cursor is decremented and the new current Key * is returned. * * You'll get a NULL pointer if the key before begin of the KeySet was reached. * * Don't delete the key, use ksPop() if you want to delete it. * * @return the new current Key * @see ksRewind(), ksCurrent() * */ Key *ksPrev(KeySet *ks) { if (ks->size == 0) return 0; if (ks->current <= 0) { ksRewind (ks); return 0; } ks->current--; return ks->cursor = ks->array[ks->current]; } /** * @internal * * Copies all Keys until the end of the array from a position * in the array to an position in the array. * * @param ks the keyset where this should be done * @param to the position where it should be copied to * @param from the position where it should be copied from * @retval -1 if length is smaller then 0 * @return the number of moved elements otherwise */ ssize_t ksCopyInternal(KeySet *ks, size_t to, size_t from) { ssize_t ssize = ks->size; ssize_t sto = to; ssize_t sfrom = from; ssize_t sizediff = sto-sfrom; ssize_t length = ssize-sfrom; size_t ret = 0; if (length < 0) return -1; if (ks->size < to) return -1; ks->size = ks->size + sizediff; ret = elektraMemmove(ks->array + to, ks->array + from, length); ks->array[ks->size] = 0; return ret; } /** * Cuts out a keyset at the cutpoint. * * Searches for the cutpoint inside the KeySet ks. * If found it cuts out everything which is below (see keyIsBelow()) this key. * If not found an empty keyset is returned. * * The cursor will stay at the same key as it was before. * If the cursor was inside the region of cutted (moved) * keys, the cursor will be set to the key before * the cutpoint. * * @return a new allocated KeySet which needs to deleted with ksDel(). * The keyset consists of all keys (of the original keyset ks) * below the cutpoint. If the key cutpoint exists, it will * also be appended. * @retval 0 on null pointers, no key name or allocation problems * @param ks the keyset to cut. It will be modified by removing * all keys below the cutpoint. * The cutpoint itself will also be removed. * @param cutpoint the point where to cut out the keyset */ KeySet *ksCut(KeySet *ks, const Key *cutpoint) { KeySet *returned = 0; size_t found = 0; size_t it = 0; size_t newsize = 0; int set_cursor = 0; if (!ks) return 0; if (!cutpoint) return 0; if (!cutpoint->key) return 0; // search the cutpoint while (it < ks->size && keyIsBelowOrSame(cutpoint, ks->array[it]) == 0) { ++it; } // we found nothing if (it == ks->size) return ksNew (0); // we found the cutpoint found = it; // search the end of the keyset to cut while (it < ks->size && keyIsBelowOrSame(cutpoint, ks->array[it]) == 1) { ++it; } // correct cursor if cursor is in cutted keyset if (ks->current >= found && ks->current < it) { if (found == 0) { ksRewind(ks); } else { ks->current = found - 1; set_cursor = 1; } } // correct the cursor for the keys after the cutted keyset if (ks->current >= it) { if (it >= ks->size) { ksRewind(ks); } else { ks->current = found + ks->current - it; set_cursor = 1; } } newsize = it-found; returned = ksNew(newsize, KS_END); elektraMemcpy (returned->array, ks->array+found, newsize); returned->size = newsize; returned->array[returned->size] = 0; if (ksCopyInternal(ks, found, it) == -1) { #if DEBUG printf ("ksCopyInternal returned an error inside ksCut\n"); #endif } if (set_cursor) ks->cursor = ks->array[ks->current]; return returned; } /** * Remove and return the last key of @p ks. * * The reference counter will be decremented by one. * * The KeySets cursor will not be effected if it did not * point to the popped key. * * @note You need to keyDel() the key afterwards, if * you don't append it to another keyset. It has the * same semantics like a key allocated with keyNew() * or keyDup(). * *@code ks1=ksNew(0); ks2=ksNew(0); k1=keyNew("user/name", KEY_END); // ref counter 0 ksAppendKey(ks1, k1); // ref counter 1 ksAppendKey(ks2, k1); // ref counter 2 k1=ksPop (ks1); // ref counter 1 k1=ksPop (ks2); // ref counter 0, like after keyNew() ksAppendKey(ks1, k1); // ref counter 1 ksDel (ks1); // key is deleted too ksDel (ks2); *@endcode * * @return the last key of @p ks * @return NULL if @p ks is empty or on NULL pointer * @param ks KeySet to work with * @see ksAppendKey(), ksAppend() * @see commandList() for an example * */ Key *ksPop(KeySet *ks) { Key *ret=0; if (!ks) return 0; ks->flags |= KS_FLAG_SYNC; if (ks->size <= 0) return 0; -- ks->size; if (ks->size+1 < ks->alloc/2) ksResize (ks, ks->alloc / 2-1); ret = ks->array[ks->size]; ks->array[ks->size] = 0; keyDecRef(ret); return ret; } /** * Builds an array of pointers to the keys in the supplied keyset. * The keys are not copied, calling keyDel may remove them from * the keyset. * * The size of the buffer can be easily allocated via ksGetSize. Example: * @code * KeySet *ks = somekeyset; * Key **keyArray = calloc (ksGetSize(ks), sizeof (Key *)); * elektraKsToMemArray (ks, keyArray); * ... work with the array ... * free (keyArray); * @endcode * * @param ks the keyset object to work with * @param buffer the buffer to put the result into * @return the number of elements in the array if successful * @return a negative number on null pointers or if an error occurred */ int elektraKsToMemArray(KeySet *ks, Key **buffer) { if (!ks) return -1; if (!buffer) return -1; /* clear the received buffer */ memset (buffer, 0, ksGetSize (ks) * sizeof(Key *)); cursor_t cursor = ksGetCursor (ks); ksRewind (ks); size_t index = 0; Key *key; while ((key = ksNext (ks)) != 0) { buffer[index] = key; ++index; } ksSetCursor (ks, cursor); return index; } /******************************************* * KeySet browsing methods * *******************************************/ /** * Rewinds the KeySet internal cursor. * * Use it to set the cursor to the beginning of the KeySet. * ksCurrent() will then always return NULL afterwards. So * you want to ksNext() first. * * @code ksRewind (ks); while ((key = ksNext (ks))!=0) {} * @endcode * * @param ks the keyset object to work with * @return 0 on success * @return -1 on NULL pointer * @see ksNext(), ksCurrent() */ int ksRewind(KeySet *ks) { if (!ks) return -1; ks->cursor=0; ks->current=0; return 0; } /** * Returns the next Key in a KeySet. * * KeySets have an internal cursor that can be reset with ksRewind(). Every * time ksNext() is called the cursor is incremented and the new current Key * is returned. * * You'll get a NULL pointer if the key after the end of the KeySet was reached. * On subsequent calls of ksNext() it will still return the NULL pointer. * * The @p ks internal cursor will be changed, so it is not const. * * @note You must not delete or change the key, use ksPop() if you want to delete it. * * @param ks the keyset object to work with * @return the new current Key * @return 0 when the end is reached * @return 0 on NULL pointer * @see ksRewind(), ksCurrent() */ Key *ksNext(KeySet *ks) { if (!ks) return 0; if (ks->size == 0) return 0; if (ks->current >= ks->size) { return 0; } if (ks->cursor) ks->current++; return ks->cursor = ks->array[ks->current]; } /** * Return the current Key. * * The pointer is NULL if you reached the end or after * ksRewind(). * * @note You must not delete the key or change the key, * use ksPop() if you want to delete it. * * @param ks the keyset object to work with * @return pointer to the Key pointed by @p ks's cursor * @return 0 on NULL pointer * @see ksNext(), ksRewind() */ Key *ksCurrent(const KeySet *ks) { if (!ks) return 0; return ks->cursor; } /** * Return the first key in the KeySet. * * The KeySets cursor will not be effected. * * If ksCurrent()==ksHead() you know you are * on the first key. * * @param ks the keyset object to work with * @return the first Key of a keyset * @return 0 on NULL pointer or empty keyset * @see ksTail() for the last key * @see ksRewind(), ksCurrent() and ksNext() for iterating over the keyset */ Key *ksHead(const KeySet *ks) { if (!ks) return 0; if (ks->size > 0) return ks->array[0]; else return 0; } /** * Return the last key in the KeySet. * * The KeySets cursor will not be effected. * * If ksCurrent()==ksTail() you know you * are on the last key. ksNext() will return * a NULL pointer afterwards. * * @param ks the keyset object to work with * @return the last Key of a keyset * @return 0 on NULL pointer or empty keyset * @see ksHead() for the first key * @see ksRewind(), ksCurrent() and ksNext() for iterating over the keyset */ Key *ksTail(const KeySet *ks) { if (!ks) return 0; if (ks->size > 0) return ks->array[ks->size-1]; else return 0; } /** * Get the KeySet internal cursor. * * Use it to get the cursor of the actual position. * * @warning Cursors are getting invalid when the key * was ksPop()ed or ksLookup() with KDB_O_POP was * used. * * @section readahead Read ahead * * With the cursors it is possible to read ahead * in a keyset: * * @code cursor_t jump; ksRewind (ks); while ((key = keyNextMeta (ks))!=0) { // now mark this key jump = ksGetCursor(ks); //code.. keyNextMeta (ks); // now browse on // use ksCurrent(ks) to check the keys //code.. // jump back to the position marked before ksSetCursor(ks, jump); } * @endcode * * @section restore Restoring state * * It can also be used to restore the state of a * keyset in a function * * @code int f (KeySet *ks) { cursor_t state = ksGetCursor(ks); // work with keyset // now bring the keyset to the state before ksSetCursor (ks, state); } * @endcode * * It is of course possible to make the KeySet const * and cast its const away to set the cursor. * Another way to achieve * the same is to ksDup() the keyset, but it is * not as efficient. * * An invalid cursor will be returned directly after * ksRewind(). When you set an invalid cursor ksCurrent() * is 0 and ksNext() == ksHead(). * * @note Only use a cursor for the same keyset which it was * made for. * * @param ks the keyset object to work with * @return a valid cursor on success * @return an invalid cursor on NULL pointer or after ksRewind() * @see ksNext(), ksSetCursor() */ cursor_t ksGetCursor(const KeySet *ks) { if (!ks) return (cursor_t) -1; if (ks->cursor == 0) return (cursor_t) -1; else return (cursor_t) ks->current; } /** * @brief return key at given cursor position * * @param ks the keyset to pop key from * @param pos where to get * @return the key at the cursor position on success * @retval NULL on NULL pointer, negative cursor position * or a position that does not lie within the keyset */ Key *ksAtCursor(KeySet *ks, cursor_t pos) { if (!ks) return 0; if (pos < 0) return 0; if (ks->size < (size_t)pos) return 0; return ks->array[pos]; } /** * @internal * * @brief Pop key at given cursor position * * @param ks the keyset to pop key from * @param c where to pop * * The internal cursor will be rewinded using ksRewind(). You can use * ksGetCursor() and ksSetCursor() jump back to the previous position. * e.g. to pop at current position within ksNext() loop: * @code * cursor_t c = ksGetCursor(ks); * keyDel (ksPopAtCursor(ks, c)); * ksSetCursor(ks, c); * ksPrev(ks); // to have correct key after next ksNext() * @endcode * * @warning do not use, will be superseded by external iterator API * * @return the popped key * @retval 0 if ks is 0 */ Key *ksPopAtCursor(KeySet *ks, cursor_t pos) { if (!ks) return 0; if (pos<0) return 0; if (pos>SSIZE_MAX) return 0; size_t c = pos; if (c>=ks->size) return 0; if (c != ks->size-1) { Key ** found = ks->array+c; Key * k = *found; /* Move the array over the place where key was found * * e.g. c = 2 * size = 6 * * 0 1 2 3 4 5 6 * |--|--|c |--|--|--|size * move to (c/pos is overwritten): * |--|--|--|--|--| * * */ memmove (found, found+1, (ks->size-c-1) * sizeof(Key *)); *(ks->array+ks->size-1) = k; // prepare last element to pop } else { // if c is on last position it is just a ksPop.. // so do nothing.. } ksRewind(ks); return ksPop(ks); } /** * Set the KeySet internal cursor. * * Use it to set the cursor to a stored position. * ksCurrent() will then be the position which you got with. * * @warning Cursors may get invalid when the key * was ksPop()ed or ksLookup() was used together * with KDB_O_POP. * * @code cursor_t cursor; .. // key now in any position here cursor = ksGetCursor (ks); while ((key = keyNextMeta (ks))!=0) {} ksSetCursor (ks, cursor); // reset state ksCurrent(ks); // in same position as before * @endcode * * An invalid cursor will set the keyset to its beginning like * ksRewind(). When you set an invalid cursor ksCurrent() * is 0 and ksNext() == ksHead(). * * @param cursor the cursor to use * @param ks the keyset object to work with * @return 0 when the keyset is ksRewind()ed * @return 1 otherwise * @return -1 on NULL pointer * @see ksNext(), ksGetCursor() */ int ksSetCursor(KeySet *ks, cursor_t cursor) { if (!ks) return -1; if ((cursor_t) -1 == cursor) { ksRewind (ks); return 0; } ks->current= (size_t)cursor; ks->cursor=ks->array[ks->current]; return 1; } /******************************************* * Looking up Keys inside KeySets * *******************************************/ static int keyCompareByName(const void *p1, const void *p2) { Key *key1=*(Key **)p1; Key *key2=*(Key **)p2; const char *name1 = keyName(key1); const char *name2 = keyName(key2); return strcmp(name1, name2); } static int keyCompareByNameCase(const void *p1, const void *p2) { Key *key1=*(Key **)p1; Key *key2=*(Key **)p2; const char *name1 = keyName(key1); const char *name2 = keyName(key2); return elektraStrCaseCmp(name1, name2); } static int keyCompareByNameOwner(const void *p1, const void *p2) { Key *key1=*(Key **)p1; Key *key2=*(Key **)p2; const char *name1 = keyName(key1); const char *name2 = keyName(key2); int result = strcmp(name1, name2); if (result == 0) { const char *owner1 = keyOwner(key1); const char *owner2 = keyOwner(key2); return strcmp(owner1, owner2); } else return result; } static int keyCompareByNameOwnerCase(const void *p1, const void *p2) { Key *key1=*(Key **)p1; Key *key2=*(Key **)p2; const char *name1 = keyName(key1); const char *name2 = keyName(key2); int result = elektraStrCaseCmp(name1, name2); if (result == 0) { const char *owner1 = keyOwner(key1); const char *owner2 = keyOwner(key2); return elektraStrCaseCmp(owner1, owner2); } else return result; } /** * Look for a Key contained in @p ks that matches the name of the @p key. * * @section Introduction * * @p ksLookup() is designed to let you work with * entirely pre-loaded KeySets, so instead of kdbGetKey(), key by key, the * idea is to fully kdbGet() for your application root key and * process it all at once with @p ksLookup(). * * This function is very efficient by using binary search. Together with * kdbGet() which can you load the whole configuration with only * some communication to backends you can write very effective but short * code for configuration. * * @section Usage * * If found, @p ks internal cursor will be positioned in the matched key * (also accessible by ksCurrent()), and a pointer to the Key is returned. * If not found, @p ks internal cursor will not move, and a NULL pointer is * returned. * * Cascading is done if the first character is a /. This leads to ignoring * the prefix like system/ and user/. * @code if (kdbGet(handle, "user/myapp", myConfig, 0 ) == -1) errorHandler ("Could not get Keys"); if (kdbGet(handle, "system/myapp", myConfig, 0 ) == -1) errorHandler ("Could not get Keys"); if ((myKey = ksLookup(myConfig, key, 0)) == NULL) errorHandler ("Could not Lookup Key"); * @endcode * * This is the way multi user Programs should get there configuration and * search after the values. It is guaranteed that more namespaces can be * added easily and that all values can be set by admin and user. * * @subsection KDB_O_NOALL * * When KDB_O_NOALL is set the keyset will be only searched from ksCurrent() * to ksTail(). You need to ksRewind() the keyset yourself. ksCurrent() is * always set properly after searching a key, so you can go on searching * another key after the found key. * * When KDB_O_NOALL is not set the cursor will stay untouched and all keys * are considered. A much more efficient binary search will be used then. * * @subsection KDB_O_POP * * When KDB_O_POP is set the key which was found will be ksPop()ed. ksCurrent() * will not be changed, only iff ksCurrent() is the searched key, then the keyset * will be ksRewind()ed. * * @note Like in ksPop() the popped key always needs to be keyDel() afterwards, even * if it is appended to another keyset. * * @warning All cursors on the keyset will be invalid * iff you use KDB_O_POP, so don't use this if you rely on a cursor, see ksGetCursor(). * * You can solve this problem by using KDB_O_NOALL, risking you have to iterate n^2 instead of n. * * The more elegant way is to separate the keyset you use for ksLookup() and ksAppendKey(): * @code int f(KeySet *iterator, KeySet *lookup) { KeySet *append = ksNew (ksGetSize(lookup), KS_END); Key *key; Key *current; ksRewind(iterator); while (current=ksNext(iterator)) { key = ksLookup (lookup, current, KDB_O_POP); // do something... ksAppendKey(append, key); // now append it to append, not lookup! keyDel (key); // make sure to ALWAYS delete poped keys. } ksAppend(lookup, append); // now lookup needs to be sorted only once, append never ksDel (append); } * @endcode * * @param ks where to look for * @param key the key object you are looking for * @param options some @p KDB_O_* option bits: * - @p KDB_O_NOCASE @n * Lookup ignoring case. * - @p KDB_O_WITHOWNER @n * Also consider correct owner. * - @p KDB_O_NOALL @n * Only search from ksCurrent() to end of keyset, see above text. * - @p KDB_O_POP @n * Pop the key which was found. * - @p KDB_O_DEL @n * Delete the passed key. * @return pointer to the Key found, 0 otherwise * @return 0 on NULL pointers * @see ksLookupByName() to search by a name given by a string * @see ksCurrent(), ksRewind(), ksNext() for iterating over a keyset */ Key *ksLookup(KeySet *ks, Key * key, option_t options) { Key *current; Key ** found; cursor_t cursor = 0; size_t jump = 0; /*If there is a known offset in the beginning jump could be set*/ if (!ks) return 0; cursor = ksGetCursor (ks); if (!key) return 0; if (options & KDB_O_NOALL) { while ((current=ksNext(ks)) != 0) { if ((options & KDB_O_WITHOWNER) && (options & KDB_O_NOCASE)) { if (!keyCompareByNameOwnerCase(&key, &current)) break; } else if (options & KDB_O_WITHOWNER) { if (!keyCompareByNameOwner(&key, &current)) break; } else if (options & KDB_O_NOCASE) { if (!keyCompareByNameCase(&key, &current)) break; } else if (!keyCompareByName(&key, &current)) break; } if (options & KDB_O_DEL) keyDel (key); if (current == 0) ksSetCursor (ks, cursor); return current; } else { if ((options & KDB_O_WITHOWNER) && (options & KDB_O_NOCASE)) found = (Key **) bsearch (&key, ks->array+jump, ks->size-jump, sizeof (Key *), keyCompareByNameOwnerCase); else if (options & KDB_O_WITHOWNER) found = (Key **) bsearch (&key, ks->array+jump, ks->size-jump, sizeof (Key *), keyCompareByNameOwner); else if (options & KDB_O_NOCASE) found = (Key **) bsearch (&key, ks->array+jump, ks->size-jump, sizeof (Key *), keyCompareByNameCase); else found = (Key **) bsearch (&key, ks->array+jump, ks->size-jump, sizeof (Key *), keyCompareByName); if (options & KDB_O_DEL) keyDel (key); if (found) { cursor = found-ks->array; if (options & KDB_O_POP) { return ksPopAtCursor(ks, cursor); } else { ksSetCursor(ks, cursor); return (*found); } } else { /*Reset Cursor to old position*/ ksSetCursor(ks, cursor); return 0; } } } /** * Look for a Key contained in @p ks that matches @p name. * * @p ksLookupByName() is designed to let you work with * entirely pre-loaded KeySets, so instead of kdbGetKey(), key by key, the * idea is to fully kdbGetByName() for your application root key and * process it all at once with @p ksLookupByName(). * * This function is very efficient by using binary search. Together with * kdbGetByName() which can you load the whole configuration with only * some communication to backends you can write very effective but short * code for configuration. * * If found, @p ks internal cursor will be positioned in the matched key * (also accessible by ksCurrent()), and a pointer to the Key is returned. * If not found, @p ks internal cursor will not move, and a NULL pointer is * returned. * If requested to pop the key, the cursor will be rewinded. * * @section cascading Cascading * * Cascading is done if the first character is a /. This leads to ignoring * the prefix like system/ and user/. * @code if (kdbGet(handle, "user/sw/myapp/current", myConfig, parentKey ) == -1) errorHandler ("Could not get Keys", parentKey); if (kdbGet(handle, "system/sw/myapp/current", myConfig, parentKey ) == -1) errorHandler ("Could not get Keys", parentKey); if ((myKey = ksLookupByName (myConfig, "/myapp/current/key", 0)) == NULL) errorHandler ("Could not Lookup Key"); * @endcode * * This is the way multi user Programs should get there configuration and * search after the values. It is guaranteed that more namespaces can be * added easily and that all values can be set by admin and user. * * It is up to the application to implement a sophisticated cascading * algorithm, for e.g. a list of profiles (specific, group and fallback): * @code if ((myKey = ksLookupByName (myConfig, "/myapp/current/specific/key", 0)) == NULL) if ((myKey = ksLookupByName (myConfig, "/myapp/current/group/key", 0)) == NULL) if ((myKey = ksLookupByName (myConfig, "/myapp/current/fallback/key", 0)) == NULL) errorHandler ("All fallbacks failed to lookup key"); * @endcode * * Note that for every profile both the user and the system key are * searched. The first key found will be used. * * @section fullsearch Full Search * * When KDB_O_NOALL is set the keyset will be only searched from ksCurrent() * to ksTail(). You need to ksRewind() the keyset yourself. ksCurrent() is * always set properly after searching a key, so you can go on searching * another key after the found key. * * When KDB_O_NOALL is not set the cursor will stay untouched and all keys * are considered. A much more efficient binary search will be used then. * * @param ks where to look for * @param name key name you are looking for * @param options some @p KDB_O_* option bits: * - @p KDB_O_NOCASE @n * Lookup ignoring case. * - @p KDB_O_WITHOWNER @n * Also consider correct owner. * - @p KDB_O_NOALL @n * Only search from ksCurrent() to end of keyset, see above text. * - @p KDB_O_POP @n * Pop the key which was found. * * Currently no options supported. * @return pointer to the Key found, 0 otherwise * @return 0 on NULL pointers * @see keyCompare() for very powerful Key lookups in KeySets * @see ksCurrent(), ksRewind(), ksNext() */ Key *ksLookupByName(KeySet *ks, const char *name, option_t options) { Key * key=0; Key * found=0; char * newname=0; if (!ks) return 0; if (!name) return 0; if (! ks->size) return 0; if (name[0] == '/') { /* Will be freed by second key */ newname = elektraMalloc (strlen (name) + sizeof ("system") + 1); if (!newname) { /*errno = KDB_ERR_NOMEM;*/ return 0; } strncpy (newname+2, "user",4); strcpy (newname+6, name); key = keyNew (newname+2, KEY_END); found = ksLookup(ks, key, options); keyDel (key); if (!found) { strncpy (newname, "system",6); key = keyNew (newname, KEY_END); found = ksLookup(ks, key, options); keyDel (key); } elektraFree (newname); return found; } else { key = keyNew (name, KEY_END); if (!key) return 0; found = ksLookup(ks, key, options); keyDel (key); return found; } } /* * Lookup for a Key contained in @p ks KeySet that matches @p value, * starting from ks' ksNext() position. * * If found, @p ks internal cursor will be positioned in the matched key * (also accessible by ksCurrent()), and a pointer to the Key is returned. * If not found, @p ks internal cursor won't move, and a NULL pointer is * returned. * * This method skips binary keys. * * @par Example: * @code ksRewind(ks); while (key=ksLookupByString(ks,"my value",0)) { // show all keys which value="my value" keyToStream(key,stdout,0); } * @endcode * * @param ks where to look for * @param value the value which owner key you want to find * @param options some @p KDB_O_* option bits. Currently supported: * - @p KDB_O_NOALL @n * Only search from ksCurrent() to end of keyset, see ksLookup(). * - @p KDB_O_NOCASE @n * Lookup ignoring case. * @return the Key found, 0 otherwise * @see ksLookupByBinary() * @see keyCompare() for very powerful Key lookups in KeySets * @see ksCurrent(), ksRewind(), ksNext() */ Key *ksLookupByString(KeySet *ks, const char *value, option_t options) { cursor_t init=0; Key *current=0; if (!ks) return 0; if (!(options & KDB_O_NOALL)) { ksRewind (ks); init=ksGetCursor(ks); } if (!value) return 0; while ((current=ksNext(ks)) != 0) { if (!keyIsString(current)) continue; /*fprintf (stderr, "Compare %s with %s\n", keyValue(current), value);*/ if ((options & KDB_O_NOCASE) && !elektraStrCaseCmp(keyValue(current),value)) break; else if (!strcmp(keyValue(current),value)) break; } /* reached end of KeySet */ if (!(options & KDB_O_NOALL)) { ksSetCursor (ks, init); } return current; } /* * Lookup for a Key contained in @p ks KeySet that matches the binary @p value, * starting from ks' ksNext() position. * * If found, @p ks internal cursor will be positioned in the matched key. * That means it is also accessible by ksCurrent(). A pointer to the Key * is returned. If not found, @p ks internal cursor won't move, and a * NULL pointer is returned. * * This method skips string keys. * * @param ks where to look for * @param value the value which owner key you want to find * @param size the size of @p value * @param options some @p KDB_O_* option bits: * - @p KDB_O_NOALL @n * Only search from ksCurrent() to end of keyset, see above text. * @return the Key found, NULL otherwise * @return 0 on NULL pointer * @see ksLookupByString() * @see keyCompare() for very powerful Key lookups in KeySets * @see ksCurrent(), ksRewind(), ksNext() */ Key *ksLookupByBinary(KeySet *ks, const void *value, size_t size, option_t options) { cursor_t init=0; Key *current=0; if (!ks) return 0; if (!(options & KDB_O_NOALL)) { ksRewind (ks); init=ksGetCursor(ks); } while ((current=ksNext(ks))) { if (!keyIsBinary(current)) continue; if (size != current->dataSize) continue; if (!value) { if (!current->data.v) break; else continue; } if (current->data.v && !memcmp(current->data.v,value,size)) break; } /* reached end of KeySet */ if (!(options & KDB_O_NOALL)) { ksSetCursor (ks, init); } return 0; } /******************************************* * Other operations * *******************************************/ /** * @internal * * Calculates the common parent to all keys in @p ks. * * This is a c-helper function, you need not implement it in bindings. * * Given the @p ks KeySet, calculates the parent name for all the keys. * So if @p ks contains this keys: * * @code * system/sw/xorg/Monitors/Monitor1/vrefresh * system/sw/xorg/Monitors/Monitor1/hrefresh * system/sw/xorg/Devices/Device1/driver * system/sw/xorg/Devices/Device1/mode * @endcode * * The common parent is @p system/sw/xorg . * * On the other hand, if we have this KeySet: * * @code * system/some/thing * system/other/thing * user/unique/thing * @endcode * * No common parent is possible, so @p returnedCommonParent will contain nothing. * * @param working the Keyset to work with * @param returnedCommonParent a pre-allocated buffer that will receive the * common parent, if found * @param maxSize size of the pre-allocated @p returnedCommonParent buffer * @return size in bytes of the parent name, or 0 if there is no common parent, * or -1 to indicate an error, then @p errno must be checked. */ ssize_t ksGetCommonParentName(const KeySet *working,char *returnedCommonParent, size_t maxSize) { size_t parentSize=0; Key *current=0; cursor_t init; KeySet *ks; ssize_t sMaxSize; if (maxSize > SSIZE_MAX) return -1; sMaxSize = maxSize; init = ksGetCursor (working); ks = (KeySet *) working; if (ks->size < 1) return 0; ksRewind(ks); current = ksNext(ks); if (keyGetNameSize(current) > sMaxSize) { /*errno=KDB_ERR_TRUNC;*/ returnedCommonParent[0]=0; return -1; } strcpy(returnedCommonParent,keyName(current)); parentSize=elektraStrLen(returnedCommonParent); while (*returnedCommonParent) { ksRewind(ks); while ((current = ksNext(ks)) != 0) { /* Test if a key doesn't match */ if (memcmp(returnedCommonParent,keyName(current),parentSize-1)) break; } if (current) { /* some key failed to be a child */ /* parent will be the parent of current parent... */ char *delim=0; if ((delim=strrchr(returnedCommonParent,KDB_PATH_SEPARATOR))) { *delim=0; parentSize=elektraStrLen(returnedCommonParent); } else { *returnedCommonParent=0; parentSize=0; break; /* Better don't make comparision with parentSize-1 now */ } } else { /* All keys matched (current==0) */ /* We have our common parent to return in commonParent */ ksSetCursor (ks, init ); return parentSize; } } ksSetCursor (ks, init ); return parentSize; /* if reached, will be zero */ } /********************************************************************* * Data constructors (protected) * *********************************************************************/ /** * @internal * * Resize keyset. * * For internal useage only. * * Don't use that function to be portable. You can give an hint * how large the keyset should be in ksNew(). * * Subsequent is the description of the implementation with array. * ksResize() enlarge or shrink the internal array to wished * size alloc. * * If you resize it to n, you can be sure to fill in n-1 elements, * the n-th element will do an automatic resize to n*2. So give * some spare to avoid wasteful duplication. * * @param ks the keyset which should be resized * @param alloc the size to which the array will be resized * @return 1 on success * @return 0 on nothing done because keyset would be too small. * @return -1 if alloc is smaller then current size of keyset. * @return -1 on memory error or null ptr */ int ksResize (KeySet *ks, size_t alloc) { if (!ks) return -1; alloc ++; /* for ending null byte */ if (alloc == ks->alloc) return 1; if (alloc < ks->size) return 0; if (alloc < KEYSET_SIZE) { if (ks->alloc != KEYSET_SIZE) alloc = KEYSET_SIZE; else return 0; } if (ks->array == NULL) { /* Not allocated up to now */ ks->alloc = alloc; ks->size = 0; ks->array = elektraMalloc (sizeof(struct _Key *) * ks->alloc); if (!ks->array) { /*errno = KDB_ERR_NOMEM;*/ return -1; } } /* This is much too verbose #if DEBUG && VERBOSE printf ("Resize from %d to %d\n",(int) ks->alloc,(int) alloc); #endif */ ks->alloc=alloc; if (elektraRealloc((void**) &ks->array, sizeof(struct _Key *) * ks->alloc) == -1) { #if DEBUG fprintf (stderr, "Reallocation error\n"); #endif elektraFree (ks->array); ks->array = 0; /*errno = KDB_ERR_NOMEM;*/ return -1; } return 1; } /** * @internal * * Returns current allocation size. * * This is the maximum size before a reallocation * happens. * * @param ks the keyset object to work with * @return allocated size*/ size_t ksGetAlloc (const KeySet *ks) { return ks->alloc-1; } /** * @internal * * KeySet object initializer. * * You should always use ksNew() instead of ksInit(). * * Every KeySet object that will be used must be initialized first, to setup * pointers, counters, etc. After use, all ksInit()ialized KeySets must be * cleaned with ksClear(). * * @see ksNew(), ksClose(), keyInit() * @return 1 on success */ int ksInit(KeySet *ks) { ks->array = 0; ks->size=0; ks->alloc=0; ks->flags=0; ksRewind(ks); return 1; } /** * @internal * * KeySet object initializer. * * @see ksDel(), ksNew(), keyInit() * @return 1 on success */ int ksClose(KeySet *ks) { Key * k; ksRewind(ks); while ((k = ksNext(ks)) != 0) { keyDecRef (k); keyDel (k); } if (ks->array) elektraFree (ks->array); ks->array = 0; ks->alloc = 0; ks->size = 0; return 0; } /** * @} */
2.46875
2
2024-11-18T22:11:20.154752+00:00
2022-05-13T00:38:02
236c59a4f30dc1f5ca9300ca379ea1ca20859125
{ "blob_id": "236c59a4f30dc1f5ca9300ca379ea1ca20859125", "branch_name": "refs/heads/master", "committer_date": "2022-05-13T00:38:02", "content_id": "2da5ac7d203d578990629130b51c75a212a17fa5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9c53eabf6e8fc1223124e0da8e8d2c051609f451", "extension": "h", "filename": "queue.h", "fork_events_count": 62, "gha_created_at": "2020-04-08T20:19:06", "gha_event_created_at": "2022-12-20T20:09:57", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 254191670, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4724, "license": "Apache-2.0", "license_type": "permissive", "path": "/projects/CYW20819A1/emulation/queue.h", "provenance": "stackv2-0072.json.gz:46790", "repo_name": "seemoo-lab/frankenstein", "revision_date": "2022-05-13T00:38:02", "revision_id": "b5053b5a1ebdd139644071c46e33053aa860672f", "snapshot_id": "7ce8d095b293d0934963517fe1240a1c58699b2e", "src_encoding": "UTF-8", "star_events_count": 410, "url": "https://raw.githubusercontent.com/seemoo-lab/frankenstein/b5053b5a1ebdd139644071c46e33053aa860672f/projects/CYW20819A1/emulation/queue.h", "visit_date": "2023-08-02T10:27:27.474008" }
stackv2
#include <frankenstein/hook.h> struct queue_access { uint32_t thread; uint32_t queue; uint32_t lr; }; struct queue_access queue_read[1024]; int queue_read_n = 0; void queue_read_access(struct saved_regs *regs, void *arg) { for (int i = 0; i < queue_read_n; i++) if ( queue_read[i].thread == _tx_thread_current_ptr && queue_read[i].queue == regs->r0 && queue_read[i].lr == regs->lr ) return; //add access queue_read[queue_read_n].thread = _tx_thread_current_ptr; queue_read[queue_read_n].queue = regs->r0; queue_read[queue_read_n].lr = regs->lr; queue_read_n ++; //dump print("queue read thread="); print_ptr(_tx_thread_current_ptr); print(" queue="); print_ptr(regs->r0); print(" lr="); print_ptr(regs->lr); print("\n"); } struct queue_access queue_write[1024]; int queue_write_n = 0; void queue_write_access(struct saved_regs *regs, void *arg) { for (int i = 0; i < queue_write_n; i++) if ( queue_write[i].thread == _tx_thread_current_ptr && queue_write[i].queue == regs->r0 && queue_write[i].lr == regs->lr ) return; //add access queue_write[queue_write_n].thread = _tx_thread_current_ptr; queue_write[queue_write_n].queue = regs->r0; queue_write[queue_write_n].lr = regs->lr; queue_write_n ++; //dump print("queue write thread="); print_ptr(_tx_thread_current_ptr); print(" queue="); print_ptr(regs->r0); print(" lr="); print_ptr(regs->lr); print("\n"); } struct queue_access slist_read[1024]; int slist_read_n = 0; void slist_read_access(struct saved_regs *regs, void *arg) { for (int i = 0; i < slist_read_n; i++) if ( slist_read[i].thread == _tx_thread_current_ptr && slist_read[i].queue == regs->r0 && slist_read[i].lr == regs->lr ) return; //add access slist_read[slist_read_n].thread = _tx_thread_current_ptr; slist_read[slist_read_n].queue = regs->r0; slist_read[slist_read_n].lr = regs->lr; slist_read_n ++; //dump print("slist read thread="); print_ptr(_tx_thread_current_ptr); print(" slist="); print_ptr(regs->r0); print(" lr="); print_ptr(regs->lr); print("\n"); } struct queue_access slist_write[1024]; int slist_write_n = 0; void slist_write_access(struct saved_regs *regs, void *arg) { for (int i = 0; i < slist_write_n; i++) if ( slist_write[i].thread == _tx_thread_current_ptr && slist_write[i].queue == regs->r1 && slist_write[i].lr == regs->lr ) return; //add access slist_write[slist_write_n].thread = _tx_thread_current_ptr; slist_write[slist_write_n].queue = regs->r1; slist_write[slist_write_n].lr = regs->lr; slist_write_n ++; //dump print("slist write thread="); print_ptr(_tx_thread_current_ptr); print(" slist="); print_ptr(regs->r1); print(" lr="); print_ptr(regs->lr); print("\n"); } void queue_add_hooks() { trace(msgqueue_Put, 2, false); trace(msgqueue_PutInFront, 2, false); trace(msgqueue_Get, 1, true); trace(msgqueue_GetNonblock, 1, true); add_hook(msgqueue_Get, &queue_read_access, NULL, NULL); add_hook(msgqueue_PrivateGet, &queue_read_access, NULL, NULL); add_hook(msgqueue_GetNonblock, &queue_read_access, NULL, NULL); add_hook(msgqueue_PrivateGet, queue_read_access, NULL, NULL); add_hook(msgqueue_Put, &queue_write_access, NULL, NULL); add_hook(msgqueue_PutInFront, &queue_write_access, NULL, NULL); add_hook(osapi_sendQueueItem, &queue_read_access, NULL, NULL); add_hook(osapi_getQueueItem, &queue_write_access, NULL, NULL); add_hook(osapi_sendQueueItemToFront, &queue_write_access, NULL, NULL); add_hook(osapi_getQueueItem_tx, &queue_read_access, NULL, NULL); add_hook(osapi_sendQueueItem_tx, &queue_write_access, NULL, NULL); add_hook(osapi_sendQueueItemToFront_tx, &queue_write_access, NULL, NULL); add_hook(_tx_queue_receive, &queue_read_access, NULL, NULL); add_hook(_tx_queue_send, &queue_write_access, NULL, NULL); add_hook(_tx_queue_front_send, &queue_write_access, NULL, NULL); //add_hook(slist_get, &slist_read_access, NULL, NULL); //Too short + misaligned //add_hook(slist_tail, &slist_read_access, NULL, NULL); // Function too short add_hook(slist_front, &slist_read_access, NULL, NULL); add_hook(slist_add_after, &slist_write_access, NULL, NULL); add_hook(slist_add_front, &slist_write_access, NULL, NULL); add_hook(slist_add_tail, &slist_write_access, NULL, NULL); add_hook(slist_add_before, &slist_write_access, NULL, NULL); }
2.15625
2
2024-11-18T22:11:23.975933+00:00
2022-05-03T06:20:18
8a2bcf478669fa4951948edca506d0ce311929cf
{ "blob_id": "8a2bcf478669fa4951948edca506d0ce311929cf", "branch_name": "refs/heads/master", "committer_date": "2022-05-03T06:20:18", "content_id": "75aa1601680c06e2276270f07cf8fc13a516438e", "detected_licenses": [ "MIT" ], "directory_id": "49131570ce0a38fd620bb3cc8c05e6ed9574f37f", "extension": "c", "filename": "List.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 206841944, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1021, "license": "MIT", "license_type": "permissive", "path": "/CS442/Assignment1/List.c", "provenance": "stackv2-0072.json.gz:47176", "repo_name": "BookerLoL/UWLCourses", "revision_date": "2022-05-03T06:20:18", "revision_id": "e9ba7a3ae1949de30e1987a0e15934ba4aaf6b2e", "snapshot_id": "739983376fb944ee7946236558628befc9c7f945", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BookerLoL/UWLCourses/e9ba7a3ae1949de30e1987a0e15934ba4aaf6b2e/CS442/Assignment1/List.c", "visit_date": "2022-05-17T03:57:51.019315" }
stackv2
#include "List.h" #include <stdio.h> #include <stdlib.h> struct List* CreateList(int type) { struct List *list = (struct List*) malloc(sizeof(struct List)); if (!list) { perror("Failed to allocate memory for list"); exit(-1); } list->type = type; list->count = 0; list->head = NULL; return list; } void AddLineNumber(struct List *list, int lineNumber) { struct Info *node = (struct Info*) malloc(sizeof(struct Info)); node->lineNumber = lineNumber; node->next = list->head; list->head = node; list->count = list->count + 1; } int GetType(struct List *list) { return list->type; } int GetCount(struct List *list) { return list->count; } void PrintLineNumber(struct List *list) { struct Info *temp = list->head; while (temp) { printf("%d, ", temp->lineNumber); temp = temp->next; } } void DestroyList(struct List *list) { struct Info *current = NULL; while ((current = list->head)) { list->head = list->head->next; free(current); } free(list); }
3.328125
3
2024-11-18T22:11:24.034202+00:00
2023-02-09T09:29:09
3700209357ff4c885d00988d7ecafff31fda3aa0
{ "blob_id": "3700209357ff4c885d00988d7ecafff31fda3aa0", "branch_name": "refs/heads/master", "committer_date": "2023-02-09T09:29:23", "content_id": "b63eb55729a1b32a362256df570090ff752fed51", "detected_licenses": [ "MIT" ], "directory_id": "572e1d9ce1ce214c4f1d549f4603cf1cc816c81a", "extension": "h", "filename": "LinkList.h", "fork_events_count": 73, "gha_created_at": "2019-06-10T04:21:30", "gha_event_created_at": "2021-02-17T06:34:41", "gha_language": "Go", "gha_license_id": "MIT", "github_id": 191095894, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1059, "license": "MIT", "license_type": "permissive", "path": "/sources/c/list/LinkList.h", "provenance": "stackv2-0072.json.gz:47306", "repo_name": "overnote/over-algorithm", "revision_date": "2023-02-09T09:29:09", "revision_id": "fa0f2e6f78500b9811bcfa111b22f20232cff929", "snapshot_id": "154eda498afce7a3b9126c2d8c080bb943d2f01d", "src_encoding": "UTF-8", "star_events_count": 343, "url": "https://raw.githubusercontent.com/overnote/over-algorithm/fa0f2e6f78500b9811bcfa111b22f20232cff929/sources/c/list/LinkList.h", "visit_date": "2023-03-03T07:15:01.394153" }
stackv2
/** * 单链表 */ typedef int DataType; // 经典教材写法 // typedef struct Node { // DataType data; // 结点数据 // struct Node *next; // 指向下一个结点的指针 // } Node, *LinkList; // 笔者的写法:方便改造,如添加尾指针等等 // 额外的 size 为 int 类型,可以避免在头结点存储数据修改 DataType 造成的尴尬 typedef struct Node{ DataType data; // 结点数据 struct Node *next; // 指向下一个结点的指针 } Node; typedef struct { struct Node *head; int size; // 链表元素个数(不包括头结点) } LinkList; Node* newNode(DataType e); LinkList* newLinkList(); int insert(LinkList *L, DataType e, int index); int delete(LinkList *L, int index, DataType *e); void update(LinkList *L, int index, DataType e); Node* search(LinkList *L, DataType e); Node* locate(LinkList *L, int index); int length(LinkList *L); void clear(LinkList *L); void destroy(LinkList *L); void display(LinkList *L);
2.78125
3
2024-11-18T22:11:24.546727+00:00
2018-06-24T18:50:01
11907a9b8a609399513927512dd769e9e40d35db
{ "blob_id": "11907a9b8a609399513927512dd769e9e40d35db", "branch_name": "refs/heads/master", "committer_date": "2018-06-24T19:36:10", "content_id": "4741cf148e9da5906f19c49cf3c4b2d70008fe5a", "detected_licenses": [ "MIT" ], "directory_id": "4e7d1290b2dcbec3ac66b70bbafc3d5347317b8c", "extension": "c", "filename": "mem.c", "fork_events_count": 0, "gha_created_at": "2018-11-22T06:46:15", "gha_event_created_at": "2018-11-22T06:46:15", "gha_language": null, "gha_license_id": "MIT", "github_id": 158654332, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2470, "license": "MIT", "license_type": "permissive", "path": "/attic/mem.c", "provenance": "stackv2-0072.json.gz:47564", "repo_name": "github188/catlib", "revision_date": "2018-06-24T18:50:01", "revision_id": "54d239e5ac9ccb6febb7d172d072f100e137cba2", "snapshot_id": "c15cd4c31168a7bd5dd46c662a6fa0dacd8264ed", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/github188/catlib/54d239e5ac9ccb6febb7d172d072f100e137cba2/attic/mem.c", "visit_date": "2020-04-07T19:34:48.502359" }
stackv2
/* * mem.c -- funtions needed by most or all modules * * by Christopher Adam Telfer * * Copyright 2003, 2004 See accompanying license * */ #include <cat/cat.h> #include <cat/mem.h> void *mem_get(struct memsys *m, unsigned long len) { if ( !m || !m->ms_alloc ) return NULL; return m->ms_alloc(m, len); } void *mem_resize(struct memsys *m, void *mem, unsigned long len) { if ( !m || !m->ms_resize ) return NULL; return m->ms_resize(m, mem, len); } void mem_free(struct memsys *m, void *mem) { if ( !m || !m->ms_free ) return; return m->ms_free(m, mem); } void applyfree(void *data, void *mp) { struct memsys *m = mp; m->ms_free(m, data); } #if defined(CAT_USE_STDLIB) && CAT_USE_STDLIB #include <stdlib.h> #include <string.h> #include <cat/err.h> void * std_alloc(struct memsys *m, unsigned size) { assert(m && size > 0); return malloc(size); } void * std_resize(struct memsys *m, void *old, unsigned newsize) { assert(m && newsize > 0); return realloc(old, newsize); } void std_free(struct memsys *m, void *old) { assert(m); return free(old); } struct memsys stdmem = { std_alloc, std_resize, std_free, &stdmem }; void * emalloc(size_t size) { void *m; if ( !(m = malloc(size)) ) errsys("emalloc: "); return m; } void * erealloc(void *old, size_t size) { void *m; if ( !(m = realloc(old, size)) ) errsys("erealloc: "); return m; } void * std_ealloc(struct memsys *mc, unsigned size) { void *m; assert(mc && size > 0); if ( !(m = malloc(size)) ) errsys("malloc: "); return m; } void * std_eresize(struct memsys *mc, void *old, unsigned newsize) { void *m; assert(mc && newsize >= 0); if ( !(m = realloc(old, newsize)) ) errsys("realloc: "); return m; } struct memsys estdmem = { std_ealloc, std_eresize, std_free, &xstdmem }; #include <cat/ex.h> const char *XMemErr = "Memory Error"; void *xmalloc(size_t size) { void *m; if ( !(m = malloc(size)) ) ex_throw((void *)XMemErr); return m; } void *xrealloc(void *old, size_t size) { void *m; if ( !(m = realloc(old, size)) ) ex_throw((void *)XMemErr); return m; } void *std_xalloc(struct memsys *msys, unsigned size) { assert(msys); return xmalloc(size); } void *std_xresize(struct memsys *msys, void *old, unsigned size) { assert(msys); return xrealloc(old, size); } struct memsys xstdmem = { std_xalloc, std_xresize, std_free, &xstdmem }; #endif /* CAT_USE_STDLIB */
2.625
3
2024-11-18T22:11:24.737007+00:00
2018-10-10T23:36:48
938688bef1128f50fb7b6d953cc4ede55d5c5c41
{ "blob_id": "938688bef1128f50fb7b6d953cc4ede55d5c5c41", "branch_name": "refs/heads/master", "committer_date": "2018-10-10T23:36:48", "content_id": "343f2577680f0f95c21ff3ed1e698afd4c9b658b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "fbd6910df876c774f09c95a6a2ace0d83a59219d", "extension": "c", "filename": "tree_buffers.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 152502717, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3700, "license": "Apache-2.0", "license_type": "permissive", "path": "/concept/tree_buffers.c", "provenance": "stackv2-0072.json.gz:47692", "repo_name": "tedinski/adtc", "revision_date": "2018-10-10T23:36:48", "revision_id": "c4649a2292e32f20636af5e0f3a3d300fd104aad", "snapshot_id": "2eb921a5a79453726172ddde57b3d5a08ee43c16", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/tedinski/adtc/c4649a2292e32f20636af5e0f3a3d300fd104aad/concept/tree_buffers.c", "visit_date": "2020-03-31T19:33:40.449486" }
stackv2
#include <stdlib.h> #include <assert.h> #include <limits.h> #include "tree.h" #include "buffers.h" typedef unsigned int idx; const int NO_IDX = UINT_MAX; struct tree_root { struct buffer buf; idx rt; }; struct tree_ref { idx index; }; struct tree_ref_any { enum { TREE_NODE, TREE_LEAF } type; }; struct tree_ref_node { struct tree_ref_any header; idx left; idx right; }; struct tree_ref_leaf { struct tree_ref_any header; int value; }; // internal apis idx tree_ref_copy(struct tree_root *target, struct buffer *buf, idx index); idx tree_node_copy(struct tree_root *target, struct buffer *buf, struct tree_ref_node *orig); idx tree_leaf_copy(struct tree_root *target, struct buffer *buf, struct tree_ref_leaf *orig); struct tree_root *tree_new() { struct tree_root *tree = malloc(sizeof(*tree)); buffer_init(&tree->buf, 3, 4*1024); tree->rt = NO_IDX; return tree; } void tree_root_set(struct tree_root *root, struct tree_ref ref) { root->rt = ref.index; } struct tree_root *tree_copy(struct tree_root *orig) { struct tree_root *tree = tree_new(); if(orig->rt != NO_IDX) { tree_root_set(tree, (struct tree_ref){ tree_ref_copy(tree, &orig->buf, orig->rt) }); } return tree; } void tree_delete(struct tree_root *root) { buffer_destroy(&root->buf); free(root); } struct tree_ref tree_node_new(struct tree_root *root) { struct tree_ref_node *ref; struct tree_ref ref_idx; buffer_alloc(&root->buf, sizeof(*ref), (void**)&ref, &ref_idx.index); ref->header.type = TREE_NODE; ref->left = NO_IDX; ref->right = NO_IDX; return ref_idx; } void tree_node_setl(struct tree_root *root, struct tree_ref ref_orig, struct tree_ref l) { struct tree_ref_node *ref = buffer_index(&root->buf, ref_orig.index); assert(ref->header.type == TREE_NODE); ref->left = l.index; } void tree_node_setr(struct tree_root *root, struct tree_ref ref_orig, struct tree_ref r) { struct tree_ref_node *ref = buffer_index(&root->buf, ref_orig.index); assert(ref->header.type == TREE_NODE); ref->right = r.index; } struct tree_ref tree_leaf_new(struct tree_root *root, int v) { struct tree_ref_leaf *ref; struct tree_ref ref_idx; buffer_alloc(&root->buf, sizeof(*ref), (void**)&ref, &ref_idx.index); ref->header.type = TREE_LEAF; ref->value = v; return ref_idx; } idx tree_ref_copy(struct tree_root *target, struct buffer *buf, idx index) { struct tree_ref_any *ref = buffer_index(buf, index); if(ref->type == TREE_NODE) { return tree_node_copy(target, buf, (struct tree_ref_node *)ref); } else if(ref->type == TREE_LEAF) { return tree_leaf_copy(target, buf, (struct tree_ref_leaf *)ref); } else { abort(); } } idx tree_node_copy(struct tree_root *target, struct buffer *buf, struct tree_ref_node *orig) { struct tree_ref ref = tree_node_new(target); idx l = tree_ref_copy(target, buf, orig->left); idx r = tree_ref_copy(target, buf, orig->right); tree_node_setl(target, ref, (struct tree_ref){l}); tree_node_setr(target, ref, (struct tree_ref){r}); return ref.index; } idx tree_leaf_copy(struct tree_root *target, struct buffer *buf, struct tree_ref_leaf *orig) { return tree_leaf_new(target, orig->value).index; } ///// This code needs to know the size of tree_ref, but it should otherwise be unchanged for other benchmarks struct tree_ref generate(struct tree_root *root, int depth) { if(depth == 1) { return tree_leaf_new(root, 0); } struct tree_ref node = tree_node_new(root); tree_node_setl(root, node, generate(root, depth - 1)); tree_node_setr(root, node, generate(root, depth - 1)); return node; } void generate_into(struct tree_root *root, int depth) { struct tree_ref ref = generate(root, depth); tree_root_set(root, ref); }
2.875
3
2024-11-18T22:11:25.219739+00:00
2021-08-22T04:06:05
e9859e168834f0c0af77cc7d86f1fb5ec1ebfbdd
{ "blob_id": "e9859e168834f0c0af77cc7d86f1fb5ec1ebfbdd", "branch_name": "refs/heads/main", "committer_date": "2021-08-22T04:06:05", "content_id": "7a5be391fa76c355f869aea14b9e0005582fa096", "detected_licenses": [ "MIT" ], "directory_id": "5bbd75d91ba4dee5807ab728f6c72f90d36937c8", "extension": "c", "filename": "xt4-5.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 378457803, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 398, "license": "MIT", "license_type": "permissive", "path": "/C5辅导程序(17.9)/第4章/xt4-5.c", "provenance": "stackv2-0072.json.gz:47821", "repo_name": "CSUBioinformatics1801/C_ZYZ", "revision_date": "2021-08-22T04:06:05", "revision_id": "fcf53ca97f2c85974874e86e2323b045e09f26ae", "snapshot_id": "fe3bfbfd78a9ae82df04d53dfd952c61c8a7d42a", "src_encoding": "GB18030", "star_events_count": 1, "url": "https://raw.githubusercontent.com/CSUBioinformatics1801/C_ZYZ/fcf53ca97f2c85974874e86e2323b045e09f26ae/C5辅导程序(17.9)/第4章/xt4-5.c", "visit_date": "2023-07-17T23:54:11.285268" }
stackv2
#include <stdio.h> #include <math.h> #define M 1000 int main() { int i,k; printf("请输入一个小于%d的整数i:",M); scanf("%d",&i); if (i>M) {printf("输入的数不符合要求,请重新输入一个小于%d的整数i:",M); scanf("%d",&i); } k=sqrt(i); printf("%d的平方根的整数部分是:%d\n",i,k); return 0; }
2.78125
3
2024-11-18T22:11:26.101722+00:00
2019-12-06T22:11:56
f89548698f610f1dc07e76f8e0b76ef43f0e9a7c
{ "blob_id": "f89548698f610f1dc07e76f8e0b76ef43f0e9a7c", "branch_name": "refs/heads/master", "committer_date": "2019-12-06T22:11:56", "content_id": "e89c25f2f97ee2a5aef5d83662b2d5fe3a9b1f97", "detected_licenses": [ "MIT" ], "directory_id": "1f497a25af0068f83539c52fcdd72c2ade9d7369", "extension": "c", "filename": "m4_palette_32.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 169236449, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 291, "license": "MIT", "license_type": "permissive", "path": "/libsrc/bitmap/mode4/m4_palette_32.c", "provenance": "stackv2-0072.json.gz:48336", "repo_name": "LinoBigatti/APIagb", "revision_date": "2019-12-06T22:11:56", "revision_id": "5401548a8e723614f19034e1411055bda500430e", "snapshot_id": "1425d1c1b7df6341f088758cbc73fed8023bfe21", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LinoBigatti/APIagb/5401548a8e723614f19034e1411055bda500430e/libsrc/bitmap/mode4/m4_palette_32.c", "visit_date": "2020-04-21T01:51:20.317712" }
stackv2
//Load a palette into mode 4, using 32 bits units. (Recommended) #include <bitmap/mode4/m4_palette_32.h> void m4_palette_32(const void *src_, u32 length) { u32 *dst = (u32*)m4_pal_memory; u32 *src = (u32*)src_; for(int ii = 0; ii < length; ii++) { dst[ii] = src[ii]; } }
2.484375
2
2024-11-18T22:11:26.802109+00:00
2022-12-12T16:35:29
a986f2f53a54ea1bf6373ab35b1b3808d04c285f
{ "blob_id": "a986f2f53a54ea1bf6373ab35b1b3808d04c285f", "branch_name": "refs/heads/master", "committer_date": "2022-12-12T16:35:29", "content_id": "4428e8dee4df4caa3629b753411556a7e6e3251b", "detected_licenses": [ "MIT" ], "directory_id": "51a62cf6043094e32b4c75da5fe20ac31f53d711", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2018-04-08T15:44:18", "gha_event_created_at": "2022-12-12T16:36:09", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 128656614, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 979, "license": "MIT", "license_type": "permissive", "path": "/C e C++/Questão 57/main.c", "provenance": "stackv2-0072.json.gz:48464", "repo_name": "AnneLivia/CollegeProjects", "revision_date": "2022-12-12T16:35:29", "revision_id": "96d33d0ed79b5efa8da4a1401acba60b0895e461", "snapshot_id": "9e32c4da216caaa973ebd4e4fe472f57557a3436", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/AnneLivia/CollegeProjects/96d33d0ed79b5efa8da4a1401acba60b0895e461/C e C++/Questão 57/main.c", "visit_date": "2022-12-23T10:13:03.503797" }
stackv2
#include <stdio.h> #include <stdlib.h> int main() { int codigo; float preco,aumento; printf("Qual o preco do produto: "); scanf("%f",&preco); printf("Qual o codigo do produto: "); scanf("%d",&codigo); switch(codigo){ case 1 : aumento = preco + (preco*15/100); printf("O produto recebeu um aumento de 15%% agora ele custa %.2f R$",aumento); break; case 3 : aumento = preco + (preco*20/100); printf("O produto recebeu um aumento de 20%% agora ele custa %.2f R$",aumento); break; case 4 : aumento = preco + (preco*35/100); printf("O produto recebeu um aumento de 35%% agora ele custa %.2f R$",aumento); break; case 8: aumento = preco + (preco*40/100); printf("O produto recebeu um aumento de 40%% agora ele custa %.2f R$",aumento); break; default : printf("Codigo nao referente ao produto"); } return 0; }
3.15625
3
2024-11-18T22:11:27.441440+00:00
2023-05-05T07:18:21
0a3d6bfca87564a576109ab12dc5cbb0539b66ab
{ "blob_id": "0a3d6bfca87564a576109ab12dc5cbb0539b66ab", "branch_name": "refs/heads/master", "committer_date": "2023-05-05T07:18:21", "content_id": "b712a46eca9467f7a637ff4ad2ffe8c9d5cca12c", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ace570f65d70e6ce9461bcb81aaaac31c57ec111", "extension": "c", "filename": "fault_handler.c", "fork_events_count": 95, "gha_created_at": "2015-12-17T16:17:35", "gha_event_created_at": "2023-05-05T07:18:22", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 48184998, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9012, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/firmware/common/fault_handler.c", "provenance": "stackv2-0072.json.gz:48981", "repo_name": "greatscottgadgets/greatfet", "revision_date": "2023-05-05T07:18:21", "revision_id": "2409575d28fc7c9cae44c9085c7457ddfb54f893", "snapshot_id": "9ed060aec2d293844c0ac59612f09ecae9c7632b", "src_encoding": "UTF-8", "star_events_count": 273, "url": "https://raw.githubusercontent.com/greatscottgadgets/greatfet/2409575d28fc7c9cae44c9085c7457ddfb54f893/firmware/common/fault_handler.c", "visit_date": "2023-05-12T18:12:31.748720" }
stackv2
/* * This file is part of GreatFET */ #include <toolchain.h> #include <stdint.h> #include <debug.h> #include <drivers/reset.h> #include <drivers/platform_clock.h> #include <drivers/arm_system_control.h> #include <backtrace.h> #include "greatfet_core.h" #include "fault_handler.h" typedef struct { // System state (stored by our prelude). uint32_t r4; uint32_t r5; uint32_t r6; union { uint32_t r7; uint32_t sp; }; uint32_t r8; uint32_t r9; uint32_t r10; uint32_t r11; // Exception stack (already pushed). uint32_t r0; uint32_t r1; uint32_t r2; uint32_t r3; uint32_t r12; uint32_t lr; /* Link Register. */ uint32_t pc; /* Program Counter. */ uint32_t psr;/* Program Status Register. */ } hard_fault_stack_t; #define SAVE_STATE_AND_CALL(target) \ __asm__("PUSH {r4-r11}"); \ __asm__("TST LR, #4"); \ __asm__("ITE EQ"); \ __asm__("MRSEQ R0, MSP"); \ __asm__("MRSNE R0, PSP"); \ __asm__("B " #target) #define HANDLER_THUNK_FOR(handler) \ ATTR_NAKED void handler(void) { SAVE_STATE_AND_CALL(handler##_c); } HANDLER_THUNK_FOR(hard_fault_handler); HANDLER_THUNK_FOR(mem_manage_handler); HANDLER_THUNK_FOR(bus_fault_handler); HANDLER_THUNK_FOR(usage_fault_handler) volatile hard_fault_stack_t* hard_fault_stack_pt; /** * Configure the system to use ancillary faults. */ static void set_up_fault_handlers() { arm_system_control_register_block_t *scb = arch_get_system_control_registers(); // Enable bus and memory-management faults. scb->memory_managemnt_faults_enabled = 1; scb->bus_faults_enabled = 1; scb->usage_faults_enabled = 1; } CALL_ON_PREINIT(set_up_fault_handlers); /** * Trigger an emergency reset, which resets with REASON_FAULT. */ static void emergency_reset(void) { pr_emergency("Resetting system following fault!\n"); pr_emergency("Performing emergency reset...\n"); system_reset(RESET_REASON_FAULT, true); } /** * Prints the system's state at a given log level. */ void print_system_state(loglevel_t loglevel, hard_fault_stack_t *args) { backtrace_frame_t frame; uintptr_t frame_pointer = args->sp - sizeof(backtrace_frame_t); uint32_t program_counter = args->pc; uint32_t *stack = (uint32_t *)args->sp; // Other interesting registers to examine: // CFSR: Configurable Fault Status Register // HFSR: Hard Fault Status Register // DFSR: Debug Fault Status Register // AFSR: Auxiliary Fault Status Register // MMAR: MemManage Fault Address Register // BFAR: Bus Fault Address Register // TODO insert special registers printk(loglevel, "\n"); printk(loglevel, "Current core: Cortex-M4\n"); // FIXME detect this; right now we're harcoding because we only use the M4 printk(loglevel, "System clock source: %s @ %" PRIu32 " Hz\n", platform_get_cpu_clock_source_name(), platform_get_cpu_clock_source_frequency()); printk(loglevel, " PC: %08" PRIx32 "\t\tLR: %08" PRIx32 "\n", program_counter, args->lr); printk(loglevel, " R0: %08" PRIx32 "\t\tR1: %08" PRIx32 "\n", args->r0, args->r1); printk(loglevel, " R2: %08" PRIx32 "\t\tR3: %08" PRIx32 "\n", args->r2, args->r3); printk(loglevel, " R4: %08" PRIx32 "\t\tR5: %08" PRIx32 "\n", args->r4, args->r5); printk(loglevel, " R6: %08" PRIx32 "\t\tR7|SP: %08" PRIx32 "\n", args->r6, args->r7); printk(loglevel, " R8: %08" PRIx32 "\t\tR9: %08" PRIx32 "\n", args->r8, args->r9); printk(loglevel, " R10: %08" PRIx32 "\t\tR11: %08" PRIx32 "\n", args->r10, args->r11); printk(loglevel, " R12: %08" PRIx32 "\t\tPSR: %08" PRIx32 "\n", args->r12, args->psr); // Print the raw stack. printk(loglevel, "Stack:\n"); for (int i = 0; i < 12; i += 4) { printk(loglevel, " %08" PRIx32 "%08" PRIx32 " %08" PRIx32 " %08" PRIx32 "\n", stack[i], stack[i + 1], stack[i + 2], stack[i + 3]); } // Print a stack trace, assuming we have one. frame.sp = frame_pointer; frame.fp = frame_pointer; frame.lr = args->lr; //frame.pc = program_counter; frame.pc = args->lr; print_backtrace_from_frame(loglevel, &frame, 0); // Fin. printk(loglevel, "\n"); } void mem_manage_handler_c(hard_fault_stack_t *state) { arm_system_control_register_block_t *scb = arch_get_system_control_registers(); pr_emergency("\n\n"); pr_emergency("FAULT: memory management fault detected!\n"); pr_emergency(" MMFSR: %02x\t MMFAR: %08" PRIx32 "\n", scb->mmfsr, scb->mmfar); pr_emergency(" is instruction access violation: %s\n", scb->memory_management_faults.instruction_access ? "yes" : "no"); pr_emergency(" is data access violation: %s\n", scb->memory_management_faults.data_access ? "yes" : "no"); pr_emergency(" during stacking for exception: %s\n", scb->memory_management_faults.on_stacking ? "yes" : "no"); pr_emergency(" during unstacking after exception: %s\n", scb->memory_management_faults.on_unstacking ? "yes" : "no"); if (scb->memory_management_faults.fault_address_valid) { pr_emergency("Faulting address: 0x%08" PRIx32 " (accessed as data)\n", scb->memory_management_faulting_address); } else { if (scb->memory_management_faults.instruction_access) { pr_emergency("Faulting address: 0x%08" PRIx32 " (accessed as instruction)\n", state->pc); } else { pr_emergency("Faulting address not known (MMFAR invalid).\n"); } } pr_emergency("\n"); print_system_state(LOGLEVEL_EMERGENCY, state); emergency_reset(); } void bus_fault_handler_c(hard_fault_stack_t *state) { arm_system_control_register_block_t *scb = arch_get_system_control_registers(); pr_emergency("\n\n"); pr_emergency("FAULT: bus fault detected!\n"); if (scb->bus_faults.fault_address_valid) { const char *decorator; if (scb->bus_faults.instruction_bus) { decorator = "(accessed as instruction)"; } else if (scb->bus_faults.precise_data_bus) { decorator = "(accessed as data)"; } else { decorator = "(unknown access via data bus)"; } pr_emergency(" faulting address: 0x%08" PRIx32 " %s\n", scb->bus_faulting_address, decorator); } else { if (scb->bus_faults.imprecise_data_bus) { pr_emergency(" faulting on data access; precise address not known (BFAR invalid).\n"); } else { pr_emergency(" faulting address not known (BFAR invalid).\n"); } } pr_emergency(" BFSR: %02x\t BFAR: %08" PRIx32 "\n", scb->bfsr, scb->bfar); pr_emergency(" is instruction access error: %s\n", scb->bus_faults.instruction_bus ? "yes" : "no"); pr_emergency(" is data bus access error: %s\n", (scb->bus_faults.precise_data_bus | scb->bus_faults.imprecise_data_bus) ? "yes" : "no"); pr_emergency(" stacking fault: %s\n", scb->bus_faults.on_stacking ? "yes" : "no"); pr_emergency(" unstacking fault: %s\n", scb->bus_faults.on_unstacking ? "yes" : "no"); print_system_state(LOGLEVEL_EMERGENCY, state); emergency_reset(); } void usage_fault_handler_c(hard_fault_stack_t *state) { arm_system_control_register_block_t *scb = arch_get_system_control_registers(); pr_emergency("\n\n"); pr_emergency("FAULT: usage fault detected!\n"); if (scb->usage_faults.unaligned_access) { pr_emergency(" reason: unaligned access\n"); } if (scb->usage_faults.divide_by_zero) { pr_emergency(" reason: divide by zero!\n"); } if (scb->usage_faults.no_coprocessor) { pr_emergency(" reason: no such coprocessor / co-processor access fault\n"); pr_emergency(" hint: this likely means this unit didn't have an accessible FPU\n"); } if (scb->usage_faults.invalid_state) { pr_emergency(" reason: invalid access to EPSR\n"); } if (scb->usage_faults.invalid_pc) { pr_emergency(" reason: PC invalid after exception / interrupt return\n"); } pr_emergency(" UFSR: %04" PRIu16 "\n", scb->ufsr); pr_emergency(" CPACR: %08" PRIu32 "\n", scb->cpacr_raw); print_system_state(LOGLEVEL_EMERGENCY, state); emergency_reset(); } __attribute__((used)) void hard_fault_handler_c(hard_fault_stack_t* state) { arm_system_control_register_block_t *scb = arch_get_system_control_registers(); // Announce the fault. pr_emergency("\n"); pr_emergency("FAULT: hard fault detected!\n"); pr_emergency("HFSR: %08" PRIx32 " \tSHCSR: %08" PRIx32 "\n", scb->hfsr, scb->shcsr); pr_emergency(" on vector table read: %s\n", (scb->hard_faults.on_vector_table_read) ? "yes" : "no"); // If this is a forced exception, we likely got here from another fault handler. if (scb->hard_faults.forced) { pr_emergency("FORCED exception! Looking for inner fault...\n"); pr_emergency(" MMFSR: %02x\tBFSR: %02x\tUFSR: %04x\n", scb->mmfsr, scb->bfsr, scb->ufsr); if (scb->mmfsr & SCB_MMFSR_FAULT_MASK) { pr_emergency("Exception has an inner MM fault. Handling accordingly.\n"); mem_manage_handler_c(state); } if (scb->bfsr & SCB_BFSR_FAULT_MASK) { pr_emergency("Exception has an inner bus fault. Handling accordingly.\n"); bus_fault_handler_c(state); } pr_emergency(" ... couldn't figure out what kind of fault this is. Continuing.\n"); } else { pr_emergency(" not a forced exception\n\n"); } print_system_state(LOGLEVEL_EMERGENCY, state); emergency_reset(); }
2.484375
2
2024-11-18T22:11:27.525414+00:00
2017-02-15T07:57:13
839b1d671e48889732ea2c325e9757780bae0270
{ "blob_id": "839b1d671e48889732ea2c325e9757780bae0270", "branch_name": "refs/heads/master", "committer_date": "2017-02-15T07:57:13", "content_id": "f4196ef416f912010e844ed8ba5e6b3880187c94", "detected_licenses": [ "Apache-2.0" ], "directory_id": "903107e8affb1bc02f83c8715735381f98c51a57", "extension": "h", "filename": "test_imu.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 82034770, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 864, "license": "Apache-2.0", "license_type": "permissive", "path": "/Test/Inc/test_imu.h", "provenance": "stackv2-0072.json.gz:49110", "repo_name": "Beck-Sisyphus/RM2017_MAIN_CONTROLLER_DJI", "revision_date": "2017-02-15T07:57:13", "revision_id": "1f136546fae76fd815d402852b2bfbfe6137bc32", "snapshot_id": "5dad531673ba10f9f4e98e4a5dcf2d1070a7c63b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Beck-Sisyphus/RM2017_MAIN_CONTROLLER_DJI/1f136546fae76fd815d402852b2bfbfe6137bc32/Test/Inc/test_imu.h", "visit_date": "2021-01-14T08:17:59.878002" }
stackv2
/** *@file test_imu.h *@date 2016-12-12 *@author Albert.D *@brief */ #ifndef _TEST__IMU_H #define _TEST__IMU_H #include "stm32f4xx_hal.h" #include "main.h" #define MPU6500_NSS_Low() HAL_GPIO_WritePin(GPIOF, GPIO_PIN_6, GPIO_PIN_RESET) #define MPU6500_NSS_High() HAL_GPIO_WritePin(GPIOF, GPIO_PIN_6, GPIO_PIN_SET) typedef struct { int16_t ax; int16_t ay; int16_t az; int16_t temp; int16_t gx; int16_t gy; int16_t gz; int16_t mx; int16_t my; int16_t mz; }IMUDataTypedef; extern uint8_t MPU_id; uint8_t MPU6500_Init(void); uint8_t MPU6500_Write_Reg(uint8_t const reg, uint8_t const data); uint8_t MPU6500_Read_Reg(uint8_t const reg); uint8_t MPU6500_Read_Regs(uint8_t const regAddr, uint8_t *pData, uint8_t len); void IMU_Get_Data(void); uint8_t IST8310_Init(void); #endif
2.0625
2
2024-11-18T22:11:27.713175+00:00
2023-07-20T16:50:46
12914c4be733786be6c82b8d985fda715e24ffeb
{ "blob_id": "12914c4be733786be6c82b8d985fda715e24ffeb", "branch_name": "refs/heads/main", "committer_date": "2023-07-20T16:50:46", "content_id": "d4c0e9c6c0aa59826d6ef518b3ad97ea6eafce0d", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "505585f1d89447adea3f9519f12255602acdb1b2", "extension": "c", "filename": "fcvband.c", "fork_events_count": 120, "gha_created_at": "2017-10-05T17:20:03", "gha_event_created_at": "2023-09-14T20:38:05", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 105918649, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3464, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/cvode/fcmix/fcvband.c", "provenance": "stackv2-0072.json.gz:49239", "repo_name": "LLNL/sundials", "revision_date": "2023-07-20T16:50:46", "revision_id": "1ea097bb3bce207335ac35f0b5e78df5d71c6409", "snapshot_id": "11a879f8c8e7a5e40d78d13d0f9baed04d37a280", "src_encoding": "UTF-8", "star_events_count": 396, "url": "https://raw.githubusercontent.com/LLNL/sundials/1ea097bb3bce207335ac35f0b5e78df5d71c6409/src/cvode/fcmix/fcvband.c", "visit_date": "2023-08-31T12:36:23.500757" }
stackv2
/* * ----------------------------------------------------------------- * Programmer(s): Daniel R. Reynolds @ SMU * Alan C. Hindmarsh and Radu Serban @ LLNL * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2023, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Fortran/C interface routines for CVODE/CVLS, for the case of * a user-supplied Jacobian approximation routine. * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include "fcvode.h" /* actual fn. names, prototypes and global vars.*/ #include "cvode_impl.h" /* definition of CVodeMem type */ #include <cvode/cvode_ls.h> #include <sunmatrix/sunmatrix_band.h> /******************************************************************************/ /* Prototype of the Fortran routine */ #ifdef __cplusplus /* wrapper to enable C++ usage */ extern "C" { #endif extern void FCV_BJAC(long int *N, long int *MU, long int *ML, long int *EBAND, realtype *T, realtype *Y, realtype *FY, realtype *BJAC, realtype *H, long int *IPAR, realtype *RPAR, realtype *V1, realtype *V2, realtype *V3, int *IER); #ifdef __cplusplus } #endif /***************************************************************************/ void FCV_BANDSETJAC(int *flag, int *ier) { if (*flag == 0) { *ier = CVodeSetJacFn(CV_cvodemem, NULL); } else { *ier = CVodeSetJacFn(CV_cvodemem, FCVBandJac); } } /***************************************************************************/ /* C function CVBandJac interfaces between CVODE and a Fortran subroutine FCVBJAC for solution of a linear system with band Jacobian approximation. Addresses of arguments are passed to FCVBJAC, using the accessor routines from the SUNBandMatrix and N_Vector modules. The address passed for J is that of the element in column 0 with row index -mupper. An extended bandwith equal to (J->smu) + mlower + 1 is passed as the column dimension of the corresponding array. */ int FCVBandJac(realtype t, N_Vector y, N_Vector fy, SUNMatrix J, void *user_data, N_Vector vtemp1, N_Vector vtemp2, N_Vector vtemp3) { int ier; realtype *ydata, *fydata, *jacdata, *v1data, *v2data, *v3data; realtype h; long int N, mupper, mlower, smu, eband; FCVUserData CV_userdata; CVodeGetLastStep(CV_cvodemem, &h); ydata = N_VGetArrayPointer(y); fydata = N_VGetArrayPointer(fy); v1data = N_VGetArrayPointer(vtemp1); v2data = N_VGetArrayPointer(vtemp2); v3data = N_VGetArrayPointer(vtemp3); N = SUNBandMatrix_Columns(J); mupper = SUNBandMatrix_UpperBandwidth(J); mlower = SUNBandMatrix_LowerBandwidth(J); smu = SUNBandMatrix_StoredUpperBandwidth(J); eband = smu + mlower + 1; jacdata = SUNBandMatrix_Column(J,0) - mupper; CV_userdata = (FCVUserData) user_data; FCV_BJAC(&N, &mupper, &mlower, &eband, &t, ydata, fydata, jacdata, &h, CV_userdata->ipar, CV_userdata->rpar, v1data, v2data, v3data, &ier); return(ier); }
2.015625
2
2024-11-18T22:11:27.918839+00:00
2016-11-07T08:08:17
b5f6ada2bd7601e16cfd4e3a88db34bc0312baf0
{ "blob_id": "b5f6ada2bd7601e16cfd4e3a88db34bc0312baf0", "branch_name": "refs/heads/master", "committer_date": "2016-11-07T08:08:17", "content_id": "cd3cdfb05d21eadee29bab569db12c5e42141d8b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d23177bc614666c4a9566b9294d0a80210902bbd", "extension": "c", "filename": "polinomial-product-in-c.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 69848029, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2420, "license": "Apache-2.0", "license_type": "permissive", "path": "/polinomial-product-in-c.c", "provenance": "stackv2-0072.json.gz:49498", "repo_name": "pro-metheus/s3-lab-programs", "revision_date": "2016-11-07T08:08:17", "revision_id": "57b9ba4e504dad8fff3439303df4b67075ee54d5", "snapshot_id": "b3c7bdd9c5120f2dcc8500e75ff5aa33ea415514", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pro-metheus/s3-lab-programs/57b9ba4e504dad8fff3439303df4b67075ee54d5/polinomial-product-in-c.c", "visit_date": "2021-05-03T10:51:54.077381" }
stackv2
#include<stdio.h> #include<stdlib.h> struct node{ int c; int e; struct node* next; }*starta=NULL,*startb=0,*cura=0,*curb=0,*pdt,*startp=0,*nextp,*curp=0,*new_node,*prevp; int main() { int n,i,tempe,tempc,j,count=0; printf("enter the number of terms :"); scanf("%d",&n); for(i=0;i<n;i++){ new_node=(struct node*)malloc(sizeof(struct node)); printf("enter the coefficient :"); scanf("%d",&new_node->c); printf("enter the exponent :"); scanf("%d",&new_node->e); new_node->next=NULL; if(starta==NULL){ starta=new_node; cura=new_node; } else{ cura->next=new_node; cura=new_node; } } printf("enter the number of terms :"); scanf("%d",&n); for(i=0;i<n;i++){ new_node=(struct node*)malloc(sizeof(struct node)); printf("enter the coefficient :"); scanf("%d",&new_node->c); printf("enter the exponent :"); scanf("%d",&new_node->e); new_node->next=NULL; if(startb==NULL){ startb=new_node; curb=new_node; } else{ curb->next=new_node; curb=new_node; } } //operations begin from here... //int tempc,tempe; count=0; for(cura=starta;cura!=0;cura=cura->next){ for(curb=startb;curb!=0;curb=curb->next){ //multiply here... //printf("iterated...\n\n\n"); count++; tempc=(cura->c)*(curb->c); tempe=(cura->e)+(curb->e); if(startp==NULL){ new_node=(struct node*)malloc(sizeof(struct node)); new_node->c=tempc; new_node->e=tempe; new_node->next=0; startp=new_node; curp=new_node; //break; }//first product else{ new_node=(struct node*)malloc(sizeof(struct node)); new_node->c=tempc; new_node->e=tempe; new_node->next=NULL; curp=startp; while(curp!=NULL){ int e; e=curp->e; if(curp->e==tempe){ int temp; curp->c=(curp->c)+tempc; break; } else { if(curp->next!=NULL){ if((curp->next)->e>=new_node->e){ curp=curp->next; } else{ new_node->next=curp->next; curp->next=new_node; count++; break; }} else{ curp->next=new_node; break; } }}} }} printf("\n\n\n"); curp=startp; while(curp!=0){ printf("%d(x^%d)",curp->c,curp->e); curp=curp->next; } curp=startp; }
2.859375
3
2024-11-18T22:11:29.883556+00:00
2019-03-18T06:53:57
80c1d4ed5f6f4deafe2305836cf2f8bdbeebbd0d
{ "blob_id": "80c1d4ed5f6f4deafe2305836cf2f8bdbeebbd0d", "branch_name": "refs/heads/master", "committer_date": "2019-03-18T06:53:57", "content_id": "b899769cc33b0f9a904db61003d0cf10f7956847", "detected_licenses": [ "MIT" ], "directory_id": "133fc01c2223f091666715725a15d74b26efdc13", "extension": "c", "filename": "collector.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 176222152, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8858, "license": "MIT", "license_type": "permissive", "path": "/runtime/collector.c", "provenance": "stackv2-0072.json.gz:49754", "repo_name": "qinsoon/mu-proto-compiler", "revision_date": "2019-03-18T06:53:57", "revision_id": "519760655e66ea9dd5a2a15726df177873f573a9", "snapshot_id": "e3ab3e1e2cc724646293d7d0b909347927d82396", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/qinsoon/mu-proto-compiler/519760655e66ea9dd5a2a15726df177873f573a9/runtime/collector.c", "visit_date": "2020-04-29T15:15:17.865918" }
stackv2
#include "runtime.h" #include <stdlib.h> #include <stdio.h> pthread_t controller; pthread_mutex_t controller_mutex; pthread_cond_t controller_cond; GCPhase_t phase; pthread_mutex_t gcPhaseLock; #define VERBOSE_GC false #define VALIDATE_HEAP false void *collector_controller_run(void *param); void initCollector() { pthread_mutex_init(&gcPhaseLock, NULL); // controller int ret = pthread_create(&controller, NULL, collector_controller_run, NULL); if (ret) { uVM_fail("failed to create controller thread"); } } void wakeCollectorController() { pthread_mutex_lock(&controller_mutex); pthread_mutex_lock(&gcPhaseLock); phase = BLOCKING_FOR_GC; pthread_mutex_unlock(&gcPhaseLock); pthread_cond_signal(&controller_cond); pthread_mutex_unlock(&controller_mutex); } // when passed for push and pop, always use these two with & AddressNode* roots; AddressNode* alive; AddressNode* pushToList(Address addr, AddressNode** list) { // check if it already exists AddressNode* cur = *list; for (; cur != NULL; cur = cur->next) { if (cur->addr == addr) return cur; } AddressNode* ret = (AddressNode*) malloc(sizeof(AddressNode)); ret->addr = addr; ret->next = *list; // this is fine even if ret is the first elem in the list *list = ret; return ret; } AddressNode* popFromList(AddressNode** list) { AddressNode* ret = *list; if (ret != NULL) *list = ret->next; else *list = NULL; return ret; } void scanGlobal() {} void scanStacks() { for (int i = 0; i < stackCount; i++) { UVMStack* stack = uvmStacks[i]; if (stack != NULL) { if (stack->thread != NULL) { // scan it scanStackForRoots(stack, &roots); // check roots if (VERBOSE_GC) { printf("Roots:\n"); AddressNode* cur = roots; for (; cur != NULL; cur = cur->next) { printf("0x%llx\n", cur->addr); } } } else { // this is an inactive stack, we didn't have correct rsp and register values on the stack yet? uVM_fail("cant scan an inactive stack"); } } } } void scanRegisters() { // suppose all the registers that represent uvm values are on the stack already // do nothing here } void traceObject(Address ref) { TypeInfo* typeInfo = getTypeInfo(ref); uVM_assert(typeInfo != NULL, "meet a non-ref in traceObject()"); if (VERBOSE_GC) { printf("tracing 0x%llx of type %lld\n", ref, typeInfo->id); printObject(ref); } // mark this object as alive/traced setMarkBitInHeader(ref, OBJECT_HEADER_MARK_BIT_MASK, markState); // additionally we need to mark lines for immix space if (isInImmixSpace(ref)) ImmixSpace_markObject(immixSpace, ref); for (int i = 0; i < typeInfo->nFixedRefOffsets; i++) { Address field = ref + OBJECT_HEADER_SIZE + typeInfo->refOffsets[i]; Address ref = * ((Address*) field); if (VERBOSE_GC) { printf("field: 0x%llx\n", field); printf("->ref: 0x%llx\n", ref); } if (ref != (Address) NULL && !testMarkBitInHeader(ref, OBJECT_HEADER_MARK_BIT_MASK, markState)) pushToList(ref, &alive); } for (int i = typeInfo->nFixedRefOffsets; i < typeInfo->nFixedRefOffsets + typeInfo->nFixedIRefOffsets; i++) { Address field = ref + OBJECT_HEADER_SIZE + typeInfo->refOffsets[i]; Address iref = *((Address*) field); Address ref = findBaseRef(iref); if (VERBOSE_GC) { printf("field: 0x%llx\n ", field); printf("->iref:0x%llx\n", iref); printf("->ref: 0x%llx\n", ref); } if (ref != (Address) NULL && !testMarkBitInHeader(ref, OBJECT_HEADER_MARK_BIT_MASK, markState)) pushToList(ref, &alive); } } void traceObjects() { // trace roots while (roots != NULL) { AddressNode* node = popFromList(&roots); Address ref = node->addr; free(node); Address baseRef = findBaseRef(ref); traceObject(baseRef); } while (alive != NULL) { AddressNode* node = popFromList(&alive); Address ref = node->addr; free(node); traceObject(ref); } } void validateObjectMap() { printf("==== valiedate object map ====\n"); int i = 0; int objects = 0; for (; i < objectMap->bitmapSize; i++) { if (get_bit(objectMap->bitmap, i) != 0) { objects++; Address obj = objectMapIndexToAddress(i); printObject(obj); } } printf("total objects in objectmap: %d\n", objects); printf("============================== \n"); } void validateLargeObjectSpace() { printf("==== valiedate large object space ====\n"); int objects = 0; FreeListNode* cur = largeObjectSpace->head; while (cur != NULL) { printObject(cur->addr); objects++; } printf("total objets in large object space: %d\n", objects); printf("======================================\n"); } void validateHeap() { validateObjectMap(); validateLargeObjectSpace(); } void release() { ImmixSpace_release(immixSpace); FreeListSpace_release(largeObjectSpace); } void prepare() { ImmixSpace_prepare(immixSpace); } void *collector_controller_run(void *param) { DEBUG_PRINT(1, ("Collector Controller running...\n")); pthread_mutex_init(&controller_mutex, NULL); pthread_cond_init(&controller_cond, NULL); // main loop while (true) { // sleep DEBUG_PRINT(1, ("Collector Controller goes asleep\n")); pthread_mutex_lock(&controller_mutex); while (phase != BLOCKING_FOR_GC) { pthread_cond_wait(&controller_cond, &controller_mutex); } pthread_mutex_unlock(&controller_mutex); // block all the mutators DEBUG_PRINT(1, ("Collector Controller is awaken to block all mutators\n")); for (int i = 0; i < threadCount; i++) { UVMThread* t = uvmThreads[i]; if (t != NULL && t->_block_status == RUNNING) { t->_block_status = NEED_TO_BLOCK; } } // ensure everything is blocked DEBUG_PRINT(1, ("Collector Controller is waiting for all mutators to block\n")); bool worldStopped = false; while (!worldStopped) { worldStopped = true; for (int i = 0; i < threadCount; i++) { UVMThread* t = uvmThreads[i]; // DEBUG_PRINT(3, ("Checking on Thread%d...", t->threadSlot)); if (t != NULL && t->_block_status == BLOCKED) { // DEBUG_PRINT(3, ("blocked\n")); continue; } else { // DEBUG_PRINT(3, ("not blocked. Status: %d\n", t->_block_status)); worldStopped = false; break; } } } DEBUG_PRINT(1, ("All mutators blocked\n")); pthread_mutex_lock(&gcPhaseLock); phase = BLOCKED_FOR_GC; pthread_mutex_unlock(&gcPhaseLock); turnOffYieldpoints(); // start to work DEBUG_PRINT(1, ("Collector is going to work\n")); pthread_mutex_lock(&gcPhaseLock); phase = GC; pthread_mutex_unlock(&gcPhaseLock); if (VALIDATE_HEAP) { validateObjectMap(); } prepare(); scanGlobal(); // empty scanStacks(); scanRegisters(); traceObjects(); release(); // reset all mutators for (int i = 0; i < threadCount; i++) { UVMThread* t = uvmThreads[i]; if (t != NULL) { ImmixMutator_reset(&(t->_mutator)); } } if (VALIDATE_HEAP) { validateHeap(); } if (VERBOSE_GC) { printf("mark state = %llx \n", markState); } flipBit(OBJECT_HEADER_MARK_BIT_MASK, &markState); if (VERBOSE_GC) { printf("mark state (after flip) = %llx\n", markState); } // uVM_suspend("check mark state"); // unblock all the mutators DEBUG_PRINT(1, ("Collector Controller is going to unblock all mutators\n")); DEBUG_PRINT(1, ("GC ends")); // uVM_suspend("gc ends"); pthread_mutex_lock(&gcPhaseLock); phase = MUTATOR; pthread_mutex_unlock(&gcPhaseLock); for (int i = 0; i < threadCount; i++) { UVMThread* t = uvmThreads[i]; if (t != NULL) { unblock(t); } } } } void triggerGC() { pthread_mutex_lock(&gcPhaseLock); if (phase != MUTATOR) { pthread_mutex_unlock(&gcPhaseLock); yieldpoint(); return; } pthread_mutex_unlock(&gcPhaseLock); // enable yieldpoint turnOnYieldpoints(); // inform collector controller (it will ensure all threads are blocked) wakeCollectorController(); // make current thread wait UVMThread* cur = getThreadContext(); cur->_block_status = NEED_TO_BLOCK; yieldpoint(); // the thread won't reach here until GC is done }
2.3125
2
2024-11-18T22:11:29.951129+00:00
2016-09-16T16:30:39
07ad62d4d80da9865f5af5f276cf8a45e4b2e3b8
{ "blob_id": "07ad62d4d80da9865f5af5f276cf8a45e4b2e3b8", "branch_name": "refs/heads/master", "committer_date": "2016-09-16T16:30:39", "content_id": "aa9f38a62cc5284ce46efe1058dbc17254bd33cb", "detected_licenses": [ "ISC" ], "directory_id": "910ad66f70466afc401b13260f447b58e8021a31", "extension": "c", "filename": "damper.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13697, "license": "ISC", "license_type": "permissive", "path": "/damper.c", "provenance": "stackv2-0072.json.gz:49882", "repo_name": "mantyr/damper", "revision_date": "2016-09-16T16:30:39", "revision_id": "528e419f5e0d1020dfbabaf71cd961bf7357000e", "snapshot_id": "ff26400ffa02fd50ab0b894a26847a0dc187407c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mantyr/damper/528e419f5e0d1020dfbabaf71cd961bf7357000e/damper.c", "visit_date": "2021-01-22T15:21:49.375660" }
stackv2
/* * $ cc -Wall -pedantic damper.c modules.conf.c -o damper -lnetfilter_queue -pthread -lrt */ #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <ctype.h> #include <linux/netfilter.h> #include <libnetfilter_queue/libnetfilter_queue.h> #include "damper.h" #define BILLION ((uint64_t)1000000000) /* convert string with optional suffixes 'k', 'm' or 'g' (bits per second) to bytes per second */ static uint64_t str2bps(const char *l) { char unit; size_t len; int64_t res; uint64_t k; char lcopy[LINE_MAX]; strncpy(lcopy, l, LINE_MAX); len = strlen(lcopy); if (len == 0) { return 0; } unit = tolower(lcopy[len - 1]); if (isdigit(unit)) { k = 1; } else if (unit == 'k') { k = 1000; } else if (unit == 'm') { k = 1000 * 1000; } else if (unit == 'g') { k = 1000 * 1000 * 1000; } else { /* unknown suffix */ k = 0; } /* drop suffix */ if (k != 1) { lcopy[len-1] = '\0'; } res = strtoll(lcopy, NULL, 10); if ((res == INT64_MIN) || (res == INT64_MAX)) { k = 0; } return res * k / 8; } static void wchart_init(struct userdata *u) { char stat_path[PATH_MAX]; size_t i; for (i=0; modules[i].name; i++) { snprintf(stat_path, PATH_MAX, "%s/%s.1.dat", u->statdir, modules[i].name); modules[i].st = fopen(stat_path, "r+"); /* can't open, try to create */ if (!modules[i].st) { modules[i].st = fopen(stat_path, "w+"); if (!modules[i].st) { fprintf(stderr, "Can't open file '%s'\n", stat_path); } } } } static void stat_init(struct userdata *u) { char stat_path[PATH_MAX]; if (u->statdir[0] == '\0') { fprintf(stderr, "Directory for statistics is not set\n"); goto fail; } snprintf(stat_path, PATH_MAX, "%s/stat.dat", u->statdir); u->statf = fopen(stat_path, "r+"); if (u->statf) { size_t s; s = fread(&u->stat_start, 1, sizeof(time_t), u->statf); if (s < sizeof(time_t)) { fprintf(stderr, "Incorrect statistics file '%s'\n", stat_path); goto fail_close; } } else { /* create new file */ u->statf = fopen(stat_path, "w+"); if (!u->statf) { fprintf(stderr, "Can't open file '%s'\n", stat_path); goto fail; } u->stat_start = time(NULL); if (u->stat_start == ((time_t) -1)) { fprintf(stderr, "time() failed\n"); goto fail_close; } fwrite(&u->stat_start, 1, sizeof(time_t), u->statf); } memset(&u->stat_info, 0, sizeof(u->stat_info)); u->curr_timestamp = time(NULL); u->old_timestamp = u->curr_timestamp; if (u->wchart) { wchart_init(u); } return; fail_close: fclose(u->statf); fail: u->stat = 0; } static void stat_write(struct userdata *u) { struct stat_info old_stat; long int off; size_t rr; off = (u->curr_timestamp - u->stat_start) * sizeof(struct stat_info) + sizeof(time_t); fseek(u->statf, off, SEEK_SET); rr = fread(&old_stat, 1, sizeof(struct stat_info), u->statf); if (rr == sizeof(struct stat_info)) { u->stat_info.packets_pass += old_stat.packets_pass; u->stat_info.octets_pass += old_stat.octets_pass; u->stat_info.packets_drop += old_stat.packets_drop; u->stat_info.octets_drop += old_stat.octets_drop; } fseek(u->statf, off, SEEK_SET); fwrite(&u->stat_info, 1, sizeof(struct stat_info), u->statf); memset(&u->stat_info, 0, sizeof(u->stat_info)); u->old_timestamp = u->curr_timestamp; } static void wchart_write(struct userdata *u, struct module_info *m) { long int off; double avg; avg = (m->nw > DBL_EPSILON) ? (m->stw / m->nw) : 0.0f; off = (u->curr_timestamp - u->stat_start) * sizeof(double); fseek(m->st, off, SEEK_SET); fwrite(&avg, 1, sizeof(double), m->st); m->stw = m->nw = 0.0f; u->old_timestamp = u->curr_timestamp; } static void * stat_thread(void *arg) { struct userdata *u = arg; size_t i; struct timespec ts; for (;;) { /* sleep for nearest second */ clock_gettime(CLOCK_MONOTONIC, &ts); ts.tv_sec++; ts.tv_nsec = 0; clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL); pthread_mutex_lock(&u->lock); u->curr_timestamp++; stat_write(u); for (i=0; modules[i].name && modules[i].enabled; i++) { wchart_write(u, &modules[i]); } pthread_mutex_unlock(&u->lock); } return NULL; } static int config_read(struct userdata *u, char *confname) { FILE *f; char line[LINE_MAX]; f = fopen(confname, "r"); if (!f) { fprintf(stderr, "Can't open file '%s'\n", confname); goto fail_open; } u->stat = 0; u->statdir[0] = '\0'; u->wchart = 0; while (fgets(line, sizeof(line), f)) { char cmd[LINE_MAX], p1[LINE_MAX], p2[LINE_MAX]; int scanres; scanres = sscanf(line, "%s %s %s", cmd, p1, p2); if ((cmd[0] == '#') || (scanres < 2)) { continue; } if (!strcmp(cmd, "queue")) { u->queue = atoi(p1); } else if (!strcmp(cmd, "limit")) { if (!strcmp(p1, "no")) { u->limit = UINT64_MAX; } else { u->limit = str2bps(p1); } } else if (!strcmp(cmd, "stat")) { if (!strcmp(p1, "yes")) { u->stat = 1; } } else if (!strcmp(cmd, "wchart")) { if (!strcmp(p1, "yes")) { u->wchart = 1; } } else if (!strcmp(cmd, "statdir")) { strncpy(u->statdir, p1, PATH_MAX); } else if (!strcmp(cmd, "packets")) { u->qlen = atoi(p1); } else { /* module parameters */ size_t i; for (i=0; modules[i].name; i++) { if (!strcmp(cmd, modules[i].name) && modules[i].conf) { if (!strcmp(p1, "k")) { /* multiplicator */ modules[i].k = atof(p2); } else { (modules[i].conf)(modules[i].mptr, p1, p2); } break; } } } } fclose(f); return 1; fail_open: return 0; } static struct userdata * userdata_init(char *confname) { struct userdata *u; size_t i; u = malloc(sizeof(struct userdata)); if (!u) { fprintf(stderr, "malloc(%lu) failed\n", (long)sizeof(struct userdata)); goto fail_create; } /* init modules */ for (i=0; modules[i].name; i++) { if (modules[i].init) { /* default multiplicator */ modules[i].k = 1.0f; modules[i].mptr = (modules[i].init)(u, i); } else { modules[i].mptr = NULL; } } if (!config_read(u, confname)) { goto fail_conf; } if (u->limit == 0) { fprintf(stderr, "Something is wrong with limit, all traffic will be blocked\n"); } /* setup statistics */ if (u->stat) { stat_init(u); } /* reserve memory for packets in queue */ u->packets = malloc(u->qlen * sizeof(struct mpacket)); if (!u->packets) { fprintf(stderr, "malloc(%lu) failed\n", (long)u->qlen * sizeof(struct mpacket)); goto fail_packets; } /* create priority array - simplified implementation of priority queue */ u->prioarray = malloc(u->qlen * sizeof(double)); if (!u->prioarray) { fprintf(stderr, "malloc(%lu) failed\n", (long)u->qlen * sizeof(double)); goto fail_prio_array; } /* fill priority array with minimal possible values */ for (i=0; i<u->qlen; i++) { u->prioarray[i] = DBL_MIN; } /* init mutex */ pthread_mutex_init(&u->lock, NULL); /* configuration done, notify modules */ for (i=0; modules[i].name; i++) { if (modules[i].postconf) { int mres; mres = (modules[i].postconf)(modules[i].mptr); if (!mres) { /* disable module */ fprintf(stderr, "Module '%s': initialization failed, disabling\n", modules[i].name); modules[i].enabled = 0; } else { modules[i].enabled = 1; } } } return u; free(u->prioarray); fail_prio_array: free(u->packets); fail_packets: fail_conf: free(u); fail_create: return NULL; } static void userdata_destroy(struct userdata *u) { size_t i; for (i=0; modules[i].name; i++) { if (modules[i].done) { (modules[i].done)(modules[i].mptr); } } pthread_mutex_destroy(&u->lock); if (u->stat) { fclose(u->statf); } free(u->prioarray); free(u->packets); free(u); } static void * sender_thread(void *arg) { struct userdata *u = arg; int vres; size_t i, idx = 0; double max = DBL_MIN; uint64_t limit; uint64_t sleep_ns; for (;;) { struct timespec ts; pthread_mutex_lock(&u->lock); limit = u->limit; if ((limit == 0) || (limit == UINT64_MAX)) { /* change limit to kbyte/sec, so will sleep about 0.1 sec */ limit = 1000; } /* search for packet with maximum priority */ max = DBL_MIN; for (i=0; i<u->qlen; i++) { if (max < u->prioarray[i]) { max = u->prioarray[i]; idx = i; } } if (max != DBL_MIN) { /* accept (send) packet */ vres = nfq_set_verdict(u->qh, u->packets[idx].id, NF_ACCEPT, u->packets[idx].size, u->packets[idx].packet); if (vres < 0) { fprintf(stderr, "nfq_set_verdict() failed, %s\n", strerror(errno)); } /* mark packet buffer as empty */ u->prioarray[idx] = DBL_MIN; /* update statistics */ if (u->stat) { u->stat_info.packets_pass += 1; u->stat_info.octets_pass+= u->packets[idx].size; } sleep_ns = (u->packets[idx].size * BILLION) / limit; } else { /* no data to send, so just sleep for time required to transfer 100 bytes */ sleep_ns = 100 * BILLION / limit; } if (sleep_ns > BILLION) { ts.tv_sec = sleep_ns / BILLION; ts.tv_nsec = sleep_ns % BILLION; } else { ts.tv_sec = 0; ts.tv_nsec = sleep_ns; } pthread_mutex_unlock(&u->lock); clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL); } return NULL; } static void add_to_queue(struct userdata *u, char *packet, int id, int plen, double prio) { size_t i, idx = 0; double min = DBL_MAX; /* search for packet with minimum priority */ for (i=0; i<u->qlen; i++) { if (min > u->prioarray[i]) { min = u->prioarray[i]; idx = i; } } /* and replace it with new packet */ if (min < prio) { if (min != DBL_MIN) { int vres; /* drop packet */ vres = nfq_set_verdict(u->qh, u->packets[idx].id, NF_DROP, 0, NULL); if (vres < 0) { fprintf(stderr, "nfq_set_verdict() failed, %s\n", strerror(errno)); } if (u->stat) { /* and update statistics */ u->stat_info.packets_drop += 1; u->stat_info.octets_drop += u->packets[idx].size; } } u->prioarray[idx] = prio; u->packets[idx].size = plen; u->packets[idx].id = id; memcpy(u->packets[idx].packet, packet, plen); } } static int on_packet(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfad, void *data) { int plen; int id; char *p; uint32_t mark; struct userdata *u; double weight = DBL_EPSILON; size_t i; int wchartstat; struct nfqnl_msg_packet_hdr *ph = nfq_get_msg_packet_hdr(nfad); if (ph) { id = ntohl(ph->packet_id); } else { return -1; } if ((plen = nfq_get_payload(nfad, (unsigned char **)&p)) < 0) { return -1; } u = data; /* there are two special cases: limit == 0 (traffic disabled) and limit == UINT64_MAX (no shaping performed) */ pthread_mutex_lock(&u->lock); if (u->limit == 0) { /* drop packet */ nfq_set_verdict(u->qh, id, NF_DROP, 0, NULL); /* and update statistics */ if (u->stat) { u->stat_info.packets_drop += 1; u->stat_info.octets_drop += plen; } } else if (u->limit == UINT64_MAX) { /* accept packet */ nfq_set_verdict(u->qh, id, NF_ACCEPT, plen, (unsigned char *)p); /* and update statistics */ if (u->stat) { u->stat_info.packets_pass += 1; u->stat_info.octets_pass += plen; } } wchartstat = u->wchart; pthread_mutex_unlock(&u->lock); if ((u->limit == 0) || (u->limit == UINT64_MAX)) { return 1; } mark = nfq_get_nfmark(nfad); /* calculate weight for each enabled module */ for (i=0; modules[i].name; i++) { if (modules[i].weight && modules[i].enabled) { double mweight = (modules[i].weight)(modules[i].mptr, p, plen, mark); if (mweight < 0.0) { weight = mweight; break; } mweight *= modules[i].k; if (wchartstat) { pthread_mutex_lock(&u->lock); modules[i].stw += mweight; modules[i].nw += 1.0f; pthread_mutex_unlock(&u->lock); } weight += mweight; } } pthread_mutex_lock(&u->lock); if (weight < 0) { /* drop packet with with negative weight */ nfq_set_verdict(u->qh, id, NF_DROP, 0, NULL); /* update statistics */ if (u->stat) { u->stat_info.packets_drop += 1; u->stat_info.octets_drop += plen; } } else { /* add to queue with positive weight */ add_to_queue(u, p, id, plen, weight); } pthread_mutex_unlock(&u->lock); return 1; } int main(int argc, char *argv[]) { struct nfq_handle *h; int fd; int rv; char buf[0xffff]; int r = EXIT_FAILURE; struct userdata *u; if (argc < 2) { fprintf(stderr, "Usage: %s config.cfg\n", argv[0]); return EXIT_FAILURE; } u = userdata_init(argv[1]); if (!u) { return EXIT_FAILURE; } h = nfq_open(); if (!h) { fprintf(stderr, "nfq_open() failed\n"); return EXIT_FAILURE; } if (nfq_unbind_pf(h, AF_INET) < 0) { fprintf(stderr, "nfq_unbind_pf() failed\n"); goto fail_unbind; } if (nfq_bind_pf(h, AF_INET) < 0) { fprintf(stderr, "nfq_bind_pf() failed\n"); goto fail_bind; } u->qh = nfq_create_queue(h, u->queue, &on_packet, u); if (!u->qh) { fprintf(stderr, "nfq_create_queue() with queue %d failed\n", u->queue); goto fail_queue; } if (nfq_set_mode(u->qh, NFQNL_COPY_PACKET, 0xffff) < 0) { fprintf(stderr, "nfq_set_mode() failed\n"); goto fail_mode; } if (nfq_set_queue_maxlen(u->qh, u->qlen * 2) < 0) { /* multiple by two just in case */ fprintf(stderr, "nfq_set_queue_maxlen() failed with qlen=%lu\n", (long)u->qlen); goto fail_mode; } /* create sending thread */ pthread_create(&u->sender_tid, NULL, &sender_thread, u); /* and thread for updating statistics */ pthread_create(&u->stat_tid, NULL, &stat_thread, u); fd = nfq_fd(h); while ((rv = recv(fd, buf, sizeof(buf), 0)) >= 0) { nfq_handle_packet(h, buf, rv); } r = EXIT_SUCCESS; fail_mode: nfq_destroy_queue(u->qh); fail_queue: fail_bind: fail_unbind: nfq_close(h); userdata_destroy(u); return r; }
2.359375
2
2024-11-18T22:11:31.092370+00:00
2015-09-14T00:51:00
5b097aa196be7f5163bad0b31cbb99913157653c
{ "blob_id": "5b097aa196be7f5163bad0b31cbb99913157653c", "branch_name": "refs/heads/master", "committer_date": "2015-09-14T00:51:00", "content_id": "75d37efe23334b0f888e227fb87f8cbc9a15cb55", "detected_licenses": [ "MIT" ], "directory_id": "1d0138d4967b0b28f706521fd45b83a50e11f8e0", "extension": "c", "filename": "acl_perms.c", "fork_events_count": 0, "gha_created_at": "2019-11-27T01:10:52", "gha_event_created_at": "2019-11-27T01:10:52", "gha_language": null, "gha_license_id": "MIT", "github_id": 224316093, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4185, "license": "MIT", "license_type": "permissive", "path": "/acl_perms.c", "provenance": "stackv2-0072.json.gz:50522", "repo_name": "zsd0101/tlpi-exercises", "revision_date": "2015-09-14T00:51:00", "revision_id": "e1aeff37953602df8a82dec5eb41df2874f23600", "snapshot_id": "e4777c5bebeb85505bbf79fa70c2e111ccdddafb", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/zsd0101/tlpi-exercises/e1aeff37953602df8a82dec5eb41df2874f23600/acl_perms.c", "visit_date": "2020-09-19T22:48:07.095089" }
stackv2
/* Exercise 17-1 */ #include <acl/libacl.h> #include <sys/acl.h> #include <sys/stat.h> #include "tlpi_hdr.h" #include "ugid_functions.h" void usage (char *); int maskPermset (acl_permset_t, acl_permset_t); int handleError(char *, int); void printPerms (acl_permset_t); void usage (char *prog_name) { usageErr("%s (u|g) (user|group) file\n", prog_name); } int maskPermset (acl_permset_t perms, acl_permset_t mask) { int a; a = acl_get_perm(mask, ACL_READ); if (a == -1) { return -1; } if (a == 0) { if (acl_delete_perm(perms, ACL_READ) == -1) { return -1; } } a = acl_get_perm(mask, ACL_WRITE); if (a == -1) { return -1; } if (a == 0) { if (acl_delete_perm(perms, ACL_WRITE) == -1) { return -1; } } a = acl_get_perm(mask, ACL_EXECUTE); if (a == -1) { return -1; } if (a == 0) { if (acl_delete_perm(perms, ACL_EXECUTE) == -1) { return -1; } } return 0; } int handleError(char *str, int a) { if (a == -1) { errExit(str); } return a; } void printPerms (acl_permset_t permset) { printf( "%c%c%c", (handleError("acl_get_perm", acl_get_perm(permset, ACL_READ)) ? 'r' : '-'), (handleError("acl_get_perm", acl_get_perm(permset, ACL_WRITE)) ? 'w' : '-'), (handleError("acl_get_perm", acl_get_perm(permset, ACL_EXECUTE)) ? 'x' : '-') ); } int main (int argc, char *argv[]) { if (argc != 4) { usage(argv[0]); } char mode; if (strcmp(argv[1], "u") == 0) { mode = 'u'; } else if (strcmp(argv[1], "g") == 0) { mode = 'g'; } else { usage(argv[0]); } uid_t uid; gid_t gid; if (mode == 'u') { uid = userIdFromName(argv[2]); if (uid == -1) { errExit("couldn't find user %s\n", argv[2]); } } else { // mode == 'g' gid = groupIdFromName(argv[2]); if (gid == -1) { errExit("couldn't find group %s\n", argv[2]); } } char *filepath = argv[3]; struct stat stats; if (stat(filepath, &stats) == -1) { errExit("stat\n"); } acl_t acl = acl_get_file(filepath, ACL_TYPE_ACCESS); if (acl == NULL) { errExit("acl_get_file\n"); } acl_entry_t entry; acl_tag_t tag; int entryId; int mask_found = 0; acl_entry_t mask; for (entryId = ACL_FIRST_ENTRY; ; entryId = ACL_NEXT_ENTRY) { if (acl_get_entry(acl, entryId, &entry) == 1) { break; } if ((tag = acl_get_tag_type(entry, &tag)) == -1) { errExit("acl_get_tag_type\n"); } if (tag == ACL_MASK) { mask_found = 1; mask = entry; break; } } acl_entry_t needle; uid_t *uid_p; gid_t *gid_p; for (entryId = ACL_FIRST_ENTRY; ; entryId = ACL_NEXT_ENTRY) { if (acl_get_entry(acl, entryId, &entry) != 1) { errExit( "couldn't find an entry for the specified %s\n", mode == 'u' ? "user" : "group" ); } if (acl_get_tag_type(entry, &tag) == -1) { errExit("acl_get_tag_type\n"); } if (mode == 'u') { if (uid == stats.st_uid && tag == ACL_USER_OBJ) { needle = entry; break; } if (tag != ACL_USER) { continue; } uid_p = acl_get_qualifier(entry); if (uid_p == NULL) { errExit("acl_get_qualifier\n"); } if (*uid_p == uid) { needle = entry; break; } } if (mode == 'g') { if (gid == stats.st_gid && tag == ACL_GROUP_OBJ) { needle = entry; break; } if (tag != ACL_GROUP) { continue; } gid_p = acl_get_qualifier(entry); if (gid_p == NULL) { errExit("acl_get_qualifier\n"); } if (*gid_p == gid) { needle = entry; break; } } } acl_permset_t needle_perms; if (acl_get_permset(needle, &needle_perms) == -1) { errExit("acl_get_permset\n"); } printPerms(needle_perms); printf("\n"); if (mask_found && !(mode == 'u' && uid == stats.st_uid && tag == ACL_USER_OBJ)) { acl_permset_t mask_perms; if (acl_get_permset(mask, &mask_perms) == -1) { errExit("acl_get_permset\n"); } printf("Effective permissions: "); if (maskPermset(needle_perms, mask_perms) == -1) { errExit("maskPermset\n"); } printPerms(needle_perms); printf("\n"); } exit(EXIT_SUCCESS); }
2.3125
2
2024-11-18T22:11:32.057143+00:00
2020-08-17T19:39:58
c5ad895277fc2c7c9e0dd20ce43dbc143e9807a5
{ "blob_id": "c5ad895277fc2c7c9e0dd20ce43dbc143e9807a5", "branch_name": "refs/heads/master", "committer_date": "2020-08-17T19:39:58", "content_id": "f6b8c33403588baec11be6cd1f00a23f625bd39f", "detected_licenses": [ "MIT" ], "directory_id": "a78b4255c76bb1e292c17c86a50816473dfd6006", "extension": "c", "filename": "vfprintf_s.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 982, "license": "MIT", "license_type": "permissive", "path": "/src/stdio/vfprintf_s.c", "provenance": "stackv2-0072.json.gz:50653", "repo_name": "ung-org/libc", "revision_date": "2020-08-17T19:39:58", "revision_id": "55fc64c7ffd7792bc88451a736c2e94e5865282f", "snapshot_id": "be61b73696766d8ca003dd3e2e94d57ea695e151", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ung-org/libc/55fc64c7ffd7792bc88451a736c2e94e5865282f/src/stdio/vfprintf_s.c", "visit_date": "2022-12-01T22:24:51.479128" }
stackv2
#include <stdio.h> #include "__stdio.h" #include <stdarg.h> /** write formatted output to a file stream **/ int vfprintf_s(FILE * restrict stream, const char * restrict format, va_list arg) { __C_EXT(1, 201112L); va_list ap; va_copy(ap, arg); int len = vsnprintf(NULL, 0, format, arg); char *buf = malloc(len + 1); len = vsnprintf(buf, len, format, ap); va_end(ap); len = (int)fwrite(buf, sizeof(*buf), len, stream); free(buf); return len; } /*** The fn(vfprintf) function is equivalent to fn(fprintf), but with a type(va_list) argument instead of variadic arguments. The argument arg(arg) must be initialized with fnmacro(va_start) prior to calling fn(vfprintf). The fn(vfprintf) function does not call fnmacro(va_end), so the calling function is responsible for this. ***/ /* UNSPECIFIED: ??? */ /* UNDEFINED: ??? */ /* IMPLEMENTATION: ??? */ /* LOCALE: ??? */ /* RETURN(NEG): an error occurred */ /* RETURN: the number of characters written */ /* CEXT1(201112) */
2.46875
2
2024-11-18T22:11:32.195575+00:00
2022-07-31T18:45:33
380c2bdb229aec18f5950ffa472ed15cf6e2249a
{ "blob_id": "380c2bdb229aec18f5950ffa472ed15cf6e2249a", "branch_name": "refs/heads/main", "committer_date": "2022-07-31T18:45:33", "content_id": "deb09efe5fe60aa95a2f9c71a943756ba04579f4", "detected_licenses": [ "MIT" ], "directory_id": "19102a3c11268052348cf669e23bbfe2780bb067", "extension": "h", "filename": "Level.h", "fork_events_count": 31, "gha_created_at": "2021-02-13T14:55:07", "gha_event_created_at": "2022-07-31T18:45:34", "gha_language": "C", "gha_license_id": "MIT", "github_id": 338597768, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3621, "license": "MIT", "license_type": "permissive", "path": "/MinecraftC/Level/Level.h", "provenance": "stackv2-0072.json.gz:50781", "repo_name": "johnpayne-dev/MinecraftC", "revision_date": "2022-07-31T18:45:33", "revision_id": "43928d42e1f32bd76a994f0bb22c0153a7271b3f", "snapshot_id": "4f6578fd12c0ff8b70e8b9d2c11c4934a822203c", "src_encoding": "UTF-8", "star_events_count": 303, "url": "https://raw.githubusercontent.com/johnpayne-dev/MinecraftC/43928d42e1f32bd76a994f0bb22c0153a7271b3f/MinecraftC/Level/Level.h", "visit_date": "2023-08-04T00:51:16.467779" }
stackv2
#pragma once #include <stdbool.h> #include "Tile/Block.h" #include "NextTickListEntry.h" #include "../MovingObjectPosition.h" #include "../Utilities/List.h" #include "../Utilities/Random.h" #include "../Particle/ParticleManager.h" #include "../Physics/AABB.h" #include "../GUI/FontRenderer.h" #include "../Entity.h" #include "Generator/LevelGenerator.h" typedef struct Level { int width, height, depth; uint8_t * blocks; int xSpawn, ySpawn, zSpawn; float spawnRotation; struct LevelRenderer * renderer; int * lightBlockers; RandomGenerator random; int randomValue; List(NextTickListEntry) tickList; int waterLevel; uint32_t skyColor; uint32_t fogColor; uint32_t cloudColor; int unprocessed; int tickCount; Entity * player; List(Entity *) entities; ParticleManager * particleEngine; LevelGenerator generator; ProgressBarDisplay * progressBar; #if MINECRAFTC_MODS uint8_t * distanceField; #endif } Level; void LevelCreate(Level * level, ProgressBarDisplay * progressBar, int size); void LevelRegenerate(Level * level, int size); bool LevelLoad(Level * level, char * filePath); bool LevelSave(Level * level, char * filePath, char * name); void LevelSetData(Level * level, int w, int d, int h, uint8_t * blocks); #if MINECRAFTC_MODS void LevelCreateDistanceField(Level * level); void LevelDestroyDistanceField(Level * level); #endif void LevelFindSpawn(Level * level); void LevelCalculateLightDepths(Level * level, int x0, int y0, int x1, int y1); void LevelSetRenderer(Level * level, struct LevelRenderer * listener); bool LevelIsLightBlocker(Level * level, int x, int y, int z); List(AABB) LevelGetCubes(Level * level, AABB box); void LevelSwap(Level * level, int x0, int y0, int z0, int x1, int y1, int z1); bool LevelSetTile(Level * level, int x, int y, int z, BlockType tile); bool LevelSetTileNoNeighborChange(Level * level, int x, int y, int z, BlockType tile); void LevelUpdateNeighborsAt(Level * Level, int x, int y, int z, BlockType tile); bool LevelSetTileNoUpdate(Level * level, int x, int y, int z, BlockType tile); bool LevelIsLit(Level * level, int x, int y, int z); BlockType LevelGetTile(Level * level, int x, int y, int z); bool LevelIsSolidTile(Level * level, int x, int y, int z); void LevelTickEntities(Level * level); void LevelTick(Level * level); bool LevelIsInBounds(Level * level, int x, int y, int z); float LevelGetGroundLevel(Level * level); float LevelGetWaterLevel(Level * level); bool LevelContainsAnyLiquid(Level * level, AABB box); bool LevelContainsLiquid(Level * level, AABB box, LiquidType liquidID); void LevelAddToNextTick(Level * level, int x, int y, int z, BlockType tile); bool LevelIsSolidSearch(Level * level, float x, float y, float z, float radius); int LevelGetHighestTile(Level * level, int x, int z); void LevelSetSpawnPosition(Level * level, int x, int y, int z, float rotation); float LevelGetBrightness(Level * level, int x, int y, int z); bool LevelIsWater(Level * level, int x, int y, int z); MovingObjectPosition LevelClip(Level * level, Vector3D v0, Vector3D v1); void LevelPlaySound(Level * level, char * sound, Entity * entity, float volume, float pitch); void LevelPlaySoundAt(Level * level, char * sound, float x, float y, float z, float volume, float pitch); bool LevelMaybeGrowTree(Level * level, int x, int y, int z); Entity * LevelGetPlayer(Level * level); void LevelAddEntity(Level * level, Entity * entity); void LevelRenderEntities(Level * level, TextureManager * textures, float dt); void LevelExplode(Level * level, float x, float y, float z, float radius); Entity * LevelFindPlayer(Level * level); void LevelDestroy(Level * level);
2.0625
2
2024-11-18T22:11:32.442248+00:00
2014-05-13T07:05:07
f441e63cf7ceb47714e047cecbd6fd5d415a289b
{ "blob_id": "f441e63cf7ceb47714e047cecbd6fd5d415a289b", "branch_name": "refs/heads/master", "committer_date": "2014-05-13T07:05:07", "content_id": "93bc1a5984b362795b96797dcfbd31b6170a881e", "detected_licenses": [ "MIT" ], "directory_id": "f8ca09031c44bdf552380b2bc082f81468676c3c", "extension": "c", "filename": "shm.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 621, "license": "MIT", "license_type": "permissive", "path": "/common/shm.c", "provenance": "stackv2-0072.json.gz:51037", "repo_name": "aragorn/wisebot", "revision_date": "2014-05-13T07:05:07", "revision_id": "fff0b4db3a14fb4f03642e3a7bb70434465265a5", "snapshot_id": "ac50b211092b4300008d5b4b299828fc2363ab31", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aragorn/wisebot/fff0b4db3a14fb4f03642e3a7bb70434465265a5/common/shm.c", "visit_date": "2016-09-06T02:58:35.912406" }
stackv2
/* $Id$ */ #include "common_core.h" #include "shm.h" #include "mm.h" void message_receptor(int ignore); // wrapper for shared memory management // void shared_init(size_t size) { MM_create(size, NULL); } void shared_attach(void *addr, size_t size) { MM_attach(addr, size, NULL); } void shared_extent(void **addr, size_t *size) { MM_extent(addr, size); } void *shared_malloc(size_t size) { return MM_malloc(size); } void shared_free(void *ptr) { MM_free(ptr); } void *shared_realloc(void *ptr, size_t size) { return MM_realloc(ptr, size); } char *shared_strdup(char *str) { return MM_strdup(str); }
2.0625
2
2024-11-18T22:11:32.507307+00:00
2016-10-25T07:37:13
badf2618d4dd407fd4602f7938f6b2f156575bb0
{ "blob_id": "badf2618d4dd407fd4602f7938f6b2f156575bb0", "branch_name": "refs/heads/master", "committer_date": "2016-10-25T07:37:13", "content_id": "173bc0b571d14897cdfc96fc7c2a5d306697797f", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "directory_id": "5eaa29d64219e69b32c0dcb3e53bcfc44a4261a4", "extension": "c", "filename": "vorbis_encoder.c", "fork_events_count": 9, "gha_created_at": "2015-07-18T20:47:04", "gha_event_created_at": "2016-09-23T03:59:22", "gha_language": "TypeScript", "gha_license_id": null, "github_id": 39312243, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3376, "license": "BSD-3-Clause,MIT", "license_type": "permissive", "path": "/native/wrapper/vorbis_encoder.c", "provenance": "stackv2-0072.json.gz:51166", "repo_name": "Garciat/libvorbis.js", "revision_date": "2016-10-25T07:37:13", "revision_id": "cd246775a8c1141744d6cbd0e411bd3ffbe6ed42", "snapshot_id": "43138d68ce410321b857eb737ed6babd253158a1", "src_encoding": "UTF-8", "star_events_count": 20, "url": "https://raw.githubusercontent.com/Garciat/libvorbis.js/cd246775a8c1141744d6cbd0e411bd3ffbe6ed42/native/wrapper/vorbis_encoder.c", "visit_date": "2021-01-19T05:29:51.055062" }
stackv2
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <time.h> #include "vorbis_encoder.h" /* source: https://svn.xiph.org/trunk/vorbis/examples/encoder_example.c */ static void encoder_write_page(encoder_instance state, ogg_page *og); static void encoder_encode_work(encoder_instance state); encoder_instance encoder_create_vbr(int ch, int bitrate, float quality) { encoder_instance state = (encoder_instance)malloc(sizeof(struct encoder_state)); state->data = NULL; state->data_len = 0; vorbis_info_init(&state->vi); if (vorbis_encode_init_vbr(&state->vi, ch, bitrate, quality) != 0) { free(state); return NULL; } vorbis_comment_init(&state->vc); vorbis_comment_add_tag(&state->vc, "ENCODER", "libvorbis.js"); vorbis_analysis_init(&state->vd, &state->vi); vorbis_block_init(&state->vd, &state->vb); srand(time(NULL)); ogg_stream_init(&state->os, rand()); return state; } void encoder_destroy(encoder_instance state) { ogg_stream_clear(&state->os); vorbis_block_clear(&state->vb); vorbis_dsp_clear(&state->vd); vorbis_comment_clear(&state->vc); vorbis_info_clear(&state->vi); free(state->data); free(state); } void encoder_write_headers(encoder_instance state) { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; ogg_page og; vorbis_analysis_headerout(&state->vd, &state->vc, &header, &header_comm, &header_code); ogg_stream_packetin(&state->os, &header); ogg_stream_packetin(&state->os, &header_comm); ogg_stream_packetin(&state->os, &header_code); while (ogg_stream_flush(&state->os, &og) != 0) { encoder_write_page(state, &og); } } void encoder_prepare_analysis_buffers(encoder_instance state, int vals) { state->analysis_buffer = vorbis_analysis_buffer(&state->vd, vals); state->analysis_vals = vals; } void encoder_encode(encoder_instance state) { vorbis_analysis_wrote(&state->vd, state->analysis_vals); encoder_encode_work(state); } void encoder_finish(encoder_instance state) { vorbis_analysis_wrote(&state->vd, 0); encoder_encode_work(state); } unsigned char *encoder_get_data(encoder_instance state) { return state->data; } long encoder_get_data_len(encoder_instance state) { return state->data_len; } void encoder_clear_data(encoder_instance state) { state->data_len = 0; } float *encoder_get_analysis_buffer(encoder_instance state, int ch) { return state->analysis_buffer[ch]; } void encoder_encode_work(encoder_instance state) { ogg_page og; while (vorbis_analysis_blockout(&state->vd, &state->vb) == 1) { vorbis_analysis(&state->vb, NULL); vorbis_bitrate_addblock(&state->vb); while (vorbis_bitrate_flushpacket(&state->vd, &state->op)) { ogg_stream_packetin(&state->os, &state->op); while (ogg_stream_pageout(&state->os, &og) != 0) { encoder_write_page(state, &og); } } } } void encoder_write_page(encoder_instance state, ogg_page *og) { long size = state->data_len + og->header_len + og->body_len; if (size == 0) { return; } state->data = (unsigned char *)realloc(state->data, size); memcpy(state->data + state->data_len, og->header, og->header_len); state->data_len += og->header_len; memcpy(state->data + state->data_len, og->body, og->body_len); state->data_len += og->body_len; }
2.4375
2
2024-11-18T22:11:32.997869+00:00
2021-10-06T06:08:13
79a15f0900343595a1f0442e0610e9068b79836a
{ "blob_id": "79a15f0900343595a1f0442e0610e9068b79836a", "branch_name": "refs/heads/main", "committer_date": "2021-10-06T06:08:13", "content_id": "da2693cab8fa23d841541d9421e78273bf65070d", "detected_licenses": [ "MIT" ], "directory_id": "a8bb2b7c59b518b82bc9aef0bd713b72443f73fb", "extension": "c", "filename": "pattern.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 413691593, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 319, "license": "MIT", "license_type": "permissive", "path": "/pattern.c", "provenance": "stackv2-0072.json.gz:51680", "repo_name": "prasadhIX/c_codes", "revision_date": "2021-10-06T06:08:13", "revision_id": "a8dc8d3f4c17a27892df45074110e4beafad014a", "snapshot_id": "acd28ecef7f41be11fd128dad87c3ed5204490ef", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/prasadhIX/c_codes/a8dc8d3f4c17a27892df45074110e4beafad014a/pattern.c", "visit_date": "2023-08-20T09:37:58.712534" }
stackv2
#include <stdio.h> #include "mystring.h" #undef MAXLINE #define MAXLINE 1000 char *pattern = "ould"; //find all lines matching patterns int main() { char line[MAXLINE]; int found = 0; while(igetline(line,MAXLINE)>0) if(stringindex(line,pattern)>=0) { printf("%s",line); found++; } return found; }
2.40625
2
2024-11-18T22:11:33.358295+00:00
2018-12-12T02:09:34
4cb569ea652e2ea745c7eeab65c9dff402a02a97
{ "blob_id": "4cb569ea652e2ea745c7eeab65c9dff402a02a97", "branch_name": "refs/heads/master", "committer_date": "2018-12-12T02:09:34", "content_id": "a3ab141d825e8023eee25741dd7eb0eeee4d183e", "detected_licenses": [ "MIT" ], "directory_id": "b483576b92cec49f86fed11e2a7f4dd36386cef4", "extension": "c", "filename": "pingpong.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1212, "license": "MIT", "license_type": "permissive", "path": "/TP_02/pingpong.c", "provenance": "stackv2-0072.json.gz:52194", "repo_name": "mvkopp/ASE", "revision_date": "2018-12-12T02:09:34", "revision_id": "6dfb726827b90637620acab3a37a798b660be167", "snapshot_id": "4bdb2f85d08f4e8c6d9b3af6e06beec8afdefe56", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mvkopp/ASE/6dfb726827b90637620acab3a37a798b660be167/TP_02/pingpong.c", "visit_date": "2021-10-08T12:29:36.926366" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "context.h" struct ctx_s ctx_ping; struct ctx_s ctx_pong; struct ctx_s ctx_pang; void f_ping(void *args); void f_pong(void *args); void f_pang(void *args); int main(int argc, char *argv[]) { init_ctx(&ctx_ping, 16384, f_ping, NULL); init_ctx(&ctx_pong, 16384, f_pong, NULL); //init_ctx(&ctx_pang, 16384, f_pang, NULL); // TEST avec pang switch_to_ctx(&ctx_ping); exit(EXIT_SUCCESS); } void f_ping(void *args) { init_ctx(&ctx_pang, 16384, f_pang, NULL); // TEST où on initialise le contexte de pang dans une autre fonction while(1) { printf("A") ; switch_to_ctx(&ctx_pong); printf("B") ; switch_to_ctx(&ctx_pong); switch_to_ctx(&ctx_pang); // TEST avec pang printf("C") ; switch_to_ctx(&ctx_pong); } } void f_pong(void *args) { while(1) { printf("1") ; switch_to_ctx(&ctx_ping); printf("2") ; switch_to_ctx(&ctx_ping); switch_to_ctx(&ctx_pang); // TEST avec pang } } void f_pang(void *args){ while(1) { printf("["); switch_to_ctx(&ctx_pong); printf("-"); switch_to_ctx(&ctx_ping); printf("]"); switch_to_ctx(&ctx_pong); } }
2.96875
3
2024-11-18T22:11:34.055721+00:00
2020-09-11T00:16:48
7dae92803cf66577f36a06e2e2fff5737e096379
{ "blob_id": "7dae92803cf66577f36a06e2e2fff5737e096379", "branch_name": "refs/heads/master", "committer_date": "2020-09-11T00:24:52", "content_id": "b81253c523fb22d8e66270299687592064de15e9", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause-Patent" ], "directory_id": "b8f4b32171bba9e60a101f5a605e084c9aa974fd", "extension": "c", "filename": "IgdOpRegionLib.c", "fork_events_count": 0, "gha_created_at": "2018-09-21T07:49:42", "gha_event_created_at": "2018-09-21T07:49:42", "gha_language": null, "gha_license_id": "BSD-2-Clause", "github_id": 149729121, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7749, "license": "BSD-3-Clause,BSD-2-Clause-Patent", "license_type": "permissive", "path": "/Silicon/CoffeelakePkg/Library/IgdOpRegionLib/IgdOpRegionLib.c", "provenance": "stackv2-0072.json.gz:52450", "repo_name": "jinjhuli/slimbootloader", "revision_date": "2020-09-11T00:16:48", "revision_id": "cfba21067cf4dce659b508833d8c886967081375", "snapshot_id": "3137ab83073865b247f69b09a628f8b39b4c05ee", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jinjhuli/slimbootloader/cfba21067cf4dce659b508833d8c886967081375/Silicon/CoffeelakePkg/Library/IgdOpRegionLib/IgdOpRegionLib.c", "visit_date": "2023-07-11T12:59:51.336343" }
stackv2
/** @file This is part of the implementation of an Intel Graphics drivers OpRegion / Software SCI interface between system Bootloader, ASL code, and Graphics drivers. The code in this file will load the driver and initialize the interface Supporting Specification: OpRegion / Software SCI SPEC 0.70 Acronyms: IGD: Internal Graphics Device NVS: ACPI Non Volatile Storage OpRegion: ACPI Operational Region VBT: Video BIOS Table (OEM customizable data) IPU: Image Processing Unit Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiPei.h> #include <Library/IgdOpRegionLib.h> #include <Library/BaseMemoryLib.h> #include <Library/PciLib.h> #include <Library/HobLib.h> #include <Library/DebugLib.h> #include <Library/PcdLib.h> #include <Library/MemoryAllocationLib.h> #include <IgdOpRegion.h> #include <IgdOpRegionDefines.h> #include <GlobalNvsAreaDef.h> // // Global variables // IGD_OPREGION_PROTOCOL mIgdOpRegion; /** Get VBT data. @param[out] VbtFileBuffer Pointer to VBT data buffer. @retval EFI_SUCCESS VBT data was returned. @exception EFI_UNSUPPORTED Invalid signature in VBT data. **/ EFI_STATUS GetVbt ( OUT VBIOS_VBT_STRUCTURE **VbtFileBuffer ) { EFI_PHYSICAL_ADDRESS VbtAddress = 0; // Get the vbt address VbtAddress = PcdGet32(PcdGraphicsVbtAddress); DEBUG ((DEBUG_INFO, "VbtAddress =0x%x \n", VbtAddress)); // Check VBT signature *VbtFileBuffer = (VBIOS_VBT_STRUCTURE *) (UINTN) VbtAddress; if (*VbtFileBuffer != NULL) { if ((*((UINT32 *) ((*VbtFileBuffer)->HeaderSignature))) != VBT_SIGNATURE) { if (*VbtFileBuffer != NULL) { *VbtFileBuffer = NULL; } return EFI_UNSUPPORTED; } // Check VBT size. if ((*VbtFileBuffer)->HeaderVbtSize > 6*SIZE_1KB) { (*VbtFileBuffer)->HeaderVbtSize = (UINT16) 6*SIZE_1KB; } } return EFI_SUCCESS; } /** Update VBT data in Igd Op Region. @retval EFI_SUCCESS VBT data was returned. @exception EFI_ABORTED Intel VBT not found. **/ EFI_STATUS UpdateVbt( VOID ) { VBIOS_VBT_STRUCTURE *VbtFileBuffer = NULL; GetVbt (&VbtFileBuffer); if (VbtFileBuffer != NULL) { DEBUG ((DEBUG_INFO, "VBT data found\n")); DEBUG ((DEBUG_INFO, "VbtFileBuffer->HeaderVbtSize = 0x%x \n", VbtFileBuffer->HeaderVbtSize)); // Initialize Video BIOS version with its build number. mIgdOpRegion.OpRegion->Header.Vver[0] = VbtFileBuffer->CoreBlockBiosBuild[0]; mIgdOpRegion.OpRegion->Header.Vver[1] = VbtFileBuffer->CoreBlockBiosBuild[1]; mIgdOpRegion.OpRegion->Header.Vver[2] = VbtFileBuffer->CoreBlockBiosBuild[2]; mIgdOpRegion.OpRegion->Header.Vver[3] = VbtFileBuffer->CoreBlockBiosBuild[3]; CopyMem (mIgdOpRegion.OpRegion->Vbt.Gvd1, VbtFileBuffer, VbtFileBuffer->HeaderVbtSize); return EFI_SUCCESS; } else { DEBUG ((DEBUG_INFO, "Intel VBT not found\n")); return EFI_ABORTED; } } /** Graphics OpRegion / Software SCI driver installation function. @retval EFI_SUCCESS - The driver installed without error. @retval EFI_OUT_OF_RESOURCES - No resource to complete operations. @retval EFI_ABORTED - The driver encountered an error and could not complete installation of the ACPI tables. **/ EFI_STATUS IgdOpRegionInit ( VOID ) { GLOBAL_NVS_AREA *Gnvs; UINT16 Data16; EFI_STATUS Status = EFI_ABORTED; mIgdOpRegion.OpRegion = (IGD_OPREGION_STRUC *) AllocatePool (sizeof(IGD_OPREGION_STRUC)); if (mIgdOpRegion.OpRegion == NULL) { return EFI_OUT_OF_RESOURCES; } SetMem(mIgdOpRegion.OpRegion, sizeof(IGD_OPREGION_STRUC), 0); // // Update OpRegion address to Gnvs // Gnvs = (GLOBAL_NVS_AREA *)(UINTN)PcdGet32(PcdAcpiGnvsAddress); Gnvs->SaNvs.IgdOpRegionAddress = (UINT32)(UINTN)(mIgdOpRegion.OpRegion); // // Initialize OpRegion Header // CopyMem (mIgdOpRegion.OpRegion->Header.Sign, HEADER_SIGNATURE, sizeof(HEADER_SIGNATURE)); // // Set OpRegion Size in KBs // mIgdOpRegion.OpRegion->Header.Size = HEADER_SIZE/1024; mIgdOpRegion.OpRegion->Header.Over = (UINT32) (LShiftU64 (HEADER_OPREGION_VER, 16) + LShiftU64 (HEADER_OPREGION_REV, 8)); // // All Mailboxes are supported. // mIgdOpRegion.OpRegion->Header.MBox = (HD_MBOX5 + HD_MBOX4 + HD_MBOX3 + HD_MBOX2 + HD_MBOX1); // // Initialize OpRegion Mailbox 1 (Public ACPI Methods). // // Note - The initial setting of mailbox 1 fields is implementation specific. // Adjust them as needed many even coming from user setting in setup. // // // Initialize OpRegion Mailbox 3 (ASLE Interrupt and Power Conservation). // // Note - The initial setting of mailbox 3 fields is implementation specific. // Adjust them as needed many even coming from user setting in setup. // // // Do not initialize TCHE. This field is written by the graphics driver only. // // // The ALSI field is generally initialized by ASL code by reading the embedded controller. // mIgdOpRegion.OpRegion->Header.PCon = 0x3; mIgdOpRegion.OpRegion->MBox3.Bclp = BACKLIGHT_BRIGHTNESS; mIgdOpRegion.OpRegion->MBox3.Pfit = (FIELD_VALID_BIT | PFIT_STRETCH); // // Reporting to driver for VR IMON Calibration. Bits [5-1] values supported 14A to 31A. // mIgdOpRegion.OpRegion->MBox3.Pcft = (Gnvs->SaNvs.GfxTurboIMON << 1) & 0x003E; /// /// Set Initial current Brightness /// mIgdOpRegion.OpRegion->MBox3.Cblv = (INIT_BRIGHT_LEVEL | FIELD_VALID_BIT); // <EXAMPLE> Create a static Backlight Brightness Level Duty cycle Mapping Table // Possible 20 entries (example used 11), each 16 bits as follows: // [15] = Field Valid bit, [14:08] = Level in Percentage (0-64h), [07:00] = Desired duty cycle (0 - FFh). mIgdOpRegion.OpRegion->MBox3.Bclm[0] = (0x0000 + WORD_FIELD_VALID_BIT); ///< 0% mIgdOpRegion.OpRegion->MBox3.Bclm[1] = (0x0A19 + WORD_FIELD_VALID_BIT); ///< 10% mIgdOpRegion.OpRegion->MBox3.Bclm[2] = (0x1433 + WORD_FIELD_VALID_BIT); ///< 20% mIgdOpRegion.OpRegion->MBox3.Bclm[3] = (0x1E4C + WORD_FIELD_VALID_BIT); ///< 30% mIgdOpRegion.OpRegion->MBox3.Bclm[4] = (0x2866 + WORD_FIELD_VALID_BIT); ///< 40% mIgdOpRegion.OpRegion->MBox3.Bclm[5] = (0x327F + WORD_FIELD_VALID_BIT); ///< 50% mIgdOpRegion.OpRegion->MBox3.Bclm[6] = (0x3C99 + WORD_FIELD_VALID_BIT); ///< 60% mIgdOpRegion.OpRegion->MBox3.Bclm[7] = (0x46B2 + WORD_FIELD_VALID_BIT); ///< 70% mIgdOpRegion.OpRegion->MBox3.Bclm[8] = (0x50CC + WORD_FIELD_VALID_BIT); ///< 80% mIgdOpRegion.OpRegion->MBox3.Bclm[9] = (0x5AE5 + WORD_FIELD_VALID_BIT); ///< 90% mIgdOpRegion.OpRegion->MBox3.Bclm[10] = (0x64FF + WORD_FIELD_VALID_BIT); ///< 100% mIgdOpRegion.OpRegion->MBox3.Iuer = 0x00; Status = UpdateVbt(); if (EFI_ERROR (Status)) { return Status; } // Initialize hardware state: // Set ASLS Register to the OpRegion physical memory address. // Set SWSCI register bit 15 to a "1" to activate SCI interrupts. PciWrite32(PCI_LIB_ADDRESS(IGD_BUS, IGD_DEV, IGD_FUN_0, IGD_ASLS_OFFSET), (UINT32)(UINTN)(mIgdOpRegion.OpRegion)); Data16 = PciRead16(PCI_LIB_ADDRESS(IGD_BUS, IGD_DEV, IGD_FUN_0, IGD_SWSCI_OFFSET)); Data16 &= ~BIT0; Data16 |= BIT15; PciWrite16(PCI_LIB_ADDRESS(IGD_BUS, IGD_DEV, IGD_FUN_0, IGD_SWSCI_OFFSET), Data16); DEBUG ((DEBUG_INFO, "IgdOpRegion ended\n")); return Status; }
2.03125
2
2024-11-18T22:11:34.173589+00:00
2021-09-10T17:31:23
5b5e7df33a08cc82442d62d6185652f0db74547c
{ "blob_id": "5b5e7df33a08cc82442d62d6185652f0db74547c", "branch_name": "refs/heads/master", "committer_date": "2021-09-10T17:31:23", "content_id": "bae53095c1ca40af52f062e19fe399bfdad4b81b", "detected_licenses": [ "MIT" ], "directory_id": "73be9931b47f69a2eb7e4b5867d21ddcb10e8e95", "extension": "c", "filename": "system.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5870, "license": "MIT", "license_type": "permissive", "path": "/src/system.c", "provenance": "stackv2-0072.json.gz:52579", "repo_name": "isabella232/flecs-lua", "revision_date": "2021-09-10T17:31:23", "revision_id": "238707f340e66d6c732b67be2d85bdd5be2bf71e", "snapshot_id": "36044326e45517935f71af1c4813d475b5f1f112", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/isabella232/flecs-lua/238707f340e66d6c732b67be2d85bdd5be2bf71e/src/system.c", "visit_date": "2023-07-18T16:31:31.596560" }
stackv2
#include "private.h" static void print_time(ecs_time_t *time, const char *str) { #ifndef NDEBUG double sec = ecs_time_measure(time); ecs_lua_dbg("Lua %s took %f milliseconds", str, sec * 1000.0); #endif } static ecs_world_t **world_buf(lua_State *L, const ecs_world_t *world) { int ret = lua_rawgetp(L, LUA_REGISTRYINDEX, world); ecs_assert(ret == LUA_TTABLE, ECS_INTERNAL_ERROR, NULL); ret = lua_rawgeti(L, -1, ECS_LUA_APIWORLD); ecs_assert(ret == LUA_TUSERDATA, ECS_INTERNAL_ERROR, NULL); ecs_world_t **wbuf = lua_touserdata(L, -1); ecs_world_t *prev_world = *wbuf; lua_pop(L, 2); return wbuf; } /* Also used for triggers */ static void system_entry_point(ecs_iter_t *it) { const char *ame = ecs_get_name(it->world, it->system); ecs_assert(it->binding_ctx != NULL, ECS_INTERNAL_ERROR, NULL); ecs_world_t *w = it->world; ecs_lua_system *sys = it->binding_ctx; const ecs_world_t *real_world = ecs_get_world(it->world); int stage_id = ecs_get_stage_id(w); int stage_count = ecs_get_stage_count(w); ecs_assert(stage_id == 0, ECS_INTERNAL_ERROR, "Lua systems must run on the main thread"); const EcsLuaHost *host = ecs_singleton_get(w, EcsLuaHost); ecs_assert(host != NULL, ECS_INVALID_PARAMETER, NULL); lua_State *L = host->L; // host->states[stage_id]; ecs_lua_ctx *ctx = ecs_lua_get_context(L, real_world); ecs_lua__prolog(L); /* Since >2.3.2 it->world != the actual world, we have to swap the world pointer for all API calls with it->world (stage pointer) */ ecs_world_t **wbuf = world_buf(L, real_world); ecs_world_t *prev_world = *wbuf; *wbuf = it->world; ecs_time_t time; ecs_lua_dbg("Lua %s: \"%s\", %d columns, count %d, func ref %d", sys->trigger ? "trigger" : "system", ecs_get_name(w, it->system), it->column_count, it->count, sys->func_ref); int type = lua_rawgeti(L, LUA_REGISTRYINDEX, sys->func_ref); ecs_assert(type == LUA_TFUNCTION, ECS_INTERNAL_ERROR, NULL); ecs_os_get_time(&time); ecs_iter_to_lua(it, L, false); print_time(&time, "iter serialization"); lua_pushvalue(L, -1); int it_ref = luaL_ref(L, LUA_REGISTRYINDEX); ecs_os_get_time(&time); int ret = lua_pcall(L, 1, 0, 0); *wbuf = prev_world; print_time(&time, "system"); if(ret) { const char *name = ecs_get_name(w, it->system); const char *err = lua_tostring(L, lua_gettop(L)); ecs_os_err("error running system \"%s\" (%d): %s", name, ret, err); } ecs_assert(!ret, ECS_INTERNAL_ERROR, NULL); lua_rawgeti(L, LUA_REGISTRYINDEX, it_ref); ecs_assert(lua_type(L, -1) == LUA_TTABLE, ECS_INTERNAL_ERROR, NULL); ecs_os_get_time(&time); ecs_lua_to_iter(L, -1); print_time(&time, "iter deserialization"); luaL_unref(L, LUA_REGISTRYINDEX, it_ref); lua_pop(L, 1); ecs_lua__epilog(L); } static int new_whatever(lua_State *L, ecs_world_t *w, bool trigger) { ecs_lua_ctx *ctx = ecs_lua_get_context(L, w); ecs_entity_t e = 0; luaL_checktype(L, 1, LUA_TFUNCTION); const char *name = luaL_checkstring(L, 2); ecs_entity_t phase = luaL_optinteger(L, 3, 0); const char *signature = luaL_optstring(L, 4, NULL); ecs_lua_system *sys = lua_newuserdata(L, sizeof(ecs_lua_system)); if(trigger) { if(phase != EcsOnAdd && phase != EcsOnRemove) return luaL_argerror(L, 3, "invalid kind"); if(signature == NULL) return luaL_argerror(L, 4, "missing signature"); e = ecs_trigger_init(w, &(ecs_trigger_desc_t) { .entity.name = name, .callback = system_entry_point, .expr = signature, .events = phase, .binding_ctx = sys }); } else { e = ecs_system_init(w, &(ecs_system_desc_t) { .entity = { .name = name, .add = phase }, .query.filter.expr = signature, .callback = system_entry_point, .binding_ctx = sys }); } if(!e) return luaL_error(L, "failed to create system"); luaL_ref(L, LUA_REGISTRYINDEX); /* *sys */ lua_pushvalue(L, 1); sys->func_ref = luaL_ref(L, LUA_REGISTRYINDEX); sys->param_ref = LUA_NOREF; sys->trigger = trigger; ecs_set_name(w, e, name); // XXX: no longer needed? lua_pushinteger(L, e); return 1; } int new_system(lua_State *L) { return new_whatever(L, ecs_lua_world(L), false); } int new_trigger(lua_State *L) { return new_whatever(L, ecs_lua_world(L), true); } int run_system(lua_State *L) { ecs_world_t *w = ecs_lua_world(L); ecs_entity_t system = luaL_checkinteger(L, 1); lua_Number delta_time = luaL_checknumber(L, 2); ecs_lua_system *sys = ecs_get_system_binding_ctx(w, system); if(sys == NULL) return luaL_argerror(L, 1, "not a Lua system"); int tmp = sys->param_ref; if(!lua_isnoneornil(L, 3)) sys->param_ref = luaL_ref(L, LUA_REGISTRYINDEX); ecs_entity_t ret = ecs_run(w, system, delta_time, NULL); if(tmp != sys->param_ref) {/* Restore previous value */ luaL_unref(L, LUA_REGISTRYINDEX, sys->param_ref); sys->param_ref = tmp; } lua_pushinteger(L, ret); return 1; } int set_system_context(lua_State *L) { ecs_world_t *w = ecs_lua_world(L); ecs_entity_t system = luaL_checkinteger(L, 1); if(lua_gettop(L) < 2) lua_pushnil(L); ecs_lua_system *sys = ecs_get_system_binding_ctx(w, system); luaL_unref(L, LUA_REGISTRYINDEX, sys->param_ref); sys->param_ref = luaL_ref(L, LUA_REGISTRYINDEX); return 0; }
2.171875
2
2024-11-18T22:11:34.426436+00:00
2020-12-21T15:13:35
4696ec9d581739d3fcb0db32c8ba2e879d856035
{ "blob_id": "4696ec9d581739d3fcb0db32c8ba2e879d856035", "branch_name": "refs/heads/master", "committer_date": "2020-12-21T15:13:35", "content_id": "1b55ba845e5ad37c1ab4430b2190bf7d9e22e2d6", "detected_licenses": [ "MIT" ], "directory_id": "3dae53692c7fab9557ae36af61e6d0d850f0b133", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 250815564, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 415, "license": "MIT", "license_type": "permissive", "path": "/HostWorkspace/003_UserInput/main.c", "provenance": "stackv2-0072.json.gz:52708", "repo_name": "nemanjadjekic/Embedded-C", "revision_date": "2020-12-21T15:13:35", "revision_id": "9d6b6231edf70c858a6c825b2400a6e583ba76fd", "snapshot_id": "c7b729943636b93257b0d3cc946e15e0a790a12e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nemanjadjekic/Embedded-C/9d6b6231edf70c858a6c825b2400a6e583ba76fd/HostWorkspace/003_UserInput/main.c", "visit_date": "2021-05-17T14:15:35.881695" }
stackv2
/* * main.c * * Created on: Mar 29, 2020 * Author: nemus */ #include <stdio.h> #include <stdlib.h> #define arr_size 6 int main(void) { printf("\nEnter 6 characters of your choice: \t"); char arr[arr_size] = {}; for(int i=0 ; i < arr_size ; i++) { scanf(" %c", &arr[i]); } printf("\nASCII representation: "); for(int i = 0; i < arr_size; i++) { printf(" %d ", arr[i]); } return 0; }
3.375
3
2024-11-18T22:11:40.936991+00:00
2017-01-30T17:57:24
0ac27f0d2bd8e7412e34cc3a6976a98fcbcc5711
{ "blob_id": "0ac27f0d2bd8e7412e34cc3a6976a98fcbcc5711", "branch_name": "refs/heads/master", "committer_date": "2017-01-30T17:57:24", "content_id": "fd85179bc51845353da53814ba793cf312908c0e", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1467a406bf0220a3d3f4936ed42caec5b6c28cd5", "extension": "h", "filename": "event.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 80448195, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 878, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/libzdgui/scripts/libzdgui/include/event.h", "provenance": "stackv2-0072.json.gz:53092", "repo_name": "Mistranger/libzdgui", "revision_date": "2017-01-30T17:57:24", "revision_id": "26fc279f7ca64d7f763ef8cea1418082ae8dbc9d", "snapshot_id": "3da2703e6f7d115be357976949e9290c6a7cb921", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Mistranger/libzdgui/26fc279f7ca64d7f763ef8cea1418082ae8dbc9d/libzdgui/scripts/libzdgui/include/event.h", "visit_date": "2020-05-20T12:25:35.068975" }
stackv2
#ifndef EVENT_H_INCLUDED #define EVENT_H_INCLUDED // Union holding all event types typedef enum eventTypes { EV_Event = 0, EV_Mouse, EV_Dimension, EV_LifeCycle, EV_Widget, EV_Focus, } guiEventTypes; typedef struct guiEvent { guiEventTypes eventType; void *sourceWidget; } guiEvent; #define event_getSource(_event) ((guiWidget*)(((guiEvent*)_event)->sourceWidget)) #define event_setSource(_event, _widget) { ((guiEvent*)_event)->sourceWidget = (void*)_widget; } guiEvent *event_new(void *widget); // Listeners // Union holding all event listeners // One listener could handle one event type // Widgets could have multiple listeners for various event types typedef struct guiEventListener { guiEventTypes listenerType; void *handlerWidget; void (*handleEvent)(struct guiEventListener *listener, guiEvent *event); } guiEventListener; #endif // EVENT_H_INCLUDED
2.09375
2
2024-11-18T22:11:41.972599+00:00
2019-08-29T10:40:32
45512449397e66344c3b1354c192df7807e0882a
{ "blob_id": "45512449397e66344c3b1354c192df7807e0882a", "branch_name": "refs/heads/master", "committer_date": "2019-08-29T10:40:32", "content_id": "4eb1173b22f806d2dc53f5211a4f7c0ec54b5edb", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8bfbde632ce125e8f11666b631020942a8908b2f", "extension": "c", "filename": "user_main.c", "fork_events_count": 0, "gha_created_at": "2018-02-07T08:27:08", "gha_event_created_at": "2019-08-29T10:40:33", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 120585967, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 952, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/esp8266/006_esp_idf_blinky/main/user_main.c", "provenance": "stackv2-0072.json.gz:53734", "repo_name": "xiaolaba/blog", "revision_date": "2019-08-29T10:40:32", "revision_id": "7a35a7838257a50ef8f4fff9cec234e43e3d815c", "snapshot_id": "4cecad20c758989f0ca41b503e7eb8ef1620d816", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xiaolaba/blog/7a35a7838257a50ef8f4fff9cec234e43e3d815c/esp8266/006_esp_idf_blinky/main/user_main.c", "visit_date": "2021-05-03T05:52:30.283106" }
stackv2
/** * Copyright (c) 2019, Łukasz Marcin Podkalicki <lpodkalicki@gmail.com> * ESP8266/006 * Simple blinky using delay function (ESP8266_RTOS_SDK). */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "driver/gpio.h" #define LED_PIN (2) void app_main(void) { /* setup */ gpio_config_t io_conf; io_conf.intr_type = GPIO_INTR_DISABLE; // disable interrupt io_conf.mode = GPIO_MODE_OUTPUT; // set as output mode io_conf.pin_bit_mask = 1 << LED_PIN; // bitmask io_conf.pull_down_en = 0; // disable pull-down mode io_conf.pull_up_en = 0; // disable pull-up mode gpio_config(&io_conf); printf("SDK version:%s\n", esp_get_idf_version()); /* loop */ while (1) { gpio_set_level(LED_PIN, 1); vTaskDelay(500 / portTICK_PERIOD_MS); gpio_set_level(LED_PIN, 0); vTaskDelay(500 / portTICK_PERIOD_MS); } }
2.640625
3
2024-11-18T22:11:42.236472+00:00
2020-03-17T05:48:13
d263a119dea5e4aabc16734e952baf24a77233a7
{ "blob_id": "d263a119dea5e4aabc16734e952baf24a77233a7", "branch_name": "refs/heads/master", "committer_date": "2020-03-17T05:48:13", "content_id": "43fb36c8bd908bd9068a6f318a6e0c02bcb2c31d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "285485f898f14764ed0d94ad0758a8155259c264", "extension": "c", "filename": "simple_tasks.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 149684553, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 873, "license": "Apache-2.0", "license_type": "permissive", "path": "/software/line-sensor/src/simple_tasks.c", "provenance": "stackv2-0072.json.gz:54121", "repo_name": "robot-corral/mazebot", "revision_date": "2020-03-17T05:48:13", "revision_id": "9820e59c876043ba4749c07a5f033cd2c63cc675", "snapshot_id": "5ab630ec23dc608c5d0abdb8aedb80d80524b8c3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/robot-corral/mazebot/9820e59c876043ba4749c07a5f033cd2c63cc675/software/line-sensor/src/simple_tasks.c", "visit_date": "2020-03-29T07:54:00.775525" }
stackv2
/******************************************************************************* * Copyright (C) 2018 Pavel Krupets * *******************************************************************************/ #include "simple_tasks.h" #include "global_data.h" #include <stdatomic.h> bool hasScheduledTasks() { return atomic_load(&g_taskSchedulerCurrentTask) != 0; } bool scheduleTask(taskFunction_t task) { taskFunction_t expected = 0; return atomic_compare_exchange_strong(&g_taskSchedulerCurrentTask, &expected, task); } void runTasks() { for (;;) { const taskFunction_t current = atomic_load(&g_taskSchedulerCurrentTask); if (current != 0) { current(); g_taskSchedulerCurrentTask = 0; atomic_store(&g_taskSchedulerCurrentTask, 0); } } }
2.40625
2
2024-11-18T20:14:01.825069+00:00
2021-06-08T13:39:13
01c20ae5afd9b9fbc85d6b0df317fd1792755404
{ "blob_id": "01c20ae5afd9b9fbc85d6b0df317fd1792755404", "branch_name": "refs/heads/main", "committer_date": "2021-06-08T13:39:13", "content_id": "fd4f478a049db22910f3647bc8493dbcc2d6d181", "detected_licenses": [ "MIT" ], "directory_id": "f99cb3f6487db2772c7ce493dd8c9dda64ca90ca", "extension": "c", "filename": "29_leap_year.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 374142991, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 602, "license": "MIT", "license_type": "permissive", "path": "/29_leap_year.c", "provenance": "stackv2-0072.json.gz:302725", "repo_name": "victor4pinheiro/exercises-college", "revision_date": "2021-06-08T13:39:13", "revision_id": "a32a3d7ceedcfd86bab00ef6e2b9e67542231cdb", "snapshot_id": "9f435210490f712b5d791dee6f9b1abf8b1d3786", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/victor4pinheiro/exercises-college/a32a3d7ceedcfd86bab00ef6e2b9e67542231cdb/29_leap_year.c", "visit_date": "2023-05-15T07:43:43.919304" }
stackv2
#include <stdio.h> int check_leap_year(int year) { int status = 0; if (year % 4 == 0 && year % 100 != 0) status = 1; else if (year % 400 == 0) status = 1; else status = 0; return status; } int main() { int year; printf("Type a year:\n"); scanf("%d", &year); int statusLeapYear = check_leap_year(year); if (statusLeapYear == 1) printf("It's a leap year.\n"); else printf("It's not a leap year.\n"); return 0; }
3.265625
3
2024-11-18T20:41:22.122304+00:00
2023-09-05T10:14:33
8748be275d983fc4f9156515cbc156b0e416a76c
{ "blob_id": "8748be275d983fc4f9156515cbc156b0e416a76c", "branch_name": "refs/heads/master", "committer_date": "2023-09-05T10:14:33", "content_id": "c0e814d217a262ef0ba3c9c68eb35f9aa5a8e837", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ], "directory_id": "f367e4b66a1ee42e85830b31df88f63723c36a47", "extension": "c", "filename": "encode.c", "fork_events_count": 1565, "gha_created_at": "2015-01-27T20:41:52", "gha_event_created_at": "2023-09-14T10:17:02", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 29933948, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11412, "license": "BSD-3-Clause,BSD-2-Clause,Apache-2.0", "license_type": "permissive", "path": "/lib/onigmo/sample/encode.c", "provenance": "stackv2-0074.json.gz:64579", "repo_name": "fluent/fluent-bit", "revision_date": "2023-09-05T10:14:33", "revision_id": "1a41f49dc2f3ae31a780caa9ffd6137b1d703065", "snapshot_id": "06873e441162b92941024e9a7e9e8fc934150bf7", "src_encoding": "UTF-8", "star_events_count": 4907, "url": "https://raw.githubusercontent.com/fluent/fluent-bit/1a41f49dc2f3ae31a780caa9ffd6137b1d703065/lib/onigmo/sample/encode.c", "visit_date": "2023-09-05T13:44:55.347372" }
stackv2
/* * encode.c */ #include <stdio.h> #include "onigmo.h" static int search(regex_t* reg, unsigned char* str, unsigned char* end) { int r; unsigned char *start, *range; OnigRegion *region; region = onig_region_new(); start = str; range = end; r = onig_search(reg, str, end, start, range, region, ONIG_OPTION_NONE); if (r >= 0) { int i; fprintf(stderr, "match at %d (%s)\n", r, ONIGENC_NAME(onig_get_encoding(reg))); for (i = 0; i < region->num_regs; i++) { fprintf(stderr, "%d: (%ld-%ld)\n", i, region->beg[i], region->end[i]); } } else if (r == ONIG_MISMATCH) { fprintf(stderr, "search fail (%s)\n", ONIGENC_NAME(onig_get_encoding(reg))); } else { /* error */ OnigUChar s[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(s, r); fprintf(stderr, "ERROR: %s\n", s); fprintf(stderr, " (%s)\n", ONIGENC_NAME(onig_get_encoding(reg))); return -1; } onig_region_free(region, 1 /* 1:free self, 0:free contents only */); return 0; } static int exec(OnigEncoding enc, OnigOptionType options, char* apattern, char* astr) { int r; unsigned char *end; regex_t* reg; OnigErrorInfo einfo; UChar* pattern = (UChar* )apattern; UChar* str = (UChar* )astr; r = onig_new(&reg, pattern, pattern + onigenc_str_bytelen_null(enc, pattern), options, enc, ONIG_SYNTAX_DEFAULT, &einfo); if (r != ONIG_NORMAL) { OnigUChar s[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(s, r, &einfo); fprintf(stderr, "ERROR: %s\n", s); return -1; } end = str + onigenc_str_bytelen_null(enc, str); r = search(reg, str, end); onig_free(reg); onig_end(); return 0; } static OnigCaseFoldType CF = ONIGENC_CASE_FOLD_MIN; #if 0 static void set_case_fold(OnigCaseFoldType cf) { CF = cf; } #endif static int exec_deluxe(OnigEncoding pattern_enc, OnigEncoding str_enc, OnigOptionType options, char* apattern, char* astr) { int r; unsigned char *end; regex_t* reg; OnigCompileInfo ci; OnigErrorInfo einfo; UChar* pattern = (UChar* )apattern; UChar* str = (UChar* )astr; ci.num_of_elements = 5; ci.pattern_enc = pattern_enc; ci.target_enc = str_enc; ci.syntax = ONIG_SYNTAX_DEFAULT; ci.option = options; ci.case_fold_flag = CF; r = onig_new_deluxe(&reg, pattern, pattern + onigenc_str_bytelen_null(pattern_enc, pattern), &ci, &einfo); if (r != ONIG_NORMAL) { OnigUChar s[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(s, r, &einfo); fprintf(stderr, "ERROR: %s\n", s); return -1; } end = str + onigenc_str_bytelen_null(str_enc, str); r = search(reg, str, end); onig_free(reg); onig_end(); return 0; } extern int main(int argc, char* argv[]) { int r = 0; /* ISO 8859-1 test */ static unsigned char str[] = { 0xc7, 0xd6, 0xfe, 0xea, 0xe0, 0xe2, 0x00 }; static unsigned char pattern[] = { '(', '?', 'u', ')', 0xe7, 0xf6, 0xde, '\\', 'w', '+', 0x00 }; r |= exec(ONIG_ENCODING_WINDOWS_1250, ONIG_OPTION_IGNORECASE, "aBc\\w", " AbCd"); r |= exec(ONIG_ENCODING_WINDOWS_1251, ONIG_OPTION_IGNORECASE, "aBc\\w", " AbCd"); r |= exec(ONIG_ENCODING_WINDOWS_1252, ONIG_OPTION_IGNORECASE, "aBc\\w", " AbCd"); r |= exec(ONIG_ENCODING_WINDOWS_1253, ONIG_OPTION_IGNORECASE, "aBc\\w", " AbCd"); r |= exec(ONIG_ENCODING_WINDOWS_1254, ONIG_OPTION_IGNORECASE, "aBc\\w", " AbCd"); r |= exec(ONIG_ENCODING_WINDOWS_1257, ONIG_OPTION_IGNORECASE, "aBc\\w", " AbCd"); r |= exec(ONIG_ENCODING_ISO_8859_1, ONIG_OPTION_IGNORECASE, " [a-c\337z] ", " SS "); r |= exec(ONIG_ENCODING_ISO_8859_1, ONIG_OPTION_IGNORECASE, " [\330-\341] ", " SS "); r |= exec(ONIG_ENCODING_ISO_8859_2, ONIG_OPTION_IGNORECASE, "\337 ", " Ss "); r |= exec(ONIG_ENCODING_ISO_8859_2, ONIG_OPTION_IGNORECASE, "SS ", " \337 "); /* Ignore the following result. It also fails with Oniguruma 5.9.5. */ /* r |= */ exec(ONIG_ENCODING_ISO_8859_2, ONIG_OPTION_IGNORECASE, "\\A\\S\\z", "ss"); r |= exec(ONIG_ENCODING_ISO_8859_2, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_3, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_4, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_5, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_6, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_7, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_8, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_9, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_10, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_11, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_13, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_14, ONIG_OPTION_IGNORECASE, "[ac]+", "bbbaAaCCC"); r |= exec(ONIG_ENCODING_ISO_8859_15, ONIG_OPTION_IGNORECASE, (char* )pattern, (char* )str); r |= exec(ONIG_ENCODING_ISO_8859_16, ONIG_OPTION_IGNORECASE, (char* )pattern, (char* )str); r |= exec(ONIG_ENCODING_KOI8_R, ONIG_OPTION_IGNORECASE, "a+", "bbbaaaccc"); r |= exec(ONIG_ENCODING_KOI8_U, ONIG_OPTION_IGNORECASE, "a+", "bbbaaaccc"); r |= exec(ONIG_ENCODING_EUC_TW, ONIG_OPTION_IGNORECASE, "b*a+?c+", "bbbaaaccc"); r |= exec(ONIG_ENCODING_EUC_KR, ONIG_OPTION_IGNORECASE, "a+", "bbbaaaccc"); r |= exec(ONIG_ENCODING_EUC_CN, ONIG_OPTION_IGNORECASE, "c+", "bbbaaaccc"); r |= exec(ONIG_ENCODING_BIG5, ONIG_OPTION_IGNORECASE, "a+", "bbbaaaccc"); r |= exec(ONIG_ENCODING_ISO_8859_1, ONIG_OPTION_IGNORECASE, "\337", "SS"); r |= exec(ONIG_ENCODING_ISO_8859_1, ONIG_OPTION_IGNORECASE, "SS", "\337"); r |= exec(ONIG_ENCODING_ISO_8859_1, ONIG_OPTION_IGNORECASE, "SSb\337ssc", "a\337bSS\337cd"); r |= exec(ONIG_ENCODING_ISO_8859_1, ONIG_OPTION_IGNORECASE, "[a\337]{0,2}", "aSS"); r |= exec(ONIG_ENCODING_ISO_8859_1, ONIG_OPTION_IGNORECASE, "is", "iss"); r |= exec_deluxe(ONIG_ENCODING_ASCII, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_NONE, "a+", "\000b\000a\000a\000a\000c\000c\000\000"); r |= exec_deluxe(ONIG_ENCODING_ASCII, ONIG_ENCODING_UTF16_LE, ONIG_OPTION_NONE, "a+", "b\000a\000a\000a\000a\000c\000\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_LE, ONIG_OPTION_NONE, "\000b\000a\000a\000a\000c\000c\000\000", "x\000b\000a\000a\000a\000c\000c\000\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF16_LE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_NONE, "b\000a\000a\000a\000c\000c\000\000\000", "\000x\000b\000a\000a\000a\000c\000c\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF32_BE, ONIG_ENCODING_UTF32_LE, ONIG_OPTION_NONE, "\000\000\000b\000\000\000a\000\000\000a\000\000\000a\000\000\000c\000\000\000c\000\000\000\000", "x\000\000\000b\000\000\000a\000\000\000a\000\000\000a\000\000\000c\000\000\000c\000\000\000\000\000\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF32_LE, ONIG_ENCODING_UTF32_BE, ONIG_OPTION_NONE, "b\000\000\000a\000\000\000a\000\000\000a\000\000\000c\000\000\000c\000\000\000\000\000\000\000", "\000\000\000x\000\000\000b\000\000\000a\000\000\000a\000\000\000a\000\000\000c\000\000\000c\000\000\000\000"); r |= exec_deluxe(ONIG_ENCODING_ISO_8859_1, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "\337", "\000S\000S\000\000"); r |= exec_deluxe(ONIG_ENCODING_ISO_8859_1, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "SS", "\000\337\000\000"); r |= exec_deluxe(ONIG_ENCODING_ISO_8859_1, ONIG_ENCODING_UTF16_LE, ONIG_OPTION_IGNORECASE, "\337", "S\000S\000\000\000"); r |= exec_deluxe(ONIG_ENCODING_ISO_8859_1, ONIG_ENCODING_UTF32_BE, ONIG_OPTION_IGNORECASE, "SS", "\000\000\000\337\000\000\000\000"); r |= exec_deluxe(ONIG_ENCODING_ISO_8859_1, ONIG_ENCODING_UTF32_LE, ONIG_OPTION_IGNORECASE, "\337", "S\000\000\000S\000\000\000\000\000\000\000"); r |= exec(ONIG_ENCODING_UTF16_BE, ONIG_OPTION_NONE, "\000[\000[\000:\000a\000l\000n\000u\000m\000:\000]\000]\000+\000\000", "\000#\002\120\000a\000Z\012\077\012\076\012\075\000\000"); /* 0x0a3d == \012\075 : is not alnum */ /* 0x0a3e == \012\076 : is alnum */ r |= exec(ONIG_ENCODING_UTF16_BE, ONIG_OPTION_NONE, "\000\\\000d\000+\000\000", "\0003\0001\377\020\377\031\377\032\000\000"); r |= exec(ONIG_ENCODING_GB18030, ONIG_OPTION_IGNORECASE, "(Aa\\d)+", "BaA5Aa0234"); r |= exec_deluxe(ONIG_ENCODING_ISO_8859_1, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_NONE, "^\\P{Hiragana}\\p{^Hiragana}(\\p{Hiragana}+)$", "\060\100\060\240\060\101\060\102\060\226\060\237\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "\000[\000\337\000]\000\000", "\000S\000S\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "\000[\000\337\000]\000\000", "\000s\000S\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "\000^\000[\000\001\000-\377\375\000]\000$\000\000", "\000s\000S\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "\000S\000S\000\000", "\000S\000T\000\337\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "\000S\000T\000S\000S\000\000", "\000S\000t\000s\000S\000\000"); { UChar pat[] = { 0x1f, 0xfc, 0x00, 0x00 }; UChar str1[] = { 0x21, 0x26, 0x1f, 0xbe, 0x00, 0x00 }; UChar str2[] = { 0x1f, 0xf3, 0x00, 0x00 }; r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, (char* )pat, (char* )str1); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, (char* )pat, (char* )str2); } #if 0 /* You should define USE_UNICODE_CASE_FOLD_TURKISH_AZERI in regenc.h. */ set_case_fold(ONIGENC_CASE_FOLD_TURKISH_AZERI); r |= exec_deluxe(ONIG_ENCODING_UTF8, ONIG_ENCODING_UTF8, ONIG_OPTION_IGNORECASE, "Ii", "\304\261\304\260"); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "\000I\000i\000\000", "\001\061\001\060\000\000"); r |= exec_deluxe(ONIG_ENCODING_UTF16_BE, ONIG_ENCODING_UTF16_BE, ONIG_OPTION_IGNORECASE, "\001\061\001\060\000\000", "\000I\000i\000\000"); set_case_fold(ONIGENC_CASE_FOLD_MIN); #endif return r; }
2.6875
3
2024-11-18T20:41:22.188721+00:00
2012-05-09T07:44:30
275aa1b688efbf2c2a8ebb9262f0e013258fe42e
{ "blob_id": "275aa1b688efbf2c2a8ebb9262f0e013258fe42e", "branch_name": "refs/heads/master", "committer_date": "2012-05-09T07:44:30", "content_id": "d81654ce94cfd3d1b83e269bef1a9f016950e49f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "0098bdba0bfcfefd5e1f46f7deaa62e5a49ab506", "extension": "c", "filename": "vfs_path.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 5254695, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4570, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/fs/vfs/vfs_path.c", "provenance": "stackv2-0074.json.gz:64707", "repo_name": "descent/bos", "revision_date": "2012-05-09T07:44:30", "revision_id": "c343686f077cc1d70383ec01099355d51a51fc05", "snapshot_id": "633cce854ea4d280431e7c02c98e9d6404736883", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/descent/bos/c343686f077cc1d70383ec01099355d51a51fc05/fs/vfs/vfs_path.c", "visit_date": "2021-01-25T02:37:46.040867" }
stackv2
/* * kernel/fs/vfs/vfs_path.c * * Copyright (c) 2007-2010 jianjun jiang <jerryjianjun@gmail.com> * official site: http://xboot.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <malloc.h> #include <fs/fs.h> #include <fs/vfs/vfs.h> /* the size of fd size */ #define FD_SIZE (256) /* * file descriptor */ static struct file * file_desc[FD_SIZE]; /* * buffer for storing cwd path */ static char cwd[MAX_PATH]; /* * current work directory's fp */ static struct file * cwdfp; /* * allocate a file descriptor. */ int fd_alloc(int low) { int fd; if( (low < 0) || (low >= FD_SIZE) ) return -1; if(low < 3) low = 3; for( fd = low; fd < FD_SIZE; fd++ ) { if( file_desc[fd] == NULL ) { return fd; } } return -1; } /* * free a file descriptor. */ int fd_free(int fd) { if( (fd < 0) || (fd >= FD_SIZE) ) return -1; file_desc[fd] = NULL; return 0; } /* * map a descriptor to a file object. */ struct file * get_fp(int fd) { if( (fd < 0) || (fd >= FD_SIZE) ) return NULL; return file_desc[fd]; } /* * set a descriptor with a file object. */ int set_fp(int fd, struct file *fp) { if( (fd < 0) || (fd >= FD_SIZE) ) return -1; file_desc[fd] = fp; return 0; } /* * convert to full path from the cwd and path by removing all "." and ".." */ int vfs_path_conv(const char * path, char * full) { char *p, *q, *s; int left_len, full_len; char left[MAX_PATH], next_token[MAX_PATH]; if(path[0] == '/') { full[0] = '/'; full[1] = '\0'; if(path[1] == '\0') return 0; full_len = 1; left_len = strlcpy(left, (const char *)(path + 1), sizeof(left)); } else { strlcpy(full, cwd, MAX_PATH); full_len = strlen(full); left_len = strlcpy(left, path, sizeof(left)); } if((left_len >= sizeof(left)) || (full_len >= MAX_PATH)) return -1; /* * iterate over path components in `left'. */ while(left_len != 0) { /* * extract the next path component and adjust left and its length. */ p = strchr(left, '/'); s = p ? p : left + left_len; if((int)(s - left) >= sizeof(next_token)) return -1; memcpy(next_token, left, s - left); next_token[s - left] = '\0'; left_len -= s - left; if(p != NULL) { memmove(left, s + 1, left_len + 1); } if(full[full_len - 1] != '/') { if (full_len + 1 >= MAX_PATH) return -1; full[full_len++] = '/'; full[full_len] = '\0'; } if(next_token[0] == '\0' || strcmp(next_token, ".") == 0) { continue; } else if(strcmp(next_token, "..") == 0) { /* * strip the last path component except when we have single '/' */ if(full_len > 1) { full[full_len - 1] = '\0'; q = strrchr(full, '/') + 1; *q = '\0'; full_len = q - full; } continue; } full_len = strlcat(full, next_token, MAX_PATH); //printk("==>%s\n",full); if(full_len >= MAX_PATH) return -1; } /* * remove trailing slash except when the full pathname is a single '/' */ if(full_len > 1 && full[full_len - 1] == '/') { full[full_len - 1] = '\0'; } return 0; } /* * set current work directory */ void vfs_setcwd(const char * path) { if(!path) return; if(strlen(path) < MAX_PATH) strcpy(cwd, path); } /* * get current work directory */ char * vfs_getcwd(char * buf, size_t size) { if( size == 0 ) return NULL; if( size < strlen(cwd) + 1 ) return NULL; strlcpy(buf, cwd, size); return buf; } /* * set current work directory's fp */ void vfs_setcwdfp(struct file * fp) { cwdfp = fp; } /* * get current work directory's fp */ struct file * vfs_getcwdfp(void) { return cwdfp; } /* * fd pure init */ static void fd_pure_sync_init(void) { int i; for( i = 0; i < FD_SIZE; i++ ) file_desc[i] = NULL; strcpy(cwd, "/"); cwdfp = NULL; }
2.609375
3
2024-11-18T20:41:23.333454+00:00
2019-02-13T12:37:57
129d81973e33200b6a2e09a1685463ffa575d97d
{ "blob_id": "129d81973e33200b6a2e09a1685463ffa575d97d", "branch_name": "refs/heads/master", "committer_date": "2019-02-13T12:37:57", "content_id": "5294b383692309dc2050f6a540442a827b1cee53", "detected_licenses": [ "MIT" ], "directory_id": "ad40a113f492c34f2087a43002f68e747198983b", "extension": "c", "filename": "create_set.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 170503672, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 485, "license": "MIT", "license_type": "permissive", "path": "/src/menu/create_set.c", "provenance": "stackv2-0074.json.gz:65221", "repo_name": "FlorianMarcon/my_rpg", "revision_date": "2019-02-13T12:37:57", "revision_id": "8c172cb18472e8deb445020803ec5ad00f3abd7f", "snapshot_id": "c935e8e4bb186c991fa9b33eaa01d669ac7813ae", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/FlorianMarcon/my_rpg/8c172cb18472e8deb445020803ec5ad00f3abd7f/src/menu/create_set.c", "visit_date": "2020-04-22T16:18:11.981330" }
stackv2
/* ** EPITECH PROJECT, 2018 ** create_set.c ** File description: ** setting */ #include "header.h" set_t *init_set(void) { set_t *elem = malloc(sizeof(set_t)); elem->sprite = sfSprite_create(); elem->texture = sfTexture_createFromFile( "src/png_menu/setting.png", NULL); elem->pos = (sfVector2f){0, 0}; elem->sprite1 = sfSprite_create(); elem->texture1 = sfTexture_createFromFile( "src/png_menu/arrow.png", NULL); elem->pos1 = (sfVector2f){9, -15}; return (elem); }
2.46875
2
2024-11-18T21:31:52.738310+00:00
2020-04-17T23:44:19
c65fc97bd8d569129aa6db90c97420b3ff59bb2b
{ "blob_id": "c65fc97bd8d569129aa6db90c97420b3ff59bb2b", "branch_name": "refs/heads/master", "committer_date": "2020-04-17T23:44:19", "content_id": "3ea32de7b0c749990c75252ad230cba07749489a", "detected_licenses": [ "MIT" ], "directory_id": "8608b9cf0db48216be38c375265d0c5ea72da9dc", "extension": "c", "filename": "antiremote.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 256632663, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5711, "license": "MIT", "license_type": "permissive", "path": "/antiremote.c", "provenance": "stackv2-0077.json.gz:68", "repo_name": "GavRobbs/AntiremoteCar", "revision_date": "2020-04-17T23:44:19", "revision_id": "c21dc7cecd62c171e4da96dd88f641187d54a793", "snapshot_id": "4429b947eaafab0f3370e2481509727def6847ed", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GavRobbs/AntiremoteCar/c21dc7cecd62c171e4da96dd88f641187d54a793/antiremote.c", "visit_date": "2022-04-21T01:50:33.250656" }
stackv2
#define F_CPU 1000000 #define BUTTON_PIN PIND #define SPEED_JUMP 20 #define CONSTANT_SPEED 80 #define MAX_PWM_VALUE 1024UL #define STOPPED 0 #define FORWARDS 1 #define BACKWARDS 2 #define STEADY 0 #define ACCELERATING 1 #define DECELERATING 2 #include<avr/io.h> #include<avr/interrupt.h> #include<util/delay.h> #include<stdlib.h> uint8_t MOVEMENT_STATE = 0; uint8_t MOVEMENT_PHASE = 0; uint8_t TARGET_STATE = STOPPED; int pwmSpeedTarget; int pwmSpeedCurrent; int lastTime; int delta; void stopVehicle(void); void startVehicle(void); void reverseVehicle(void); void continueCurrently(void); ISR(PCINT2_vect){ if(bit_is_clear(PIND, PD0)){ cli(); stopVehicle(); } else if(bit_is_clear(PIND, PD1)){ cli(); startVehicle(); } else if(bit_is_clear(PIND, PD2)){ cli(); reverseVehicle(); } else{ } sei(); } void initInterrupts(){ PCICR |= (1 << PCIE2); PCMSK2 |= (1 << PD0) | (1 << PD1) | (1 << PD2); sei(); } void initADC(){ ADMUX |= (1 << REFS0) | (1 << MUX2) | (1 << MUX0); ADCSRA |= (1 << ADPS1) | (1 << ADPS0); ADCSRA |= (1 << ADEN); } void initPWMAndTimers(){ TCCR1B = (1 << CS10) |(1 << WGM13) | (1 << WGM11); TCCR1A = (1 << COM1A1); ICR1 = 150; OCR1A = 0; TCCR0B = (1 << CS02) | (1 << CS00); //1 tick is 1 ms } void initInputs(){ DDRD = 0b00000000; PORTD = 0b00000111; DDRB = 0b00100110; } void setPWMSpeed(){ uint16_t ocrval = (((uint16_t)pwmSpeedCurrent) * 150) / MAX_PWM_VALUE; OCR1A = ocrval; } uint16_t readADC(){ ADCSRA |= (1 << ADSC); loop_until_bit_is_clear(ADCSRA, ADSC); return ADC; } void stopVehicle(){ TARGET_STATE = STOPPED; pwmSpeedTarget = 0; if(pwmSpeedCurrent == 0){ if(MOVEMENT_STATE == STOPPED){ MOVEMENT_PHASE = STEADY; } else{ MOVEMENT_STATE = STOPPED; MOVEMENT_PHASE = STEADY; } DDRB &= ~(1 << PB1); PORTB &= ~((1 << PB5) | (1 << PB2)); } else{ MOVEMENT_PHASE = DECELERATING; } } void startVehicle(){ //Read the value of PWM speed target, don't forget to put it here pwmSpeedTarget = readADC(); /*When this button is pressed, checks if the vehicle is already moving forwards. If it isn't, it slows the vehicle down to a complete halt*/ if(MOVEMENT_STATE != FORWARDS || MOVEMENT_STATE != STOPPED){ stopVehicle(); while(pwmSpeedCurrent != 0){ continueCurrently(); } } TARGET_STATE = FORWARDS; DDRB &= (1 << PB1); PORTB &= ~((1 << PB5) | (1 << PB2)); PORTB |= (1 << PB2); /*If the vehicle is already going forwards, all we have to do is change the current speed. The new speed can be higher and lower than the old, so it can be accelerating or decelerating*/ if(MOVEMENT_STATE == FORWARDS){ if(abs(pwmSpeedCurrent - pwmSpeedTarget) <= SPEED_JUMP){ pwmSpeedCurrent = pwmSpeedTarget; MOVEMENT_PHASE = STEADY; } else if(pwmSpeedTarget > pwmSpeedCurrent){ MOVEMENT_PHASE = ACCELERATING; } else{ MOVEMENT_PHASE = DECELERATING; } return; } else{ MOVEMENT_STATE = FORWARDS; MOVEMENT_PHASE = ACCELERATING; } } void reverseVehicle(){ //Read the value of PWM speed target, don't forget to put it here pwmSpeedTarget = readADC(); /*When this button is pressed, checks if the vehicle is already moving forwards. If it isn't, it slows the vehicle down to a complete halt*/ if(MOVEMENT_STATE != BACKWARDS || MOVEMENT_STATE != STOPPED){ stopVehicle(); while(pwmSpeedCurrent != 0){ continueCurrently(); } } TARGET_STATE = BACKWARDS; DDRB &= (1 << PB1); PORTB = ~((1 << PB5) | (1 << PB2)); PORTB |= (1 << PB5); if(MOVEMENT_STATE == BACKWARDS){ if(abs(pwmSpeedCurrent - pwmSpeedTarget) <= SPEED_JUMP){ pwmSpeedCurrent = pwmSpeedTarget; MOVEMENT_PHASE = STEADY; } else if(pwmSpeedTarget > pwmSpeedCurrent){ MOVEMENT_PHASE = ACCELERATING; } else{ MOVEMENT_PHASE = DECELERATING; } return; } else{ MOVEMENT_STATE = BACKWARDS; MOVEMENT_PHASE = ACCELERATING; } } void continueCurrently(){ int ct = TCNT0; delta = ct - lastTime; lastTime = ct; if(MOVEMENT_PHASE == STEADY){ return; } if(abs(pwmSpeedCurrent - pwmSpeedTarget) <= SPEED_JUMP){ pwmSpeedCurrent = pwmSpeedTarget; MOVEMENT_PHASE = STEADY; } if(MOVEMENT_PHASE == ACCELERATING){ pwmSpeedCurrent += ((uint8_t)CONSTANT_SPEED * (uint8_t)delta)/255; if(pwmSpeedCurrent >= pwmSpeedTarget){ pwmSpeedCurrent = pwmSpeedTarget; MOVEMENT_PHASE = STEADY; } } else{ pwmSpeedCurrent -= ((uint8_t)CONSTANT_SPEED * (uint8_t)delta)/255; if(pwmSpeedCurrent <= pwmSpeedTarget){ pwmSpeedCurrent = pwmSpeedTarget; MOVEMENT_PHASE = STEADY; } } _delay_ms(1); setPWMSpeed(); } int main(void){ pwmSpeedTarget = 0; pwmSpeedCurrent = 0; MOVEMENT_STATE = STOPPED; TARGET_STATE = STOPPED; MOVEMENT_PHASE = STEADY; TCNT0 = 0; initInputs(); initADC(); initPWMAndTimers(); lastTime = TCNT0; initInterrupts(); while(1){ continueCurrently(); } return 0; }
2.71875
3
2024-11-18T21:31:52.814618+00:00
2020-12-23T08:36:28
5352ee171e772ab4a12996d2c23945c8dfb0e104
{ "blob_id": "5352ee171e772ab4a12996d2c23945c8dfb0e104", "branch_name": "refs/heads/main", "committer_date": "2020-12-23T08:36:28", "content_id": "efe403e65013235392e9d7055e1787b6cd530297", "detected_licenses": [ "CC0-1.0" ], "directory_id": "75e1d9446cb1fca5c6a79ad0ba7f38268df1161f", "extension": "c", "filename": "matrix-row-sum.c", "fork_events_count": 1, "gha_created_at": "2020-12-24T19:12:54", "gha_event_created_at": "2020-12-24T19:12:54", "gha_language": null, "gha_license_id": "CC0-1.0", "github_id": 324221340, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 684, "license": "CC0-1.0", "license_type": "permissive", "path": "/C Programs/matrix-row-sum.c", "provenance": "stackv2-0077.json.gz:197", "repo_name": "muhammad-masood-ur-rehman/Skillrack", "revision_date": "2020-12-23T08:36:28", "revision_id": "71a25417c89d0efab40ee6229ccd758b26ae4312", "snapshot_id": "6e9b6d93680dfef6f40783f02ded8a0d4283c98a", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/muhammad-masood-ur-rehman/Skillrack/71a25417c89d0efab40ee6229ccd758b26ae4312/C Programs/matrix-row-sum.c", "visit_date": "2023-02-03T16:45:54.462561" }
stackv2
Matrix Row Sum Matrix Row Sum: Given a R*C matrix (R - rows and C- Columns), print the sum of the values in each row as the output. Input Format: First line will contain R and C separated by a space. Next R lines will contain C values, each separated by a space. Output Format: R lines representing the sum of elements of rows 1 to R. Boundary Conditions: 2 <= R, C <= 50 Example Input/Output 1: Input: 4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 10 26 42 58 #include<stdio.h> #include <stdlib.h> int main() { int a,b,i,j,t,s; scanf("%d %d",&a,&b); for(i=0;i<a;i++){ t=0; for(j=0;j<b;j++) { scanf("%d",&s); t+=s; } printf("%d\n",t); } }
3.25
3
2024-11-18T21:31:53.532510+00:00
2019-10-23T08:13:40
16cc3c2fb75dab47c2ef74c8a1c70e1df4211308
{ "blob_id": "16cc3c2fb75dab47c2ef74c8a1c70e1df4211308", "branch_name": "refs/heads/master", "committer_date": "2019-10-23T08:13:40", "content_id": "20b7bb1546de9cafc5a485253a9e6cef8657f6ca", "detected_licenses": [ "MIT" ], "directory_id": "e69461ba0999a9b46d14633810c002d5a2e83a40", "extension": "c", "filename": "mpi_sls_lu.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 201009330, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8177, "license": "MIT", "license_type": "permissive", "path": "/sources/mpi_sls_lu.c", "provenance": "stackv2-0077.json.gz:455", "repo_name": "jgurhem/MPI_XMP_SCA_LA", "revision_date": "2019-10-23T08:13:40", "revision_id": "54630c2072c6b0e8f1965111ccfa7eeaff0d8489", "snapshot_id": "b53942a63628e3dec5ebf4d0857664bc1ba71e0a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jgurhem/MPI_XMP_SCA_LA/54630c2072c6b0e8f1965111ccfa7eeaff0d8489/sources/mpi_sls_lu.c", "visit_date": "2022-02-20T01:29:17.317923" }
stackv2
#include "mpiio_dmat.h" #include "parse_args.h" #include <assert.h> #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> void printMat(double *mat, int size, int rank, int nprocs, char *modif) { int i, j; int nbR = size / nprocs; int mod = size % nprocs; if (rank < mod) nbR++; for (j = 0; j < nbR; j++) { for (i = 0; i < size; i++) { printf("%s%d %d %lf\n", modif, rank * nbR + j, i, mat[i + j * size]); } } } double *initVect(int size, int rank, int nprocs) { int nbR = size / nprocs; int mod = size % nprocs; double *v; if (rank < mod) nbR++; v = (double *)malloc(nbR * sizeof(double)); srandom((unsigned)23 * rank); int i; for (i = 0; i < nbR; i++) { v[i] = 100.0 * rand() / RAND_MAX; // printf("v %d %lf\n", i, v[i]); } return v; } double *loadVect(int size, int rank, int nprocs, char *path) { int nbR = size / nprocs; int mod = size % nprocs; double *v; if (rank < mod) nbR++; v = (double *)malloc(nbR * sizeof(double)); MPI_File fh; MPI_Status status; MPI_File_open(MPI_COMM_SELF, path, MPI_MODE_RDONLY, MPI_INFO_NULL, &fh); if (rank < mod) MPI_File_read_at_all(fh, rank * nbR * sizeof(double), v, nbR, MPI_DOUBLE, &status); else MPI_File_read_at_all(fh, (rank * nbR + mod) * sizeof(double), v, nbR, MPI_DOUBLE, &status); MPI_File_close(&fh); return v; } void saveVect(double *v, int size, int rank, int nprocs, char *path) { int nbR = size / nprocs; int mod = size % nprocs; if (rank < mod) nbR++; MPI_File fh; MPI_Status status; MPI_File_open(MPI_COMM_SELF, path, MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &fh); if (rank < mod) MPI_File_write_at_all(fh, rank * nbR * sizeof(double), v, nbR, MPI_DOUBLE, &status); else MPI_File_write_at_all(fh, (rank * nbR + mod) * sizeof(double), v, nbR, MPI_DOUBLE, &status); MPI_File_close(&fh); } void lu(int size, double *m, int nprocs, int rank) { int i, j, k, k_mod, k_loc, i_incr; double tmp, *ik; int nbR = size / nprocs; int mod = size % nprocs; if (rank < mod) nbR++; for (k = 0; k < size - 1; k++) { k_loc = k / nprocs; k_mod = k % nprocs; ik = (double *)malloc((size - k - 1) * sizeof(double)); if (rank == k_mod) { for (i = k + 1; i < size; i++) { m[k_loc * size + i] = m[k_loc * size + i] / m[k_loc * size + k]; ik[i - k - 1] = m[k_loc * size + i]; } } if (rank <= k_mod) { k_loc++; } MPI_Bcast(ik, size - k - 1, MPI_DOUBLE, k_mod, MPI_COMM_WORLD); for (j = k_loc; j < nbR; j++) { tmp = m[j * size + k]; for (i = k + 1; i < size; i++) { m[j * size + i] = m[j * size + i] - ik[i - k - 1] * tmp; } } free(ik); } } void resUx(int size, double *m, double *v, int nprocs, int rank) { int i, j, k, k_mod, k_div, js, k_loc, depla; double tmp, *vFull, *ik, mkk; int nbR = size / nprocs; int mod = size % nprocs; int counts[nprocs], displs[nprocs]; displs[0] = 0; counts[nprocs - 1] = nbR; for (i = 0; i < nprocs - 1; i++) { if (i < mod) { counts[i] = nbR + 1; displs[i + 1] = displs[i] + nbR + 1; } else { counts[i] = nbR; displs[i + 1] = displs[i] + nbR; } } if (rank == 0) vFull = (double *)malloc(size * sizeof(double)); if (rank < mod) nbR++; MPI_Gatherv(v, nbR, MPI_DOUBLE, vFull, counts, displs, MPI_DOUBLE, 0, MPI_COMM_WORLD); for (k = size - 1; k >= 0; k--) { k_loc = k / nprocs; k_mod = k % nprocs; int t = size / nprocs; if (k < mod * (t + 1)) { k_div = k / (t + 1); } else { k_div = mod + (k - mod * (t + 1)) / t; } ik = (double *)malloc((k + 1) * sizeof(double)); if (rank != 0 && k_mod != 0) { mkk = m[k_loc * size + k]; MPI_Send(&m[k_loc * size], k + 1, MPI_DOUBLE, 0, k, MPI_COMM_WORLD); } if (rank == 0 && k_mod == 0) { vFull[k] /= m[k_loc * size + k]; for (i = 0; i < k; i++) { vFull[i] -= m[k_loc * size + i] * vFull[k]; } } if (rank == 0 && k_mod != 0) { MPI_Status status; MPI_Recv(ik, k + 1, MPI_DOUBLE, k_mod, k, MPI_COMM_WORLD, &status); vFull[k] /= ik[k]; for (i = 0; i < k; i++) { vFull[i] -= ik[i] * vFull[k]; } } free(ik); } MPI_Scatterv(vFull, counts, displs, MPI_DOUBLE, v, nbR, MPI_DOUBLE, 0, MPI_COMM_WORLD); } void resLx(int size, double *m, double *v, int nprocs, int rank) { int i, j, k, k_mod, k_div, js, k_loc, depla; double tmp, *jk, vk; int nbR = size / nprocs; int mod = size % nprocs; int recvcounts[nprocs], displs[nprocs]; displs[0] = 0; recvcounts[nprocs - 1] = nbR; for (i = 0; i < nprocs - 1; i++) { if (i < mod) { recvcounts[i] = nbR + 1; displs[i + 1] = displs[i] + nbR + 1; } else { recvcounts[i] = nbR; displs[i + 1] = displs[i] + nbR; } } if (rank < mod) nbR++; for (k = 0; k < size - 1; k++) { k_loc = k / nprocs; k_mod = k % nprocs; jk = (double *)malloc(nbR * sizeof(double)); MPI_Scatterv(&m[k_loc * size], recvcounts, displs, MPI_DOUBLE, jk, nbR, MPI_DOUBLE, k_mod, MPI_COMM_WORLD); int t = size / nprocs; if (k < mod * (t + 1)) { k_div = k / (t + 1); } else { k_div = mod + (k - mod * (t + 1)) / t; } if (rank == k_div) vk = v[k % nbR]; MPI_Bcast(&vk, 1, MPI_DOUBLE, k_div, MPI_COMM_WORLD); if (k + 1 < mod * (t + 1)) { k_div = (k + 1) / (t + 1); } else { k_div = mod + (k + 1 - mod * (t + 1)) / t; } if (rank < k_div) js = nbR; else if (rank > k_div) js = 0; else { js = (k + 1) % nbR; } for (j = js; j < nbR; j++) { v[j] -= jk[j] * vk; } free(jk); } } int main(int argc, char **argv) { // Initialize the MPI environment MPI_Init(NULL, NULL); int size; char *fileA, *fileB, *fileV, *fileR; char docstr[] = "Linear system solution with LU factorization: " "Ax=LUx=v\nUsage : -s size -A <path to binary file " "containing A> -V <path to binary file containing v> -R " "<path to binary file that will contain x>\n"; parse_args_2mat_2vect(argc, argv, docstr, &size, &fileA, &fileB, &fileV, &fileR); // Get the number of processes int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); // Get the rank of the process int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); double *m, *v; struct timeval ts, te, t1, t2; MPI_Barrier(MPI_COMM_WORLD); if (world_rank == 0) { gettimeofday(&ts, 0); } m = mat_malloc(size, world_rank, world_size); if (fileA == 0) { mat_init(m, size, world_rank, world_size); } else { mat_read_cyclic(size, world_rank, world_size, m, fileA); } if (fileV == 0) { v = initVect(size, world_rank, world_size); } else { v = loadVect(size, world_rank, world_size, fileV); } MPI_Barrier(MPI_COMM_WORLD); if (world_rank == 0) { gettimeofday(&t1, 0); } MPI_Barrier(MPI_COMM_WORLD); lu(size, m, world_size, world_rank); resLx(size, m, v, world_size, world_rank); resUx(size, m, v, world_size, world_rank); MPI_Barrier(MPI_COMM_WORLD); if (world_rank == 0) { gettimeofday(&t2, 0); } MPI_Barrier(MPI_COMM_WORLD); if (fileR != 0) { saveVect(v, size, world_rank, world_size, fileR); } MPI_Barrier(MPI_COMM_WORLD); if (world_rank == 0) { gettimeofday(&te, 0); printf("%f\n", (t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec) / 1000000.0); printf("%f\n", (t2.tv_sec - ts.tv_sec) + (t2.tv_usec - ts.tv_usec) / 1000000.0); printf("%f\n", (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec) / 1000000.0); } if (fileB != 0) { mat_write_cyclic(size, world_rank, world_size, m, fileB); } free(v); free(m); // Finalize the MPI environment. MPI_Finalize(); return 0; }
2.359375
2
2024-11-18T22:07:57.045078+00:00
2017-06-02T05:15:07
15fe3846a7b5dac06ba35d21aaa03ede6b4f2518
{ "blob_id": "15fe3846a7b5dac06ba35d21aaa03ede6b4f2518", "branch_name": "refs/heads/master", "committer_date": "2017-06-02T05:15:07", "content_id": "10f1dfb8324c9d9f39ad6faf293c7d5b05f3a50c", "detected_licenses": [ "MIT" ], "directory_id": "cc2cf54fec2a124531b74615f4fb25659486b454", "extension": "c", "filename": "psystem.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40343335, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1043, "license": "MIT", "license_type": "permissive", "path": "/psystem.c", "provenance": "stackv2-0078.json.gz:237843", "repo_name": "AoEiuV020/linux", "revision_date": "2017-06-02T05:15:07", "revision_id": "644c25e39e6d647b70114c49434d8e01ef031328", "snapshot_id": "324941325933c632561ca2a0948050bfb1373ce6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AoEiuV020/linux/644c25e39e6d647b70114c49434d8e01ef031328/psystem.c", "visit_date": "2020-03-30T01:28:18.994895" }
stackv2
/***************************************************** ^> File Name: psystem.c ^> Author: AoEiuV020 ^> Mail: 490674483@qq.com ^> Created Time: 2015/09/14 - 20:39:37 ****************************************************/ #include <stdio.h> #include <stdarg.h> #include <unistd.h> /* psystem("ls -al /proc/%d/fd",getpid()); // */ int psystem(char *format,...) { int err=0; va_list arg; static FILE *fpipe;/*FILE porinter for sand commond*/ static pid_t cpid;/*parent pid*/ static int pfd[2]; static int init=1; if(init) { pipe(pfd); cpid=vfork(); if(cpid<0) { perror("vfork error"); return -1; } if(cpid==0) { dup2(pfd[0],STDIN_FILENO); close(pfd[0]); close(pfd[1]); execlp("sh","sh",NULL); } close(pfd[0]); fpipe=fdopen(pfd[1],"wb"); init=0; } va_start(arg,format); vfprintf(fpipe,format,arg); fprintf(fpipe,"\n"); fflush(fpipe); va_end(arg); return err; } int main(int argc, char **argv) { char cmd[333]={0}; while(fgets(cmd,sizeof(cmd),stdin)) { psystem(cmd); } return 0; }
2.453125
2
2024-11-18T22:07:57.102609+00:00
2016-03-28T02:12:19
091788d40cd1f8dfc8a647633fd4a2bb7cfca450
{ "blob_id": "091788d40cd1f8dfc8a647633fd4a2bb7cfca450", "branch_name": "refs/heads/master", "committer_date": "2016-03-28T02:12:19", "content_id": "3a5413f26017c9840ab402ebc7e897e1254ea7b4", "detected_licenses": [ "MIT" ], "directory_id": "cedf1c3adb455674dcfbf5671e4543712508d191", "extension": "c", "filename": "p1.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 49218050, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2166, "license": "MIT", "license_type": "permissive", "path": "/src/hw1/latency/p1.c", "provenance": "stackv2-0078.json.gz:237975", "repo_name": "rahlk/Parallel-Systems", "revision_date": "2016-03-28T02:12:19", "revision_id": "75a4acf4fcf6cf0f0927b1c8674d48ed939a6424", "snapshot_id": "9bdf5451398f734e204667c529ff19c5909853e9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rahlk/Parallel-Systems/75a4acf4fcf6cf0f0927b1c8674d48ed939a6424/src/hw1/latency/p1.c", "visit_date": "2020-12-03T09:33:10.124344" }
stackv2
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <math.h> #include <string.h> /* memset */ #define NUMBER_REPS 1000 float std(double data[], int n); int main (int argc, char *argv[]) { // MPI variables int reps, tag, numtasks, rank, dest, source, rc, n, i=3; float avgT, stdev; // Stats stuff... double Tstart, Tend, delT, sumT; MPI_Status status; // Initialize MPI MPI_Init(&argc,&argv); // Assign MPI variables MPI_Comm_size(MPI_COMM_WORLD,&numtasks); MPI_Comm_rank(MPI_COMM_WORLD,&rank); // Block the caller until all processes in the communicator have called it MPI_Barrier(MPI_COMM_WORLD); // time = 0; tag = 1; reps = NUMBER_REPS; // Do 1000 repeats - For stats. /* Note: Rank 0 sends data, Rank 1 receives it.*/ for (i=5; i<12; i++) { int n_char = pow(2,i); // char msg = 'x';//[2^i]; char msg[n_char]; memset(msg, 'x', n_char*sizeof(char)); int chunksize = sizeof(msg); if (rank == 0) { printf("%d \t ", sizeof(char)*sizeof(msg)); for (dest=1;dest<numtasks;dest++) { sumT=0; double tarray[NUMBER_REPS]; for (n = 0; n < reps; n++) { // Initialize MPI clock Tstart = MPI_Wtime(); rc = MPI_Send(&msg, chunksize, MPI_CHAR, dest, tag, MPI_COMM_WORLD); rc = MPI_Recv(&msg, chunksize, MPI_CHAR, dest, tag, MPI_COMM_WORLD, &status); Tend = MPI_Wtime(); delT = Tend - Tstart; sumT+=delT; tarray[n]=delT; } avgT = (sumT)/reps; stdev = std(tarray, reps); printf("%0.2e %0.2e ",avgT, stdev); } printf("\n"); } else { dest = 0; source = 0; for (n = 1; n <= reps; n++) { rc = MPI_Recv(&msg, chunksize, MPI_CHAR, source, tag, MPI_COMM_WORLD, &status); rc = MPI_Send(&msg, chunksize, MPI_CHAR, dest, tag, MPI_COMM_WORLD); } } } MPI_Finalize(); exit(0); } float std(double data[], int n) { float mean=0.0, sum_deviation=0.0; int i; for(i=0; i<n;++i) { mean+=data[i]; } mean=mean/n; for(i=0; i<n;i++) sum_deviation+=(data[i]-mean); return sqrt(sum_deviation/(n-1)); }
3
3
2024-11-18T22:07:57.765150+00:00
2018-05-04T15:16:40
7680a5318eccca3d66ff6aeca7de835094126f3f
{ "blob_id": "7680a5318eccca3d66ff6aeca7de835094126f3f", "branch_name": "refs/heads/master", "committer_date": "2018-05-04T15:16:40", "content_id": "6e14e49909d8ae0aa351722d780c504b8151d1de", "detected_licenses": [ "MIT" ], "directory_id": "ea3ebb112fb3426eae07d93ca9c6ddfb9ade3339", "extension": "c", "filename": "sol_box2.c", "fork_events_count": 0, "gha_created_at": "2018-05-15T19:51:04", "gha_event_created_at": "2018-05-15T19:51:04", "gha_language": null, "gha_license_id": null, "github_id": 133565926, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7557, "license": "MIT", "license_type": "permissive", "path": "/src/c/sol_box2.c", "provenance": "stackv2-0078.json.gz:238491", "repo_name": "Jipok/sol", "revision_date": "2018-05-04T15:16:40", "revision_id": "a4e5dd8819c964ce07d5951806fcd16aad2f13cd", "snapshot_id": "c3d163983468624ccd268438d7d9adcfe7f2bfd1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Jipok/sol/a4e5dd8819c964ce07d5951806fcd16aad2f13cd/src/c/sol_box2.c", "visit_date": "2020-03-17T11:51:05.162417" }
stackv2
///////////////////////////////////////////////////////////////// // sol_box2.c /////////////////////////////////////////////////// // Description: Adds 2D bounding boxes to Sol. ////////////////// // Author: David Garland (https://github.com/davidgarland/sol) // ///////////////////////////////////////////////////////////////// #include "../sol.h" ///////////////////////// // Box2 Initialization // ///////////////////////// /// box2_init /// // Description // Initializes a bounding box with lower and upper // bounds. // Arguments // lower: Bounds (Vec2) // upper: Bounds (Vec2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_init(Vec2 lower, Vec2 upper) { Box2 out; out.lower = lower; out.upper = upper; return out; } /// box2_initv /// // Description // Initializes a bounding box with the same // position as lower and upper bounds. // Arguments // v: Bounds (Vec2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_initv(Vec2 v) { return box2_init(v, v); } /// box2_initf /// // Description // Initializes a bounding box with a scalar // as the XY dimensions for the position of // the lower and upper bounds. // Arguments // f: Bounds (Float) // Returns // Bounding Box (Box2) _sol_ Box2 box2_initf(Float f) { return box2_initv(vec2_initf(f)); } /// box2_zero /// // Description // Initializes a bounding box with all // dimensions zeroed out. // Arguments // void // Returns // Bounding Box (Box2) _sol_ Box2 box2_zero(void) { return box2_initf((Float) 0); } ////////////////////////// // Box2 Core Operations // ////////////////////////// /// box2_pos /// // Description // Finds the position of a // bounding box. // Arguments // b: Bounding Box (Box2) // Returns // Position (Vec2) _sol_ Vec2 box2_pos(Box2 b) { return vec2_avg(b.lower, b.upper); } /// box2_x /// // Description // Finds the width // Arguments // b: Bounding Box (Box2) // Returns // Box Width (Float) _sol_ Float box2_x(Box2 b) { return b.upper[X] - b.lower[X]; } /// box2_y /// // Description // Finds the height of a bounding box. // Arguments // b: Bounding Box (Box2) // Returns // Box Height (Float) _sol_ Float box2_y(Box2 b) { return b.upper[Y] - b.lower[Y]; } /// box2_pip /// // Description // Does a point-in-polygon test with a // point and a bounding box. // Arguments // b: Bounding Box (Box2) // v: Point (Vec2) // Returns // Point In Polygon (bool) _sol_ bool box2_pip(Box2 b, Vec2 v) { return (b.lower[X] >= v[X]) && (v[X] <= b.upper[X]) && (b.lower[Y] >= v[Y]) && (v[Y] <= b.upper[Y]); } ///////////////////// // Box2 Basic Math // ///////////////////// /// box2_add /// // Description // Adds the lower and upper bounds of one bounding // box to that of another. // Arguments // a: Bounding Box (Box2) // b: Bounding Box (Box2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_add(Box2 a, Box2 b) { return box2_init(vec2_add(a.lower, b.lower), vec2_add(a.upper, b.upper)); } /// box2_addv /// // Description // Adds a vector to the lower and upper bounds // of a bounding box. // Arguments // b: Bounding Box (Box2) // v: Vector (Vec2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_addv(Box2 b, Vec2 v) { return box2_add(b, box2_initv(v)); } /// box2_addf /// // Description // Adds a scalar to the lower and upper bounds // of a bounding box. // Arguments // b: Bounding Box (Box2) // f: Scalar (Float) // Returns // Bounding Box (Box2) _sol_ Box2 box2_addf(Box2 b, Float f) { return box2_addv(b, vec2_initf(f)); } /// box2_sub /// // Description // Subtracts the lower and upper bounds of // one bounding box from another. // Arguments // a: Bounding Box (Box2) // b: Bounding Box (Box2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_sub(Box2 a, Box2 b) { return box2_init(vec2_sub(a.lower, b.lower), vec2_sub(a.upper, b.upper)); } /// box2_subv /// // Description // Subtracts a vector from the lower // and upper bounds of a bounding box. // Arguments // b: Bounding Box (Box2) // v: Vector (Vec2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_subv(Box2 b, Vec2 v) { return box2_sub(b, box2_initv(v)); } /// box2_vsub /// // Description // Subtracts the lower and upper bounds // of a bounding box from a vector. // Arguments // v: Vector (Vec2) // b: Bounding Box (Box2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_vsub(Vec2 v, Box2 b) { return box2_sub(box2_initv(v), b); } /// box2_subf /// // Description // Subtracts a scalar from the lower // and upper bounds of a bounding box // Arguments // b: Bounding Box (Box2) // f: Scalar (Float) // Returns // Bounding Box (Box2) _sol_ Box2 box2_subf(Box2 b, Float f) { return box2_subv(b, vec2_initf(f)); } /// box2_fsub /// // Description // Subtracts the lower and upper bounds // of a bounding box from a scalar. // Arguments // f: Scalar (Float) // b: Bounding Box (Box2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_fsub(Float f, Box2 b) { return box2_vsub(vec2_initf(f), b); } /// box2_mul /// // Description // Multiplies the lower and upper bounds // of a bounding box by another. // Arguments // a: Bounding Box (Box2) // b: Bounding Box (Box2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_mul(Box2 a, Box2 b) { return box2_init(vec2_mul(a.lower, b.lower), vec2_mul(a.upper, b.upper)); } /// box2_mulv /// // Description // Multiplies the lower and upper bounds // of a bounding box by a vector. // Arguments // b: Bounding Box (Box2) // v: Vector (Vec2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_mulv(Box2 b, Vec2 v) { return box2_mul(b, box2_initv(v)); } /// box2_mulf /// // Description // Multiplies the lower and upper bounds // of a bounding box by a scalar. // Arguments // b: Bounding Box (Box2) // f: Scalar (Float) // Returns // Bounding Box (Box2) _sol_ Box2 box2_mulf(Box2 b, Float f) { return box2_mulv(b, vec2_initf(f)); } /// box2_div /// // Description // Divides the lower and upper bounds // of a bounding box by another. // Arguments // a: Bounding Box (Box2) // b: Bounding Box (Box2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_div(Box2 a, Box2 b) { return box2_init(vec2_div(a.lower, b.lower), vec2_div(a.upper, b.upper)); } /// box2_divv /// // Description // Divides the lower and upper bounds // of a bounding box by a vector. // Arguments // b: Bounding Box (Box2) // v: Vector (Vec2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_divv(Box2 b, Vec2 v) { return box2_div(b, box2_initv(v)); } /// box2_vdiv /// // Description // Divides a vector by the lower and // upper bounds of a bounding box. // Arguments // v: Vector (Vec2) // b: Bounding Box (Box2) // Returns // Bounding Box (Box2) _sol_ Box2 box2_vdiv(Vec2 v, Box2 b) { return box2_div(box2_initv(v), b); } /// box2_divf /// // Description // Divides the lower and upper bounds // of a bounding box by a scalar. // Arguments // b: Bounding Box (Box2) // f: Scalar (Float) // Returns // Bounding Box (Box2) _sol_ Box2 box2_divf(Box2 b, Float f) { return box2_divv(b, vec2_initf(f)); } /// box2_fdiv /// // Description // Divides a scalar by the lower and // upper bounds of a bounding box. // Arguments // f: Scalar (Float) // b: Bounding Box (Box2) _sol_ Box2 box2_fdiv(Float f, Box2 b) { return box2_vdiv(vec2_initf(f), b); }
3.046875
3
2024-11-18T22:07:57.836565+00:00
2021-02-28T02:09:00
b443c7ab31b0eaf41e0051de2aa5cbd3a20ce9c1
{ "blob_id": "b443c7ab31b0eaf41e0051de2aa5cbd3a20ce9c1", "branch_name": "refs/heads/master", "committer_date": "2021-02-28T02:09:00", "content_id": "846fd9b342d46d7f4cc1877122bbb78ac9d5d57c", "detected_licenses": [ "MIT" ], "directory_id": "be49368b9305139e4a48b19eab6248ede08b1530", "extension": "c", "filename": "testMain.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 240278130, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3592, "license": "MIT", "license_type": "permissive", "path": "/assignments/a2/External Resources/myAssignments/traffic_simulator/src/testMain.c", "provenance": "stackv2-0078.json.gz:238619", "repo_name": "ShararAwsaf/OS", "revision_date": "2021-02-28T02:09:00", "revision_id": "1bec85330b129c1759a6576865640281cb33100c", "snapshot_id": "1f2460e29a0889b73a7b82dcc2d54c3436cd86e2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ShararAwsaf/OS/1bec85330b129c1759a6576865640281cb33100c/assignments/a2/External Resources/myAssignments/traffic_simulator/src/testMain.c", "visit_date": "2023-03-17T01:21:38.602447" }
stackv2
/* * author : Sharar mahmood * date : Oct 1 2017 * name : main.c * */ # ifndef LINKEDLISAPI_H # define LINKEDLISAPI_H # include "LinkedListAPI.h" # include "direction.h" void deleteListNode(void * element){ free((Node*)element); element = NULL; } typedef void(*deleteFunction)(void*); typedef int(*compareFunction)(const void*,const void *); typedef void (*printFunction)(void*); int main(void){ List *dList; Node *dNode; char come1 ,come2 ,come3 ,come4; char go1 ,go2 ,go3 ,go4; int arrive1 ,arrive2 ,arrive3 ,arrive4; double finish1 ,finish2 ,finish3 ,finish4; Dir *dir1 , *dir2 , *dir3 , *dir4; deleteFunction dirDel; compareFunction dirComp; printFunction dirPrint; dirDel = &deleteDir; dirComp = &compareDir; dirPrint = &printDir; /* * Values for cars * */ come1 = 'N'; come2 = 'E'; come3 = 'S'; come4 = 'W'; go1 = 'L'; go2 = 'R'; go3 = 'F'; go4 = 'R'; arrive1 = 2; arrive2 = 3; arrive3 = 4; arrive4 = 5; finish1 = 12.3; finish2 = 14.5; finish3 = 30.0; finish4 = 31.0; dir1 = malloc(sizeof(Dir)); dir2 = malloc(sizeof(Dir)); dir3 = malloc(sizeof(Dir)); dir4 = malloc(sizeof(Dir)); setArrival(dir1,come1); setArrival(dir2,come2); setArrival(dir3,come3); setArrival(dir4,come4); setDeparture(dir1,go1); setDeparture(dir2,go2); setDeparture(dir3,go3); setDeparture(dir4,go4); setTime(dir1,arrive1); setTime(dir2,arrive2); setTime(dir3,arrive3); setTime(dir4,arrive4); setFinishTime(dir1,finish1); setFinishTime(dir2,finish2); setFinishTime(dir3,finish3); setFinishTime(dir4,finish4); printf("Testing initialization of a list\n\n"); dList = initializeList(dirPrint,dirDel,dirComp); printf("Testing for successful list initialization : %s\n\n", dList == NULL ? "Failed":"Passed"); printf("Testing initialization of a Node\n\n"); dNode = initializeNode(dir4); printf("Testing for successful node initialization : %s\n\n", dNode == NULL ? "Failed":"Passed"); printf("Testing adding to the front of list\n\n"); insertFront(dList,(void*)dir1); printf("Testing for successful adding to front : %s\n\n", ((Dir*)(dList->head->data)) == dir1 ? "Passed" : "Failed"); printf("Testing for finding the first element in list\n\n"); printf("Testing for successful peeking head : %s\n\n", (Dir*)getFromFront(dList) == dir1 ? "Passed":"Failed"); printf("Testing adding to the end of list\n\n"); insertBack(dList,(void*)dir2); printf("Testing for successful adding to end : %s\n\n", ((Dir*)(dList->tail->data)) == dir2 ? "Passed" : "Failed"); printf("Testing finding tail of list\n\n"); printf("Testing for successful peeking tail : %s\n\n", (Dir*)getFromBack(dList) == dir2 ? "Passed":"Failed"); printf("Testing for printing list forwards\n\n"); printForward(dList); printf("Testing for printing list backwards\n\n"); printBackwards(dList); printf("Testing to remove non existent node keeping list unchanged\n\n"); printf("Testing removal of non existent data : %s\n\n", deleteNodeFromList(dList,(void*)dir3) == -1 ? "Passed" : "Failed"); printf("Testing to remove node keeping list unchanged\n\n"); deleteNodeFromList(dList,(void*)dir1); printf("Testing removal of the head: %s\n\n", (Dir*)(dList->head->data) == dir2 ? "Passed" : "Failed"); deleteListNode((void*)dNode); printf("Testing if deleting of list occurs : %s\n\n", (Dir*)dNode->data == dir4 ? "Failed":"Passed"); deleteList(dList); printf("Testing if deleting of list occurs : %s\n\n", dList-> head != NULL ? "Failed":"Passed"); return 0; } #endif
3.015625
3
2024-11-18T22:07:58.236424+00:00
2021-09-28T02:25:06
4db11e46969669fc2f16154b5eccfd15067a6371
{ "blob_id": "4db11e46969669fc2f16154b5eccfd15067a6371", "branch_name": "refs/heads/main", "committer_date": "2021-09-28T02:25:06", "content_id": "4fe1723aa6f774ee6bb710a3b373cc72dae5bd1f", "detected_licenses": [ "MIT" ], "directory_id": "ed143fc81cdf338e2b2c3e8ab8288abdb746bf55", "extension": "c", "filename": "5-3.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 305714969, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 436, "license": "MIT", "license_type": "permissive", "path": "/C Primer Plus/Chapter 5 - Operators, Expressions, Statements/Programming Exercises/5-3.c", "provenance": "stackv2-0078.json.gz:239136", "repo_name": "yoonBot/Computer-Science-and-Engineering", "revision_date": "2021-09-28T02:25:06", "revision_id": "34a267a0f4debc2082d6ec11e289e4250019fb96", "snapshot_id": "f64230dc52ecb98ed641b190b2a3d15c513874cf", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/yoonBot/Computer-Science-and-Engineering/34a267a0f4debc2082d6ec11e289e4250019fb96/C Primer Plus/Chapter 5 - Operators, Expressions, Statements/Programming Exercises/5-3.c", "visit_date": "2023-08-14T01:40:31.765474" }
stackv2
/* C Primer Plus Ch.5 - Problem 3 * @reproduced by yoonBot */ #include <stdio.h> #define WEEK 7 int main(void){ int input; printf("Enter the number of days: "); scanf("%d", &input); while (1){ printf("%d days are %d weeks, %d days.\n", input, input / WEEK, input % WEEK); printf("Enter the number of days: "); scanf("%d", &input); if(input <= 0) break; } return 0; }
2.859375
3
2024-11-18T22:07:58.354886+00:00
2020-06-04T08:34:30
674805a4c9284e164c3c1e52eca12bbf32a89e55
{ "blob_id": "674805a4c9284e164c3c1e52eca12bbf32a89e55", "branch_name": "refs/heads/master", "committer_date": "2020-06-04T08:34:30", "content_id": "38a3518f4d71175c04d6d1c969fbee281995759c", "detected_licenses": [ "MIT" ], "directory_id": "6292d4940cb999b0a6a0d1d306e84413de437aaa", "extension": "c", "filename": "Error.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 221437462, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 425, "license": "MIT", "license_type": "permissive", "path": "/Error.c", "provenance": "stackv2-0078.json.gz:239264", "repo_name": "AndreaG93/TEN-Project", "revision_date": "2020-06-04T08:34:30", "revision_id": "42af952bdcd979ee0a1ba5300bc7f5ae52f7e48b", "snapshot_id": "0aa51e39f318c7aa46188bb96cabba21f07f8255", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AndreaG93/TEN-Project/42af952bdcd979ee0a1ba5300bc7f5ae52f7e48b/Error.c", "visit_date": "2020-09-09T11:41:31.779489" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> void exitPrintingFatalErrorMessage(char *functionName, char *errorMessageOrSyscallName) { if (errno != 0) fprintf(stderr, "[FATAL] '%s': %s --> %s\n", functionName, errorMessageOrSyscallName, strerror(errno)); else fprintf(stderr, "[FATAL] '%s': %s\n", functionName, errorMessageOrSyscallName); exit(EXIT_FAILURE); }
2.4375
2
2024-11-18T22:07:58.730481+00:00
2022-09-06T20:43:52
dc356f9cfab1da6345b830fd8639107a05a2d8cf
{ "blob_id": "dc356f9cfab1da6345b830fd8639107a05a2d8cf", "branch_name": "refs/heads/master", "committer_date": "2022-09-06T20:43:52", "content_id": "db7d4b78c659fed132a134bc8abd6fcfc82ef428", "detected_licenses": [ "Unlicense" ], "directory_id": "3d5f6d704b151a2886a9e128eee2f4467bf98d2d", "extension": "c", "filename": "NESTFUN.C", "fork_events_count": 31, "gha_created_at": "2018-08-26T18:14:50", "gha_event_created_at": "2022-01-09T14:37:36", "gha_language": "C", "gha_license_id": "Unlicense", "github_id": 146205056, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 473, "license": "Unlicense", "license_type": "permissive", "path": "/function/NESTFUN.C", "provenance": "stackv2-0078.json.gz:239393", "repo_name": "harsh98trivedi/C-Programs", "revision_date": "2022-09-06T20:43:52", "revision_id": "cee0838bd28065e0e55ace69cdd202c2b996f3d0", "snapshot_id": "ef499b6c89cb310e003b7fcb09f591953426a8e4", "src_encoding": "UTF-8", "star_events_count": 18, "url": "https://raw.githubusercontent.com/harsh98trivedi/C-Programs/cee0838bd28065e0e55ace69cdd202c2b996f3d0/function/NESTFUN.C", "visit_date": "2022-09-29T10:05:28.454245" }
stackv2
//prog on nesting fun float tom(float); float dick(float); main() { float km,cm; clrscr(); printf("enter the distance in kilometer"); scanf("%f",&km); cm=tom(km); printf("\n the distance in cm %.2f",cm); getch(); } float tom(float i) { float j,k; j=i*1000; //calculate km to meter printf("\n distance in meter=%f",j); k=dick(j); return(k); } float dick(float a) { float b; b=a*100; return(b); //calculate to cm return b) }
3.234375
3
2024-11-18T22:07:58.914810+00:00
2018-05-23T06:55:18
57b8de5e4a857380b8ecdaf86c56d7f7bca1b9b4
{ "blob_id": "57b8de5e4a857380b8ecdaf86c56d7f7bca1b9b4", "branch_name": "refs/heads/master", "committer_date": "2018-05-23T06:55:18", "content_id": "9d154a9f647205e2781496231e576083f7279935", "detected_licenses": [ "MIT" ], "directory_id": "2bc3398063fd7251c46a2d93d2e301cd063befcd", "extension": "c", "filename": "mudao01.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 134525191, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1852, "license": "MIT", "license_type": "permissive", "path": "/nitan/d/gumu/mudao01.c", "provenance": "stackv2-0078.json.gz:239522", "repo_name": "HKMUD/NT6", "revision_date": "2018-05-23T06:55:18", "revision_id": "bb518e2831edc6a83d25eccd99271da06eba8176", "snapshot_id": "ae6a3c173ea07c156e8dc387b3ec21f3280ee0be", "src_encoding": "GB18030", "star_events_count": 9, "url": "https://raw.githubusercontent.com/HKMUD/NT6/bb518e2831edc6a83d25eccd99271da06eba8176/nitan/d/gumu/mudao01.c", "visit_date": "2020-03-18T08:44:12.400598" }
stackv2
// mudao01.c 墓道 // Java Oct.10 1998 #include <ansi.h> inherit ROOM; void create() { set("short", HIG"墓道"NOR); set("long", @LONG 这里是古墓中的墓道,四周密不透风,借着墙上昏暗的灯光,你能 勉强分辨出方向。墙是用整块的青石砌合起来的,接合得甚是完美,难 以从中找出一丝缝隙。灯光照在青石壁上,闪烁着碧幽幽的光点。 LONG ); set("exits", ([ "north" : __DIR__"mumen", "south" : __DIR__"qianting", ])); set("no_clean_up", 0); set("coor/x", -3220); set("coor/y", 20); set("coor/z", 90); setup(); } /* void init() { add_action("do_move", "move"); add_action("do_move", "luo"); add_action("do_move", "tui"); } int do_move(string arg) { object room, me = this_player(); if( !arg || arg != "shi" ) { return notify_fail("你要移动什么?\n"); } if( !query("exits/north")) { return notify_fail("降龙石已经落下,你还能移动什么?\n"); } if((int)me->query_str()>33) { message_vision("$N站在降龙石前,双掌发力推动降龙石,只听得降龙石吱吱连声,缓缓向下落去,封住了墓门。\n", me); delete("exits/north"); if( !(room = find_object(__DIR__"mumen")) ) room = load_object(__DIR__"mumen"); delete("exits/south", room); tell_room(room,"只听得降龙石吱吱连声,缓缓向下落去,封住了墓门。\n"); } else message_vision("$N试着推了推巨石,巨石纹丝不动,只得罢了。\n", this_player()); return 1; } */
2.390625
2
2024-11-18T20:41:30.816901+00:00
2023-08-07T06:44:29
381f5c1c2013f5c6c37f2bb88ab0c3694829fd67
{ "blob_id": "381f5c1c2013f5c6c37f2bb88ab0c3694829fd67", "branch_name": "refs/heads/master", "committer_date": "2023-08-07T09:04:55", "content_id": "0b682f0de08c890d02776e06f56af5fe9c4684ea", "detected_licenses": [ "Apache-2.0" ], "directory_id": "13726de7883e87a67757740bb9417e8fbdf1c1a3", "extension": "h", "filename": "libtbd.h", "fork_events_count": 186, "gha_created_at": "2015-01-15T07:37:41", "gha_event_created_at": "2023-08-07T09:04:56", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 29286224, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10208, "license": "Apache-2.0", "license_type": "permissive", "path": "/modules/isp/libtbd.h", "provenance": "stackv2-0082.json.gz:31078", "repo_name": "intel/libxcam", "revision_date": "2023-08-07T06:44:29", "revision_id": "97c90b05775d0b7cb78a35e966c51ec92fdd7525", "snapshot_id": "1a816ec797871f1a3254b86995763753b4321aa4", "src_encoding": "UTF-8", "star_events_count": 493, "url": "https://raw.githubusercontent.com/intel/libxcam/97c90b05775d0b7cb78a35e966c51ec92fdd7525/modules/isp/libtbd.h", "visit_date": "2023-09-04T10:25:29.965048" }
stackv2
/* ** Copyright 2012-2013 Intel Corporation ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ /* * \file libtbd.h * \brief Tagged Binary Data handling */ #ifndef __LIBTBD_H__ #define __LIBTBD_H__ #include <stddef.h> /* defines size_t */ #include <stdint.h> /* defines integer types with specified widths */ #include <stdio.h> /* defines FILE */ #ifdef __cplusplus extern "C" { #endif /*! * Revision of TBD System, format 0xYYMMDDVV, where: * - YY: year, * - MM: month, * - DD: day, * - VV: version ('01','02' etc.) */ #define IA_TBD_VERSION 0x12032201 /*! * Revision of TBD data set, format 0xYYMMDDVV, where: * - YY: year, * - MM: month, * - DD: day, * - VV: version ('01','02' etc.) */ #define IA_TBD_REVISION 0x13091001 /*! * \brief Error codes for libtbd. */ typedef enum { tbd_err_none = 0 , /*!< No errors */ tbd_err_general = (1 << 1), /*!< General error */ tbd_err_nomemory = (1 << 2), /*!< Out of memory */ tbd_err_data = (1 << 3), /*!< Corrupted data */ tbd_err_internal = (1 << 4), /*!< Error in code */ tbd_err_argument = (1 << 5) /*!< Invalid argument for a function */ } tbd_error_t; /*! * \brief Header structure for TBD container, followed by actual records. */ typedef struct { uint32_t tag; /*!< Tag identifier, also checks endianness */ uint32_t size; /*!< Container size including this header */ uint32_t version; /*!< Version of TBD system, format 0xYYMMDDVV */ uint32_t revision; /*!< Revision of TBD data set, format 0xYYMMDDVV */ uint32_t config_bits; /*!< Configuration flag bits set */ uint32_t checksum; /*!< Global checksum, header included */ } tbd_header_t; /*! * \brief Tag identifiers used in TBD container header. */ #define CHTOU32(a,b,c,d) ((uint32_t)(a)|((uint32_t)(b)<<8)|((uint32_t)(c)<<16)|((uint32_t)(d)<<24)) typedef enum { tbd_tag_cpff = CHTOU32('C', 'P', 'F', 'F'), /*!< CPF File */ tbd_tag_aiqb = CHTOU32('A', 'I', 'Q', 'B'), /*!< AIQ configuration */ tbd_tag_aiqd = CHTOU32('A', 'I', 'Q', 'D'), /*!< AIQ data */ tbd_tag_halb = CHTOU32('H', 'A', 'L', 'B'), /*!< CameraHAL configuration */ tbd_tag_drvb = CHTOU32('D', 'R', 'V', 'B') /*!< Sensor driver configuration */ } tbd_tag_t; /*! * \brief Record structure. Data is located right after this header. */ typedef struct { uint32_t size; /*!< Size of record including header */ uint8_t format_id; /*!< tbd_format_t enumeration values used */ uint8_t packing_key; /*!< Packing method; 0 = no packing */ uint16_t class_id; /*!< tbd_class_t enumeration values used */ } tbd_record_header_t; /*! * \brief Format ID enumeration describes the data format of the record. */ typedef enum { tbd_format_any = 0, /*!< Unspecified format */ tbd_format_custom, /*!< User specified format */ tbd_format_container /*!< Record is actually another TBD container */ } tbd_format_t; /*! * \brief Class ID enumeration describes the data class of the record. */ typedef enum { tbd_class_any = 0, /*!< Unspecified record class */ tbd_class_aiq, /*!< Used for AIC and 3A records */ tbd_class_drv, /*!< Used for driver records */ tbd_class_hal /*!< Used for HAL records */ } tbd_class_t; /*! * \brief Creates a new Tagged Binary Data container. * Creates a new, empty Tagged Binary Data container with the tag * that was given. Also updates the checksum and size accordingly. * Note that the buffer size must be large enough for the header * to fit in, the exact amount being 24 bytes (for tbd_header_t). * @param[in] a_data_ptr Pointer to modifiable container buffer * @param[in] a_data_size Size of the container buffer * @param[in] a_tag Tag the container shall have * @param[out] a_new_size Updated container size * @return Return code indicating possible errors */ tbd_error_t tbd_create(void *a_data_ptr, size_t a_data_size, tbd_tag_t a_tag, size_t *a_new_size); /*! * \brief Checks if Tagged Binary Data is valid. All tags are accepted. * Performs number of checks to given Tagged Binary Data container, * including the verification of the checksum. The function does not * care about the tag type of the container. * @param[in] a_data_ptr Pointer to container buffer * @param[in] a_data_size Size of the container buffer * @return Return code indicating possible errors */ tbd_error_t tbd_validate_anytag(void *a_data_ptr, size_t a_data_size); /*! * \brief Checks if Tagged Binary Data is valid, and tagged properly. * Performs number of checks to given Tagged Binary Data container, * including the verification of the checksum. Also, the data must have * been tagged properly. The tag is further used to check endianness, * and if it seems wrong, a specific debug message is printed out. * @param[in] a_data_ptr Pointer to container buffer * @param[in] a_data_size Size of the container buffer * @param[in] a_tag Tag the data must have * @return Return code indicating possible errors */ tbd_error_t tbd_validate(void *a_data_ptr, size_t a_data_size, tbd_tag_t a_tag); /*! * \brief Finds a record of given kind from within the container. * Checks if a given kind of record exists in the Tagged Binary Data, * and if yes, tells the location of such record as well as its size. * If there are multiple records that match the query, the indicated * record is the first one. * @param[in] a_data_ptr Pointer to container buffer * @param[in] a_record_class Class the record must have * @param[in] a_record_format Format the record must have * @param[out] a_record_data Record data (or NULL if not found) * @param[out] a_record_size Record size (or 0 if not found) * @return Return code indicating possible errors */ tbd_error_t tbd_get_record(void *a_data_ptr, tbd_class_t a_record_class, tbd_format_t a_record_format, void **a_record_data, uint32_t *a_record_size); /*! * \brief Updates the Tagged Binary Data with the given record inserted. * The given record is inserted into the Tagged Binary Data container * that must exist already. New records are always added to the end, * regardless if a record with the same class and format field already * exists in the data. Also updates the checksum and size accordingly. * Note that the buffer size must be large enough for the inserted * record to fit in, the exact amount being the size of original * Tagged Binary Data container plus the size of record data to be * inserted plus 8 bytes (for tbd_record_header_t). * @param[in] a_data_ptr Pointer to modifiable container buffer * @param[in] a_data_size Size of buffer (surplus included) * @param[in] a_record_class Class the record shall have * @param[in] a_record_format Format the record shall have * @param[in] a_record_data Record data * @param[in] a_record_size Record size * @param[out] a_new_size Updated container size * @return Return code indicating possible errors */ tbd_error_t tbd_insert_record(void *a_data_ptr, size_t a_data_size, tbd_class_t a_record_class, tbd_format_t a_record_format, void *a_record_data, size_t a_record_size, size_t *a_new_size); /*! * \brief Updates the Tagged Binary Data with the given record removed. * The indicated record is removed from the Tagged Binary Data, after * which the checksum and size are updated accordingly. If there are * multiple records that match the class and format, only the first * instance is removed. If no record is found, nothing will be done. * Note that the resulting Tagged Binary Data container will * be smaller than the original, but it does not harm to store the * resulting container in its original length, either. * @param[in] a_data_ptr Pointer to modifiable container buffer * @param[in] a_record_class Class the record should have * @param[in] a_record_format Format the record should have * @param[out] a_new_size Updated container size * @return Return code indicating possible errors */ tbd_error_t tbd_remove_record(void *a_data_ptr, tbd_class_t a_record_class, tbd_format_t a_record_format, size_t *a_new_size); /*! * \brief Writes all possible information about the Tagged Binary Data. * Validates the Tagged Binary data container and generates a human * readable detailed report on the content, including information about * the records contained. * @param[in] a_data_ptr Pointer to container buffer * @param[in] a_data_size Size of the container buffer * @param[in] a_outfile Pointer to open file (may be stdout) * @return Return code indicating possible errors */ tbd_error_t tbd_infoprint(void *a_data_ptr, size_t a_data_size, FILE *a_outfile); #ifdef __cplusplus } #endif #endif /* __LIBTBD_H__ */
2.171875
2
2024-11-18T20:41:30.932084+00:00
2023-08-17T19:32:17
76f445cd8ef39fae2f799abbf030ae7af5269f50
{ "blob_id": "76f445cd8ef39fae2f799abbf030ae7af5269f50", "branch_name": "refs/heads/master", "committer_date": "2023-08-17T19:32:17", "content_id": "4f21fcc555bdcb0a4bb2fd8dad31adad2d9c6d53", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "directory_id": "42ea124983b717e3f6a8acfaf16bb6f455e23d12", "extension": "c", "filename": "bas1.c", "fork_events_count": 140, "gha_created_at": "2015-04-23T20:09:23", "gha_event_created_at": "2023-04-28T17:13:20", "gha_language": "VHDL", "gha_license_id": "BSD-2-Clause", "github_id": 34478922, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 28948, "license": "BSD-2-Clause,BSD-3-Clause,MIT", "license_type": "permissive", "path": "/src/lang/basic/bas1.c", "provenance": "stackv2-0082.json.gz:31206", "repo_name": "f32c/f32c", "revision_date": "2023-08-17T19:32:17", "revision_id": "115c2d582296c8af6e9fc24e2355e5f31ff2f3b6", "snapshot_id": "4a3f026c6a3e30089976c523861bf46c047bed1b", "src_encoding": "UTF-8", "star_events_count": 399, "url": "https://raw.githubusercontent.com/f32c/f32c/115c2d582296c8af6e9fc24e2355e5f31ff2f3b6/src/lang/basic/bas1.c", "visit_date": "2023-09-01T19:32:24.288992" }
stackv2
/* * BASIC by Phil Cockcroft */ /* * This file contains the main routines of the interpreter. */ /* * the core is arranged as follows: - * ------------------------------------------------------------------- - - - * | file | text | string | user | array | simple | for/ | unused * | buffers | of | space | def | space | variables | gosub | memory * | | program | | fns | | | stack | * ------------------------------------------------------------------- - - - * ^ ^ ^ ^ ^ ^ ^ ^ * filestart fendcore ecore estring edefns earray vend vvend * ^eostring ^estarr */ #define PART1 #include "bas.h" #undef PART1 extern void _exit(); static CHAR *eql(const CHAR *, const CHAR *, const CHAR *); static void docont(void); static void free_ar(struct entry *); static SIGFUNC trap(int); #ifndef f32c static SIGFUNC seger(int), mcore(int), quit1(int), catchfp(int); #ifdef SIGTSTP static SIGFUNC onstop(int); #endif #endif /* !f32c */ #ifdef MSDOS static int lcount; #endif /* * The main program , it sets up all the files, signals,terminal * and pointers and prints the start up message. * It then calls setexit(). * IMPORTANT NOTE:- * setexit() sets up a point of return for a function * It saves the local environment of the calling routine * and uses that environment for further use. * The function reset() uses the information saved in * setexit() to perform a non-local goto , e.g. poping the stack * until it looks as though it is a return from setexit() * The program then continues as if it has just executed setexit() * This facility is used all over the program as a way of getting * out of functions and returning to command mode. * The one exception to this is during error trapping , The error * routine must pop the stack so that there is not a recursive call * on execute() but if it does then it looks like we are back in * command mode. The flag ertrap is used to signal that we want to * go straight on to execute() the error trapping code. The pointers * must be set up before the execution of the reset() , (see error ). * N.B. reset() NEVER returns , so error() NEVER returns. */ static int firstrun = 1; int main(int argc, char **argv) { int i = 0; int fp; #ifdef f32c setup_f32c(); maxfiles = MAXFILES; #else catchsignal(); #endif startfp(); /* start up the floating point hardware */ setup_fb(); /* video framebuffer */ #ifndef f32c setupfiles(argc,argv); setupmyterm(); /* set up files after processing files */ #endif program = 0; clear(); prints("Rabbit BASIC version 2.1.3 (built " __DATE__ ")\n"); if(setexit() == ERR_RESET){ drop_fns(); execute(); /* execute the line */ } drop_fns(); docont(); stocurlin=0; /* say we are in immeadiate mode */ if(cursor) /* put cursor on a blank line */ prints( (char *)nl); if (firstrun && ( #ifdef f32c (fp = open("d:autoexec.bas",0)) > 0 || #endif (fp = open("autoexec.bas",0)) > 0)) { firstrun = 0; readfi(fp, 0, 0); close(fp); clear(); if (program) { stocurlin=program; point= program->lin; elsecount=0; execute(); } } firstrun = 0; prints("Ready\n"); for(;;){ do{ trapped=0; line[0] = '>'; line[1] = 0; VOID edit( (ival)1, (ival)1, (ival)0); }while( trapped || ( !(i=compile(1, nline, 0)) && !linenumber)); if(!linenumber) break; insert(i); } if(inserted){ inserted=0; clear(); closeall(); } #ifdef MSDOS lcount = 0; #endif clr_stack(bstack); /* reset the gosub stack */ bstack = estack = 0; if(str_used) /* free any spare strings */ FREE_STR(str_used); trap_env.e_stolin = 0; /* disable error traps */ intrap=0; /* say we are not in the error trap */ trapped=0; /* say we haven't got a cntrl-c */ cursor=0; /* cursor is at start of line */ elsecount=0; /* disallow elses as terminators */ point=nline; /* start executing at start of input line */ stocurlin=0; /* start of current line is null- see 'next' */ execute(); /* execute the line */ return(-1); /* see note below */ } /* * Execute will return by calling reset and so if execute returns then * there is a catastrophic error and we should exit with -1 or something */ /* * compile converts the input line (in line[]) into tokenised * form for execution(in nline). If the line starts with a linenumber * then that is converted to binary and is stored in 'linenumber' N.B. * not curline (see evalu() ). A linenumber of zero is assumed to * be non existant and so the line is executed immeadiately. * The parameter to compile() is an index into line that is to be * ignored, e.g. the prompt. */ int compile(fl, fline, hasnolnumb) int fl, hasnolnumb; CHAR *fline; { CHAR *p, *k, *q; const struct tabl *l; lnumb lin=0; CHAR *tmp; CHAR charac; p= &line[fl]; q=fline; while(*p ==' ') p++; if(!hasnolnumb){ /*LINTED*/ while(isdigit(*p)){ /* get line number */ if(lin >= 6553) error(7); lin = lin*10 + (*p++ -'0'); } while(*p==' ') *q++ = *p++; } if(!*p){ *q = 0; linenumber =lin; return(0); /* no characters on the line */ } while(*p){ /*LINTED*/ if(!isalpha(*p)){ /* not a keyword. check for special characters */ switch(*p++){ case '"': case '`': /* quoted strings */ *q++ = charac = *(p-1); while(*p && *p != charac) *q++ = *p++; if(*p) *q++ = *p++; continue; case '?': *q++ = (CHAR)QPRINT; continue; case '\'': /* a rem statement */ *q++ = (CHAR)QUOTE; while(*p) *q++ = *p++; continue; case '<': if(*p == '='){ *q++ = (CHAR)LTEQ; p++; continue; } if(*p == '>'){ *q++ = (CHAR)NEQE; p++; continue; } break; case '>': if(*p == '='){ *q++ = (CHAR)GTEQ; p++; continue; } break; case '=': if(*p == '='){ *q++ = (CHAR)APRX; p++; continue; } break; } *q++ = *(p-1); continue; } /* * now do a quick check on the first character */ charac = toupper(*p); for(l = table ; l->string ; l++) if(charac == *l->string) break; /* * not found. not a keyword */ if(l->string == 0){ *q++ = *p++; /*LINTED*/ while(isalpha(*p)) *q++ = *p++; continue; } /* * get the length of the word */ /*LINTED*/ for(k = p, p++ ; isalnum(*p) || *p == '_'; p++); /* special case for FN */ if(p >= k + 2 && charac == 'f' && tolower(k[1]) == 'n'){ /* * and make certain it isn't fnend */ if(p != k+5 || tolower(k[2]) != 'e' || tolower(k[3]) != 'n' || tolower(k[4]) != 'd'){ *q++ = (CHAR)FN; for(k += 2; k < p ;) *q++ = *k++; continue; } } if(*p == '$') p++; /* * check entry in the table */ for(; l->string ; l++) if (charac == *l->string && (tmp = eql(k, l->string, p)) != 0){ if(l->chval > 0377){ *q++ = (CHAR)(EXFUNC + (l->chval >> 8)); *q++ = (CHAR)(l->chval & MASK); } else *q++ = (CHAR)l->chval; p = tmp; if(l->chval == DATA || l->chval == REM) while(*p) *q++ = *p++; break; } if(!l->string) while(k < p) *q++ = *k++; } *q='\0'; linenumber=lin; return(q-fline); /* return length of line */ } /* * eql() returns true if the strings are the same . * this routine is only called if the first letters are the same. * hence the increment of the pointers , we don't need to compare * the characters they point to. * To increase speed this routine could be put into machine code * the overheads on the function call and return are excessive * for what it accomplishes. (it fails most of the time , and * it can take a long time to load a large program ). */ static CHAR * eql(p, q, end) const CHAR *p, *q, *end; { p++, q++; while(p < end){ if(*p != *q && tolower(*p) != tolower(*q)) return(0); p++, q++; } #ifndef NO_SCOMMS if(*p == '.' && *q) return((char *) &p[1]); #endif if(*q) return(NULL); return((char *) p); } /* * Puts a line in the table of lines then sets a flag (inserted) so that * the variables are cleared , since it is very likely to have moved * 'ecore' and so the variables will all be corrupted. The clearing * of the variables is not done in this routine since it is only needed * to clear the variables once and that is best accomplished in main * just before it executes the immeadiate mode line. * If the line existed before this routine is called then it is deleted * and then space is made available for the new line, which is then * inserted. * The structure of a line in memory has the following structure:- * struct olin{ * unsigned linnumb; * unsigned llen; * char lin[1]; * } * The linenumber of the line is stored in linnumb , If this is zero * then this is the end of the program (all searches of the line table * terminate if it finds the linenumber is zero. * The variable 'llen' is used to store the length of the line (in * characters including the above structure and any padding needed to * make the line an even length. * To search through the table of lines then:- * XXXX g it as a variable * length array ( impossible in 'pure' C ). * The pointers used by the program storage routines are:- * fendcore = start of text storage segment * ecore = end of text storage * = start of data segment (string space ). * strings are stored after the text but before the numeric variables * only 512 bytes are allocated at the start of the program for strings * but clear can be called to get more core for the strings. */ void insert(lsize) int lsize; { lpoint p, op; lnumb l; inserted=1; /* say we want the variables cleared */ l= linenumber; last_ins_line = 0; for(op = 0, p = program; p ; op = p, p = p->next) if(p->linnumb >= l){ if(p->linnumb != l){ if(p->linnumb == CONTLNUMB) continue; break; } if(!op) program = p->next; else op->next = p->next; mfree( (MEMP)p); break; } if(!lsize) /* if no line to put in just ignore */ return; ins_line(op, lsize); } void ins_line(op, lsize) lpoint op; int lsize; { lpoint p; /* align the length */ /* * no longer needed. * lsize = (lsize + sizeof(struct olin) + WORD_SIZ - 1) & ~WORD_MASK; */ lsize += sizeof(struct olin); p = mmalloc((ival)lsize); VOID str_cpy(nline, p->lin); /* move the line into the space */ p->linnumb = linenumber; /* give it a linenumber */ if(!op){ p->next = program; program = p; } else { p->next = op->next; op->next = p; } last_ins_line = p; } /* * The interpreter needs three variables to control the flow of the * the program. These are:- * stocurlin : This is the pointer to the start of the current * line it is used to index the next line. * If the program is in immeadiate mode then * this variable is NULL (very important for 'next') * point: This points to the current location that * we are executing. * curline: The current line number ( zero in immeadiate mode) * this is not needed for program exection , * but is used in error etc. It could be made faster * if this variable is not used.... */ /* * The main loop of the execution of a program. * It does the following:- * FOR(ever){ * save point so that resume will go to the right place * IF cntrl-c THEN stop * IF NOT a reserved word THEN do_assignment * ELSE IF legal command THEN execute_command * IF return is NORMAL THEN * BEGIN * IF terminator is ':' THEN continue * ELSE IF terminator is '\0' THEN * goto next line ; continue * ELSE IF terminator is 'ELSE' AND * 'ELSES' are enabled THEN * goto next line ; continue * END * ELSE IF return is < NORMAL THEN continue * ( used by goto etc. ). * ELSE IF return is > NORMAL THEN * ignore_rest_of_line ; goto next line ; continue * } * All commands return a value ( if they return ). This value is NORMAL * if the command is standard and does not change the flow of the program. * If the value is greater than zero then the command wants to miss the * rest of the line ( comments and data ). * If the value is less than zero then the program flow has changed * and so we should go back and try to execute the new command ( we are * now at the start of a command ). */ void execute() { int c, i = NORMAL; lpoint p; for(;;){ #ifdef MSDOS if(++lcount > 100){ lcount = 0; if(CHK_KEY()) trap(0); } #endif #ifdef f32c if (sio_getchar(0) == 3) trap(0); #endif savepoint=point; if(trapped) dobreak(); if(tron_flag && stocurlin) prsline("**", stocurlin); if( ((c = getch()) & SPECIAL) == 0){ if(!c) i = GTO; else { point--; assign(ISFUNC|IS_MPR); i = NORMAL; } } else { if (c == EXCMD) { c = getch(); /* execute the command */ i = (*xcmdf[c&0177])(); } else if(c >= MAXCOMMAND) error(8); else { /* execute the command */ i = (*commandf[c&0177])(); } #ifndef f32c update_x11(0); #endif } if(i == NORMAL){ if((c=getch())==':') continue; /* `else` is a terminator */ if(c && (c != ELSE || !elsecount)) error(SYNTAX); } else if(i < NORMAL) continue; if(stocurlin){ /* not in immeadiate mode */ p = stocurlin->next; /* goto next line */ stocurlin=p; if(p){ point=p->lin; elsecount=0; /* disable `else`s */ continue; } } break; } reset(); /* end of program */ } /* * save the current running environment */ void save_env(e) struct env *e; { e->e_point = point; e->e_stolin = stocurlin; e->e_ertrap = trap_env.e_stolin; e->e_elses = elsecount; } /* * save the current running environment */ void ret_env(e) struct env *e; { point = e->e_point; stocurlin = e->e_stolin; trap_env.e_stolin = e->e_ertrap; elsecount = e->e_elses; } /* * The error routine , this is called whenever there is any error * it does some tidying up of file descriptors and sets the error line * number and the error code. If there is error trapping ( errortrap is * non-zero and in runmode ), then save the old pointers and set up the * new pointers for the error trap routine. * Otherwise print out the error message and the current line if in * runmode. * Finally call reset() ( which DOES NOT return ) to pop * the stack and to return to the main routine. */ static const char _on_line_[] = " on line "; void error(i) int i; /* error code */ { forstp fp; if(newentry){ drop_val(newentry, 1); newentry = 0; } if(readfile){ /* close file descriptor */ VOID close(readfile); /* from loading a file */ readfile=0; } if(renstr != 0){ mfree(renstr); renstr = 0; } if(str_used) FREE_STR(str_used); evallock=0; /* stop the recursive eval message */ fnlock = 0; ecode=i; /* set up the error code */ if(stocurlin) elinnumb = getrline(stocurlin);/* set up the error line number*/ else elinnumb=0; /* we have error trapping */ if(stocurlin && trap_env.e_stolin && !inserted){ point = savepoint; /* go back to start of command */ save_env(&err_env); ret_env(&trap_env); intrap=1; /* say we are trapped */ /* * return to enclosing function level. (if any) */ for(fp = estack ; fp ; fp = fp->prev) if(fp->fortyp == FNTYP){ str_used = fp->fnSBEG; str_uend = fp->fnSEND; longjmp(fp->fnenv, ERR_RESET); } errreset(); /* no return - goes to main */ } else { /* no error trapping */ if(cursor){ prints( (char *)nl); cursor=0; } prints( (char *)ermesg[i-1]); /* error message */ if(stocurlin) prsline(_on_line_, stocurlin); prints( (char *)nl); reset(); /* no return - goes to main */ } } void c_error(err) int err; { if(trap_env.e_stolin != 0 && stocurlin && !inserted) error(err); if(cursor){ prints( (char *)nl); cursor=0; } prints("Warning: "); prints( (char *)ermesg[err-1]); /* error message */ if(stocurlin) prsline(_on_line_, stocurlin); prints( (char *)nl); } /* * This is executed by the ON ERROR construct it checks to see * that we are not executing an error trap then set up the error * trap pointer. */ void errtrap() { lpoint p; lnumb l; l=getlin(); if(l == NOLNUMB) error(SYNTAX); check(); if(intrap) error(8); if(l == 0){ trap_env.e_stolin = 0; return; } p = getsline(l); trap_env.e_stolin = p; trap_env.e_point = p->lin; trap_env.e_ertrap = 0; trap_env.e_elses = 0; } /* * The 'resume' command , checks to see that we are actually * executing an error trap. If there is an optional linenumber then * we resume from there else we resume from where the error was. */ int resume() { lpoint p; lnumb i; int c; if(!intrap) error(8); c = getch(); if(c != NEXT){ point--; i= getlin(); } else i = 0; check(); if(i != NOLNUMB && i != 0){ p = getsline(i); ret_env(&err_env); stocurlin= p; /* resume at that line */ point= p->lin; elsecount=0; } else { ret_env(&err_env); if(c == NEXT){ if( (p = stocurlin->next) == 0) reset(); stocurlin= p; /* resume at next line */ point= p->lin; elsecount=0; } } intrap=0; /* get out of the trap */ return(-1); /* return to re-execute */ } /* * The 'error' command , this calls the error routine ( used in testing * an error trapping routine. */ int doerror() { itype i; i=evalint(); check(); if(i<1 || i >MAXERR) error(22); /* illegal error code */ error( (int)i); normret; } int tron() { tron_flag = 1; normret; } int troff() { tron_flag = 0; normret; } /* * This routine is used to clear space for strings and to reset all * other pointers so that it effectively clears the variables. */ void clear() { /* * reset the gosub stack, clear the stack before the symbol * table, because of multiline functions and ncall */ clr_stack(savbstack); clr_stack(bstack); savestack = savbstack = bstack = estack = 0; set_mem(tcharmap, (ival)TMAPSIZ, RVAL); /* * clear the variables */ clear_htab(&hshtab); /* * free any spare string blocks */ DROP_STRINGS(); datastolin = 0; /* reset the pointer to data */ datapoint = 0; /* reset the pointer to data */ contpos = 0; } /* * free one entry */ void free_entry(op) struct entry *op; { if(op->vtype == UNK_VAL){ mfree( (MEMP)op); return; } if(op->dimens){ if(op->vtype == SVAL) free_ar(op); mfree( (MEMP)op->_darr); } else if(op->vtype & ISFUNC){ if(op->_deffn != 0) mfree( (MEMP)op->_deffn); } else if(op->vtype == SVAL && !(op->flags & IS_FSTRING)){ if(op->_dstr != 0) mfree( (MEMP)op->_dstr); } mfree( (MEMP)op); } static void free_ar(op) struct entry *op; { int j = 1; stringp sp; int i; for(i = 0 ; i < op->dimens ; i++) j *= op->_dims[i]; /*LINTED pointer conversion */ for(sp = (stringp)op->_darr ; j ; sp++, j--) if(sp->str) mfree( (MEMP)sp->str); } /* clear the hash table*/ void clear_htab(htab) struct hash *htab; { struct entry **p, *op; int i = 0; for(p = htab->hasht ; i < HSHTABSIZ ; i++, p++) while( (op = *p) != 0){ *p = op->link; free_entry(op); } } void clr_stack(sptr) forstp sptr; { forstp np; struct entry *ep; while(sptr){ if(sptr->fortyp == FNTYP){ ep = sptr->fnvar; ep->_deffn->ncall--; if(ep->vtype == SVAL && ep->_deffn->mline == IS_MFN){ if(sptr->fnsval.str != 0){ mfree( (MEMP)sptr->fnsval.str); sptr->fnsval.str = 0; } } if(sptr->fnLOCAL) recover_vars(sptr, 1); if(str_used) FREE_STR(str_used); str_used = sptr->fnSBEG; str_uend = sptr->fnSEND; } np = sptr->next; mfree( (MEMP)sptr); sptr = np; } } /* * when closing a blocked file. zap all fstring variables. * do this quickly by just resetting the bit and then setting their * pointers to zero */ void kill_fstrs(bstr, estr) CHAR *bstr, *estr; { struct entry **p, *op; for(p = hshtab.hasht ; p < &hshtab.hasht[HSHTABSIZ]; p++) for(op = *p ; op ; op = op->link) if( (op->flags & IS_FSTRING) == 0) continue; else if(op->_dstr >= bstr && op->_dstr < estr){ op->flags &= ~IS_FSTRING; op->_dstr = 0; op->_dslen = 0; } } /* * drop all variables which are not common, only used in chain */ void ch_clear(doall) int doall; { struct hash tmphshtab; struct entry **p, **q; struct entry *ep, **nep, **neq, *tep = 0; q = tmphshtab.hasht; for(p = hshtab.hasht ; p < &hshtab.hasht[HSHTABSIZ] ; p++, q++){ ep = *p; neq = q; nep = p; for(*neq = *nep = 0 ; ep ; ep = tep){ tep = ep->link; ep->link = 0; if(!doall && (ep->flags & IS_COMMON) == 0){ *nep = ep; nep = &ep->link; } else { *neq = ep; neq = &ep->link; } } } clear(); hshtab = tmphshtab; } void add_entry(op) struct entry *op; { int i; i = MKhash(op->ln_hash); op->link = hshtab.hasht[i]; hshtab.hasht[i] = op; } /* * mtest() is used to set the amount of core for the current program * it uses brk() to ask the system for more core. * The core is allocated in 1K chunks, this is so that the program does * not spend most of is time asking the system for more core and at the * same time does not hog more core than is neccasary ( be friendly to * the system ). * Any test that is less than 'ecore' is though of as an error and * so is any test greater than the size that seven memory management * registers can handle. * If there is this error then a test is done to see if 'ecore' can * be accomodated. If so then that size is allocated and error() is called * otherwise print a message and exit the interpreter. * If the value of the call is less than 'ecore' we have a problem * with the interpreter and we should cry for help. (It doesn't ). */ void * mmalloc(len) ival len; { void *p; if ((p = malloc((unsigned int)len)) != NULL) return(p); clear(); if ((p = malloc((unsigned int)len)) != NULL) return(p); prints("out of core\n"); /* print message */ VOID quit(); /* exit flushing buffers */ NO_RET; /* should never be reached */ } void mfree(mem) MEMP mem; { free( (void *)mem); } int mtestalloc(len) ival len; { void *p; if( (p = malloc((unsigned int)len)) != NULL) { mfree(p); return (1); } return (0); } /* * This routine tries to set up the system to catch all the signals that * can be produced. (except kill ). and do something sensible if it * gets one. ( There is no way of producing a core image through the * sending of signals). */ #ifndef f32c #ifndef MSDOS /*ARGSUSED*/ static SIGFUNC squit(int x) { VOID quit(); } static SIGFUNC sexit(int x) { _exit(x); } #endif static const struct mysigs { int sigval; SIGFUNC (*sigfunc)(int); } traps[] = { #ifndef MSDOS {SIGHUP, squit}, /* hang up */ #endif {SIGINT, trap}, #ifndef MSDOS {SIGQUIT, quit1}, {SIGILL, sexit}, {SIGTRAP, sexit}, {SIGIOT, sexit}, #ifdef SIGEMT {SIGEMT, sexit}, #endif {SIGFPE, catchfp}, /* fp exception */ /* SIGKILL, 0, / * kill */ {SIGBUS, seger}, /* seg err */ {SIGSEGV, mcore}, /* bus err */ /* SIGSYS, 0, */ {SIGPIPE, sexit}, {SIGALRM, squit}, {SIGTERM, sexit}, {SIGUSR1, sexit}, #ifdef SIGUSR2 {SIGUSR2, sexit}, #endif #ifdef SIGTSTP {SIGTSTP, onstop}, #endif #endif }; void catchsignal() { const struct mysigs *sp; for(sp = traps ; sp < &traps[sizeof(traps) / sizeof(traps[0])]; sp++) if(sp->sigval) VOID signal(sp->sigval, sp->sigfunc); } /* * this routine deals with floating exceptions via fpfunc * this is a function pointer set up in fpstart so that trapping * can be done for floating point exceptions. */ /*ARGSUSED*/ static SIGFUNC catchfp(x) int x; { #ifndef MSDOS VOID signal(SIGFPE,catchfp); /* restart catching */ #endif if(fpfunc== 0) /* this is set up in fpstart() */ _exit(1); (*fpfunc)(); } /* * we have a segmentation violation and so should print the message and * exit. Either a kill() from another process or an interpreter bug. */ /*ARGSUSED*/ static SIGFUNC seger(x) int x; { prints("segmentation violation\n"); _exit(-1); /*NOTREACHED*/ } /* * This does the same for bus errors as seger() does for segmentation * violations. The interpreter is pretty nieve about the execution * of complex expressions and should really check the stack every time, * to see if there is space left. This is an easy error to fix, but * it was not though worthwhile at the moment. If it runs out of stack * space then there is a vain attempt to call mcore() that fails and * so which produces another bus error and a core image. */ /*ARGSUSED*/ static SIGFUNC mcore(x) int x; { prints("bus error\n"); _exit(-1); /*NOTREACHED*/ } #endif /* !f32c */ /* * Called by the cntrl-c signal (number 2 ). It sets 'trapped' to * signify that there has been a cntrl-c and then re-enables the trap. * It also bleeps at you. */ /*ARGSUSED*/ static SIGFUNC trap(x) int x; { VOID signal(SIGINT, SIG_IGN);/* ignore signal for the bleep */ VOID write(1, "\07", 1); /* bleep */ VOID signal(SIGINT, trap); /* re-enable the trap */ trapped=1; /* say we have had a cntrl-c */ #ifdef SIG_JMP if(ecalling){ ecalling = 0; longjmp(ecall, 1); /*NOTREACHED*/ } #endif } #ifndef f32c /* * called by cntrl-\ trap , It prints the message and then exits * via quit() so flushing the buffers, and getting the terminal back * in a sensible mode. */ /*ARGSUSED*/ static SIGFUNC quit1(x) int x; { #ifndef MSDOS VOID signal(SIGQUIT,SIG_IGN);/* ignore any more */ #endif if(cursor){ /* put cursor on a new line */ prints( (char *)nl); cursor=0; } prints("quit\n\r"); /* print the message */ VOID quit(); /* exit */ } #endif /* !f32c */ /* * resets the terminal , flushes all files then exits * this is the standard route exit from the interpreter. The seger() * and mcore() traps should not go through these traps since it could * be the access to the files that is causing the error and so this * would produce a core image. * From this it may be gleened that I don't like core images. */ int quit() { flushall(); /* flush the files */ #if 0 // XXX #ifndef f32c rset_term(1); #endif if(cursor) prints( (char *)nl); exit(0); /* goodbye */ normret; } static void docont() { if(stocurlin){ contpos=0; clr_stack(savbstack); if(cancont){ savestack = estack; savbstack = bstack; bstack = estack = 0; contpos=cancont; } else savbstack = savestack = 0; } cancont=0; } #ifndef f32c #ifdef SIGTSTP extern int kill(pid_t, int); /* * support added for job control */ /*ARGSUSED*/ static SIGFUNC onstop(x) int x; { flushall(); /* flush the files */ if(cursor){ prints( (char *)nl); cursor = 0; } #ifdef SIG_JMP VOID sigsetmask(0); /* Urgh !!!!!! */ #endif VOID signal(SIGTSTP, SIG_DFL); VOID kill(0,SIGTSTP); /* The PC stops here */ VOID signal(SIGTSTP,onstop); } #endif #endif /* !f32c */
2.296875
2
2024-11-18T20:41:31.039476+00:00
2019-04-17T12:04:59
af813f984afeec975973c952cb5b7888174cdbb8
{ "blob_id": "af813f984afeec975973c952cb5b7888174cdbb8", "branch_name": "refs/heads/master", "committer_date": "2019-04-17T12:05:59", "content_id": "c64a8be58e72cb2786748ca362f38dcd0e28373d", "detected_licenses": [ "MIT" ], "directory_id": "febd18a85df90a0b49819edb03189da55cfc7697", "extension": "c", "filename": "node_like.c", "fork_events_count": 0, "gha_created_at": "2018-10-18T20:38:10", "gha_event_created_at": "2019-04-15T19:40:25", "gha_language": "C", "gha_license_id": "MIT", "github_id": 153684555, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1093, "license": "MIT", "license_type": "permissive", "path": "/node_like.c", "provenance": "stackv2-0082.json.gz:31334", "repo_name": "shijinglu/lure.c", "revision_date": "2019-04-17T12:04:59", "revision_id": "1f76fcb085302b0476d69abb9a7bba19383064ca", "snapshot_id": "cfd3c89fb0ff6c5140b4813a504708f646ccac02", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/shijinglu/lure.c/1f76fcb085302b0476d69abb9a7bba19383064ca/node_like.c", "visit_date": "2020-04-01T21:58:31.615477" }
stackv2
#include<assert.h> #include<stdlib.h> #include<memory.h> #include "node.h" #include "data.h" #include "util.h" #include "hashmap.h" #include "re.h" /* evaluate, allocate and return a data struct. */ Data *node_like_evaluate(Node *node, map_t context) { LURE_ASSERT(node != NULL, "cannot evaluate against an empty node"); LURE_ASSERT(node->left != NULL, "left side of a <like> node must not be NULL"); LURE_ASSERT(node->right != NULL, "right side of a <like> node must not be NULL"); Data *leftRes = node->left->evaluate(node->left, context); Data *rightRes = node->right->evaluate(node->right, context); int m = re_match(leftRes->getCStr(leftRes), rightRes->getCStr(rightRes)); leftRes->clean(leftRes); free(leftRes); rightRes->clean(rightRes); free(rightRes); return NewBoolData(m != -1); } Node *NewNodeLike(Node *left, Node *right) { Node *node = (Node *)calloc(1, sizeof(Node)); node->type = NodeType_Identity; node->left = left; node->right = right; node->list = NULL; node->evaluate = node_like_evaluate; return node; }
2.328125
2
2024-11-18T20:41:31.271707+00:00
2021-04-19T06:19:33
a22027dc046660eeff6629909b78bedbe6c5bf22
{ "blob_id": "a22027dc046660eeff6629909b78bedbe6c5bf22", "branch_name": "refs/heads/master", "committer_date": "2021-04-19T06:19:33", "content_id": "7252c2d904ae3094bacf1d7f979f2c0a4ca51d9d", "detected_licenses": [ "MIT" ], "directory_id": "234810bba02519c0a5990c8e5e2d0195a4b91e2c", "extension": "c", "filename": "set.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5887, "license": "MIT", "license_type": "permissive", "path": "/COEN/COEN12/Lab4/set.c", "provenance": "stackv2-0082.json.gz:31462", "repo_name": "hmuroavila/SCU", "revision_date": "2021-04-19T06:19:33", "revision_id": "7b904ce02b4a6804eaeaba290b0acc3f29041568", "snapshot_id": "b320852d414e90835fdb5bf22317fe16978bbf97", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hmuroavila/SCU/7b904ce02b4a6804eaeaba290b0acc3f29041568/COEN/COEN12/Lab4/set.c", "visit_date": "2023-04-06T17:29:03.639324" }
stackv2
/* Tamir Enkhjargal COEN 12 Lab 4 May 19, 2019 Creating Lab 4. Set implementation */ /* Calling necessary libraries */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "set.h" #include <assert.h> #include <stdbool.h> #include "list.h" #define alpha 20 /* ---------------------------------------------------------------------- */ /* Defining the private function search() */ static int search(SET *sp, void *elt, bool *found); /* ---------------------------------------------------------------------- */ /* Creating the structure for our Set */ typedef struct set { LIST **data; int length; int count; int (*compare)(); unsigned (*hash)(); } SET; /* ---------------------------------------------------------------------- */ /* Create set function, O(n) runtime */ SET *createSet(int maxElts, int (*compare)(), unsigned (*hash)()) { SET *sp = malloc(sizeof(SET)); // Allocate memory for pointer assert(sp != NULL); // check if successful sp->length = maxElts/alpha; // set max elements sp->count = 0; // start counter at 0 sp->compare = compare; // call compare function sp->hash = hash; // call hash function sp->data = malloc(sizeof(LIST *)*sp->length); // Allocate memory for data pointer assert(sp->data != NULL); // check if successful int i; for(i = 0; i < sp->length; i++) { // loop through to make a list in sp->data[i] = createList(sp->compare); // each data point } return sp; } /* ---------------------------------------------------------------------- */ /* Destroy set function, O(n) runtime */ void destroySet(SET *sp) { assert(sp != NULL); int i; for(i = 0; i < sp->length; i++) { // loop through destroyList(sp->data[i]); // call destroyList() } free(sp->data); // then free the data free(sp); // free sp overall return; } /* ---------------------------------------------------------------------- */ /* Number of elements function, O(1) runtime */ int numElements(SET *sp) { assert(sp != NULL); return sp->count; } /* ---------------------------------------------------------------------- */ /* Add element function, O(n) runtime */ void addElement(SET *sp, void *elt) { assert(sp != NULL && elt != NULL); bool found = false; int index = search(sp, elt, &found); // call search function if(found == false) { // if didn't find addLast(sp->data[index], elt); // add to end of the list sp->count++; // increase counter } return; } /* ---------------------------------------------------------------------- */ /* Remove element function, O(n) runtime */ void removeElement(SET *sp, void *elt) { assert(sp != NULL && elt != NULL); bool found = false; int index = search(sp, elt, &found); // call search function if(found == false) { // if didn't find return; // do nothing (remove nothing) } else { removeItem(sp->data[index], elt); // if found, remove it sp->count--; // decrement counter return; } } /* ---------------------------------------------------------------------- */ /* Find element function, O(n^2) runtime */ void *findElement(SET *sp, void *elt) { assert(sp != NULL && elt != NULL); bool found = false; int index = search(sp, elt, &found); // call search function if(found == false) { // if not found return NULL; // return nothing } else { // if found return findItem(sp->data[index], elt); // return element } } /* ---------------------------------------------------------------------- */ /* Get elements function, O(n^3) runtime */ void *getElements(SET *sp) { assert(sp != NULL); void **temp; void **list; int i, j; int counter = 0; temp = malloc(sizeof(void *)*sp->count); assert(temp != NULL); for(i = 0; i < sp->length; i++) { // loop through everything list = malloc(sizeof(void *)*numItems(sp->data[i])); // create a secondary list array list = getItems(sp->data[i]); // call get elements on everything for(j = 0; j < numItems(sp->data[i]); j++) { // loop through list size temp[counter] = list[j]; // copy elements in list counter++; // to the temp array } } return temp; // return our copied array } /* ---------------------------------------------------------------------- */ /* Private search function, O(n^2) runtime */ static int search(SET *sp, void *elt, bool *found) { assert(sp != NULL && elt != NULL); int index = (*sp->hash)(elt)%sp->length; // use hash function for max size if(findItem(sp->data[index], elt) != NULL) { // call findItem *found = true; // if found, return location return index; } else { *found = false; // if not found, still return index return index; } } /* ---------------------------------------------------------------------- */
3.46875
3
2024-11-18T20:56:19.327540+00:00
2016-09-27T16:08:22
0e513abdac5e371920194390ec11a21666557619
{ "blob_id": "0e513abdac5e371920194390ec11a21666557619", "branch_name": "refs/heads/master", "committer_date": "2016-09-27T16:08:22", "content_id": "340024fa3212df9a96b8629bce1461aa0499bb4a", "detected_licenses": [ "MIT" ], "directory_id": "6fb96af28baa9cff4231b067576998a765eec4a6", "extension": "c", "filename": "hm10.c", "fork_events_count": 1, "gha_created_at": "2015-07-11T23:17:36", "gha_event_created_at": "2016-08-19T10:53:53", "gha_language": "C", "gha_license_id": null, "github_id": 38943640, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5510, "license": "MIT", "license_type": "permissive", "path": "/fw/peripherals/hal/hm10.c", "provenance": "stackv2-0082.json.gz:226115", "repo_name": "Octanis1/Octanis1-Mainboard-Firmware_MSP_EXP432P401RLP", "revision_date": "2016-09-27T16:08:22", "revision_id": "015f00bb391c37f91f093ed68fb704193a5257de", "snapshot_id": "e440c14bbc2d4e8a0312758be540b2b976ddf733", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Octanis1/Octanis1-Mainboard-Firmware_MSP_EXP432P401RLP/015f00bb391c37f91f093ed68fb704193a5257de/fw/peripherals/hal/hm10.c", "visit_date": "2021-01-23T19:33:39.563377" }
stackv2
/* * File: hm10.c * Description: BLE modem driver * Author: Sam Sulaimanov */ #include "../../../Board.h" #include "hm10.h" #define HM10_BAUD_RATE 9600 #define HM10_READ_TIMEOUT 3000 static const char hm10_at[] = "AT"; //does not require return characters static const char hm10_at_name[] = "AT+NAMEmars3"; static const char hm10_at_clear[] = "AT+CLEAR"; //clear last connected device static const char hm10_at_wakestring[] = "I am iron man,I am iron man,I am iron man,I am iron man, I am iron man, I am iron man I am iron I am iron man, I am iron man."; static const char hm10_at_imme1[] = "AT+IMME1"; //When module is powered on, only respond the AT Command, don’t do anything. static const char hm10_at_start[] = "AT+START"; //start connecting to devices static const char hm10_at_pwrm1[] = "AT+PWRM1"; //doesnt go to sleep in this mode static const char hm10_at_pwrm0[] = "AT+PWRM0"; //sleep mode static UART_Handle uart; static UART_Params uartParams; static int hm10_initialised = 0; static char hm10_rxBuffer[HM10_RXBUFFER_SIZE]; static int hm10_rxCount; void hm10_read_callback(UART_Handle handle, void *buf, size_t count); int hm10_callback; //must be called from within a task - this function will block! //returns 1 if modem responds with OK int hm10_begin(){ memset(&hm10_rxBuffer, 0, sizeof(hm10_rxBuffer)); UART_Params_init(&uartParams); uartParams.writeDataMode = UART_DATA_BINARY; uartParams.readMode = UART_MODE_BLOCKING; uartParams.readTimeout = HM10_READ_TIMEOUT; uartParams.readDataMode = UART_DATA_BINARY; uartParams.readReturnMode = UART_RETURN_FULL; uartParams.readEcho = UART_ECHO_OFF; uartParams.baudRate = HM10_BAUD_RATE; uart = UART_open(Board_UART2_COMM, &uartParams); if (uart == NULL) { //debug GPIO_toggle(Board_LED_GREEN); Task_sleep(300); GPIO_toggle(Board_LED_GREEN); return 0; } else { Task_sleep(1000); UART_write(uart, hm10_at_wakestring, strlen(hm10_at_wakestring)); UART_read(uart, hm10_rxBuffer, sizeof(hm10_rxBuffer)); serial_printf(cli_stdout, "%s\n", hm10_rxBuffer); memset(&hm10_rxBuffer, 0, sizeof(hm10_rxBuffer)); UART_write(uart, hm10_at_pwrm1, strlen(hm10_at_pwrm1)); UART_read(uart, hm10_rxBuffer, sizeof(hm10_rxBuffer)); serial_printf(cli_stdout, "%s\n", hm10_rxBuffer); memset(&hm10_rxBuffer, 0, sizeof(hm10_rxBuffer)); Task_sleep(1000); UART_write(uart, hm10_at_clear, strlen(hm10_at_clear)); UART_read(uart, hm10_rxBuffer, sizeof(hm10_rxBuffer)); serial_printf(cli_stdout, "%s\n", hm10_rxBuffer); memset(&hm10_rxBuffer, 0, sizeof(hm10_rxBuffer)); Task_sleep(500); UART_write(uart, hm10_at_imme1, strlen(hm10_at_imme1)); UART_read(uart, hm10_rxBuffer, sizeof(hm10_rxBuffer)); serial_printf(cli_stdout, "%s\n", hm10_rxBuffer); memset(&hm10_rxBuffer, 0, sizeof(hm10_rxBuffer)); Task_sleep(1000); UART_write(uart, hm10_at_name, strlen(hm10_at_name)); UART_read(uart, hm10_rxBuffer, sizeof(hm10_rxBuffer)); serial_printf(cli_stdout, "%s\n", hm10_rxBuffer); memset(&hm10_rxBuffer, 0, sizeof(hm10_rxBuffer)); Task_sleep(1000); UART_write(uart, hm10_at, strlen(hm10_at)); UART_read(uart, hm10_rxBuffer, sizeof(hm10_rxBuffer)); serial_printf(cli_stdout, "%s\n", hm10_rxBuffer); if(!strcmp("OK", hm10_rxBuffer)){ UART_write(uart, hm10_at_start, strlen(hm10_at_start)); hm10_end(); // Close UART port to configure Text mode to callback @ newline + CR uartParams.writeDataMode = UART_DATA_BINARY; /* Experimental: use callback mode such that the comm task is not blocked * while waiting for incoming commands. * * Note: think about using void UART_readCancel ( UART_Handle handle ) * WARNING: It is STRONGLY discouraged to call UART_read from its own callback function (UART_MODE_CALLBACK). */ uartParams.readMode = UART_MODE_CALLBACK; uartParams.readCallback = hm10_read_callback; uartParams.readTimeout = UART_WAIT_FOREVER; //HM10_READ_TIMEOUT; uartParams.readDataMode = UART_DATA_TEXT; uartParams.readReturnMode = UART_RETURN_NEWLINE; uart = UART_open(Board_UART2_COMM, &uartParams); if (uart == NULL) { //debug GPIO_toggle(Board_LED_GREEN); Task_sleep(300); GPIO_toggle(Board_LED_GREEN); return 0; } else { hm10_initialised = 1; // directly be receptive for commands hm10_callback = 0; UART_read(uart, hm10_rxBuffer, sizeof(hm10_rxBuffer)); return 1; //modem can now communicate with us } } else { return 0; } } } /* function checks if new data has been received via BLE module and starts a new UART_read. * Returns 1 if new data was received, 0 if no new data is present. */ int hm10_receive(char* rxdata, int* stringlength) { if(hm10_callback == 1) { (*stringlength) = hm10_rxCount; memcpy(rxdata,hm10_rxBuffer,hm10_rxCount); hm10_callback = 0; if(hm10_initialised) { //generate next read command UART_read(uart, hm10_rxBuffer, sizeof(hm10_rxBuffer)); return 1; } else { serial_printf(cli_stdout, "RX failed. hm10 not init\n"); } } return 0; } void hm10_send(char * tx_buffer, int tx_size) { if(hm10_initialised){ UART_write(uart, tx_buffer, tx_size); UART_write(uart, "\n", 1); }else{ serial_printf(cli_stdout, "TX failed. hm10 not init\n"); } } void hm10_end(){ if(uart != NULL) { hm10_initialised = 0; UART_close(uart); uart = NULL; } } void hm10_read_callback(UART_Handle handle, void *buf, size_t count) { hm10_rxCount = (int)count; hm10_callback = 1; }
2.265625
2
2024-11-18T20:56:19.477815+00:00
2023-07-30T07:00:50
1eca7280e43845f8c20de69fab067d951a356647
{ "blob_id": "1eca7280e43845f8c20de69fab067d951a356647", "branch_name": "refs/heads/master", "committer_date": "2023-07-30T07:00:50", "content_id": "f7322aae312f63a44cce8e028d6c82073c206e3d", "detected_licenses": [ "MIT" ], "directory_id": "db04ecf258aef8a187823b8e47f4a1ae908e5897", "extension": "c", "filename": "NumberofWaystoReorderArraytoGetSameBST.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 74735489, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 918, "license": "MIT", "license_type": "permissive", "path": "/C/NumberofWaystoReorderArraytoGetSameBST.c", "provenance": "stackv2-0082.json.gz:226243", "repo_name": "JumHorn/leetcode", "revision_date": "2023-07-30T07:00:50", "revision_id": "abf145686dcfac860b0f6b26a04e3edd133b238c", "snapshot_id": "9612a26e531ceae7f25e2a749600632da6882075", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JumHorn/leetcode/abf145686dcfac860b0f6b26a04e3edd133b238c/C/NumberofWaystoReorderArraytoGetSameBST.c", "visit_date": "2023-08-03T21:12:13.945602" }
stackv2
#include <string.h> static const int MOD = 1e9 + 7; int recursive(int *nums, int numsSize, int N, int (*cache)[N + 1]) { if (numsSize <= 2) return 1; int left[N + 1], leftSize = 0, right[N + 1], rightSize = 0; for (int i = 1; i < numsSize; ++i) nums[i] > nums[0] ? (right[rightSize++] = nums[i]) : (left[leftSize++] = nums[i]); int l = recursive(left, leftSize, N, cache), r = recursive(right, rightSize, N, cache); long res = cache[numsSize - 1][leftSize]; return res * l % MOD * r % MOD; } int numOfWays(int *nums, int numsSize) { int N = numsSize; //combination table int combination[N + 1][N + 1]; memset(combination, 0, sizeof(combination)); combination[0][0] = 1; for (int i = 1; i <= N; ++i) { combination[i][0] = 1; for (int j = 1; j <= N; ++j) combination[i][j] = (combination[i - 1][j] + combination[i - 1][j - 1]) % MOD; } return recursive(nums, numsSize, N, combination) - 1; }
2.859375
3
2024-11-18T20:56:19.555950+00:00
2021-06-13T07:11:07
ec534402faf81931e47f326b85099b1260d9aa24
{ "blob_id": "ec534402faf81931e47f326b85099b1260d9aa24", "branch_name": "refs/heads/master", "committer_date": "2021-06-13T07:11:07", "content_id": "e5c9e332a70a85dcec597ea45484e32d150c18e9", "detected_licenses": [ "CC0-1.0" ], "directory_id": "21e4f908e97df0da9f08fcd4ceaa4971cc09b15a", "extension": "c", "filename": "SortAccount.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 356250127, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 941, "license": "CC0-1.0", "license_type": "permissive", "path": "/3_Implementation/src/SortAccount.c", "provenance": "stackv2-0082.json.gz:226373", "repo_name": "256018/MiniProject_C", "revision_date": "2021-06-13T07:11:07", "revision_id": "0101c9c449d8a0b007cd174a25b34ba0f8e5373b", "snapshot_id": "73d03b37706d80c8248a9b60ce771d451daa0839", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/256018/MiniProject_C/0101c9c449d8a0b007cd174a25b34ba0f8e5373b/3_Implementation/src/SortAccount.c", "visit_date": "2023-05-21T00:56:04.763885" }
stackv2
#include "header.h" error_t sort_account(AccountInfo *account, int *numberOfAccounts) { int i=0,j=0,k,choice; AccountInfo tempstruct; printf("Press 1 To Sort By Account Number.\n"); printf("Press 2 To Sort By Account Balance.\n"); printf("Please Enter your choice\n"); scanf("%d",&choice); if(choice == 1) { for(i=0;i<*numberOfAccounts-1;i++) { for(j=i+1;j<*numberOfAccounts;j++) { if(account[i].account_no>account[j].account_no) { tempstruct=account[i]; account[i]=account[j]; account[j]=tempstruct; } } } return SUCCESS; } if(choice == 2) { for(i=0;i<*numberOfAccounts-1;i++) { for(j=i+1;j<*numberOfAccounts;j++) { if(account[i].balance<account[j].balance) { tempstruct=account[i]; account[i]=account[j]; account[j]=tempstruct; } } } return SUCCESS; } }
2.90625
3
2024-11-18T20:56:19.797451+00:00
2015-08-04T08:26:54
f56e645f580ad0770a36cb2f81ed22b2b1d3f209
{ "blob_id": "f56e645f580ad0770a36cb2f81ed22b2b1d3f209", "branch_name": "refs/heads/master", "committer_date": "2015-08-04T08:26:54", "content_id": "b605543bd7962ab2e5f22e6a2fd980fe572f0184", "detected_licenses": [ "MIT" ], "directory_id": "addfcd571f271f643ed81a6f6d6512b17154275b", "extension": "c", "filename": "mooves.c", "fork_events_count": 1, "gha_created_at": "2015-06-17T15:43:32", "gha_event_created_at": "2015-08-04T08:26:54", "gha_language": "C", "gha_license_id": null, "github_id": 37604360, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 928, "license": "MIT", "license_type": "permissive", "path": "/mooves.c", "provenance": "stackv2-0082.json.gz:226503", "repo_name": "Aracthor/ascii-minesweeper", "revision_date": "2015-08-04T08:26:54", "revision_id": "8944deff2da555a385b1490f02acd775b8296099", "snapshot_id": "077b1674c4a7551600206497b419631d6653d2af", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/Aracthor/ascii-minesweeper/8944deff2da555a385b1490f02acd775b8296099/mooves.c", "visit_date": "2021-01-15T08:10:46.952510" }
stackv2
#include <unistd.h> #include "mooves.h" #include "keyboard.h" static void moove_cursor(int moove) { int moovement[2]; moovement[0] = moove; moovement[1] = moove; write(1, moovement, sizeof(moovement)); } bool moove_up(struct s_grid *grid, coord *select) { (void)(grid); if (select->y > 0) --select->y; moove_cursor(UP); return true; } bool moove_down(struct s_grid *grid, coord *select) { if (select->y < grid->width - 1) ++select->y; moove_cursor(DOWN); return true; } bool moove_right(struct s_grid *grid, coord *select) { if (select->x < grid->longer - 1) ++select->x; moove_cursor(RIGHT); return true; } bool moove_left(struct s_grid *grid, coord *select) { (void)(grid); if (select->x > 0) --select->x; moove_cursor(LEFT); return true; }
2.515625
3
2024-11-18T21:05:50.832828+00:00
2019-04-04T05:02:19
7ff0dfda92bdb0599475e92361be97484cbf5268
{ "blob_id": "7ff0dfda92bdb0599475e92361be97484cbf5268", "branch_name": "refs/heads/master", "committer_date": "2019-04-04T05:02:19", "content_id": "6023a323a513809a2338df3afc6cd4eb68afaa75", "detected_licenses": [ "MIT-Modern-Variant" ], "directory_id": "5a186133a7c7a9983d5ca4671b2e0e02d97bd8f5", "extension": "c", "filename": "append.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 168332986, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1547, "license": "MIT-Modern-Variant", "license_type": "permissive", "path": "/nachos-3.4/code/test/append.c", "provenance": "stackv2-0083.json.gz:501", "repo_name": "TTNguyenDev/nachOS", "revision_date": "2019-04-04T05:02:19", "revision_id": "b765808b1e31c1c19dce56845dabf267c357e897", "snapshot_id": "beb5deea53ca15352357a9e52a52834a0dfe6127", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TTNguyenDev/nachOS/b765808b1e31c1c19dce56845dabf267c357e897/nachos-3.4/code/test/append.c", "visit_date": "2020-04-19T17:21:28.941452" }
stackv2
#include "syscall.h" #define MAX_LENGTH 255 int main() { OpenFileId sourceFile1, sourceFile2, destinationFile; int i = 0, fileSize1, fileSize2; char *mChar; char source1[MAX_LENGTH], source2[MAX_LENGTH], destination[MAX_LENGTH]; PrintString("Enter file 1 name: \n"); ReadString(source1, MAX_LENGTH); sourceFile1 = Open(source1, 1); if (sourceFile1 == -1) { PrintString("This file is read-only file \n"); return 0; } PrintString("Enter file 2 name: \n"); ReadString(source2, MAX_LENGTH); sourceFile2 = Open(source2, 1); if (sourceFile2 == -1) { PrintString("This file is read-only file \n"); return 0; } PrintString("Enter destination file name: \n"); ReadString(destination, MAX_LENGTH); destinationFile = Open(destination, 0); if (destinationFile == -1) { PrintString("File doesn't existed, Want to create new file? (y/n) \n"); ReadString(mChar, MAX_LENGTH); if (mChar[0] == "n" || mChar[0] == "N") return 0; else { Create(destination); destinationFile = Open(destination, 0); } } fileSize1 = Seek(-1, sourceFile1); // coppy file 1 Seek(0, sourceFile1); Seek(-1, destinationFile); while (i < fileSize1) { Read(mChar, 1, sourceFile1); Write(mChar, 1, destinationFile); i++; } i = 0; fileSize2 = Seek(-1, sourceFile2); // coppy file 2 Seek(0, sourceFile2); Seek(-1, destinationFile); while(i < fileSize2) { Read(mChar, 1, sourceFile2); Write(mChar, 1, destinationFile); i++; } Close(sourceFile1); Close(sourceFile2); Close(destinationFile); return 0; }
2.875
3
2024-11-18T21:05:50.905924+00:00
2020-05-10T11:37:26
e7ee593482759ff4ced0bb9a45d0cdbf41a6d641
{ "blob_id": "e7ee593482759ff4ced0bb9a45d0cdbf41a6d641", "branch_name": "refs/heads/master", "committer_date": "2020-05-10T11:37:26", "content_id": "90115d994cf644903e58e7a52c6a40ed2eea9565", "detected_licenses": [ "MIT" ], "directory_id": "dc8e9b0cd523eeba2138df2feb5cbacb00114f77", "extension": "c", "filename": "motor.c", "fork_events_count": 9, "gha_created_at": "2020-03-23T11:24:24", "gha_event_created_at": "2020-05-10T07:56:59", "gha_language": "C", "gha_license_id": "MIT", "github_id": 249411424, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4943, "license": "MIT", "license_type": "permissive", "path": "/sources/platforms/recovid_revB/drivers/motor.c", "provenance": "stackv2-0083.json.gz:630", "repo_name": "Recovid/Controller", "revision_date": "2020-05-10T11:37:26", "revision_id": "8d21bcf0d47361b8765bdfaf8fb14667b4a0a777", "snapshot_id": "7e10bf0ca45ad079016f8971c2baaf44976bc0b7", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Recovid/Controller/8d21bcf0d47361b8765bdfaf8fb14667b4a0a777/sources/platforms/recovid_revB/drivers/motor.c", "visit_date": "2021-04-17T04:08:33.000094" }
stackv2
#include "recovid_revB.h" #include "platform.h" static TIM_HandleTypeDef *_motor_tim = NULL; static volatile bool _moving; static volatile bool _homing; static volatile bool _home; static volatile bool _limit_sw_A; static volatile bool _limit_sw_B; static volatile bool _active; static void period_elapsed_callback(TIM_HandleTypeDef *tim); static void do_motor_stop(); static void check_home(); bool init_motor(uint32_t home_step_us) { if (_motor_tim == NULL) { _motor_tim = &motor_tim; // register IT callbacks HAL_TIM_RegisterCallback(_motor_tim, HAL_TIM_PERIOD_ELAPSED_CB_ID, period_elapsed_callback); _active = HAL_GPIO_ReadPin(MOTOR_ACTIVE_GPIO_Port, MOTOR_ACTIVE_Pin); _limit_sw_A = !HAL_GPIO_ReadPin(MOTOR_LIMIT_SW_A_GPIO_Port, MOTOR_LIMIT_SW_A_Pin); _limit_sw_B = !HAL_GPIO_ReadPin(MOTOR_LIMIT_SW_B_GPIO_Port, MOTOR_LIMIT_SW_B_Pin); check_home(); HAL_TIM_Base_Start(_motor_tim); motor_enable(true); if (_home) { taskENTER_CRITICAL(); HAL_GPIO_WritePin(MOTOR_DIR_GPIO_Port, MOTOR_DIR_Pin, MOTOR_PRESS_DIR); _motor_tim->Init.Period = home_step_us; HAL_TIM_Base_Init(_motor_tim); _motor_tim->Instance->CNT=0; _moving = true; _homing = false; HAL_TIM_PWM_Start(_motor_tim, MOTOR_TIM_CHANNEL); taskEXIT_CRITICAL(); while (_home) { wait_ms(2); } wait_ms(200); motor_stop(); wait_ms(500); } taskENTER_CRITICAL(); _homing = true; _moving = true; HAL_GPIO_WritePin(MOTOR_DIR_GPIO_Port, MOTOR_DIR_Pin, MOTOR_RELEASE_DIR); _motor_tim->Init.Period = home_step_us; HAL_TIM_Base_Init(_motor_tim); _motor_tim->Instance->CNT=0; HAL_TIM_PWM_Start(_motor_tim, MOTOR_TIM_CHANNEL); taskEXIT_CRITICAL(); while (!_home) { wait_ms(2); } } return true; } bool motor_release(uint32_t step_us) { motor_stop(); if (!_home) { taskENTER_CRITICAL(); HAL_GPIO_WritePin(MOTOR_DIR_GPIO_Port, MOTOR_DIR_Pin, MOTOR_RELEASE_DIR); _moving = true; _homing = true; _motor_tim->Init.Period = step_us; HAL_TIM_Base_Init(_motor_tim); _motor_tim->Instance->CNT=0; HAL_TIM_PWM_Start(_motor_tim, MOTOR_TIM_CHANNEL); taskEXIT_CRITICAL(); } return true; } bool motor_press(uint32_t *steps_profile_us, unsigned int nb_steps) { motor_stop(); if (nb_steps > 0) { taskENTER_CRITICAL(); motor_enable(true); HAL_GPIO_WritePin(MOTOR_DIR_GPIO_Port, MOTOR_DIR_Pin, MOTOR_PRESS_DIR); _moving = true; _motor_tim->Init.Period = steps_profile_us[0]; HAL_TIM_Base_Init(_motor_tim); _motor_tim->Instance->CNT=0; HAL_DMA_Init(_motor_tim->hdma[TIM_DMA_ID_UPDATE]); HAL_TIM_PWM_Start_IT(_motor_tim, MOTOR_TIM_CHANNEL); HAL_TIM_DMABurst_MultiWriteStart(_motor_tim, TIM_DMABASE_ARR, TIM_DMA_UPDATE, &steps_profile_us[1], TIM_DMABURSTLENGTH_1TRANSFER, nb_steps - 1); taskEXIT_CRITICAL(); } return true; } bool motor_stop() { taskENTER_CRITICAL(); if (_moving) { do_motor_stop(); } taskEXIT_CRITICAL(); return true; } void motor_enable(bool ena) { HAL_GPIO_WritePin(MOTOR_ENA_GPIO_Port, MOTOR_ENA_Pin, ena ? GPIO_PIN_SET : GPIO_PIN_RESET); } bool is_motor_moving() { return _moving; } bool is_motor_home() { return _home; } bool is_motor_ok() { return _motor_tim != NULL; } void motor_limit_sw_A_irq() { __disable_irq(); _limit_sw_A = !HAL_GPIO_ReadPin(MOTOR_LIMIT_SW_A_GPIO_Port, MOTOR_LIMIT_SW_A_Pin); check_home(); __enable_irq(); } void motor_limit_sw_B_irq() { __disable_irq(); _limit_sw_B = !HAL_GPIO_ReadPin(MOTOR_LIMIT_SW_B_GPIO_Port, MOTOR_LIMIT_SW_B_Pin); check_home(); __enable_irq(); } void motor_active_irq() { static uint32_t last_time = 0; uint32_t time = HAL_GetTick(); if (time - last_time > 10) { _active = HAL_GPIO_ReadPin(MOTOR_ACTIVE_GPIO_Port, MOTOR_ACTIVE_Pin); } last_time = time; } static void period_elapsed_callback(TIM_HandleTypeDef *tim) { __disable_irq(); do_motor_stop(); __enable_irq(); } static void check_home() { if (_limit_sw_A && _limit_sw_B) { _home = true; if (_homing) { do_motor_stop(); _homing = false; } } else { _home = false; } } static void do_motor_stop() { if (_moving) { HAL_TIM_DMABurst_WriteStop(_motor_tim, TIM_DMA_ID_UPDATE); HAL_DMA_DeInit(_motor_tim->hdma[TIM_DMA_ID_UPDATE]); HAL_TIM_PWM_Stop(_motor_tim, MOTOR_TIM_CHANNEL); _moving = false; } }
2.0625
2
2024-11-18T21:05:51.513162+00:00
2018-02-01T10:43:18
bbe9819f1defa0b2480f55f20ee4c899b406ae7e
{ "blob_id": "bbe9819f1defa0b2480f55f20ee4c899b406ae7e", "branch_name": "refs/heads/master", "committer_date": "2018-02-01T10:43:18", "content_id": "b2d606aa190801a6269058b0d915bf603eacfd90", "detected_licenses": [ "MIT" ], "directory_id": "caa520ae1ab2fb14fa78bcdd353bd7d1195006c2", "extension": "c", "filename": "ow_search.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3694, "license": "MIT", "license_type": "permissive", "path": "/ow_search.c", "provenance": "stackv2-0083.json.gz:1402", "repo_name": "gavinlwz/1wire-search", "revision_date": "2018-02-01T10:43:18", "revision_id": "cc979602f3752019979a18f79b30fe8c187cad75", "snapshot_id": "8ed3acedfc23fcd19b0840442a095c7880d3b08b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gavinlwz/1wire-search/cc979602f3752019979a18f79b30fe8c187cad75/ow_search.c", "visit_date": "2021-09-06T01:39:18.923109" }
stackv2
// // Created by MightyPork on 2018/02/01. // MIT license // #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include "ow_search.h" // -------- CHECKSUM -------- static inline uint8_t crc8_bits(uint8_t data) { uint8_t crc = 0; if(data & 1) crc ^= 0x5e; if(data & 2) crc ^= 0xbc; if(data & 4) crc ^= 0x61; if(data & 8) crc ^= 0xc2; if(data & 0x10) crc ^= 0x9d; if(data & 0x20) crc ^= 0x23; if(data & 0x40) crc ^= 0x46; if(data & 0x80) crc ^= 0x8c; return crc; } static uint8_t crc8_add(uint8_t cksum, uint8_t byte) { return crc8_bits(byte ^ cksum); } uint8_t ow_checksum(const uint8_t *buff, uint16_t len) { uint8_t cksum = 0; for(uint16_t i = 0; i < len; i++) { cksum = crc8_add(cksum, buff[i]); } return cksum; } // ----------------------------- void ow_search_init(struct ow_search_state *state, uint8_t command, bool test_checksums) { state->prev_last_fork = 64; memset(state->prev_code, 0, 8); state->status = OW_SEARCH_MORE; state->command = command; state->first = true; state->test_checksums = test_checksums; } uint16_t ow_search_run(struct ow_search_state *state, ow_romcode_t *codes, uint16_t capacity) { if (state->status != OW_SEARCH_MORE) return 0; uint16_t found_devices = 0; while (found_devices < capacity) { uint8_t index = 0; ow_romcode_t code = {}; int8_t last_fork = -1; // Start a new transaction. Devices respond to reset if (!ow_reset()) { state->status = OW_SEARCH_FAILED; goto done; } // Send the search command (SEARCH_ROM, SEARCH_ALARM) ow_write_u8(state->command); uint8_t *code_byte = &code[0]; bool p, n; while (index != 64) { // Read a bit and its complement p = ow_read_bit(); n = ow_read_bit(); if (!p && !n) { // A fork: there are devices on the bus with different bit value // (the bus is open-drain, in both cases one device pulls it low) if ((found_devices > 0 || !state->first) && index < state->prev_last_fork) { // earlier than the last fork, take the same turn as before p = ow_code_getbit(state->prev_code, index); if (!p) last_fork = index; // remember for future runs, 1 not explored yet } else if (index == state->prev_last_fork) { p = 1; // both forks are now exhausted } else { // a new fork last_fork = index; } } else if (p && n) { // No devices left connected - this doesn't normally happen state->status = OW_SEARCH_FAILED; goto done; } // All devices have a matching bit here, or it was resolved in a fork if (p) *code_byte |= (1 << (index & 7)); ow_write_bit(p); index++; if((index & 7) == 0) { code_byte++; } } memcpy(state->prev_code, code, 8); if (!state->test_checksums || 0 == ow_checksum(code, 8)) { // Record a found address memcpy(codes[found_devices], code, 8); found_devices++; } // Stop condition if (last_fork == -1) { state->status = OW_SEARCH_DONE; goto done; } state->prev_last_fork = last_fork; } done: state->first = false; return found_devices; }
2.734375
3
2024-11-18T21:05:51.734547+00:00
2023-08-29T06:33:10
c768315a6523ba64b0e9d311d2189ecec0ade285
{ "blob_id": "c768315a6523ba64b0e9d311d2189ecec0ade285", "branch_name": "refs/heads/master", "committer_date": "2023-08-29T06:33:10", "content_id": "392e90449ffc91f714ecc2abce9d4e4e27e89cd8", "detected_licenses": [ "Apache-2.0" ], "directory_id": "676acab8ff535019faff7da3afb8eecc3fa127f5", "extension": "c", "filename": "drv_i2c_soft.c", "fork_events_count": 143, "gha_created_at": "2021-09-02T20:42:56", "gha_event_created_at": "2023-09-12T05:28:39", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 402557689, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4248, "license": "Apache-2.0", "license_type": "permissive", "path": "/target/amov/icf5/drivers/drv_i2c_soft.c", "provenance": "stackv2-0083.json.gz:1660", "repo_name": "Firmament-Autopilot/FMT-Firmware", "revision_date": "2023-08-29T06:33:10", "revision_id": "0212fe89820376bfbedaded519552f6b011a7b8a", "snapshot_id": "f8c324577245bd7e91af436954b4ce9421acbb41", "src_encoding": "UTF-8", "star_events_count": 351, "url": "https://raw.githubusercontent.com/Firmament-Autopilot/FMT-Firmware/0212fe89820376bfbedaded519552f6b011a7b8a/target/amov/icf5/drivers/drv_i2c_soft.c", "visit_date": "2023-09-01T11:37:46.194145" }
stackv2
/****************************************************************************** * Copyright 2020-2021 The Firmament Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <firmament.h> #include "drv_i2c_soft.h" #include "hal/i2c/i2c.h" #include "hal/i2c/i2c_bit_ops.h" #define BSP_I2C0_SCL_PORT GPIOB #define BSP_I2C0_SDA_PORT GPIOB #define BSP_I2C0_SCL_PIN GPIO_PIN_8 #define BSP_I2C0_SDA_PIN GPIO_PIN_9 #define I2C_DELAY_US (10) #define I2C_TIMEOUT_TICKS TICKS_FROM_MS(1) static struct rt_i2c_bus i2c0_dev; void gd32_set_sda(void* data, rt_int32_t state) { struct rt_i2c_bus* i2c_bus = (struct rt_i2c_bus*)data; if (i2c_bus == &i2c0_dev) { if (state == 1) gpio_bit_set(BSP_I2C0_SDA_PORT, BSP_I2C0_SDA_PIN); else if (state == 0) gpio_bit_reset(BSP_I2C0_SDA_PORT, BSP_I2C0_SDA_PIN); } } void gd32_set_scl(void* data, rt_int32_t state) { struct rt_i2c_bus* i2c_bus = (struct rt_i2c_bus*)data; if (i2c_bus == &i2c0_dev) { if (state == 1) gpio_bit_set(BSP_I2C0_SCL_PORT, BSP_I2C0_SCL_PIN); else if (state == 0) gpio_bit_reset(BSP_I2C0_SCL_PORT, BSP_I2C0_SCL_PIN); } } rt_int32_t gd32_get_sda(void* data) { rt_int32_t val; struct rt_i2c_bus* i2c_bus = (struct rt_i2c_bus*)data; if (i2c_bus == &i2c0_dev) { gpio_mode_set(BSP_I2C0_SDA_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, BSP_I2C0_SDA_PIN); val = (rt_int32_t)gpio_input_bit_get(BSP_I2C0_SDA_PORT, BSP_I2C0_SDA_PIN); gpio_mode_set(BSP_I2C0_SDA_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, BSP_I2C0_SDA_PIN); } return val; } rt_int32_t gd32_get_scl(void* data) { rt_int32_t val; struct rt_i2c_bus* i2c_bus = (struct rt_i2c_bus*)data; if (i2c_bus == &i2c0_dev) { gpio_mode_set(BSP_I2C0_SCL_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, BSP_I2C0_SCL_PIN); val = (rt_int32_t)gpio_input_bit_get(BSP_I2C0_SCL_PORT, BSP_I2C0_SCL_PIN); gpio_mode_set(BSP_I2C0_SCL_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, BSP_I2C0_SCL_PIN); } return val; } rt_inline void gd32_udelay(rt_uint32_t us) { systime_udelay(us); } static rt_err_t gd32_i2c_pin_init(struct rt_i2c_bus* i2c_bus) { if (i2c_bus == &i2c0_dev) { gpio_output_options_set(BSP_I2C0_SCL_PORT, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, BSP_I2C0_SCL_PIN); gpio_mode_set(BSP_I2C0_SCL_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, BSP_I2C0_SCL_PIN); gpio_output_options_set(BSP_I2C0_SDA_PORT, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ, BSP_I2C0_SDA_PIN); gpio_mode_set(BSP_I2C0_SDA_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, BSP_I2C0_SDA_PIN); } else { return RT_EINVAL; } return RT_EOK; } struct rt_i2c_bit_ops gd32_i2c0_bit_ops = { (void*)NULL, gd32_set_sda, gd32_set_scl, gd32_get_sda, gd32_get_scl, gd32_udelay, I2C_DELAY_US, I2C_TIMEOUT_TICKS }; /* i2c device instances */ static struct rt_i2c_device i2c0_dev0 = { .slave_addr = 0x45, /* AW2023 7 bit address */ .flags = 0 }; static struct rt_i2c_device i2c0_dev1 = { .slave_addr = 0x28, /* MS4525 7 bit address */ .flags = 0 }; rt_err_t drv_i2c_soft_init(void) { gd32_i2c0_bit_ops.data = &i2c0_dev; i2c0_dev.priv = (void*)&gd32_i2c0_bit_ops; i2c0_dev.retries = 3; gd32_i2c_pin_init(&i2c0_dev); rt_i2c_soft_bus_register(&i2c0_dev, "i2c0"); /* attach i2c devices */ RT_TRY(rt_i2c_bus_attach_device(&i2c0_dev0, "i2c0_dev0", "i2c0", RT_NULL)); /* attach i2c devices */ RT_TRY(rt_i2c_bus_attach_device(&i2c0_dev1, "i2c0_dev1", "i2c0", RT_NULL)); return RT_EOK; }
2.078125
2
2024-11-18T21:05:51.932738+00:00
2021-10-16T05:49:22
34968d6c10699581c37a594978dbde7120a61950
{ "blob_id": "34968d6c10699581c37a594978dbde7120a61950", "branch_name": "refs/heads/main", "committer_date": "2021-10-16T07:31:21", "content_id": "d287e93092abe1806496af6be880e8d5cb40618c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "91729ccf7286bddffb04df2f4889462e4a40a294", "extension": "c", "filename": "riscv_fast_math.c", "fork_events_count": 0, "gha_created_at": "2021-06-05T00:30:58", "gha_event_created_at": "2021-06-05T00:30:59", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 373988418, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4231, "license": "Apache-2.0", "license_type": "permissive", "path": "/NMSIS/DSP/Test/FastMathFunctions/trigonometricPart/riscv_fast_math.c", "provenance": "stackv2-0083.json.gz:2045", "repo_name": "soburi/NMSIS", "revision_date": "2021-10-16T05:49:22", "revision_id": "bfb0709d919e9fb3d96a8c75b5d04500943b7240", "snapshot_id": "dd244e2ebcd0424f361286b475e3a447c4003271", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/soburi/NMSIS/bfb0709d919e9fb3d96a8c75b5d04500943b7240/NMSIS/DSP/Test/FastMathFunctions/trigonometricPart/riscv_fast_math.c", "visit_date": "2023-08-22T03:35:32.818232" }
stackv2
// // Created by lujun on 19-6-28. // // This contains sin, cos and sqrt calculates // each one has it's own function. // All function can be found in main function. // If you don't want to use it, then comment it. #include "riscv_math.h" #include <stdint.h> #include <stdlib.h> #include "../common.h" #include "../HelperFunctions/math_helper.c" #include "../HelperFunctions/ref_helper.c" #include <stdio.h> #define DELTAF32 (0.05f) #define DELTAQ31 (63) #define DELTAQ15 (1) #define DELTAQ7 (1) int test_flag_error = 0; static int DSP_COS(void) { // f32_cos float32_t f32_cosoutput, f32_cosoutput_ref; uint16_t i; BENCH_START(riscv_cos_f32); for (int i = 0; i < 1000; i++) f32_cosoutput = riscv_cos_f32(PI); BENCH_END(riscv_cos_f32); f32_cosoutput_ref = ref_cos_f32(PI); if (fabs(f32_cosoutput - f32_cosoutput_ref) > DELTAF32) { BENCH_ERROR(riscv_cos_f32); printf("expect: %f, actual: %f\n", f32_cosoutput_ref, f32_cosoutput); test_flag_error = 1; } BENCH_STATUS(riscv_cos_f32); // q31_cos q31_t q31_cosoutput, q31_cosoutput_ref; BENCH_START(riscv_cos_q31); for (int i = 0; i < 1000; i++) q31_cosoutput = riscv_cos_q31(0x7ffffff0); BENCH_END(riscv_cos_q31); q31_cosoutput_ref = ref_cos_q31(0x7ffffff0); if (labs(q31_cosoutput - q31_cosoutput_ref) > DELTAQ31) { BENCH_ERROR(riscv_cos_q31); printf("expect: %x, actual: %x\n", q31_cosoutput_ref, q31_cosoutput); test_flag_error = 1; } BENCH_STATUS(riscv_cos_q31); // q15_cos q15_t q15_cosoutput, q15_cosoutput_ref; BENCH_START(riscv_cos_q15); for (int i = 0; i < 1000; i++) q15_cosoutput = riscv_cos_q15(0x7000); BENCH_END(riscv_cos_q15); q15_cosoutput_ref = ref_cos_q15(0x7000); if (abs(q15_cosoutput - q15_cosoutput_ref) > DELTAQ15) { BENCH_ERROR(riscv_cos_q15); printf("expect: %x, actual: %x\n", q15_cosoutput_ref, q15_cosoutput); test_flag_error = 1; } BENCH_STATUS(riscv_cos_q15); printf("all cos tests are passed,well done!\n"); } /* ********************************************************************************************************* * 函 数 名: DSP_Sine * 功能说明: 求sine函数 * 形 参:无 * 返 回 值: 无 ********************************************************************************************************* */ static int DSP_SIN(void) { // f32_sin float32_t f32_sinoutput, f32_sinoutput_ref; uint16_t i; BENCH_START(riscv_sin_f32); for (int i = 0; i < 1000; i++) f32_sinoutput = riscv_sin_f32(PI); BENCH_END(riscv_sin_f32); f32_sinoutput_ref = ref_sin_f32(PI); if (fabs(f32_sinoutput - f32_sinoutput_ref) > DELTAF32) { BENCH_ERROR(riscv_sin_f32); printf("expect: %f, actual: %f\n", f32_sinoutput_ref, f32_sinoutput); test_flag_error = 1; } BENCH_STATUS(riscv_sin_f32); // q31_sin q31_t q31_sinoutput, q31_sinoutput_ref; BENCH_START(riscv_sin_q31); for (int i = 0; i < 1000; i++) q31_sinoutput = riscv_sin_q31(PI); BENCH_END(riscv_sin_q31); q31_sinoutput_ref = ref_sin_q31(PI); if (labs(q31_sinoutput - q31_sinoutput_ref) > DELTAQ31) { BENCH_ERROR(riscv_sin_q31); printf("expect: %x, actual: %x\n", q31_sinoutput_ref, q31_sinoutput); test_flag_error = 1; } BENCH_STATUS(riscv_sin_q31); // q15_sin q15_t q15_sinoutput, q15_sinoutput_ref; BENCH_START(riscv_sin_q15); for (int i = 0; i < 1000; i++) q15_sinoutput = riscv_sin_q15(PI); BENCH_END(riscv_sin_q15); q15_sinoutput_ref = ref_sin_q15(PI); if (abs(q15_sinoutput - q15_sinoutput_ref) > DELTAQ15) { BENCH_ERROR(riscv_sin_q15); printf("expect: %x, actual: %x\n", q15_sinoutput_ref, q15_sinoutput); test_flag_error = 1; } BENCH_STATUS(riscv_sin_q15); printf("all sin tests are passed,well done!\n"); } int main() { BENCH_INIT; DSP_COS(); DSP_SIN(); BENCH_FINISH; if (test_flag_error) { printf("test error apprears, please recheck.\n"); return 1; } else { printf("all test are passed. Well done!\n"); } return 0; }
2.59375
3
2024-11-18T21:05:52.756226+00:00
2018-10-14T18:29:19
2cce4394e2dd63042a27eba2d1a0cb432791dbb6
{ "blob_id": "2cce4394e2dd63042a27eba2d1a0cb432791dbb6", "branch_name": "refs/heads/master", "committer_date": "2018-10-14T18:29:19", "content_id": "a83cc67c8a27fb9e2809d9dd80c9ac96daba3a0b", "detected_licenses": [ "MIT" ], "directory_id": "0f140a1af4389803df75b9aa79018ddbf4b4ed42", "extension": "c", "filename": "sqlsfromcsv.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2496, "license": "MIT", "license_type": "permissive", "path": "/src/sqlsfromcsv.c", "provenance": "stackv2-0083.json.gz:2561", "repo_name": "OsvaldoJ/multicoresql", "revision_date": "2018-10-14T18:29:19", "revision_id": "c6f7acc875e5f4ef66eee216cf5f7648ff53f5e6", "snapshot_id": "69f5df8c7327a1c39a50c4fb8b7193146e85923c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/OsvaldoJ/multicoresql/c6f7acc875e5f4ef66eee216cf5f7648ff53f5e6/src/sqlsfromcsv.c", "visit_date": "2023-03-19T04:02:59.086421" }
stackv2
/* sqlsfromcsv.c Copyright 2015 Paul Brewer <drpaulbrewer@eaftc.com> Economic and Financial Technology Consulting LLC License: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "multicoresql.h" long int get_long_int_or_die(const char *instring, const char *errfmt){ long int result = strtol(instring, NULL, 10); if ((0==result) && (errno)){ fprintf(stderr, errfmt, instring); exit(EXIT_FAILURE); } return result; } int main(int argc, char **argv){ if (argc!=7){ fprintf(stderr, "%s\n%s\n", "Usage: sqlsfromcsv csvfile skiplines schemafile tablename dbDir shardcount", "Example: sqlsfromcsv example.csv 1 createmytable.sql mytable ./mytable 100"); exit(EXIT_FAILURE); } int skiplines = 0; int shardcount = 0; const char *csvname = argv[1]; skiplines = (int) get_long_int_or_die(argv[2], "sqlsfromcsv: parameter skiplines, expected number of lines to skip, got: %s \n"); if (skiplines < 0) skiplines = -skiplines; const char *schemaname = argv[3]; const char *tablename = argv[4]; const char *dbDir = argv[5]; shardcount = (int) get_long_int_or_die(argv[6], "sqlsfromscsv: expected positive number of shards, got: %s \n"); if (shardcount<0) shardcount = -shardcount; if (shardcount<3) shardcount=3; int status = mu_create_shards_from_csv(csvname,skiplines,schemaname,tablename,dbDir,shardcount); const char *err = mu_error_string(); if (err) fputs(err,stderr); return status; }
2.15625
2
2024-11-18T21:05:53.010924+00:00
2019-08-06T14:24:54
034499e346e227c41069e944f54abbb936c911c9
{ "blob_id": "034499e346e227c41069e944f54abbb936c911c9", "branch_name": "refs/heads/master", "committer_date": "2019-08-06T14:24:54", "content_id": "7a5f5400564461e86b69e3bea0b98cfee6c754b6", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "021a3ccdcb91d84629f1de7343981b572840b169", "extension": "c", "filename": "ex5.c", "fork_events_count": 8, "gha_created_at": "2016-02-22T11:40:41", "gha_event_created_at": "2023-04-11T09:20:08", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 52269402, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6932, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/dm/impls/stag/examples/tests/ex5.c", "provenance": "stackv2-0083.json.gz:2817", "repo_name": "firedrakeproject/petsc", "revision_date": "2019-08-06T14:24:54", "revision_id": "7afe75c1a0a66862f32d7a0f5c0c5ae5079c4c77", "snapshot_id": "dcf7b32e83bdc88d37099904960d7a4c3c4a89e4", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/firedrakeproject/petsc/7afe75c1a0a66862f32d7a0f5c0c5ae5079c4c77/src/dm/impls/stag/examples/tests/ex5.c", "visit_date": "2023-08-31T22:16:45.175956" }
stackv2
static char help[] = "Test DMStag ghosted boundaries in 1d\n\n"; /* This solves a very contrived problem - the "pressure" terms are set to a constant function and the "velocity" terms are just the sum of neighboring values of these, hence twice the constant */ #include <petscdm.h> #include <petscksp.h> #include <petscdmstag.h> #define LEFT DMSTAG_LEFT #define RIGHT DMSTAG_RIGHT #define ELEMENT DMSTAG_ELEMENT #define PRESSURE_CONST 2.0 PetscErrorCode ApplyOperator(Mat,Vec,Vec); int main(int argc,char **argv) { PetscErrorCode ierr; DM dmSol; Vec sol,solRef,solRefLocal,rhs,rhsLocal; Mat A; KSP ksp; PC pc; PetscInt start,n,e,nExtra; PetscInt iu,ip; PetscScalar **arrSol,**arrRHS; ierr = PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr; ierr = DMStagCreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_GHOSTED,3,1,1,DMSTAG_STENCIL_BOX,1,NULL,&dmSol);CHKERRQ(ierr); ierr = DMSetFromOptions(dmSol);CHKERRQ(ierr); ierr = DMSetUp(dmSol);CHKERRQ(ierr); /* Compute reference solution on the grid, using direct array access */ ierr = DMCreateGlobalVector(dmSol,&rhs);CHKERRQ(ierr); ierr = DMCreateGlobalVector(dmSol,&solRef);CHKERRQ(ierr); ierr = DMGetLocalVector(dmSol,&solRefLocal);CHKERRQ(ierr); ierr = DMGetLocalVector(dmSol,&rhsLocal);CHKERRQ(ierr); ierr = DMStagVecGetArrayDOF(dmSol,solRefLocal,&arrSol);CHKERRQ(ierr); ierr = DMStagGetCorners(dmSol,&start,NULL,NULL,&n,NULL,NULL,&nExtra,NULL,NULL);CHKERRQ(ierr); ierr = DMStagVecGetArrayDOF(dmSol,rhsLocal,&arrRHS);CHKERRQ(ierr); /* Get the correct entries for each of our variables in local element-wise storage */ ierr = DMStagGetLocationSlot(dmSol,LEFT,0,&iu);CHKERRQ(ierr); ierr = DMStagGetLocationSlot(dmSol,ELEMENT,0,&ip);CHKERRQ(ierr); for (e=start; e<start+n+nExtra; ++e) { { arrSol[e][iu] = 2*PRESSURE_CONST; arrRHS[e][iu] = 0.0; } if (e < start+n) { arrSol[e][ip] = PRESSURE_CONST; arrRHS[e][ip] = PRESSURE_CONST; } } ierr = DMStagVecRestoreArrayDOF(dmSol,rhsLocal,&arrRHS);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(dmSol,rhsLocal,INSERT_VALUES,rhs);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(dmSol,rhsLocal,INSERT_VALUES,rhs);CHKERRQ(ierr); ierr = DMStagVecRestoreArrayDOF(dmSol,solRefLocal,&arrSol);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(dmSol,solRefLocal,INSERT_VALUES,solRef);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(dmSol,solRefLocal,INSERT_VALUES,solRef);CHKERRQ(ierr); ierr = DMRestoreLocalVector(dmSol,&solRefLocal);CHKERRQ(ierr); ierr = DMRestoreLocalVector(dmSol,&rhsLocal);CHKERRQ(ierr); /* Matrix-free Operator */ ierr = DMSetMatType(dmSol,MATSHELL);CHKERRQ(ierr); ierr = DMCreateMatrix(dmSol,&A);CHKERRQ(ierr); ierr = MatShellSetOperation(A,MATOP_MULT,(void(*) (void)) ApplyOperator);CHKERRQ(ierr); /* Solve */ ierr = DMCreateGlobalVector(dmSol,&sol);CHKERRQ(ierr); ierr = KSPCreate(PETSC_COMM_WORLD,&ksp);CHKERRQ(ierr); ierr = KSPSetOperators(ksp,A,A);CHKERRQ(ierr); ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr); ierr = PCSetType(pc,PCNONE);CHKERRQ(ierr); ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr); ierr = KSPSolve(ksp,rhs,sol);CHKERRQ(ierr); /* Check Solution */ { Vec diff; PetscReal normsolRef,errAbs,errRel; ierr = VecDuplicate(sol,&diff);CHKERRQ(ierr); ierr = VecCopy(sol,diff);CHKERRQ(ierr); ierr = VecAXPY(diff,-1.0,solRef);CHKERRQ(ierr); ierr = VecNorm(diff,NORM_2,&errAbs);CHKERRQ(ierr); ierr = VecNorm(solRef,NORM_2,&normsolRef);CHKERRQ(ierr); errRel = errAbs/normsolRef; if (errAbs > 1e14 || errRel > 1e14) { ierr = PetscPrintf(PetscObjectComm((PetscObject)dmSol),"Error (abs): %g\nError (rel): %g\n",(double)errAbs,(double)errRel);CHKERRQ(ierr); ierr = PetscPrintf(PetscObjectComm((PetscObject)dmSol),"Non-zero error. Probable failure.\n");CHKERRQ(ierr); } ierr = VecDestroy(&diff);CHKERRQ(ierr); } ierr = KSPDestroy(&ksp);CHKERRQ(ierr); ierr = VecDestroy(&sol);CHKERRQ(ierr); ierr = VecDestroy(&solRef);CHKERRQ(ierr); ierr = VecDestroy(&rhs);CHKERRQ(ierr); ierr = MatDestroy(&A);CHKERRQ(ierr); ierr = DMDestroy(&dmSol);CHKERRQ(ierr); ierr = PetscFinalize(); return ierr; } PetscErrorCode ApplyOperator(Mat A,Vec in,Vec out) { PetscErrorCode ierr; DM dm; Vec inLocal,outLocal; PetscScalar **arrIn; PetscScalar **arrOut; PetscInt start,n,nExtra,ex,idxP,idxU,startGhost,nGhost; DMBoundaryType boundaryType; PetscBool isFirst,isLast; PetscFunctionBeginUser; ierr = MatGetDM(A,&dm);CHKERRQ(ierr); ierr = DMStagGetBoundaryTypes(dm,&boundaryType,NULL,NULL);CHKERRQ(ierr); if (boundaryType != DM_BOUNDARY_GHOSTED) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_INCOMP,"Ghosted boundaries required"); ierr = DMGetLocalVector(dm,&inLocal);CHKERRQ(ierr); ierr = DMGetLocalVector(dm,&outLocal);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(dm,in,INSERT_VALUES,inLocal);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(dm,in,INSERT_VALUES,inLocal);CHKERRQ(ierr); ierr = DMStagGetCorners(dm,&start,NULL,NULL,&n,NULL,NULL,&nExtra,NULL,NULL);CHKERRQ(ierr); ierr = DMStagGetGhostCorners(dm,&startGhost,NULL,NULL,&nGhost,NULL,NULL);CHKERRQ(ierr); ierr = DMStagVecGetArrayDOFRead(dm,inLocal,&arrIn);CHKERRQ(ierr); ierr = DMStagVecGetArrayDOF(dm,outLocal,&arrOut);CHKERRQ(ierr); ierr = DMStagGetLocationSlot(dm,LEFT,0,&idxU);CHKERRQ(ierr); ierr = DMStagGetLocationSlot(dm,ELEMENT,0,&idxP);CHKERRQ(ierr); ierr = DMStagGetIsFirstRank(dm,&isFirst,NULL,NULL);CHKERRQ(ierr); ierr = DMStagGetIsLastRank(dm,&isLast,NULL,NULL);CHKERRQ(ierr); /* Set "pressures" on ghost boundaries by copying neighboring values*/ if (isFirst) { arrIn[-1][idxP] = arrIn[0][idxP]; } if (isLast){ arrIn[start + n][idxP] = arrIn[start + n - 1][idxP]; } /* Apply operator on physical points */ for (ex=start; ex<start + n + nExtra; ++ex) { if (ex < start + n) { /* Don't compute pressure outside domain */ arrOut[ex][idxP] = arrIn[ex][idxP]; } arrOut[ex][idxU] = arrIn[ex][idxP] + arrIn[ex-1][idxP] - arrIn[ex][idxU]; } ierr = DMStagVecRestoreArrayDOFRead(dm,inLocal,&arrIn);CHKERRQ(ierr); ierr = DMStagVecRestoreArrayDOF(dm,outLocal,&arrOut);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(dm,outLocal,INSERT_VALUES,out);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(dm,outLocal,INSERT_VALUES,out);CHKERRQ(ierr); ierr = DMRestoreLocalVector(dm,&inLocal);CHKERRQ(ierr); ierr = DMRestoreLocalVector(dm,&outLocal);CHKERRQ(ierr); PetscFunctionReturn(0); } /*TEST test: suffix: 1 nsize: 1 test: suffix: 2 nsize: 2 test: suffix: 3 nsize: 3 args: -stag_grid_x 19 test: suffix: 4 nsize: 5 args: -stag_grid_x 21 -stag_stencil_width 2 TEST*/
2.296875
2
2024-11-18T21:05:53.139864+00:00
2016-02-01T01:03:14
5e7781bea864ca18796d89eacaa36580b3a1f670
{ "blob_id": "5e7781bea864ca18796d89eacaa36580b3a1f670", "branch_name": "refs/heads/master", "committer_date": "2016-02-01T01:03:14", "content_id": "386e340c76d7bb9843fb80a32407aa7051f5cf56", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "3eadad0711e70790ce93b0c2bfd66d645c80d5cc", "extension": "c", "filename": "numerus_cli.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 48202895, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11793, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/src/numerus_cli.c", "provenance": "stackv2-0083.json.gz:3075", "repo_name": "TheMatjaz/Numerus", "revision_date": "2016-02-01T01:03:14", "revision_id": "61fc67bfbf88707d8fef6fdc7aea644d2922cd09", "snapshot_id": "5ce6e60116b6ab1b26da9178036d582c72b1f3eb", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/TheMatjaz/Numerus/61fc67bfbf88707d8fef6fdc7aea644d2922cd09/src/numerus_cli.c", "visit_date": "2021-05-04T10:28:39.011578" }
stackv2
/** * @file numerus_cli.c * @brief Numerus command line interface for user-friendly conversions. * @copyright Copyright © 2015-2016, Matjaž Guštin <dev@matjaz.it> * <http://matjaz.it>. All rights reserved. * @license This file is part of the Numerus project which is released under * the BSD 3-clause license. * * This file contains a command line interface that converts any typed value * to a roman numeral or vice-versa. To use it, just call * * `numerus_cli(argc, args);` * * with `argc` and `args` the arguments of the main. This allows any command * line parameters passed to the numerus executable to be interpreted as if * they were written withing the command line interface. */ #include <stdio.h> /* For `printf()` */ #include <stdlib.h> /* For `malloc()`, `free()`, `strtod()` */ #include <ctype.h> /* For `isspace()`, `tolower()` */ #include <string.h> /* For `strcmp()` */ #include "numerus.h" /** * @internal * Macro to indicate that the CLI should continue its execution. */ #define NUMERUS_PROMPT_AGAIN 1 /** * @internal * Macro ro indicate that the CLI should terminate. */ #define NUMERUS_STOP_REPL 0 static const char *PROMPT_TEXT = "numerus> "; static const char *WELCOME_TEXT = "" "+-----------------+\n" "| N V M E R V S |\n" "+-----------------+\n"; static const char *INFO_TEXT = "" "Numerus, C library for conversion and manipulation of roman numerals.\n" "Version 2.0.0, Command Line Interface\n" "Copyright (c) 2015-2016 Matjaž Guštin <dev@matjaz.it> http://matjaz.it\n" "This software is subject to the terms of the BSD 3-Clause license.\n" "Project page and source code: https://github.com/TheMatjaz/Numerus\n"; static const char *MOO_TEXT = "This is not an easter egg. Try `ascii`.\n"; static const char *PING_TEXT = "Pong.\n"; static const char *AVE_TEXT = "Ave tibi!\n"; static const char *HELP_TEXT = "" "For ANY information about the library or the syntax of roman numeral, \n" "check the documentation available on https://thematjaz.github.io/Numerus/\n\n" "" "To convert an (arabic) integer to a roman numeral or vice-versa,\n" "just type it in the shell and press enter.\n" "Other Numerus commands are:\n\n" "" "pretty switches on/off the pretty printing of long roman numerals\n" " (with overlined notation instead of underscore notation)\n" " and the pretty printing of values as integer and fractional part\n" "?, help shows this help text\n" "info, about shows version, credits, licence, repository of Numerus\n" "exit, quit ends this shell\n\n" "" "We also have: moo, ping, ave.\n"; static const char *QUIT_TEXT = "Vale!\n"; static const char *ASCII_TEXT = "" " ____ _____ ____ ____ ____ ____ _________ _______ ____ ____ _______ \n" "|_ \\|_ _| |_ _| |_ _| |_ \\ / _| |_ ___ | |_ __ \\ |_ _| |_ _| / ___ |\n" " | \\ | | \\ \\ / / | \\/ | | |_ \\_| | |__) | \\ \\ / / | (__ \\_|\n" " | |\\ \\| | \\ \\ / / | |\\ /| | | _| _ | __ / \\ \\ / / '.___`-. \n" " _| |_\\ |_ \\ ' / _| |_\\/_| |_ _| |___/ | _| | \\ \\_ \\ ' / |`\\____) |\n" "|_____|\\____| \\_/ |_____||_____| |_________| |____| |___| \\_/ |_______.'\n"; static const char *UNKNOWN_COMMAND_TEXT = "Unknown command or wrong roman numeral syntax:\n"; static const char *PRETTY_ON_TEXT = "Pretty printing is enabled.\n"; static const char *PRETTY_OFF_TEXT = "Pretty printing is disabled.\n"; static int pretty_printing = 0; /** * Returns a pointer the first word of string that is terminated after that. * * Modifies the original string, because of the null-termination after the * first word. * * The extracted word is also lowercased. Do not free() the pointer returned * by this function, as it may not point to the start of the original string. * free() the original pointer to it. * * @param char* string to find the first word in. * @returns char* pointer to the start of the first word in the passed string. */ static char *_num_get_first_word_trimmed_lowercased(char *string) { while(isspace(*string)) { string++; } if(*string == '\0') { /* The string was full of whitespaces */ return string; } char *first_word_start = string; while (*string != '\0' && !isspace(*string)) { *string = (char) tolower(*string); string++; } *string = '\0'; return first_word_start; } /** * Verifies if a string is just any strange form of a double with value zero. * * This includes: (-)0, (-)000.000, (-)000,000 (with decimal comma). * * @param char* containing a zero-valued double. * @returns short 1 if the string contains a zero-valued double, 0 otherwise. */ static short _num_string_is_double_zero(char *zero_as_string) { if (*zero_as_string == '-') { zero_as_string++; } while (*zero_as_string == '0') { zero_as_string++; } if (*zero_as_string == '.' || *zero_as_string == ',') { zero_as_string++; if (*zero_as_string == '0') { while (*zero_as_string == '0') { zero_as_string++; } } else { return 0; } } if (*zero_as_string == '\0') { return 1; } else { return 0; } } /** * Tries to convert the string from a double to roman numeral then vice versa * and prints the result to stdout. * * If no conversion can be done (for instance because of wrong roman syntax or * the string is not a value not a roman), an error is printed. If the pretty * printing options is activated, performs it. * * @param char* string containing a value or a roman numeral. * @returns void since prints the result to stdout. */ void _num_convert_to_other_form_and_print(char *string) { double value; char *roman; int errcode; /* This check is necessary because strtod() returns 0 in case of errors * AND in case finds an actual zero. Duh! */ if (_num_string_is_double_zero(string)) { printf("%s\n", roman = numerus_double_to_roman(0, NULL)); free(roman); return; } value = strtod(string, NULL); if (value != 0) { /* The string is a double */ roman = numerus_double_to_roman(value, &errcode); if (errcode != NUMERUS_OK) { printf("%s\n", numerus_explain_error(errcode)); if (errcode != NUMERUS_ERROR_MALLOC_FAIL) { free(roman); } return; } /* Successful conversion */ if (pretty_printing == 1) { /* Enabled pretty printing */ char *roman_pretty = numerus_overline_long_numerals(roman, &errcode); if (errcode != NUMERUS_OK) { printf("%s\n", numerus_explain_error(errcode)); } else { /* Successful transformed into pretty format */ printf("%s\n", roman_pretty); free(roman_pretty); } } else { /* Disabled pretty printing, just print the roman numeral */ printf("%s\n", roman); } free(roman); return; } /* The string is not a double, trying as a roman numeral */ value = numerus_roman_to_double(string, &errcode); if (errcode == NUMERUS_OK) { /* The string is a roman numeral */ if (pretty_printing == 1) { /* Pretty printing enabled */ char *pretty_value = numerus_create_pretty_value_as_double(value); if (pretty_value == NULL) { printf("%s\n", numerus_explain_error(NUMERUS_ERROR_MALLOC_FAIL)); } else { /* Successful transformed into pretty format */ printf("%s\n", pretty_value); free(pretty_value); } } else { /* Pretty printing disabled, just print the value */ printf("%f\n", value); } } else { /* The command is not a value/a roman numeral or it has wrong syntax */ printf("%s -> %s\n", UNKNOWN_COMMAND_TEXT, numerus_explain_error(errcode)); } } /** * Parses the already cleaned command and reacts accordingly. * * Command should be already trimmed and lowercased. */ static int _num_parse_command(char *command) { if (strcmp(command, "?") == 0 || strcmp(command, "help") == 0) { printf("%s", HELP_TEXT); return NUMERUS_PROMPT_AGAIN; } else if (strcmp(command, "moo") == 0) { printf("%s", MOO_TEXT); return NUMERUS_PROMPT_AGAIN; } else if (strcmp(command, "ascii") == 0) { printf("%s", ASCII_TEXT); return NUMERUS_PROMPT_AGAIN; } else if (strcmp(command, "info") == 0 || strcmp(command, "about") == 0) { printf("%s", INFO_TEXT); return NUMERUS_PROMPT_AGAIN; } else if (strcmp(command, "ave") == 0) { printf("%s", AVE_TEXT); return NUMERUS_PROMPT_AGAIN; } else if (strcmp(command, "pretty") == 0) { /* Toggles pretty printing */ if (pretty_printing == 1) { pretty_printing = 0; printf("%s", PRETTY_OFF_TEXT); return NUMERUS_PROMPT_AGAIN; } else { pretty_printing = 1; printf("%s", PRETTY_ON_TEXT); return NUMERUS_PROMPT_AGAIN; } } else if (strcmp(command, "ping") == 0) { printf("%s", PING_TEXT); return NUMERUS_PROMPT_AGAIN; } else if (strcmp(command, "exit") == 0 || strcmp(command, "quit") == 0) { printf("%s", QUIT_TEXT); return NUMERUS_STOP_REPL; } else if (*command == '\0') { /* No inserted command, just an <enter> */ return NUMERUS_PROMPT_AGAIN; } else { _num_convert_to_other_form_and_print(command); return NUMERUS_PROMPT_AGAIN; } } /** * Starts a command line interface that converts any typed value to a roman * numeral or vice-versa. * * The `argc` and `args` arguments of the main may be passed to it. This allows * any command line parameters passed to the numerus executable to be * interpreted as if they were written withing the command line interface. * To avoid this option, set `argc` to 0 and `args` to anything, e.g. NULL. * * @param argc int number of main arguments. Set to 0 to disable parsing of * main arguments. * @param args array of main arguments to be parsed as commands. * @returns int status code: 0 if everything went ok or a NUMERUS_ERROR_* * otherwise. */ int numerus_cli(int argc, char **args) { char *command; /* line_buffer_size = 50 enough for every command, * gets reallocated by getline() if not enough */ size_t line_buffer_size = 50; char *line = malloc(line_buffer_size); if (line == NULL) { numerus_error_code = NUMERUS_ERROR_MALLOC_FAIL; return NUMERUS_ERROR_MALLOC_FAIL; } if (argc > 1) { /* Parse main arguments and exit */ args++; pretty_printing = 0; while (argc > 1) { command = _num_get_first_word_trimmed_lowercased(*args); _num_parse_command(command); args++; argc--; } } else { /* Enter command line interface */ pretty_printing = 1; printf("%s", WELCOME_TEXT); int command_result = NUMERUS_PROMPT_AGAIN; while (command_result == NUMERUS_PROMPT_AGAIN) { printf("%s", PROMPT_TEXT); if (getline(&line, &line_buffer_size, stdin) == -1) { break; } else { command = _num_get_first_word_trimmed_lowercased(line); command_result = _num_parse_command(command); } } } free(line); return 0; }
2.328125
2
2024-11-18T21:05:53.238509+00:00
2017-06-26T18:13:40
3822ef5076983ba496bec586527534e7427e3a86
{ "blob_id": "3822ef5076983ba496bec586527534e7427e3a86", "branch_name": "refs/heads/main", "committer_date": "2017-06-26T18:13:40", "content_id": "2f55c1eb3ce03226e0a8d0eb67f408ec707c1239", "detected_licenses": [ "MIT" ], "directory_id": "11262f2d81d1516ad831fe30b13987b443cfb437", "extension": "c", "filename": "darren-mark-bot-code.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 95428948, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14157, "license": "MIT", "license_type": "permissive", "path": "/EECS290O-Spring-2002/code/darren-mark-bot-code.c", "provenance": "stackv2-0083.json.gz:3204", "repo_name": "ckirsch/classes", "revision_date": "2017-06-26T18:13:40", "revision_id": "1623d70a04ac9891d98354223ebee307c7891924", "snapshot_id": "20fbcab840ca1fbbef8af2fbafe7d6f128f85cf4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ckirsch/classes/1623d70a04ac9891d98354223ebee307c7891924/EECS290O-Spring-2002/code/darren-mark-bot-code.c", "visit_date": "2022-12-01T05:32:40.436361" }
stackv2
#include <conio.h> #include <unistd.h> #include <dsound.h> #include <dsensor.h> #include <unistd.h> #include <dmotor.h> #include <lnp.h> #include <lnp-logical.h> #include <string.h> /* defines for motor setup */ #define driveSpeed motor_c_speed #define steerSpeed motor_b_speed #define liftSpeed motor_a_speed #define driveDir motor_c_dir #define steerDir motor_b_dir #define liftDir motor_a_dir #define left fwd #define right rev #define lift rev #define drop fwd /* some constants */ //90 degree turn is 480 rotation ticks #define TICKS_PER_RAD 306.0 #define TICKS_PER_HALF_CIRCLE 960 //num ticks per 180 degrees #define TICKS_PER_90_DEGREES 480 #define SETPOINT_ERROR_SQUARED 1 //for x,y controller #define SETPOINT_ERROR 80 //for travel distance controller (quarter ticks) #define STEER_SETPOINT_ERROR 5 #define LENGTH 452.0 //length of car (quarter ticks) #define MAX_STEER_ANGLE_FULL_SPEED 100 //the max steer angle at full drive speed #define MIN_DRIVE_SPEED 50 //the minimum robot speed #define RCX_PORT 5 #define DEST_PORT 0x9 #define DEST_HOST 0x1 #define DEST_ADDR (DEST_HOST << 4 | DEST_PORT) pid_t pid1, pid2, pid3; void b2(); void b3(); void b4(); //PORTS AND STATE int controlMode=0; //the controller mode int liftState=0; int x=0; //state (quarter rotation units) int y=0; //state (quarter rotation units) int theta=0; //state int volatile thetaSetPoint; int volatile steerAngleSetPoint=0; //steer angle set point in 1/16 rotation units int volatile steerAngle=0; int volatile prevSteerAngle=0; int volatile speed = 0; int volatile steer_speed = 0; int blockDetected=0; //are we over a block int deltaDistance; int xSetPoint, ySetPoint, travelDistance; int RCX_RANGE = 0; // Set IR range on RCX, #define didn't work! //e machine state int eState = 0; //communication char rcvMsg[12]; // Data received int rcvMsgLen = 0; // Length of received data, zero if nothing to receive char sendMsg[12]; // Data to send int sendMsgLen = 0; // Length of data to send, zero if nothing to send //UTILITIES //480 ticks/90 degrees //306 ticks/rad //taylor series around zero (theta in ticks) float sinZero(int theta) { float r=theta/TICKS_PER_RAD; float rr=r*r; return (-(rr*r)/5040.0*(rr*rr)) + ((rr*rr*r)/120.0) - ((rr*r)/6.0) + r; } //taylor series around pi (theta in ticks) float sinPi(int theta) { float r,rr; if(theta<0) r=(theta+TICKS_PER_HALF_CIRCLE)/TICKS_PER_RAD; else r=(theta-TICKS_PER_HALF_CIRCLE)/TICKS_PER_RAD; rr=r*r; return ((rr*r)/5040.0*(rr*rr)) - ((rr*rr*r)/120.0) + ((rr*r)/6.0) - r; } //accepts angles -pi to pi float sin(int theta) { if(theta>-TICKS_PER_90_DEGREES && theta<TICKS_PER_90_DEGREES) return sinZero(theta); else return sinPi(theta); } //accepts angles -pi to pi float cos(int theta) { if(theta>0) return sinPi(theta+TICKS_PER_90_DEGREES); else return sinZero(theta+TICKS_PER_90_DEGREES); } //taylor series around zero (theta in ticks) float tan(int theta) { float r=theta/TICKS_PER_RAD; float rr=r*r; return ((rr*rr*r)/5.0) + ((rr*r)/3.0) + r; } //taylor series around zero (returns angle in ticks) //only accurate from -1 to 1, threshold at pi/2 int arctan(float x) { float xx=x*x; float result = ((xx*xx*x)/5.0) - ((xx*x)/3.0) + x; int ticks = (int)(result*TICKS_PER_RAD); if(ticks>TICKS_PER_90_DEGREES) return TICKS_PER_90_DEGREES; else if(ticks<-TICKS_PER_90_DEGREES) return -TICKS_PER_90_DEGREES; else return ticks; } //DRIVERS // Called each time an addressing packet arrives on receiving port void handler(const unsigned char* data, unsigned char len, unsigned char src) { int i; for (i = 0; (i < len); i++) rcvMsg[i] = data[i]; rcvMsg[i] = '\0'; rcvMsgLen = len; } void sendDriver () { if (sendMsgLen != 0) { lnp_addressing_write(sendMsg, sendMsgLen, DEST_ADDR, RCX_PORT); //Sends message across network sendMsgLen = 0; } } void lightDriver() { lcd_int(LIGHT_3); if(LIGHT_3<55 && blockDetected==0) blockDetected=1; } void beepDriver() { dsound_system(DSOUND_BEEP); } void motorDrivers() { if(speed < 0) { driveDir(fwd); if(speed>-MIN_DRIVE_SPEED) speed=-MIN_DRIVE_SPEED; driveSpeed(-speed); } else if(speed > 0){ driveDir(rev); if(speed<MIN_DRIVE_SPEED) speed=MIN_DRIVE_SPEED; driveSpeed(speed); } else driveSpeed(0); if(steer_speed < 0) { steerDir(right); if(steer_speed>-35) steer_speed=-35; steerSpeed(-steer_speed); } else if(steer_speed > 0) { steerDir(left); if(steer_speed<35) steer_speed=35; steerSpeed(steer_speed); } else { steerDir(brake); steerSpeed(50); } } void liftDriver() { if(liftState==1) { liftSpeed(50); liftDir(lift); } else if(liftState==0) { liftDir(brake); liftSpeed(255); } } void rotationDrivers() { deltaDistance = ROTATION_2*4; //quarter rotation units ds_rotation_set(&SENSOR_2, 0); prevSteerAngle = steerAngle; steerAngle = -ROTATION_1; } void initDriver() { int i; liftDir(drop); liftSpeed(100); driveDir(fwd); driveSpeed(0); steerSpeed(0); ds_active(&SENSOR_2); ds_rotation_set(&SENSOR_2, 0); ds_rotation_on(&SENSOR_2); ds_active(&SENSOR_1); ds_rotation_set(&SENSOR_1, 0); ds_rotation_on(&SENSOR_1); ds_active(&SENSOR_3); lnp_logical_range(RCX_RANGE); // Sets transmitter range on RCX lnp_addressing_set_handler(RCX_PORT, handler); // Installs a handler on receiving port msleep(3000); liftDir(brake); liftSpeed(200); } //TASKS void liftTask() { speed=0; liftState=1; } void returnTask() { liftState=0; xSetPoint=0; ySetPoint=0; controlMode=4; } int round(float x) { if(x>0) return (int)(x+0.5); else if(x<0) return(int)(x-0.5); else return 0; } void stateEstimator() { theta = theta + round((deltaDistance/(float)(LENGTH)) * tan((steerAngle+prevSteerAngle)/2) * (float)TICKS_PER_RAD); if(theta>TICKS_PER_HALF_CIRCLE) theta-=2*TICKS_PER_HALF_CIRCLE; else if(theta<-TICKS_PER_HALF_CIRCLE) theta+=2*TICKS_PER_HALF_CIRCLE; x = x + round((float)(deltaDistance)*cos(theta)); y = y + round((float)(deltaDistance)*sin(theta)); //lcd_int(deltaDistance); exit(0); } void sendState() { sendMsg[0]=theta; sendMsg[1]=(theta>>8); sendMsg[2]=x; sendMsg[3]=(x>>8); sendMsg[4]=y; sendMsg[5]=(y>>8); sendMsg[6] = '\0'; sendMsgLen = 7; exit(0); } void controlModeSwitcher() { if(rcvMsgLen!=0) { beepDriver(); controlMode = rcvMsg[0]; switch(controlMode) { case 1: steerAngleSetPoint=(rcvMsg[1]<<8) + (unsigned)rcvMsg[2]; speed=(rcvMsg[3]<<8) + (unsigned)rcvMsg[4]; break; case 2: steerAngleSetPoint=(rcvMsg[1]<<8) + (unsigned)rcvMsg[2]; travelDistance=(rcvMsg[3]<<8) + (unsigned)rcvMsg[4]; break; case 3: thetaSetPoint=(rcvMsg[1]<<8) + (unsigned)rcvMsg[2]; travelDistance=(rcvMsg[3]<<8) + (unsigned)rcvMsg[4]; break; case 4: case 5: xSetPoint=(rcvMsg[1]<<8) + (unsigned)rcvMsg[2]; ySetPoint=(rcvMsg[3]<<8) + (unsigned)rcvMsg[4]; break; } rcvMsgLen=0; } } //steering angle controller //TO DO: D control void steerAngleController() { int error = steerAngleSetPoint - steerAngle; if(error > STEER_SETPOINT_ERROR || error < -STEER_SETPOINT_ERROR) { error = error/8; if(error > 255) steer_speed=255; else if(error < -255) steer_speed=-255; else steer_speed=error; } else steer_speed=0; } //theta controller void thetaController() { int thetaError = thetaSetPoint - theta; if(thetaError<-TICKS_PER_HALF_CIRCLE) thetaError+=TICKS_PER_HALF_CIRCLE*2; else if(thetaError>TICKS_PER_HALF_CIRCLE) thetaError-=TICKS_PER_HALF_CIRCLE*2; steerAngleSetPoint = -steerAngleSetPoint/4 + thetaError; //pd control on theta if(steerAngleSetPoint>200) steerAngleSetPoint=200; else if(steerAngleSetPoint<-200) steerAngleSetPoint=-200; } //backward theta controller void backwardThetaController() { int thetaError = thetaSetPoint - theta; if(thetaError<-TICKS_PER_HALF_CIRCLE) thetaError+=TICKS_PER_HALF_CIRCLE*2; else if(thetaError>TICKS_PER_HALF_CIRCLE) thetaError-=TICKS_PER_HALF_CIRCLE*2; steerAngleSetPoint = -steerAngleSetPoint/4 - thetaError; //minus pd control on theta if(steerAngleSetPoint>200) steerAngleSetPoint=200; else if(steerAngleSetPoint<-200) steerAngleSetPoint=-200; } //travel distance controller //TO DO: scale speed for high steer angle //TO DO: soft start void travelDistanceController() { int error; travelDistance -= deltaDistance; error = travelDistance; if(error > SETPOINT_ERROR || error<-SETPOINT_ERROR) { error = error/8; if(error > 150) speed=150; else if(error < -150) speed=-150; else speed=error; } else speed=0; } //xy pointing controller void pointingController(int delX, int delY) { int absDelX, absDelY; float arc; if(delY<0) absDelY=-delY; else if(delY>0) absDelY=delY; else if(delX>0) { thetaSetPoint=0; return; } else { thetaSetPoint=TICKS_PER_HALF_CIRCLE; return; } if(delX<0) absDelX=-delX; else if(delX>0) absDelX=delX; else if(delY>0) { thetaSetPoint = TICKS_PER_90_DEGREES; return; } else { thetaSetPoint = -TICKS_PER_90_DEGREES; return; } if(absDelY<absDelX) { arc = (float)delY/(float)delX; thetaSetPoint=arctan(arc); if(delX<0) thetaSetPoint+=TICKS_PER_HALF_CIRCLE; } else { arc = (float)delX/(float)delY; thetaSetPoint=arctan(arc); if(delY<0) thetaSetPoint=-TICKS_PER_90_DEGREES-thetaSetPoint; else thetaSetPoint=TICKS_PER_90_DEGREES-thetaSetPoint; } } void controller() { long error=0; int delX, delY; switch(controlMode) { case 0: //stop steer_speed=0; speed=0; break; case 2: //const. steer angle, travel distance travelDistanceController(); //fall through case 1: //const. steer angle, const. speed steerAngleController(); break; case 3: //const.theta, drive for travel distance. travelDistanceController(); thetaController(); lcd_int(steerAngleSetPoint); steerAngleController(); lcd_int(steerAngleSetPoint); break; case 4: delX=xSetPoint-x; delY=ySetPoint-y; pointingController(delX, delY); delX=delX/4; delY=delY/4; if(delX>150 || delX<-150 || delY<-150 || delY>150) speed=150; else { error = (delX/16 * delX/16) + (delY/16 * delY/16); if(error > 300) speed=150; else if(error < 120) speed=60; else speed=error/2; if(error < SETPOINT_ERROR_SQUARED) { speed=0; controlMode=0; } } if(error > SETPOINT_ERROR_SQUARED && speed==0) speed=50; //soft start thetaController(); steerAngleController(); break; case 5: //navigate backwards to pick up blocks! delX=xSetPoint-x; delY=ySetPoint-y; pointingController(delX, delY); delX=delX/4; delY=delY/4; //backwards thetaSetPoint-=TICKS_PER_HALF_CIRCLE; if(thetaSetPoint<-TICKS_PER_HALF_CIRCLE) thetaSetPoint+=TICKS_PER_HALF_CIRCLE*2; if(delX>150 || delX<-150 || delY<-150 || delY>150) speed=-150; else { error = (delX/16 * delX/16) + (delY/16 * delY/16); if(error > 300) speed=-150; else if(error < 120) speed=-60; else speed=-error/2; if(error < SETPOINT_ERROR_SQUARED) { speed=0; controlMode=0; } } backwardThetaController(); steerAngleController(); break; } //lcd_int(steerAngle); exit(0); } //E MACHINE void call(void (*ptToFunc) ()) { ptToFunc(); } void future(int timeTrigger, void (*ptToFunc) ()) { msleep(timeTrigger); execi(ptToFunc, 0, NULL, 5, DEFAULT_STACK_SIZE); exit(0); } void branchingFuture(int timeTrigger, int(*ptToPredicate) (), void(*ptToTrueFunc) (), void(*ptToFalseFunc) ()) { msleep(timeTrigger); if(ptToPredicate()) execi(ptToTrueFunc, 0, NULL, 5, DEFAULT_STACK_SIZE); else execi(ptToFalseFunc, 0, NULL, 5, DEFAULT_STACK_SIZE); exit(0); } void schedule(void (*ptToFunc) (), int priority) { execi(ptToFunc, 0, NULL, priority, DEFAULT_STACK_SIZE); } //E MACHINE PROGRAM int programCount() { if(eState==0) eState=9; else eState-=1; return eState; } int blockDetector() { //debouced if(blockDetected==1) blockDetected=2; else return 0; return blockDetected; } void b1() { call(&motorDrivers); call(&rotationDrivers); schedule(&controlModeSwitcher, 9); schedule(&stateEstimator, 8); schedule(&sendState, 7); future(50, &b4); } void b4() { call(&rotationDrivers); call(&sendDriver); schedule(&stateEstimator, 8); schedule(&controller, 7); future(50, &b2); } void b7() { call(&motorDrivers); call(&liftDriver); call(&rotationDrivers); schedule(&stateEstimator, 8); schedule(&controller, 7); branchingFuture(50, &programCount,&b2, &b1); } void b6() { call(&motorDrivers); call(&liftDriver); call(&rotationDrivers); schedule(&stateEstimator, 9); schedule(&returnTask, 8); future(3000, &b7); } void b5() { call(&rotationDrivers); schedule(&stateEstimator, 9); schedule(&liftTask, 8); future(50, &b6); } void b2() { call(&motorDrivers); call(&rotationDrivers); call(&lightDriver); schedule(&stateEstimator, 8); branchingFuture(50, &blockDetector, &b5, &b3); } void b3() { call(&rotationDrivers); schedule(&stateEstimator, 8); schedule(&controller, 7); branchingFuture(50, &programCount,&b2, &b1); } /* void b1() { call(&motorDrivers); call(&rotationDrivers); call(&sendDriver); schedule(&controlModeSwitcher, 9); schedule(&stateEstimator, 8); schedule(&controller, 7); //beepDriver(); future(200, &b2); } void b2() { call(&motorDrivers); call(&rotationDrivers); schedule(&stateEstimator, 8); schedule(&controller, 7); future(200, &b3); } void b3() { call(&motorDrivers); call(&rotationDrivers); schedule(&stateEstimator, 8); schedule(&controller, 7); future(200, &b4); } void b4() { call(&motorDrivers); call(&rotationDrivers); schedule(&stateEstimator, 8); schedule(&controller, 7); schedule(&sendState, 6); future(200, &b1); } */ void bInit() { call(&initDriver); execi(&b1, 0, NULL, 6, DEFAULT_STACK_SIZE); } //the main block int main(int argc, char **argv) { int i; bInit(); speed=0; xSetPoint=0; ySetPoint=0; /*for(i=0;i<10;i+=1) { while(controlMode!=0) sleep(2); if(blockDetected!=0) break; beepDriver(); if(i%2==0) { xSetPoint=-5200; ySetPoint=i*1000; } else { xSetPoint=0; ySetPoint=i*1000; } controlMode=5; sleep(2); }*/ while(1) { sleep(250); } }
2.53125
3
2024-11-18T21:05:53.562149+00:00
2014-02-12T13:41:34
115e11cb705b32ed69f6a68dc15e03b3c3ee6783
{ "blob_id": "115e11cb705b32ed69f6a68dc15e03b3c3ee6783", "branch_name": "refs/heads/master", "committer_date": "2014-02-12T13:41:34", "content_id": "d6b8771c7cac1bff5c308f453113773aab621d7d", "detected_licenses": [ "MIT" ], "directory_id": "d0980383a92ca7e026e156e3d3baa9d372520eb3", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2544, "license": "MIT", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0083.json.gz:3332", "repo_name": "BlooKe/NaiveBayes", "revision_date": "2014-02-12T13:41:34", "revision_id": "abed5ab8ba106a210b3b5397448da084172222e1", "snapshot_id": "134edd70aeb5051abc56b7c89d72234a2e7a44fb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BlooKe/NaiveBayes/abed5ab8ba106a210b3b5397448da084172222e1/src/main.c", "visit_date": "2016-09-10T18:41:41.780294" }
stackv2
/**************************************************************************** * Copyright (c) 2014 Lauris Radzevics * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be * * included in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "definitions.h" #include "typedefs.h" #include "getfunctions.h" #include "calculations.h" #include "fileread.h" int main(void) { int ret=SUCCEED; int datacount = 0; Data_t *dataset; clock_t toc; Results_t results = { 0.0, 0.0, 0.0}; clock_t tic = clock(); dataset = (Data_t *)malloc(sizeof(*dataset) * 700); memset(dataset, FAIL, sizeof(*dataset)*700); ret = readfile(DATAFILE, dataset, &datacount); ret = naiveBayes(dataset, THREE, ONE, THREE, ONE, &results, datacount); printf("Left: %f Balanced: %f Right: %f \n", results.left, results.balance, results.right); toc = clock(); printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC); return 0; }
2.015625
2
2024-11-18T21:05:53.730299+00:00
2021-07-29T15:52:35
f2afedbbfa04af264e42f8c0037667f4a8996ccb
{ "blob_id": "f2afedbbfa04af264e42f8c0037667f4a8996ccb", "branch_name": "refs/heads/main", "committer_date": "2021-07-29T15:52:35", "content_id": "168ee5adaa665a6002bc2004419827c96b291df5", "detected_licenses": [ "MIT" ], "directory_id": "501ba72a7d1d610ab486a3de3c5c92c9d264fbc7", "extension": "c", "filename": "numberguess.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 306371749, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 366, "license": "MIT", "license_type": "permissive", "path": "/beginners/numberguess.c", "provenance": "stackv2-0083.json.gz:3589", "repo_name": "Argonyte/Mini-Projects", "revision_date": "2021-07-29T15:52:35", "revision_id": "78f25f3f08b66c885621395bdbd089ee92f31be1", "snapshot_id": "e59c63ee2dc009c8888f225ccec6e5ae5480b840", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Argonyte/Mini-Projects/78f25f3f08b66c885621395bdbd089ee92f31be1/beginners/numberguess.c", "visit_date": "2023-07-02T16:19:58.729524" }
stackv2
#include <stdio.h> int main(void){ int digit = 0, randint = 0; randint = (rand() % 10) + 1; printf("\n Enter a number between 1 and 10: "); scanf("%d", &digit); if (isdigit(digit == 0)) { printf("\nEnter a number!!!\n"); } else if (randint == digit) printf("\nCorrect Number"); else printf("\nMissed Number. Correct number was: %d", randint); }
3.421875
3
2024-11-18T21:05:53.803672+00:00
2017-02-05T14:46:15
ed4a55e22d7758361554ba603059c7d9c7da8cf0
{ "blob_id": "ed4a55e22d7758361554ba603059c7d9c7da8cf0", "branch_name": "refs/heads/master", "committer_date": "2017-02-05T14:46:15", "content_id": "8587fc17eb4ed8d85da22fbb618e9544947a2192", "detected_licenses": [ "MIT" ], "directory_id": "24b9174e8d641c99eb4894af5bb314e2124c4957", "extension": "c", "filename": "routine_clients_gui.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 80998361, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2584, "license": "MIT", "license_type": "permissive", "path": "/ZappyServer/server/network/routine_clients_gui.c", "provenance": "stackv2-0083.json.gz:3717", "repo_name": "AkselsLedins/academic-zappy", "revision_date": "2017-02-05T14:46:15", "revision_id": "53025ee1549dd8ad693ca647888eb77985875547", "snapshot_id": "6279936bcfe1e364c16418028a1c4aad8a5789b3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AkselsLedins/academic-zappy/53025ee1549dd8ad693ca647888eb77985875547/ZappyServer/server/network/routine_clients_gui.c", "visit_date": "2021-01-09T06:30:46.672587" }
stackv2
/* ** routine_clients_gui.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/network ** ** Made by ** Login <thebau_j@epitech.net> ** ** Started on Sun Jul 13 15:58:32 2014 ** Last update dim. juil. 13 17:47:46 2014 julien thebaud */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include "zappy.h" static int read_node_gui(t_zappy *s, t_clientGUI *client); static int write_node_gui(t_zappy *s, t_clientGUI *client); static int actions_node_gui(t_zappy *s, t_clientGUI *client); static int error_node_gui(t_zappy *s, t_clientGUI * client); t_node *routine_clientGUI(t_zappy *s, t_node *node, t_type type, int *ret) { t_clientGUI *client; (void)ret; if (type != GUI) return (NULL); client = ((t_clientGUI*)node->data); if (client) { if (error_node_gui(s, client) == -1) return rm_node(s->listGUI, node); if (read_node_gui(s, client) == -1) return rm_node(s->listGUI, node); if (actions_node_gui(s, client) == -1) return rm_node(s->listGUI, node); if (write_node_gui(s, client) == -1) return rm_node(s->listGUI, node); } return (node->next); } static int actions_node_gui(t_zappy *s, t_clientGUI *client) { char *str; t_cmd_gui num; if ((str = try_get_cmd(client->buff_read))) { if ((num = find_cmd_gui(str)) != NONE) (*s->ptr_func_gui[num])(s, client, str); else client->error = true; free(str); } return (0); } static int write_node_gui(t_zappy *s, t_clientGUI *client) { const char *error = "suc\n"; ssize_t nbwrites; if (client->error && FD_ISSET(client->socket, &(s->writesd))) { nbwrites = write(client->socket, error, strlen(error)); if (nbwrites != ((ssize_t)strlen(error))) fprintf(stderr, "send() failed.\n"); client->error = false; } else write_gui(s, client); return (0); } static int read_node_gui(t_zappy *s, t_clientGUI *client) { if (FD_ISSET(client->socket, &(s->readsd))) { if (write_in_buff(client->socket, client->buff_read, false, 0) <= 0) { printf("Déco client GUI :%d\n", client->socket); if (close(client->socket) == -1) perror("Close failed. Error"); return (-1); } } return (0); } static int error_node_gui(t_zappy *s, t_clientGUI *client) { if (FD_ISSET(client->socket, &(s->exceptsd))) { fprintf(stderr, "Except on socket client\n"); if (close(client->socket) == -1) perror("Close failed. Error"); client->socket = -1; return (-1); } return (0); }
2.421875
2
2024-11-18T21:05:54.236071+00:00
2018-07-20T08:29:34
1dd1050812062e82ebcbbd33af4a7d86548c5641
{ "blob_id": "1dd1050812062e82ebcbbd33af4a7d86548c5641", "branch_name": "refs/heads/master", "committer_date": "2018-07-25T04:41:56", "content_id": "ba1204b2bc8df43c1b32f74096ac49f7a6cc2752", "detected_licenses": [ "MIT" ], "directory_id": "e958dd014027f8a6c05fe7c3a435401f27240015", "extension": "c", "filename": "crypto.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 141514354, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2034, "license": "MIT", "license_type": "permissive", "path": "/src/crypto.c", "provenance": "stackv2-0083.json.gz:4231", "repo_name": "xingfeng2510/pandora-c", "revision_date": "2018-07-20T08:29:34", "revision_id": "4df154ede9657a6e7306a85ffd2bc8f43651074c", "snapshot_id": "198843e3fa95271f9c8e06c0c3193e5c27288588", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xingfeng2510/pandora-c/4df154ede9657a6e7306a85ffd2bc8f43651074c/src/crypto.c", "visit_date": "2020-03-23T11:39:30.031558" }
stackv2
#include "crypto.h" #include <apr_md5.h> #include <apr_sha1.h> void hmac_sha1(unsigned char hmac[20], const unsigned char *key, int key_len, const unsigned char *message, int message_len) { unsigned char kopad[64], kipad[64]; int i; unsigned char digest[APR_SHA1_DIGESTSIZE]; apr_sha1_ctx_t context; if (key_len > 64) { key_len = 64; } for (i = 0; i < key_len; i++) { kopad[i] = key[i] ^ 0x5c; kipad[i] = key[i] ^ 0x36; } for ( ; i < 64; i++) { kopad[i] = 0 ^ 0x5c; kipad[i] = 0 ^ 0x36; } apr_sha1_init(&context); apr_sha1_update(&context, (const char *)kipad, 64); apr_sha1_update(&context, (const char *)message, (unsigned int)message_len); apr_sha1_final(digest, &context); apr_sha1_init(&context); apr_sha1_update(&context, (const char *)kopad, 64); apr_sha1_update(&context, (const char *)digest, 20); apr_sha1_final(hmac, &context); } int base64_encode(const unsigned char *in, int inLen, char *out) { static const char *ENC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; char *orig_out = out; while (inLen) { // first 6 bits of char 1 *out++ = ENC[*in >> 2]; if (!--inLen) { // last 2 bits of char 1, 4 bits of 0 *out++ = ENC[(*in & 0x3) << 4]; *out++ = '='; *out++ = '='; break; } // last 2 bits of char 1, first 4 bits of char 2 *out++ = ENC[((*in & 0x3) << 4) | (*(in + 1) >> 4)]; in++; if (!--inLen) { // last 4 bits of char 2, 2 bits of 0 *out++ = ENC[(*in & 0xF) << 2]; *out++ = '='; break; } // last 4 bits of char 2, first 2 bits of char 3 *out++ = ENC[((*in & 0xF) << 2) | (*(in + 1) >> 6)]; in++; // last 6 bits of char 3 *out++ = ENC[*in & 0x3F]; in++, inLen--; } *out = '\0'; return (out - orig_out); }
2.703125
3
2024-11-18T21:05:54.336625+00:00
2017-06-19T10:16:26
dc2444e7908ddb95121a03fff003db385a15060e
{ "blob_id": "dc2444e7908ddb95121a03fff003db385a15060e", "branch_name": "refs/heads/master", "committer_date": "2017-06-19T10:16:26", "content_id": "ee9bfc73203cce531cc4f36993950e65b4bf31a0", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "311afa0aae6c2fc2f7e0bad9bd46b1a41b643402", "extension": "h", "filename": "memory_allocation.h", "fork_events_count": 0, "gha_created_at": "2017-12-19T09:17:44", "gha_event_created_at": "2017-12-19T09:17:44", "gha_language": null, "gha_license_id": null, "github_id": 114744405, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6057, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/base_c/include/embb/base/c/memory_allocation.h", "provenance": "stackv2-0083.json.gz:4361", "repo_name": "philipp-weiss/embb", "revision_date": "2017-06-19T10:16:26", "revision_id": "35dc6e2bcc2ef8660a96d883458c4e3e8eadb20c", "snapshot_id": "c8412f6ad87047cbe05d2286ad1eedeb890d9d73", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/philipp-weiss/embb/35dc6e2bcc2ef8660a96d883458c4e3e8eadb20c/base_c/include/embb/base/c/memory_allocation.h", "visit_date": "2021-08-30T20:25:26.878869" }
stackv2
/* * Copyright (c) 2014-2017, Siemens AG. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef EMBB_BASE_C_MEMORY_ALLOCATION_H_ #define EMBB_BASE_C_MEMORY_ALLOCATION_H_ /** * \defgroup C_BASE_ALLOC Memory Allocation * * \ingroup C_BASE * * Functions for dynamic memory allocation * * There are functions for aligned and unaligned memory allocation. In debug * mode, memory usage is tracked to detect memory leaks. */ #include <stdlib.h> #include <embb/base/c/internal/config.h> #ifdef __cplusplus extern "C" { #endif // __cplusplus /** * Allocates \p size bytes of memory. * * Keeps track of allocated memory in debug mode. * * \return NULL in case of failure, otherwise address of allocated memory * block. * * \memory <tt>size+3*sizeof(size_t)</tt> bytes in debug mode, otherwise \c * size bytes * * \threadsafe * * \see embb_get_bytes_allocated() * * \ingroup C_BASE_ALLOC */ void* embb_alloc( size_t size /**< [IN] Size of memory block to be allocated in bytes */ ); /** * Frees memory that has been allocated by embb_alloc() for some pointer * \p ptr. * * Keeps track of freed memory in debug mode. * * \pre \c ptr is not NULL. * * \threadsafe * * \see embb_get_bytes_allocated() * * \ingroup C_BASE_ALLOC */ void embb_free( void* ptr /**< [IN,OUT] Pointer to memory block to be freed */ ); /** * Allocates \p size bytes of memory with alignment \p alignment. * * This function can be used to align objects to certain boundaries such as * cache lines, memory pages, etc. * * Keeps track of allocated memory in debug mode. * * It is not required that \p size is a multiple of \p alignment as, e.g., * for the \c aligned\_alloc function of the C11 standard. * * \pre The alignment has to be power of 2 and a multiple of * <tt>size(void*)</tt>. * \post The returned pointer is a multiple of \p alignment. * * \return NULL in case of failure, otherwise address of allocated memory * block. * * \memory Debug mode: Let \c n be the number of aligned cells necessary to * fit the payload. Then, <tt>(n+1)*alignment+3*size_of(size_t)-1</tt> * bytes are allocated.<br> Release mode: \c size bytes are requested * using the functions provided by the operating systems. * * \threadsafe * * \note Memory allocated using this function must be freed using * embb_free_aligned(). * * \see embb_alloc_cache_aligned(), embb_free_aligned(), * embb_get_bytes_allocated() * * \ingroup C_BASE_ALLOC */ void* embb_alloc_aligned( size_t alignment, /**< [IN] Alignment in bytes */ size_t size /**< [IN] Size of memory block to be allocated in bytes */ ); /** * Allocates \p size bytes of cache-aligned memory. * * Specialized version of embb_alloc_aligned(). The alignment is chosen * automatically (usually 64 bytes). * * Keeps track of allocated memory in debug mode. * * \post The returned pointer is a multiple of the cache line size. * * \return NULL in case of failure, otherwise address of allocated memory * block. * * \memory See embb_alloc_aligned() * * \threadsafe * * \note Memory allocated using this function must be freed using * embb_free_aligned(). * * \see embb_alloc_aligned(), embb_free_aligned(), embb_get_bytes_allocated() * * \ingroup C_BASE_ALLOC */ void* embb_alloc_cache_aligned( size_t size /**< [IN] Size of memory block to be allocated in bytes */ ); /** * Frees memory that has been allocated by an aligned method for \c ptr. * * The available aligned methods are embb_alloc_aligned() or * embb_alloc_cache_aligned(). * * Keeps track of freed memory in debug mode. * * \pre \c ptr is not NULL and was allocated by an aligned method. * * \threadsafe * * \see embb_alloc_aligned(), embb_alloc_cache_aligned(), * embb_get_bytes_allocated() * * \ingroup C_BASE_ALLOC */ void embb_free_aligned( void* ptr /**< [IN,OUT] Pointer to memory block to be freed */ ); /** * Returns the total number of bytes currently allocated. * * Only the bytes allocated by embb_alloc(), embb_alloc_aligned(), and * embb_alloc_cache_aligned() in debug mode are counted. * * \return Number of currently allocated bytes in debug mode, otherwise 0. * * \waitfree * * \see embb_alloc(), embb_alloc_aligned(), embb_alloc_cache_aligned() * * \ingroup C_BASE_ALLOC */ size_t embb_get_bytes_allocated(); #ifdef __cplusplus } #endif // __cplusplus #endif // EMBB_BASE_C_MEMORY_ALLOCATION_H_
2.078125
2
2024-11-18T21:05:54.418268+00:00
2023-06-30T12:11:58
7264da4532e43d461142f41ff2e4dffbda33a209
{ "blob_id": "7264da4532e43d461142f41ff2e4dffbda33a209", "branch_name": "refs/heads/master", "committer_date": "2023-06-30T12:11:58", "content_id": "b1cd89a74cb7e21bab8a8dab025096f755845a63", "detected_licenses": [ "MIT" ], "directory_id": "d9fc7041be4cc304782cb9b824be532715936459", "extension": "h", "filename": "driver.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 223477259, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1565, "license": "MIT", "license_type": "permissive", "path": "/source/drivers/driver.h", "provenance": "stackv2-0083.json.gz:4492", "repo_name": "teplofizik/stm32f0drivers", "revision_date": "2023-06-30T12:11:58", "revision_id": "525e82c2952eef519506e0ce09ffd833c1699f23", "snapshot_id": "37dd25afa0a48ffbb331920895de2e1846853b6c", "src_encoding": "WINDOWS-1251", "star_events_count": 1, "url": "https://raw.githubusercontent.com/teplofizik/stm32f0drivers/525e82c2952eef519506e0ce09ffd833c1699f23/source/drivers/driver.h", "visit_date": "2023-07-05T22:31:26.545485" }
stackv2
// *********************************************************** // driver.h // Базовый код для работы с драйверами // // teplofizik, 2016 // *********************************************************** #include <stdint.h> #include <stdbool.h> // Список поддерживаемого железа #include "hw_avail.h" // Стандартные типы #include "../types.h" #ifndef _DRIVER_H #define _DRIVER_H #define MAX_DRIVER_COUNT 20 typedef struct { const char * Name; // Инициализация - если false, то не загрузилось (не добавляем в список) bool (* Init)(void); // Выгрузка драйвера void (* Uninit)(void); // Основной цикл - если false, то выгружаем из-за ошибки. bool (* Main)(void); } TDriver; // Инициализация подсистемы драйверов void drv_Init(void); // Основной цикл для драйверов void drv_Main(void); // Загрузить драйвер void drv_Load(const TDriver * Drv); // Драйвер загружен? bool drv_IsLoaded(const char * name); // Требование наличия драйвера // Если не загружен - false bool drv_Require(const TDriver * Drv, const char * name); // Строка в лог void drv_DebugLog(const TDriver * Drv, const char * Text); #endif
2.171875
2
2024-11-18T21:05:54.662301+00:00
2023-09-01T14:47:06
ce65cc1c2139189f98ad4dd99a0002eef5b7c407
{ "blob_id": "ce65cc1c2139189f98ad4dd99a0002eef5b7c407", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T14:47:06", "content_id": "1d5f2bebe4115eb97cf4e0b9d6e43eabaf871d2b", "detected_licenses": [ "MIT" ], "directory_id": "6a531e292af43d3e7aec6d3019e0333362afe454", "extension": "c", "filename": "cactusSegment.c", "fork_events_count": 106, "gha_created_at": "2011-02-01T20:17:33", "gha_event_created_at": "2023-09-05T20:27:44", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 1317650, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11176, "license": "MIT", "license_type": "permissive", "path": "/api/impl/cactusSegment.c", "provenance": "stackv2-0083.json.gz:4876", "repo_name": "ComparativeGenomicsToolkit/cactus", "revision_date": "2023-09-01T14:47:06", "revision_id": "41d99360cfa79ada5bdca307883c30c7fb59a06d", "snapshot_id": "2d4d891b6b3af0a22b64aba11f18a867a7666e58", "src_encoding": "UTF-8", "star_events_count": 369, "url": "https://raw.githubusercontent.com/ComparativeGenomicsToolkit/cactus/41d99360cfa79ada5bdca307883c30c7fb59a06d/api/impl/cactusSegment.c", "visit_date": "2023-09-01T20:38:37.550816" }
stackv2
/* * Copyright (C) 2009-2011 by Benedict Paten (benedictpaten@gmail.com) * * Released under the MIT license, see LICENSE.txt */ #include "cactusGlobalsPrivate.h" //////////////////////////////////////////////// //////////////////////////////////////////////// //////////////////////////////////////////////// //Basic segment functions //////////////////////////////////////////////// //////////////////////////////////////////////// //////////////////////////////////////////////// SegmentCapContents *segment_getContents(Segment *segment) { assert(cap_isSegment(segment)); return cap_getSegmentContents(segment); } Segment *segment_construct(Block *block, Event *event) { assert(event != NULL); assert(block != NULL); Name instance = cactusDisk_getUniqueIDInterval(flower_getCactusDisk(block_getFlower(block)), 3); assert(instance != NULL_NAME); // Create the combined forward and reverse caps Cap *cap = st_calloc(1, 6*sizeof(Cap) + sizeof(SegmentCapContents)); // see above comment to decode what is set // Bits: strand / forward / part_of_segment / is_segment / left / event_not_sequence (cap+0)->bits = 0x37; // binary: 110111 (cap+1)->bits = 0x34; // binary: 110100 (cap+2)->bits = 0x2F; // binary: 101111 (cap+3)->bits = 0x2C; // binary: 101100 (cap+4)->bits = 0x27; // binary: 100111 (cap+5)->bits = 0x24; // binary: 100100 // Set the attributes of the combined caps/segments cap_getCoreContents(cap)->instance = instance; cap_getCoreContents(cap)->coordinate = INT64_MAX; cap_getCoreContents(cap)->eventOrSequence = event; cap_getSegmentContents(cap)->block = block; // Add the cap and segments to the appropriate indexes block_addInstance(block, cap_getSegment(cap)); flower_addCap(end_getFlower(cap_getEnd(cap)), cap); flower_addCap(end_getFlower(cap_getEnd(cap)), cap_getOtherSegmentCap(cap)); // Do (non exhaustive) checks // Check left caps assert(cap_getStrand(cap)); assert(!cap_getStrand(cap_getReverse(cap))); assert(cap_getReverse(cap_getReverse(cap)) == cap); // check reversal works assert(cap_getSegmentContents(cap) == cap_getSegmentContents(cap_getReverse(cap))); assert(cap_getName(cap) == instance); assert(cap_getName(cap_getReverse(cap)) == instance); assert(cap_getCoordinate(cap) == INT64_MAX); assert(cap_getCoordinate(cap_getReverse(cap)) == INT64_MAX); assert(cap_getSequence(cap) == NULL); assert(cap_getSequence(cap_getReverse(cap)) == NULL); assert(cap_getAdjacency(cap) == NULL); assert(cap_getAdjacency(cap_getReverse(cap)) == NULL); assert(cap_getEvent(cap) == event); assert(cap_getEvent(cap_getReverse(cap)) == event); // Check segment assert(cap_getSegment(cap) != NULL); assert(cap_getName(cap_getSegment(cap)) == instance+1); assert(cap_getName(segment_getReverse(cap_getSegment(cap))) == instance+1); assert(cap_getStrand(cap_getSegment(cap))); assert(!cap_getStrand(cap_getSegment(cap_getReverse(cap)))); assert(segment_get5Cap(cap_getSegment(cap)) == cap); assert(segment_get3Cap(cap_getReverse(cap_getSegment(cap))) == cap_getReverse(cap)); assert(cap_getEvent(cap_getSegment(cap)) == event); assert(cap_getEvent(cap_getReverse(cap_getSegment(cap))) == event); assert(cap_getSequence(cap_getSegment(cap)) == NULL); assert(cap_getSequence(cap_getReverse(cap_getSegment(cap))) == NULL); // Check right caps assert(cap_getOtherSegmentCap(cap) != NULL); assert(cap_getStrand(cap_getOtherSegmentCap(cap))); assert(!cap_getStrand(cap_getOtherSegmentCap(cap_getReverse(cap)))); assert(cap_getOtherSegmentCap(cap_getOtherSegmentCap(cap)) == cap); assert(cap_getOtherSegmentCap(cap_getOtherSegmentCap(cap_getReverse(cap))) == cap_getReverse(cap)); assert(cap_getName(cap_getOtherSegmentCap(cap)) == instance+2); assert(cap_getName(cap_getOtherSegmentCap(cap_getReverse(cap))) == instance+2); assert(cap_getEvent(cap_getOtherSegmentCap(cap)) == event); assert(cap_getEvent(cap_getReverse(cap_getOtherSegmentCap(cap))) == event); assert(cap_getSequence(cap_getOtherSegmentCap(cap)) == NULL); assert(cap_getSequence(cap_getReverse(cap_getOtherSegmentCap(cap))) == NULL); assert(cap_getAdjacency(cap_getOtherSegmentCap(cap)) == NULL); assert(cap_getAdjacency(cap_getReverse(cap_getOtherSegmentCap(cap))) == NULL); // Check indexes assert(flower_getCap(block_getFlower(block), instance) == cap_getPositiveOrientation(cap)); assert(block_getInstance(block, instance+1) == cap_getSegment(cap)); assert(block_getInstance(block_getReverse(block), instance+1) == segment_getReverse(cap_getSegment(cap))); assert(end_getInstance(block_get5End(block), instance) == cap); assert(end_getInstance(end_getReverse(block_get5End(block)), instance) == cap_getReverse(cap)); assert(end_getInstance(block_get3End(block), instance+2) == cap_getOtherSegmentCap(cap)); assert(end_getInstance(end_getReverse(block_get3End(block)), instance+2) == cap_getReverse(cap_getOtherSegmentCap(cap))); return cap_getSegment(cap); } Segment *segment_construct2(Block *block, int64_t startCoordinate, bool strand, Sequence *sequence) { assert(startCoordinate >= sequence_getStart(sequence)); assert(startCoordinate + block_getLength(block) <= sequence_getStart(sequence) + sequence_getLength(sequence)); int64_t i = (startCoordinate == INT64_MAX || strand) ? startCoordinate : startCoordinate + block_getLength(block) - 1; Segment *segment = segment_construct(block, sequence_getEvent(sequence)); assert(cap_left(segment_get5Cap(segment))); cap_setCoordinates(segment_get5Cap(segment), i, strand, sequence); return segment; } void segment_destruct(Segment *segment) { block_removeInstance(segment_getBlock(segment), segment); assert(cap_isSegment(segment)); free(cap_forward(segment) ? segment - 2 : segment - 3); } Block *segment_getBlock(Segment *segment) { assert(cap_isSegment(segment)); Block *block = cap_getSegmentContents(segment)->block; return cap_forward(segment) ? block : block_getReverse(block); } Name segment_getName(Segment *segment) { assert(cap_isSegment(segment)); return cap_getName(segment); } bool segment_getOrientation(Segment *segment) { assert(cap_isSegment(segment)); return block_getOrientation(segment_getBlock(segment)); } Segment *segment_getPositiveOrientation(Segment *segment) { assert(cap_isSegment(segment)); return segment_getOrientation(segment) ? segment : segment_getReverse( segment); } Segment *segment_getReverse(Segment *segment) { assert(cap_isSegment(segment)); return cap_forward(segment) ? segment+1 : segment-1; //segment_getContents(segment)->rInstance; } Event *segment_getEvent(Segment *segment) { return cap_getEvent(segment_get5Cap(segment)); } int64_t segment_getStart(Segment *segment) { return cap_getCoordinate(segment_get5Cap(segment)); } bool segment_getStrand(Segment *segment) { return cap_getStrand(segment_get5Cap(segment)); } int64_t segment_getLength(Segment *segment) { return block_getLength(segment_getBlock(segment)); } Sequence *segment_getSequence(Segment *segment) { return cap_getSequence(segment_get5Cap(segment)); } char *segment_getString(Segment *segment) { assert(cap_isSegment(segment)); Sequence *sequence = segment_getSequence(segment); return sequence == NULL ? NULL : sequence_getString(sequence, segment_getStart(segment_getStrand(segment) ? segment : segment_getReverse(segment)), segment_getLength(segment), segment_getStrand(segment)); } Cap *segment_get5Cap(Segment *segment) { assert(cap_isSegment(segment)); return cap_forward(segment) ? segment-2 : segment+2; } Cap *segment_get3Cap(Segment *segment) { assert(cap_isSegment(segment)); return cap_forward(segment) ? segment+2 : segment-2; } void segment_check(Segment *segment) { //Check segment is properly linked to block. Block *block = segment_getBlock(segment); assert(block_getInstance(block, segment_getName(segment)) == segment); //Orientations consistent. assert(segment_getOrientation(segment) == block_getOrientation(block)); //Check lengths are consistent assert(segment_getLength(segment) == block_getLength(block)); //Checks the two ends have caps. Cap *_5Cap = segment_get5Cap(segment); Cap *_3Cap = segment_get3Cap(segment); assert(_5Cap != NULL); //check segment has other ends. assert(_3Cap != NULL); assert(cap_getOtherSegmentCap(_5Cap) == _3Cap); //check we can get the other end assert(cap_getOtherSegmentCap(_3Cap) == _5Cap); //Checks the coordinates of the caps are consistent with the segment. assert(cap_getOrientation(_5Cap) == segment_getOrientation(segment)); //check orientations consistent assert(cap_getOrientation(_3Cap) == segment_getOrientation(segment)); assert(cap_getSide(_5Cap)); //check sides correctly configured assert(!cap_getSide(_3Cap)); assert(segment_getStrand(segment) == cap_getStrand(_5Cap)); //Check strand is consistent. assert(segment_getStrand(segment) == cap_getStrand(_3Cap)); assert(segment_getSequence(segment) == cap_getSequence(_5Cap)); //Check sequences are common (may be null). assert(segment_getSequence(segment) == cap_getSequence(_3Cap)); assert(segment_getStart(segment) == cap_getCoordinate(_5Cap)); //Check 5End coordinate is same as start, may both be INT64_MAX. assert(segment_getLength(segment) == block_getLength(block)); //Check coordinate length is consistent with block if (segment_getStart(segment) != INT64_MAX) { //check _3End coordinate is consistent if (segment_getStrand(segment)) { assert(segment_getStart(segment) + segment_getLength(segment) - 1 == cap_getCoordinate(_3Cap)); } else { assert(segment_getStart(segment) - segment_getLength(segment) + 1 == cap_getCoordinate(_3Cap)); } } else { assert(cap_getCoordinate(_3Cap) == INT64_MAX); } //Check the reverse.. Segment *rSegment = segment_getReverse(segment); assert(rSegment != NULL); assert(segment_getReverse(rSegment) == segment); assert(block == block_getReverse(segment_getBlock(rSegment))); assert(segment_getOrientation(segment) == !segment_getOrientation(rSegment)); assert(segment_getName(segment) == segment_getName(rSegment)); assert(segment_getEvent(segment) == segment_getEvent(rSegment)); assert(segment_getSequence(segment) == segment_getSequence(rSegment)); assert(segment_getStrand(segment) == !segment_getStrand(rSegment)); assert(segment_getStart(segment) == cap_getCoordinate(segment_get3Cap(rSegment))); assert(segment_getStart(rSegment) == cap_getCoordinate(segment_get3Cap(segment))); assert(segment_getLength(segment) == segment_getLength(rSegment)); assert(segment_get5Cap(segment) == cap_getReverse(segment_get3Cap(rSegment))); assert(segment_get3Cap(segment) == cap_getReverse(segment_get5Cap(rSegment))); }
2.453125
2
2024-11-18T21:05:54.831729+00:00
2020-03-13T19:45:29
30c422cf56c1329838e23084265c1ca5ed42ca80
{ "blob_id": "30c422cf56c1329838e23084265c1ca5ed42ca80", "branch_name": "refs/heads/master", "committer_date": "2020-03-13T19:45:29", "content_id": "ea97b32032785179ed469585aa079aeb9466a65e", "detected_licenses": [ "MIT" ], "directory_id": "aa592e6dcc1c2fe188e0208ff1b115ac827f8646", "extension": "c", "filename": "SHA256.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 238045608, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6358, "license": "MIT", "license_type": "permissive", "path": "/SHA256.c", "provenance": "stackv2-0083.json.gz:5005", "repo_name": "aaronBurns59/SHA-256-Algorithm", "revision_date": "2020-03-13T19:45:29", "revision_id": "761396268c3c4044ae08e859a047237be1f2e44d", "snapshot_id": "aebbd27796bdd97cca9a7ac2ab62e2019e25bf81", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aaronBurns59/SHA-256-Algorithm/761396268c3c4044ae08e859a047237be1f2e44d/SHA256.c", "visit_date": "2020-12-27T20:39:00.220595" }
stackv2
// Aaron Burns - SHA 256 functions // Sourced from: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf #include<stdio.h> #include<stdint.h> #include<inttypes.h> // Section 4.2.2 const uint32_t K[] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f }; // total amount of memory is 512 bits // the message that is going to be hashed is stored in this union structure union block{ uint32_t threeTwo[16]; uint64_t sixFour[8]; uint8_t eight[64]; }; // Ch is for choose, you use x to determine what bits from z or y you take from uint32_t Ch(uint32_t x, uint32_t y, uint32_t z){ // Section 4.1.2 of SHA Standard // ~ NOT in c // ^ XOR in c return (x & y) ^ (~x & z); } // If there are two or more 1s in any bit position between x, y and z, // its going to take a 1 and if there is less thentwo 1s we get a zero in the output uint32_t Maj(uint32_t x, uint32_t y, uint32_t z){ // Section 4.1.2 of SHA Standard return (x & y) ^ (x & z) ^ (y & z); } uint32_t SHR(uint32_t x, int n){ // Section 3.2 of SHA Standard // bit-shift x to the right the value of n return x>>n; } uint32_t ROTR(uint32_t x, int n){ // Section 3.2 of SHA Standard // bit-shift x to the right the value of n return (x>>n) | (x << (32 - n)); } uint32_t Sig0(uint32_t x){ // Section 4.1.2 of SHA Standard return ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22); } uint32_t Sig1(uint32_t x){ // Section 4.1.2 of SHA Standard return ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25); } uint32_t sig0(uint32_t x){ // Section 4.1.2 of SHA Standard return ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3); } uint32_t sig1(uint32_t x){ // Section 4.1.2 of SHA Standard return ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10); } uint64_t NoZerosBytes(uint64_t nobits){ // the number of bits from the file retrieved from the read file block of code () // ULL : Unsigned Long Long integer (Makes sure c saves var as a 64 bit integer) // The final output needs to be a multiple of 512 bits uint64_t result = 512ULL - (nobits % 512ULL); // find out if there is enough room in the last block to do the padding or will a new block be needed if (result < 65)// 65 (length of integer and the 1) result += 512; // get the number of 0 bytes needed to pad between the 1 and the 64 bit integer printed at the end result -=72; return (result/ 8ULL); } // handy list of constantsi // these are the 4 possible scenarios nextblock can come across enum flag {READ, PAD0, FINISH}; // *status gets the enum value of the current state // *nobits is for this function to keep track of the bits it has read int nextblock(union block *M, FILE *infile, uint64_t *nobits, enum flag *status){ // check the status of the padding flag before anything is read in if(*status == FINISH) return 0; if(*status == PAD0) { // < 56 because you need to leave room for the last 8 bytes of the message 64 - 8 = 56 for(int i = 0; i < 56; i++) M->eight[0]; // need to stick the 64 bit message into the last 8 bytes of the now padded message // index 7 is the last byte of this version of M in its 64 bit form // make the last byte of M equal to the message passed in // the rest of the bytes in M are now 0's except for the first bit which is a single 1-bit M->sixFour[7] = *nobits; // the padding is done, set the status to finish *status= FINISH; return 1; }// if size_t noBytesRead = fread(M->eight, 1, 64, infile); if(noBytesRead == 64) return 1; // can fit all the padding in the last block if(noBytesRead < 56) { // this will be the position to put the 1 bit M->eight[noBytesRead] = 0x80; for(int i = noBytesRead + 1; i < 56; i++) M->eight[i] = 0; M->sixFour[7] = *nobits; *status = FINISH; return 1; }// if } void nexthash(union block *M, uint32_t *H){ uint32_t W[64]; uint32_t T1,T2,a,b,c,d,e,f,g,h; int t; for(t = 0; t <= 15; t++){ // The union M->threeTwo allows W to be handled as a 32-bit integer W[t] = M->threeTwo[t]; } // Section 6.2.2 for(t = 16; t <= 63; t++){ W[t]= sig1(W[t-2]) + W[t-7] + sig0(W[t-15]) + W[t-16]; } // Store the values in H in 8 different variables // automatically gets the index from the pointer a = H[0]; b = H[1]; c = H[2]; d = H[3]; e = H[4]; f = H[5]; g = H[6]; h = H[7]; for(t = 0; t <= 63; t++){ T1 = h + Sig1(e) + Ch(e,f,g) + K[t] + W[t]; T2 = Sig0(a) + Maj(a,b,c); h=g; g=f; f=e; e=d + T1; d=c; c=b; b=a; a=T1 + T2; H[0] = a + H[0]; H[1] = b + H[1]; H[2] = c + H[2]; H[3] = d + H[3]; H[4] = e + H[4]; H[5] = f + H[5]; H[6] = g + H[6]; H[7] = h + H[7]; } } int main(int argc, char* argv[]){ if (argc != 2){ printf("Error: Expecting single filename as argument\n"); // if main returns anything other then 0 that indicates an error return 1; } // declare for reading file FILE *infile = fopen(argv[1], "rb"); if(!infile){ printf("Error: Could not open file %s\n", argv[1]); return 1; } // keep track of the number of bits read from the input // Current padded message block union block M; // Section 5.3.3 uint32_t H[] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; uint64_t nobits = 0; enum flag status = READ; // reads from the file until the end it reads blocks and returns padded blocks // reads in an 8-bit value while (nextblock(&M, infile, nobits, &status)){ // calculate the next hash value // uses the 32-bit value nexthash(&M, &H); } // need to close the file when finished with it // print the last hash value for(int i; i < 8; i++) printf("%02" PRIX32, H[i]); printf("\n"); fclose(infile); return 0; }
2.84375
3
2024-11-18T21:05:54.970712+00:00
2020-02-02T21:55:54
2c9c0e6cf35dc217347fd6e487f8b058e3cde29c
{ "blob_id": "2c9c0e6cf35dc217347fd6e487f8b058e3cde29c", "branch_name": "refs/heads/master", "committer_date": "2020-02-02T21:55:54", "content_id": "60801035482f5c88daac0095dddaa53906d5c5e2", "detected_licenses": [ "MIT" ], "directory_id": "a6caa80992a9a2593a8fb608f2f89083fa94d727", "extension": "c", "filename": "getCountTest.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 237070370, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 465, "license": "MIT", "license_type": "permissive", "path": "/getCountTest.c", "provenance": "stackv2-0083.json.gz:5134", "repo_name": "Sepehr1812/xv6-public", "revision_date": "2020-02-02T21:55:54", "revision_id": "8b7f92648f853def797c2de4cba4eed44afd0b31", "snapshot_id": "688b05a7cff042a3d25df0c2b83a0ef2125da9d5", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/Sepehr1812/xv6-public/8b7f92648f853def797c2de4cba4eed44afd0b31/getCountTest.c", "visit_date": "2020-12-23T06:41:57.150098" }
stackv2
// Test for Q 2.2 #include "types.h" #include "user.h" int main(int argc, char const *argv[]) { int scn = atoi(argv[1]); // sys call number 22 has repeated for 5 times to test. // It prints a doubled number after each time we call "getCountTest 22" : 7, 14, 21, ... . getppid(); getppid(); getppid(); getppid(); getppid(); getppid(); getppid(); printf(1, "System Call Count: %d\n", getCount(scn)); exit(); }
2.34375
2
2024-11-18T21:05:55.292188+00:00
2016-10-04T16:43:01
b4bfd66cea2711b388ce9180dcee0a8c2313b9f4
{ "blob_id": "b4bfd66cea2711b388ce9180dcee0a8c2313b9f4", "branch_name": "refs/heads/master", "committer_date": "2016-10-04T16:43:01", "content_id": "8c36ff15df7fd8479cfdc86b7323e53dcb62104c", "detected_licenses": [ "MIT" ], "directory_id": "2fed16453d49da3435fd80fd0e7c5f8455595d55", "extension": "c", "filename": "furkan.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 69984704, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1649, "license": "MIT", "license_type": "permissive", "path": "/FourİnOne/Src/furkan.c", "provenance": "stackv2-0083.json.gz:5392", "repo_name": "fmut/Stm32f407-Discovery", "revision_date": "2016-10-04T16:43:01", "revision_id": "48dbabdc8868b44ec94019da19ae47cdfdb3e2a6", "snapshot_id": "681d4b8bb8623907a3a35a86eec6d4f1fe1166bb", "src_encoding": "ISO-8859-3", "star_events_count": 2, "url": "https://raw.githubusercontent.com/fmut/Stm32f407-Discovery/48dbabdc8868b44ec94019da19ae47cdfdb3e2a6/FourİnOne/Src/furkan.c", "visit_date": "2020-12-11T02:00:25.142530" }
stackv2
#include "furkan.h" #include <stdint.h> #include "usart.h" #define BUFF_SIZE 1024 uint8_t terminalRx, pairRx; char hello[] = "hello\r\n"; uint8_t cbufTerm[BUFF_SIZE], cbufPair[BUFF_SIZE]; static uint16_t Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength); void FRK_Init(void) { HAL_UART_Transmit_IT(&huart1, (uint8_t*)hello, 7); HAL_UART_Transmit_IT(&huart2, (uint8_t*)hello, 7); HAL_UART_Receive(&huart1, (uint8_t *)&terminalRx, 1, 1); HAL_UART_Receive(&huart2, (uint8_t *)&pairRx, 1, 1); } // usart1'den gelen terminalden gelir // usart2'ye (diger karta) yönlendilir // usart2'den gelen diger karttan gelir // usart1'den (terminale) yönlendilir void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { if (huart == NULL) { return; } else if (huart == &huart1) { } else if (huart == &huart2) { } } void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if (huart == NULL) { return; } else if (huart == &huart1) { // terminalden gelmis //FRK_AddToTermBuf(terminalRx); HAL_NVIC_DisableIRQ(USART1_IRQn); HAL_UART_Transmit(&huart2, &terminalRx, 1, 1); HAL_NVIC_EnableIRQ(USART1_IRQn); HAL_UART_Receive(&huart1, &terminalRx, 1, 1); } else if (huart == &huart2) { // diger karttan gelmis //FRK_AddToPairBuf(pairRx); HAL_NVIC_DisableIRQ(USART2_IRQn); HAL_UART_Transmit(&huart1, &pairRx, 1, 1); HAL_NVIC_EnableIRQ(USART2_IRQn); HAL_UART_Receive(&huart2, &pairRx, 1, 1); } } void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { } void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { }
2.21875
2
2024-11-18T21:05:55.404385+00:00
2021-04-03T22:32:44
ceec266f2d1cbf0aec3b7c3ab6b84680e850cbdf
{ "blob_id": "ceec266f2d1cbf0aec3b7c3ab6b84680e850cbdf", "branch_name": "refs/heads/master", "committer_date": "2021-04-03T22:32:44", "content_id": "ffd11d7ee171978d8089757c81e0b8f1be58f989", "detected_licenses": [ "MIT" ], "directory_id": "7e31c5cb44e540a296c556a2200c1d131b42fe49", "extension": "c", "filename": "receptionist.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 290646750, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1632, "license": "MIT", "license_type": "permissive", "path": "/Flame-GPU/examples/PedestrianNavigation/src/model/receptionist.c", "provenance": "stackv2-0083.json.gz:5521", "repo_name": "Fedeblasco/PPS-Flame-GPU", "revision_date": "2021-04-03T22:32:44", "revision_id": "c3e32447bf085ee5b6cec46b2fc6b8e8df8ee546", "snapshot_id": "6350e5ac3776ae02463500175189dbf793d29bf6", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Fedeblasco/PPS-Flame-GPU/c3e32447bf085ee5b6cec46b2fc6b8e8df8ee546/Flame-GPU/examples/PedestrianNavigation/src/model/receptionist.c", "visit_date": "2023-04-05T05:27:41.875312" }
stackv2
//Archivo con las funciones del recepcionista //Función que chequea los pacientes que llegan y los atiende __FLAME_GPU_FUNC__ int reception_server(xmachine_memory_receptionist* agent, xmachine_message_check_in_list* checkInMessages, xmachine_message_check_in_response_list* patientMessages){ xmachine_message_check_in* current_message = get_first_check_in_message(checkInMessages); while(current_message){ //Si llega el paciente que tengo que atender, prendo el flag de atención if(current_message->id == agent->current_patient){ agent->attend_patient = 1; }else{ enqueue(agent->patientQueue, current_message->id,&agent->size, &agent->rear); } current_message = get_next_check_in_message(current_message, checkInMessages); } //Si tengo algun paciente esperando y no estoy procesando a nadie if((!isEmpty(&agent->size)) && (agent->current_patient == -1)){ unsigned int patient = dequeue(agent->patientQueue, &agent->size, &agent->front); add_check_in_response_message(patientMessages, patient); agent->current_patient = patient; //printf("Enviando mensaje 1 a %d\n",agent->current_patient); }else if(agent->attend_patient == 1){ agent->tick++; if(agent->tick * SECONDS_PER_TICK >= RECEPTION_SECONDS){ //printf("Enviando mensaje 2 a %d\n",agent->current_patient); add_check_in_response_message(patientMessages, agent->current_patient); agent->tick = 0; agent->current_patient = -1; agent->attend_patient = 0; } } return 0; }
2.3125
2
2024-11-18T21:05:56.018569+00:00
2018-05-16T08:23:00
1fab0a11fb091f4164efc482da2793cd5b8a678f
{ "blob_id": "1fab0a11fb091f4164efc482da2793cd5b8a678f", "branch_name": "refs/heads/master", "committer_date": "2018-05-16T08:23:00", "content_id": "d7244b58d854592997a4ca7cfcbcce92f59f95e7", "detected_licenses": [ "MIT" ], "directory_id": "c9f9d82a8913030dd12af0c2703b2bc0537fb92a", "extension": "c", "filename": "gps.c", "fork_events_count": 0, "gha_created_at": "2018-05-11T13:55:25", "gha_event_created_at": "2018-05-11T13:55:25", "gha_language": null, "gha_license_id": null, "github_id": 133046320, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1999, "license": "MIT", "license_type": "permissive", "path": "/src/gps.c", "provenance": "stackv2-0083.json.gz:6163", "repo_name": "ccoff/libgps", "revision_date": "2018-05-16T08:23:00", "revision_id": "9dbd197dd4848ffa9cb561ce69c5d99c38fb8919", "snapshot_id": "efe1c93082dcb4906d0b58c25b69d19f8d105794", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ccoff/libgps/9dbd197dd4848ffa9cb561ce69c5d99c38fb8919/src/gps.c", "visit_date": "2020-03-16T22:37:24.582869" }
stackv2
#include "gps.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include "nmea.h" #include "serial.h" extern void gps_init(char *devname) { serial_init(devname); serial_config(); //Write commands } extern void gps_on(void) { //Write on } // Compute the GPS location using decimal scale extern void gps_location(loc_t *coord) { uint8_t status = _EMPTY; while(status != _COMPLETED) { gpgga_t gpgga; gprmc_t gprmc; char buffer[256]; serial_readln(buffer, 256); switch (nmea_get_message_type(buffer)) { case NMEA_GPGGA: nmea_parse_gpgga(buffer, &gpgga); gps_convert_deg_to_dec(&(gpgga.latitude), gpgga.lat, &(gpgga.longitude), gpgga.lon); coord->latitude = gpgga.latitude; coord->longitude = gpgga.longitude; coord->altitude = gpgga.altitude; status |= NMEA_GPGGA; break; case NMEA_GPRMC: nmea_parse_gprmc(buffer, &gprmc); coord->speed = gprmc.speed; coord->course = gprmc.course; status |= NMEA_GPRMC; break; } } } extern void gps_off(void) { //Write off serial_close(); } // Convert lat e lon to decimals (from deg) void gps_convert_deg_to_dec(double *latitude, char ns, double *longitude, char we) { double lat = (ns == 'N') ? *latitude : -1 * (*latitude); double lon = (we == 'E') ? *longitude : -1 * (*longitude); *latitude = gps_deg_dec(lat); *longitude = gps_deg_dec(lon); } double gps_deg_dec(double deg_point) { double ddeg; double sec = modf(deg_point, &ddeg)*60; int deg = (int)(ddeg/100); int min = (int)(deg_point-(deg*100)); double absdlat = round(deg * 1000000.); double absmlat = round(min * 1000000.); double absslat = round(sec * 1000000.); return round(absdlat + (absmlat/60) + (absslat/3600)) /1000000; }
2.890625
3
2024-11-18T21:05:56.104119+00:00
2018-09-21T07:45:49
1a3e7fa28dc790acd0777e6b4a42e45395e6e0a1
{ "blob_id": "1a3e7fa28dc790acd0777e6b4a42e45395e6e0a1", "branch_name": "refs/heads/master", "committer_date": "2018-09-21T07:45:49", "content_id": "576d6db6776d081bd29cab1f53040aa20d2d26e7", "detected_licenses": [ "MIT" ], "directory_id": "47a9f0cc28f20a0dee99ea9f26118193084acdf4", "extension": "c", "filename": "485_new.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 828, "license": "MIT", "license_type": "permissive", "path": "/program_data/github_cpp_program_data/6/485_new.c", "provenance": "stackv2-0083.json.gz:6292", "repo_name": "Peiyance/ggnn.pytorch", "revision_date": "2018-09-21T07:45:49", "revision_id": "87c6736b40358fb1ecdedec4d13931a46c9364a1", "snapshot_id": "d5efe4d345f1be249dcff3c88f285b318fe71b63", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Peiyance/ggnn.pytorch/87c6736b40358fb1ecdedec4d13931a46c9364a1/program_data/github_cpp_program_data/6/485_new.c", "visit_date": "2020-03-29T11:25:58.362404" }
stackv2
#include "LinkedList.h" #include "Node.h" #include <string> #include <cassert> template <typename T> LinkedList<T>::LinkedList() { head=0; numElements=0; } template <typename T> LinkedList<T>::LinkedList(Node<T>* h, int nE) { head=h; numElements=nE; } template <typename T> LinkedList<T>::~LinkedList() {} template <typename T> Node<T>* LinkedList<T>::getHead() { return head; } template <typename T> void LinkedList<T>::setHead(Node<T>* h) { head=h; } template <typename T> int LinkedList<T>::getSize() { return numElements; } template <typename T> void LinkedList<T>::setSize(int nE) { numElements=nE; } template <typename T> bool LinkedList<T>::isEmpty() { return numElements==0; } template class LinkedList<int>; template class LinkedList<double>; template class LinkedList<std::string>;
2.359375
2
2024-11-18T21:05:56.171018+00:00
2020-04-19T02:21:22
5730efa6641ad6f0fa4ebf8f6e807d79e3efb44c
{ "blob_id": "5730efa6641ad6f0fa4ebf8f6e807d79e3efb44c", "branch_name": "refs/heads/master", "committer_date": "2020-04-19T02:21:22", "content_id": "f79059e6a92c6c9b0b054ee73b8ec7f4358c6f9d", "detected_licenses": [ "MIT" ], "directory_id": "b79c9cd0ffb488eb3e4f409ed2c00e61e6d02ec3", "extension": "c", "filename": "3-strspn.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 209338104, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 296, "license": "MIT", "license_type": "permissive", "path": "/0x07-pointers_arrays_strings/3-strspn.c", "provenance": "stackv2-0083.json.gz:6421", "repo_name": "calypsobronte/holbertonschool-low_level_programming", "revision_date": "2020-04-19T02:21:22", "revision_id": "c892ea08220229c72ce6bf6827ced23146ff663f", "snapshot_id": "bb696ef219a4a2bcbc68f394284d42805c7d22da", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/calypsobronte/holbertonschool-low_level_programming/c892ea08220229c72ce6bf6827ced23146ff663f/0x07-pointers_arrays_strings/3-strspn.c", "visit_date": "2020-07-28T06:37:49.957265" }
stackv2
#include "holberton.h" /** * _strspn - comparacion entre cada posicion * @s: point * @accept: point * Return: c */ unsigned int _strspn(char *s, char *accept) { unsigned int a, b, c = 0; for (a = 0; s[a] != 32; a++) for (b = 0; accept[b] != 0; b++) if (s[a] == accept[b]) c++; return (c); }
2.484375
2
2024-11-18T21:05:56.359971+00:00
2023-08-03T15:53:40
a037fd213e94a8bbfb34ea1ede98f97a65a523d2
{ "blob_id": "a037fd213e94a8bbfb34ea1ede98f97a65a523d2", "branch_name": "refs/heads/master", "committer_date": "2023-08-03T15:53:40", "content_id": "f052e08b68d543585608a80c797a3d9768438ecd", "detected_licenses": [ "MIT" ], "directory_id": "19c8f714f77aba731fbe4569501d63a51946f24e", "extension": "h", "filename": "AtmelAtsha204a.h", "fork_events_count": 42, "gha_created_at": "2015-11-06T11:18:35", "gha_event_created_at": "2023-03-16T09:43:28", "gha_language": "Tcl", "gha_license_id": "NOASSERTION", "github_id": 45677828, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2957, "license": "MIT", "license_type": "permissive", "path": "/os/alpha/fsbl/AtmelAtsha204a.h", "provenance": "stackv2-0083.json.gz:6678", "repo_name": "Koheron/koheron-sdk", "revision_date": "2023-08-03T15:53:40", "revision_id": "4a4010f9b94c45e3245ff4b6823b1bcf7be563aa", "snapshot_id": "dca220c632ea77f755b638f0dd53389d77e9f72a", "src_encoding": "UTF-8", "star_events_count": 95, "url": "https://raw.githubusercontent.com/Koheron/koheron-sdk/4a4010f9b94c45e3245ff4b6823b1bcf7be563aa/os/alpha/fsbl/AtmelAtsha204a.h", "visit_date": "2023-08-15T12:08:26.156853" }
stackv2
/** \file AtmelAtsha204a.h * Header file for plain-C atmel_atsha204a functions, used in module tests. * \author Garry Jeromson * \date 16.06.2015 * * Copyright (c) 2015 Enclustra GmbH, Switzerland. * All rights reserved. */ #pragma once //------------------------------------------------------------------------------------------------- // Includes //------------------------------------------------------------------------------------------------- #include "AtmelAtsha204aTypes.h" #include "StandardIncludes.h" //------------------------------------------------------------------------------------------------- // Constants //------------------------------------------------------------------------------------------------- /// The number of milliseconds it takes for the device to come out of sleep mode #define ATMEL_ATSHA204A_WAKE_TIME_MILLISECONDS (10) /// Average time for the read command to complete, after which polling should start #define ATMEL_ATSHA204A_READ_EXECUTION_TIME_MILLISECONDS (1) //------------------------------------------------------------------------------------------------- // Global variables //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- // Function declarations //------------------------------------------------------------------------------------------------- /** * \brief Wake the device by setting I2C SDA low for the required time period. * * Note that this is achieved by a general call to device address 0x00. ** * @param verifyDeviceType Set true to verify the device type by reading back a command response * immediately after wake * @return Result code */ EN_RESULT AtmelAtsha204a_Wake(bool verifyDeviceType); /** * \brief Put the device in low-power sleep mode. * @return Result code */ EN_RESULT AtmelAtsha204a_Sleep(); /** * \brief Encode an address for reading or writing. * * @param[in] zone Zone select * @param[in] slotIndex Slot select * @param[in] wordOffset Word offset within the given slot * @param[out] encodedAddress The encoded address * @return Result code */ EN_RESULT AtmelAtsha204a_EncodeAddress(EZoneSelect_t zone, uint8_t slotIndex, uint8_t wordOffset, uint16_t* encodedAddress); /** * \brief Read from the device. * * @param[in] sizeSelect Size select, 4 or 32 bytes * @param[in] zoneSelect Zone select * @param[in] encodedAddress Encoded address * @param[out] pReadData Buffer to receive read data * @return Result code */ EN_RESULT AtmelAtsha204a_Read(EReadSizeSelect_t sizeSelect, EZoneSelect_t zoneSelect, uint16_t encodedAddress, uint8_t* pReadData);
2.28125
2
2024-11-18T21:05:56.450665+00:00
2016-07-16T20:12:37
37ebbd3f6cf68fa32ecc28660982b74276a95229
{ "blob_id": "37ebbd3f6cf68fa32ecc28660982b74276a95229", "branch_name": "refs/heads/master", "committer_date": "2016-07-16T20:12:37", "content_id": "9cefe8947d1329567f1851eeb7975a16ac789fa5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "25b780871d6b6abf551243e548ab0592a04c460b", "extension": "h", "filename": "sram.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2151, "license": "Apache-2.0", "license_type": "permissive", "path": "/source/sram.h", "provenance": "stackv2-0083.json.gz:6807", "repo_name": "tgwjw/wearable-reference-design-example-watch", "revision_date": "2016-07-16T20:12:37", "revision_id": "eaadc01cd8a03798e3165836f604c3aa128deb15", "snapshot_id": "63e1e9d426893ec0c2a4f1bb2fdb87d83bfa8316", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tgwjw/wearable-reference-design-example-watch/eaadc01cd8a03798e3165836f604c3aa128deb15/source/sram.h", "visit_date": "2021-06-01T04:14:40.388010" }
stackv2
/* SRAM properties */ #define EXT_SRAM_HIGHEST_ADDRESS_BIT (16) #define EXT_SRAM_LOWEST_ADDRESS_BIT (0) #define EXT_SRAM_DATA_WIDTH (16) #define EXT_SRAM_SIZE ( ( 1 << (EXT_SRAM_HIGHEST_ADDRESS_BIT - EXT_SRAM_LOWEST_ADDRESS_BIT + 2) ) - 1 ) /* SRAM Address pins */ #define EXT_SRAM_A0 PA12 #define EXT_SRAM_A1 PA13 #define EXT_SRAM_A2 PA14 #define EXT_SRAM_A3 PB9 #define EXT_SRAM_A4 PB10 #define EXT_SRAM_A5 PC6 #define EXT_SRAM_A6 PC7 #define EXT_SRAM_A7 PE0 #define EXT_SRAM_A8 PE1 #define EXT_SRAM_A9 PE2 #define EXT_SRAM_A10 PE3 #define EXT_SRAM_A11 PE4 #define EXT_SRAM_A12 PE5 #define EXT_SRAM_A13 PE6 #define EXT_SRAM_A14 PE7 #define EXT_SRAM_A15 PC8 #define EXT_SRAM_A16 PB0 /* SRAM Data pins */ #define EXT_SRAM_D0 PE8 #define EXT_SRAM_D1 PE9 #define EXT_SRAM_D2 PE10 #define EXT_SRAM_D3 PE11 #define EXT_SRAM_D4 PE12 #define EXT_SRAM_D5 PE13 #define EXT_SRAM_D6 PE14 #define EXT_SRAM_D7 PE15 #define EXT_SRAM_D8 PA15 #define EXT_SRAM_D9 PA0 #define EXT_SRAM_D10 PA1 #define EXT_SRAM_D11 PA2 #define EXT_SRAM_D12 PA3 #define EXT_SRAM_D13 PA4 #define EXT_SRAM_D14 PA5 #define EXT_SRAM_D15 PA6 /* SRAM control pins */ /* (SRAM configured to bank 0 of EBI) */ #define EXT_SRAM_nCS PD9 #define EXT_SRAM_nOE PF5 #define EXT_SRAM_nWE PF4 #define EXT_SRAM_EBI_BANK (0x0) /* Pin setup array */ static const PinName sramSetupArray[(EXT_SRAM_HIGHEST_ADDRESS_BIT - EXT_SRAM_LOWEST_ADDRESS_BIT) + 1 + EXT_SRAM_DATA_WIDTH + 3] = { EXT_SRAM_A0, EXT_SRAM_A1, EXT_SRAM_A2, EXT_SRAM_A3, EXT_SRAM_A4, EXT_SRAM_A5, EXT_SRAM_A6, EXT_SRAM_A7, EXT_SRAM_A8, EXT_SRAM_A9, EXT_SRAM_A10, EXT_SRAM_A11, EXT_SRAM_A12, EXT_SRAM_A13, EXT_SRAM_A14, EXT_SRAM_A15, EXT_SRAM_A16, EXT_SRAM_D0, EXT_SRAM_D1, EXT_SRAM_D2, EXT_SRAM_D3, EXT_SRAM_D4, EXT_SRAM_D5, EXT_SRAM_D6, EXT_SRAM_D7, EXT_SRAM_D8, EXT_SRAM_D9, EXT_SRAM_D10, EXT_SRAM_D11, EXT_SRAM_D12, EXT_SRAM_D13, EXT_SRAM_D14, EXT_SRAM_D15, EXT_SRAM_nCS, EXT_SRAM_nOE, EXT_SRAM_nWE };
2.15625
2
2024-11-18T21:05:56.976503+00:00
2020-04-30T20:53:25
fcd109d2f05fd37b2924f14904944f6788ed8a44
{ "blob_id": "fcd109d2f05fd37b2924f14904944f6788ed8a44", "branch_name": "refs/heads/dev-test", "committer_date": "2020-04-30T20:53:25", "content_id": "9b1db9843b08cf3f4884a7a9bd6dd06f0de68b00", "detected_licenses": [ "MIT" ], "directory_id": "48ef720c1e853bd95d46bb8e5cd1915a22e5b1ab", "extension": "c", "filename": "mini-uart.c", "fork_events_count": 0, "gha_created_at": "2020-04-25T09:30:06", "gha_event_created_at": "2020-05-01T13:50:28", "gha_language": "C", "gha_license_id": "MIT", "github_id": 258733413, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3246, "license": "MIT", "license_type": "permissive", "path": "/raspberrypi/mini-uart.c", "provenance": "stackv2-0083.json.gz:7064", "repo_name": "ZuluSpl0it/micropython-raspberrypi", "revision_date": "2020-04-30T20:53:25", "revision_id": "db63ff3cd3159ad0381a4525950711f581dcced4", "snapshot_id": "13dd6b33b5760fce8b179b782bfa141dfa9aba7e", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/ZuluSpl0it/micropython-raspberrypi/db63ff3cd3159ad0381a4525950711f581dcced4/raspberrypi/mini-uart.c", "visit_date": "2022-06-04T01:51:48.169925" }
stackv2
#include "bcm283x_gpio.h" #include "bcm283x_aux.h" #include "bcm283x_it.h" #include "rpi.h" #include "mini-uart.h" #include "lib/utils/interrupt_char.h" // Set this to 0 for avoiding mini-UART interrupts. #define USE_IRQ 1 mini_uart_t volatile *mini_uart = (mini_uart_t*) AUX_MU; #define RX_CH (mini_uart->IO) #define TX_FULL ((mini_uart->LSR & 0x20) == 0x0) #define TX_CH(c) (mini_uart->IO = (c)) #if USE_IRQ // Receive interrupt only. Transmit interrput is not supported. #define IRQ_MU_PENDING ((mini_uart->IIR & 1U) == 0) #define RX_BUF_SIZE 0xfff volatile unsigned char rbuf[RX_BUF_SIZE + 1]; volatile uint32_t rbuf_w; volatile uint32_t rbuf_r; #define RX_BUF_INIT {rbuf_w = 0; rbuf_r = 0;} #define RX_EMPTY (rbuf_w == rbuf_r) #define RX_FULL (((rbuf_w + 1) & RX_BUF_SIZE) == rbuf_r) #define RX_WRITE(c) \ rbuf[rbuf_w] = (c); \ rbuf_w = (rbuf_w + 1) & RX_BUF_SIZE; \ if RX_EMPTY { rbuf_r = (rbuf_r + 1) & RX_BUF_SIZE; } #define RX_READ(c) \ c = rbuf[rbuf_r]; \ rbuf_r = (rbuf_r + 1) & RX_BUF_SIZE; static void mini_uart_irq_enable() { IRQ_ENABLE1 = IRQ_AUX; } static void mini_uart_irq_disable() { IRQ_DISABLE1 = IRQ_AUX; } void isr_irq_mini_uart(void) { while (IRQ_MU_PENDING) { if (mini_uart->IIR & MU_IIR_RX_AVAIL) { unsigned char c = (RX_CH & 0xff); if (c == mp_interrupt_char) { mp_keyboard_interrupt(); } else { RX_WRITE(c); } } } } #else // USE_IRQ #define RX_EMPTY !(mini_uart->LSR & 1U) #define RX_READ(c) (c = RX_CH) void isr_irq_mini_uart(void) { return; } #endif // USE_IRQ void mini_uart_set_speed(uint32_t speed) { mini_uart->CNTL = 0; // disable mini uart mini_uart->BAUD = ((rpi_freq_core() / speed) >> 3) - 1; mini_uart->CNTL = 3; // enable mini uart } void mini_uart_init() { // set GPIO14, GPIO15, alternate function 5 IOREG(GPFSEL1) = (GPF_ALT_5 << (3*4)) | (GPF_ALT_5 << (3*5)); // UART basic settings #if USE_IRQ mini_uart_irq_disable(); #endif AUX_ENABLES |= AUX_FLAG_MU; mini_uart->IER = 0; // disable interrupts mini_uart->CNTL = 0; // disable mini uart #if USE_IRQ mini_uart->IER = MU_IER_RX_AVAIL; // enable receive interrupt #else mini_uart->IER = 0; // disable receive/transmit interrupts #endif mini_uart->IIR = 0xC6; // enable FIFO(0xC0), clear FIFO(0x06) mini_uart->MCR = 0; // set RTS to High // data and speed (mini uart is always parity none, 1 start bit 1 stop bit) mini_uart->LCR = 3; // 8 bits; Note: BCM2835 manual p14 is incorrect mini_uart->BAUD = ((rpi_freq_core() / 115200) >> 3) - 1; // mini_uart->BAUD = 270; // 1115200 bps @ core_freq=250 // mini_uart->BAUD = 434; // 1115200 bps @ core_freq=400 // enable transmit and receive #if USE_IRQ RX_BUF_INIT; mini_uart_irq_enable(); #endif mini_uart->CNTL = 3; }; void mini_uart_putc(char c) { while(TX_FULL) { } TX_CH(c); } uint32_t mini_uart_getc(void) { uint32_t c; while(RX_EMPTY) { } RX_READ(c); return c & 0xffU; } uint32_t mini_uart_rx_state(void) { return !RX_EMPTY; }
2.28125
2
2024-11-18T21:05:57.134075+00:00
2020-06-24T22:00:20
0ff7520ce950e577c2ff960ace1785f4ada6958a
{ "blob_id": "0ff7520ce950e577c2ff960ace1785f4ada6958a", "branch_name": "refs/heads/master", "committer_date": "2020-06-24T22:00:20", "content_id": "89a205d598f2db9835641bd7622dca8753cdf28e", "detected_licenses": [ "MIT" ], "directory_id": "c9c4f6fef90743bcc770fc307dabc563a96a2516", "extension": "h", "filename": "mlx90614.h", "fork_events_count": 0, "gha_created_at": "2020-06-24T21:59:56", "gha_event_created_at": "2020-06-24T21:59:57", "gha_language": null, "gha_license_id": "MIT", "github_id": 274777647, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1616, "license": "MIT", "license_type": "permissive", "path": "/Inc/mlx90614.h", "provenance": "stackv2-0083.json.gz:7321", "repo_name": "BryanMierzwa/MLX90614_STM32_HAL", "revision_date": "2020-06-24T22:00:20", "revision_id": "3fca246dfab460cadeea03f2af16367e5490ed53", "snapshot_id": "3a5af5aa456e7bace1990f02a9c33dad0c336cc3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/BryanMierzwa/MLX90614_STM32_HAL/3fca246dfab460cadeea03f2af16367e5490ed53/Inc/mlx90614.h", "visit_date": "2022-11-09T23:14:39.538736" }
stackv2
/* * mlx90614.h * * The MIT License. * Created on: 25.01.2019 * Author: Mateusz Salamon * www.msalamon.pl * mateusz@msalamon.pl * * https://github.com/lamik/MLX90614_STM32_HAL * https://msalamon.pl/jak-chuck-norris-mierzy-temperature-patrzy-na-nia-mlx90614-na-stm32/ */ #ifndef MLX90614_H_ #define MLX90614_H_ #define MLX90614_DEFAULT_ADDRESS ((0x5A)<<1) // RAM #define MLX90614_RAWIR1 0x04 #define MLX90614_RAWIR2 0x05 #define MLX90614_TA 0x06 #define MLX90614_TOBJ1 0x07 #define MLX90614_TOBJ2 0x08 // EEPROM #define MLX90614_TOMAX 0x00 #define MLX90614_TOMIN 0x01 #define MLX90614_PWMCTRL 0x02 #define MLX90614_TARANGE 0x03 #define MLX90614_EMISS 0x04 #define MLX90614_CONFIG 0x05 #define MLX90614_ADDR 0x0E #define MLX90614_EMISS_CALIBRATION 0x0F #define MLX90614_ID1 0x1C #define MLX90614_ID2 0x1D #define MLX90614_ID3 0x1E #define MLX90614_ID4 0x1F #define MLX90614CMD_UNLOCK_EMISS_CALIBRATION 0x60 #define MLX90614_SLEEP_MODE 0xFF typedef enum { MLX90614_OK = 0, MLX90614_ERROR = 1 }MLX90614_STATUS; MLX90614_STATUS MLX90614_Init(I2C_HandleTypeDef *hi2c); MLX90614_STATUS MLX90614_SetAddress(uint8_t Address); MLX90614_STATUS MLX90614_GetId(uint32_t *Id); MLX90614_STATUS MLX90614_ReadObjectTemperature(float *Temperature); MLX90614_STATUS MLX90614_ReadAmbientTemperature(float *Temperature); // // IR Emissivity Table - https://msalamon.pl/download/691/ // MLX90614_STATUS MLX90614_GetEmissivity(float *Emissivity); MLX90614_STATUS MLX90614_SetEmissivity(float Emissivity); MLX90614_STATUS MLX90614_ResetEmissivity(float DefaultEmissivity); #endif /* MLX90614_H_ */
2.015625
2
2024-11-18T21:05:57.822218+00:00
2018-06-08T18:45:29
60326407278a8c09249a78c85f585bb7fa58d86f
{ "blob_id": "60326407278a8c09249a78c85f585bb7fa58d86f", "branch_name": "refs/heads/master", "committer_date": "2018-06-08T18:45:29", "content_id": "d85768696b74861f4597848b874af9274fbd2bf5", "detected_licenses": [ "MIT" ], "directory_id": "016c5202fd1c748b4ec7a199433640924a475205", "extension": "h", "filename": "ztype.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 75004941, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10525, "license": "MIT", "license_type": "permissive", "path": "/include/SHIZEN/ztype.h", "provenance": "stackv2-0083.json.gz:7964", "repo_name": "jhauberg/SHIZEN", "revision_date": "2018-06-08T18:45:29", "revision_id": "a6ce6339296b8c14e4290de035701db083efa8ac", "snapshot_id": "f6057bc4a3858cac76b53eb4d21b71ab893e5957", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jhauberg/SHIZEN/a6ce6339296b8c14e4290de035701db083efa8ac/include/SHIZEN/ztype.h", "visit_date": "2020-06-17T13:21:15.714353" }
stackv2
//// // __| | | _ _| __ / __| \ | // \__ \ __ | | / _| . | // ____/ _| _| ___| ____| ___| _|\_| // // Copyright (c) 2016 Jacob Hauberg Hansen // // This library is free software; you can redistribute and modify it // under the terms of the MIT license. See LICENSE for details. // #ifndef ztype_h #define ztype_h #include <stdbool.h> #include "zlayer.h" typedef struct SHIZVector2 { float x, y; } SHIZVector2; typedef struct SHIZSize { float width; float height; } SHIZSize; typedef struct SHIZRect { SHIZVector2 origin; SHIZSize size; } SHIZRect; typedef struct SHIZColor { float r, g, b; float alpha; } SHIZColor; typedef enum SHIZDrawMode { SHIZDrawModeFill, SHIZDrawModeOutline } SHIZDrawMode; /** * @brief Represents a 2-dimensional frame of an image resource. * * The source frame can either be a subset of, or span the entire image. */ typedef struct SHIZSprite { /* The frame that specifies which part of the image to draw */ SHIZRect source; /** The image resource */ uint8_t resource_id; } SHIZSprite; typedef enum SHIZSpriteFlipMode { SHIZSpriteFlipModeNone = 0, SHIZSpriteFlipModeVertical = 1, SHIZSpriteFlipModeHorizontal = 2 } SHIZSpriteFlipMode; typedef struct SHIZSpriteSheet { SHIZSprite resource; SHIZSize sprite_size; SHIZSize sprite_padding; uint16_t columns; uint16_t rows; } SHIZSpriteSheet; typedef struct SHIZSpriteSize { SHIZSize target; SHIZVector2 scale; } SHIZSpriteSize; typedef enum SHIZSpriteFontAlignment { SHIZSpriteFontAlignmentTop = 1, SHIZSpriteFontAlignmentLeft = 2, SHIZSpriteFontAlignmentRight = 4, SHIZSpriteFontAlignmentCenter = 8, SHIZSpriteFontAlignmentMiddle = 16, SHIZSpriteFontAlignmentBottom = 32 } SHIZSpriteFontAlignment; typedef enum SHIZSpriteFontWrapMode { SHIZSpriteFontWrapModeCharacter, SHIZSpriteFontWrapModeWord } SHIZSpriteFontWrapMode; typedef struct SHIZSpriteFontTable { uint32_t const * codepage; uint16_t columns; uint16_t rows; } SHIZSpriteFontTable; /** * @brief Represents a set of attributes that specify how text should be drawn. */ typedef struct SHIZSpriteFontAttributes { /** A scale defining the final size of the text */ SHIZVector2 scale; /** A scale defining how "tight" characters are drawn */ float character_spread; /** A value that adds padding to each character */ float character_padding; /** A value that adds padding to each line */ float line_padding; /** The word-wrapping mode */ SHIZSpriteFontWrapMode wrap; /** A pointer to an array of tint colors */ SHIZColor const * colors; /** The amount of colors these attributes point to */ uint8_t colors_count; } SHIZSpriteFontAttributes; /** * @brief Represents a set of sprite characters aligned to an ASCII table. */ typedef struct SHIZSpriteFont { /** The ASCII table that aligns with the font sprite */ SHIZSpriteFontTable table; /** A sprite that defines the font resource */ SHIZSprite sprite; /** The size of each sprite character */ SHIZSize character; /** Determines whether the font resource includes a sprite for the * whitespace character */ bool includes_whitespace; } SHIZSpriteFont; /** * @brief Default font attributes. * * Default font attributes apply scaling at 1:1 and enables word-wrapping. */ extern SHIZSpriteFontAttributes const SHIZSpriteFontAttributesDefault; extern SHIZVector2 const SHIZVector2Zero; extern SHIZVector2 const SHIZVector2One; extern SHIZColor const SHIZColorWhite; extern SHIZColor const SHIZColorBlack; extern SHIZColor const SHIZColorRed; extern SHIZColor const SHIZColorGreen; extern SHIZColor const SHIZColorBlue; extern SHIZColor const SHIZColorYellow; extern SHIZSize const SHIZSizeZero; extern SHIZRect const SHIZRectEmpty; /** * @brief An empty sprite. This sprite cannot be drawn. */ extern SHIZSprite const SHIZSpriteEmpty; extern SHIZSpriteSheet const SHIZSpriteSheetEmpty; extern SHIZSpriteFont const SHIZSpriteFontEmpty; extern SHIZSpriteFontTable const SHIZSpriteFontTableEmpty; /** * @brief Size a sprite to its intrinsic (or natural) size. */ extern SHIZSpriteSize const SHIZSpriteSizeIntrinsic; extern SHIZVector2 const SHIZAnchorCenter; extern SHIZVector2 const SHIZAnchorTop; extern SHIZVector2 const SHIZAnchorTopLeft; extern SHIZVector2 const SHIZAnchorLeft; extern SHIZVector2 const SHIZAnchorBottomLeft; extern SHIZVector2 const SHIZAnchorBottom; extern SHIZVector2 const SHIZAnchorTopRight; extern SHIZVector2 const SHIZAnchorRight; extern SHIZVector2 const SHIZAnchorBottomRight; /** * @brief Do not apply scaling (scale = 1). */ #define SHIZSpriteNoScale 1.0f /** * @brief Do not apply rotation. */ #define SHIZSpriteNoAngle 0.0f /** * @brief Do not apply a tint. */ #define SHIZSpriteNoTint SHIZColorWhite /** * @brief Repeat the sprite. */ #define SHIZSpriteRepeat true /** * @brief Do not repeat the sprite. */ #define SHIZSpriteNoRepeat false /** * @brief The sprite contains transparent pixels. */ #define SHIZSpriteNotOpaque false /** * @brief The sprite does not contain transparent pixels. */ #define SHIZSpriteIsOpaque true #define SHIZSpriteFontAlignmentDefault (SHIZSpriteFontAlignmentTop|SHIZSpriteFontAlignmentLeft) /** * @brief Do not constrain text to bounds. */ #define SHIZSpriteFontSizeToFit SHIZSizeMake(SHIZSpriteSizeIntrinsic.target.width, \ SHIZSpriteSizeIntrinsic.target.height) /** * @brief Do not constrain text to horizontal bounds. */ #define SHIZSpriteFontSizeToFitHorizontally SHIZSpriteFontSizeToFit.width /** * @brief Do not constrain text to vertical bounds. */ #define SHIZSpriteFontSizeToFitVertically SHIZSpriteFontSizeToFit.height /** * @brief Apply normal font spread; characters will be spaced normally. */ #define SHIZSpriteFontSpreadNormal 1.0f /** * @brief Apply tight font spread; characters will be spaced with smaller gaps. */ #define SHIZSpriteFontSpreadTight 0.9f /** * @brief Apply loose font spread; characters will be spaced with larger gaps. */ #define SHIZSpriteFontSpreadLoose 1.1f /** * @brief Do not apply. */ #define SHIZSpriteFontNoPadding 0.0f static inline SHIZVector2 const SHIZVector2Make(float const x, float const y) { SHIZVector2 const vector = { x, y }; return vector; } static inline SHIZSize const SHIZSizeMake(float const width, float const height) { SHIZSize const size = { width, height }; return size; } static inline SHIZRect const SHIZRectMake(SHIZVector2 const origin, SHIZSize const size) { SHIZRect const rect = { origin, size }; return rect; } static inline SHIZRect SHIZRectFromPoints(SHIZVector2 const points[], uint16_t const count) { if (count == 0) { return SHIZRectEmpty; } SHIZVector2 min = points[0]; SHIZVector2 max = points[0]; for (uint8_t i = 1; i < count; i++) { SHIZVector2 const point = points[i]; if (point.x < min.x) { min.x = point.x; } if (point.y < min.y) { min.y = point.y; } if (point.x > max.x) { max.x = point.x; } if (point.y > max.y) { max.y = point.y; } } float const width = max.x - min.x; float const height = max.y - min.y; SHIZSize const size = SHIZSizeMake(width, height); return SHIZRectMake(min, size); } static inline SHIZVector2 SHIZVector2CenterFromPoints(SHIZVector2 const points[], uint16_t const count) { SHIZVector2 sum = SHIZVector2Zero; for (uint8_t i = 0; i < count; i++) { SHIZVector2 const point = points[i]; sum.x += point.x; sum.y += point.y; } return SHIZVector2Make(sum.x / count, sum.y / count); } static inline SHIZRect const SHIZRectMakeEx(float const x, float const y, float const width, float const height) { return SHIZRectMake(SHIZVector2Make(x, y), SHIZSizeMake(width, height)); } static inline SHIZColor const SHIZColorMake(float const r, float const g, float const b, float const alpha) { SHIZColor const color = { r, g, b, alpha }; return color; } static inline SHIZColor const SHIZColorFromHex(int32_t const value) { SHIZColor const color = SHIZColorMake(((value >> 16) & 0xFF) / 255.0f, ((value >> 8) & 0xFF) / 255.0f, ((value >> 0) & 0xFF) / 255.0f, 1); return color; } static inline SHIZColor const SHIZColorWithAlpa(SHIZColor const color, float const alpha) { SHIZColor result_color = color; result_color.alpha = alpha; return result_color; } static inline SHIZColor const SHIZSpriteTintDefaultWithAlpa(float const alpha) { return SHIZColorWithAlpa(SHIZSpriteNoTint, alpha); } static inline SHIZSpriteSize const SHIZSpriteSized(SHIZSize const size, SHIZVector2 const scale) { SHIZSpriteSize sprite_size; sprite_size.target = size; sprite_size.scale = scale; return sprite_size; } static inline SHIZSpriteSize const SHIZSpriteSizedIntrinsicallyWithScale(SHIZVector2 const scale) { SHIZSpriteSize size = SHIZSpriteSizeIntrinsic; size.scale = scale; return size; } static inline SHIZSpriteFontAttributes const SHIZSpriteFontAttributesWithScaleAndWrap(float const scale, SHIZSpriteFontWrapMode const wrap) { SHIZSpriteFontAttributes attrs = SHIZSpriteFontAttributesDefault; attrs.scale = SHIZVector2Make(scale, scale); attrs.wrap = wrap; return attrs; } static inline SHIZSpriteFontAttributes const SHIZSpriteFontAttributesWithScale(float const scale) { SHIZSpriteFontWrapMode const wrap = SHIZSpriteFontAttributesDefault.wrap; return SHIZSpriteFontAttributesWithScaleAndWrap(scale, wrap); } static inline SHIZSpriteFontAttributes const SHIZSpriteFontAttributesWithWrap(SHIZSpriteFontWrapMode const wrap) { return SHIZSpriteFontAttributesWithScaleAndWrap(SHIZSpriteNoScale, wrap); } static inline SHIZVector2 const SHIZAnchorInverse(SHIZVector2 const anchor) { return SHIZVector2Make(anchor.x * -1, anchor.y * -1); } #endif // ztype_h
2
2
2024-11-18T21:05:57.980010+00:00
2021-04-08T12:59:04
14e7489b352f77f010304e13f59f39aecd1a14f8
{ "blob_id": "14e7489b352f77f010304e13f59f39aecd1a14f8", "branch_name": "refs/heads/main", "committer_date": "2021-04-08T12:59:04", "content_id": "6a55e261e9570ff6dafdbe8e300b7f62010c562b", "detected_licenses": [ "MIT" ], "directory_id": "dee21d18848785c1680466fc1b1f5de2f33609e6", "extension": "c", "filename": "radix.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 348977027, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2857, "license": "MIT", "license_type": "permissive", "path": "/radix_sort/rtems/radix.c", "provenance": "stackv2-0083.json.gz:8092", "repo_name": "veyselharun/MBBench", "revision_date": "2021-04-08T12:59:04", "revision_id": "7e44027fa3bdec831192739bba039e6f1ae7f11c", "snapshot_id": "af41d83cc63624070c029e76fcd069cf7d22347e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/veyselharun/MBBench/7e44027fa3bdec831192739bba039e6f1ae7f11c/radix_sort/rtems/radix.c", "visit_date": "2023-04-03T03:09:24.118646" }
stackv2
/* * Radix Sort Algorithm * File: radix.c * Author: Metin Kuzhan * */ #include <bsp.h> #define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER #define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER #define CONFIGURE_USE_DEVFS_AS_BASE_FILESYSTEM #define CONFIGURE_RTEMS_INIT_TASKS_TABLE #define CONFIGURE_MAXIMUM_TASKS 1 #define CONFIGURE_INIT #define RAND_MAX 0x7fffffff #include <rtems/confdefs.h> #include <rtems.h> #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #include<string.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> rtems_task Init(rtems_task_argument arg) { int number_count=5; int * numbers,*numbers_copy; numbers= malloc(sizeof(int)*number_count); numbers_copy= malloc(sizeof(int)*number_count); numbers[0]=20; numbers[1]=5; numbers[2]=45; numbers[3]=34; numbers[4]=53; int units_digit[number_count]; for( int k=0 ; k < number_count ; k++ ) { units_digit[k]= numbers[k]%10; } int most_greatest= 0; int place=0; for(int k= 0 ; k < number_count ; k++ ) { most_greatest= 0; for( int j=0 ; j < number_count ; j++ ) { if( units_digit[j] >= most_greatest ) { most_greatest= units_digit[j]; place= j; } } numbers_copy[k]= numbers[place]; units_digit[place]= -1; numbers[place]= -1; } int indices=0; for(int k=number_count-1 ; k >= 0 ; k-- ) { numbers[indices]= numbers_copy[k]; indices++; } for( int k=0 ; k < number_count ; k++ ) { units_digit[k]= numbers[k] % 100; units_digit[k]= units_digit[k] / 10; } most_greatest= 0; place=0; for( int k= 0 ; k < number_count ; k++ ) { most_greatest= 0; for( int j= 0 ; j < number_count ; j++ ) { if(units_digit[j] >= most_greatest ) { most_greatest= units_digit[j]; place= j; } } numbers_copy[k]=numbers[place]; units_digit[place]= -1; numbers[place]= -1; } indices=0; for( int k= number_count-1; k >=0 ; k-- ) { numbers[indices]= numbers_copy[k]; indices++; } for( int k= 0 ; k < number_count ; k++ ) { units_digit[k]= numbers[k] / 100; } most_greatest= 0; place=0; for( int k= 0 ; k < number_count ; k++ ) { most_greatest= 0; for( int j=0 ; j < number_count ; j++) { if( units_digit[j] >= most_greatest ) { most_greatest= units_digit[j]; place= j; } } numbers_copy[k]=numbers[place]; units_digit[place]= -1; numbers[place]= -1; } indices=0; for( int k= number_count-1 ; k >= 0 ; k-- ) { numbers[indices]= numbers_copy[k]; indices++; } exit(0); }
2.640625
3
2024-11-18T21:05:58.160951+00:00
2023-08-02T09:06:56
3120c98d7a922b975c1d9e62beaffc3ccf1250f4
{ "blob_id": "3120c98d7a922b975c1d9e62beaffc3ccf1250f4", "branch_name": "refs/heads/master", "committer_date": "2023-08-08T07:01:20", "content_id": "0464585672c811a4f5ce3f1b3032da58e7fc1911", "detected_licenses": [ "Intel", "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "a8194cf6ffd12f7551eaba53572744080a0bfef3", "extension": "c", "filename": "json_write_ut.c", "fork_events_count": 1158, "gha_created_at": "2015-07-13T23:15:15", "gha_event_created_at": "2023-08-11T09:50:50", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 39042157, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19128, "license": "Intel,BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/test/unit/lib/json/json_write.c/json_write_ut.c", "provenance": "stackv2-0083.json.gz:8221", "repo_name": "spdk/spdk", "revision_date": "2023-08-02T09:06:56", "revision_id": "d62a3810364cb87be352c66acf7c7f968508ca17", "snapshot_id": "51294f67104b8c3d18f19147d63a212e9486c687", "src_encoding": "UTF-8", "star_events_count": 2708, "url": "https://raw.githubusercontent.com/spdk/spdk/d62a3810364cb87be352c66acf7c7f968508ca17/test/unit/lib/json/json_write.c/json_write_ut.c", "visit_date": "2023-08-08T16:07:41.263000" }
stackv2
/* SPDX-License-Identifier: BSD-3-Clause * Copyright (C) 2016 Intel Corporation. * All rights reserved. */ #include "spdk/stdinc.h" #include "spdk_internal/cunit.h" #include "json/json_write.c" #include "json/json_parse.c" #include "spdk/util.h" static uint8_t g_buf[1000]; static uint8_t *g_write_pos; static int write_cb(void *cb_ctx, const void *data, size_t size) { size_t buf_free = g_buf + sizeof(g_buf) - g_write_pos; if (size > buf_free) { return -1; } memcpy(g_write_pos, data, size); g_write_pos += size; return 0; } #define BEGIN() \ memset(g_buf, 0, sizeof(g_buf)); \ g_write_pos = g_buf; \ w = spdk_json_write_begin(write_cb, NULL, 0); \ SPDK_CU_ASSERT_FATAL(w != NULL) #define END(json) \ CU_ASSERT(spdk_json_write_end(w) == 0); \ CU_ASSERT(g_write_pos - g_buf == sizeof(json) - 1); \ CU_ASSERT(memcmp(json, g_buf, sizeof(json) - 1) == 0) #define END_SIZE(val, size) \ CU_ASSERT(spdk_json_write_end(w) == 0); \ CU_ASSERT(g_write_pos - g_buf == size); \ CU_ASSERT(memcmp(val, g_buf, size) == 0) #define END_NOCMP() \ CU_ASSERT(spdk_json_write_end(w) == 0) #define END_SIZE_NOCMP(size) \ CU_ASSERT(spdk_json_write_end(w) == 0); \ CU_ASSERT(g_write_pos - g_buf == size) #define END_FAIL() \ CU_ASSERT(spdk_json_write_end(w) < 0) #define VAL_STRING(str) \ CU_ASSERT(spdk_json_write_string_raw(w, str, sizeof(str) - 1) == 0) #define VAL_STRING_FAIL(str) \ CU_ASSERT(spdk_json_write_string_raw(w, str, sizeof(str) - 1) < 0) #define STR_PASS(in, out) \ BEGIN(); VAL_STRING(in); END("\"" out "\"") #define STR_FAIL(in) \ BEGIN(); VAL_STRING_FAIL(in); END_FAIL() #define VAL_STRING_UTF16LE(str) \ CU_ASSERT(spdk_json_write_string_utf16le_raw(w, (const uint16_t *)str, sizeof(str) / sizeof(uint16_t) - 1) == 0) #define VAL_STRING_UTF16LE_FAIL(str) \ CU_ASSERT(spdk_json_write_string_utf16le_raw(w, (const uint16_t *)str, sizeof(str) / sizeof(uint16_t) - 1) < 0) #define STR_UTF16LE_PASS(in, out) \ BEGIN(); VAL_STRING_UTF16LE(in); END("\"" out "\"") #define STR_UTF16LE_FAIL(in) \ BEGIN(); VAL_STRING_UTF16LE_FAIL(in); END_FAIL() #define VAL_NAME(name) \ CU_ASSERT(spdk_json_write_name_raw(w, name, sizeof(name) - 1) == 0) #define VAL_NULL() CU_ASSERT(spdk_json_write_null(w) == 0) #define VAL_TRUE() CU_ASSERT(spdk_json_write_bool(w, true) == 0) #define VAL_FALSE() CU_ASSERT(spdk_json_write_bool(w, false) == 0) #define VAL_INT32(i) CU_ASSERT(spdk_json_write_int32(w, i) == 0); #define VAL_UINT32(u) CU_ASSERT(spdk_json_write_uint32(w, u) == 0); #define VAL_INT64(i) CU_ASSERT(spdk_json_write_int64(w, i) == 0); #define VAL_UINT64(u) CU_ASSERT(spdk_json_write_uint64(w, u) == 0); #define VAL_UINT128(low, high) \ CU_ASSERT(spdk_json_write_uint128(w, low, high) == 0); #define VAL_NAME_UINT128(name, low, high) \ CU_ASSERT(spdk_json_write_named_uint128(w, name, low, high) == 0); #define VAL_DOUBLE(d) CU_ASSERT(spdk_json_write_double(w, d) == 0); #define VAL_ARRAY_BEGIN() CU_ASSERT(spdk_json_write_array_begin(w) == 0) #define VAL_ARRAY_END() CU_ASSERT(spdk_json_write_array_end(w) == 0) #define VAL_OBJECT_BEGIN() CU_ASSERT(spdk_json_write_object_begin(w) == 0) #define VAL_OBJECT_END() CU_ASSERT(spdk_json_write_object_end(w) == 0) #define VAL(v) CU_ASSERT(spdk_json_write_val(w, v) == 0) static void test_write_literal(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_NULL(); END("null"); BEGIN(); VAL_TRUE(); END("true"); BEGIN(); VAL_FALSE(); END("false"); } static void test_write_string_simple(void) { struct spdk_json_write_ctx *w; STR_PASS("hello world", "hello world"); STR_PASS(" ", " "); STR_PASS("~", "~"); } static void test_write_string_escapes(void) { struct spdk_json_write_ctx *w; /* Two-character escapes */ STR_PASS("\b", "\\b"); STR_PASS("\f", "\\f"); STR_PASS("\n", "\\n"); STR_PASS("\r", "\\r"); STR_PASS("\t", "\\t"); STR_PASS("\"", "\\\""); STR_PASS("\\", "\\\\"); /* JSON defines an escape for forward slash, but it is optional */ STR_PASS("/", "/"); STR_PASS("hello\nworld", "hello\\nworld"); STR_PASS("\x00", "\\u0000"); STR_PASS("\x01", "\\u0001"); STR_PASS("\x02", "\\u0002"); STR_PASS("\xC3\xB6", "\\u00F6"); STR_PASS("\xE2\x88\x9A", "\\u221A"); STR_PASS("\xEA\xAA\xAA", "\\uAAAA"); /* Surrogate pairs */ STR_PASS("\xF0\x9D\x84\x9E", "\\uD834\\uDD1E"); STR_PASS("\xF0\xA0\x9C\x8E", "\\uD841\\uDF0E"); /* Examples from RFC 3629 */ STR_PASS("\x41\xE2\x89\xA2\xCE\x91\x2E", "A\\u2262\\u0391."); STR_PASS("\xED\x95\x9C\xEA\xB5\xAD\xEC\x96\xB4", "\\uD55C\\uAD6D\\uC5B4"); STR_PASS("\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E", "\\u65E5\\u672C\\u8A9E"); STR_PASS("\xEF\xBB\xBF\xF0\xA3\x8E\xB4", "\\uFEFF\\uD84C\\uDFB4"); /* UTF-8 edge cases */ STR_PASS("\x7F", "\\u007F"); STR_FAIL("\x80"); STR_FAIL("\xC1"); STR_FAIL("\xC2"); STR_PASS("\xC2\x80", "\\u0080"); STR_PASS("\xC2\xBF", "\\u00BF"); STR_PASS("\xDF\x80", "\\u07C0"); STR_PASS("\xDF\xBF", "\\u07FF"); STR_FAIL("\xDF"); STR_FAIL("\xE0\x80"); STR_FAIL("\xE0\x1F"); STR_FAIL("\xE0\x1F\x80"); STR_FAIL("\xE0"); STR_FAIL("\xE0\xA0"); STR_PASS("\xE0\xA0\x80", "\\u0800"); STR_PASS("\xE0\xA0\xBF", "\\u083F"); STR_FAIL("\xE0\xA0\xC0"); STR_PASS("\xE0\xBF\x80", "\\u0FC0"); STR_PASS("\xE0\xBF\xBF", "\\u0FFF"); STR_FAIL("\xE0\xC0\x80"); STR_FAIL("\xE1"); STR_FAIL("\xE1\x80"); STR_FAIL("\xE1\x7F\x80"); STR_FAIL("\xE1\x80\x7F"); STR_PASS("\xE1\x80\x80", "\\u1000"); STR_PASS("\xE1\x80\xBF", "\\u103F"); STR_PASS("\xE1\xBF\x80", "\\u1FC0"); STR_PASS("\xE1\xBF\xBF", "\\u1FFF"); STR_FAIL("\xE1\xC0\x80"); STR_FAIL("\xE1\x80\xC0"); STR_PASS("\xEF\x80\x80", "\\uF000"); STR_PASS("\xEF\xBF\xBF", "\\uFFFF"); STR_FAIL("\xF0"); STR_FAIL("\xF0\x90"); STR_FAIL("\xF0\x90\x80"); STR_FAIL("\xF0\x80\x80\x80"); STR_FAIL("\xF0\x8F\x80\x80"); STR_PASS("\xF0\x90\x80\x80", "\\uD800\\uDC00"); STR_PASS("\xF0\x90\x80\xBF", "\\uD800\\uDC3F"); STR_PASS("\xF0\x90\xBF\x80", "\\uD803\\uDFC0"); STR_PASS("\xF0\xBF\x80\x80", "\\uD8BC\\uDC00"); STR_FAIL("\xF0\xC0\x80\x80"); STR_FAIL("\xF1"); STR_FAIL("\xF1\x80"); STR_FAIL("\xF1\x80\x80"); STR_FAIL("\xF1\x80\x80\x7F"); STR_PASS("\xF1\x80\x80\x80", "\\uD8C0\\uDC00"); STR_PASS("\xF1\x80\x80\xBF", "\\uD8C0\\uDC3F"); STR_PASS("\xF1\x80\xBF\x80", "\\uD8C3\\uDFC0"); STR_PASS("\xF1\xBF\x80\x80", "\\uD9BC\\uDC00"); STR_PASS("\xF3\x80\x80\x80", "\\uDAC0\\uDC00"); STR_FAIL("\xF3\xC0\x80\x80"); STR_FAIL("\xF3\x80\xC0\x80"); STR_FAIL("\xF3\x80\x80\xC0"); STR_FAIL("\xF4"); STR_FAIL("\xF4\x80"); STR_FAIL("\xF4\x80\x80"); STR_PASS("\xF4\x80\x80\x80", "\\uDBC0\\uDC00"); STR_PASS("\xF4\x8F\x80\x80", "\\uDBFC\\uDC00"); STR_PASS("\xF4\x8F\xBF\xBF", "\\uDBFF\\uDFFF"); STR_FAIL("\xF4\x90\x80\x80"); STR_FAIL("\xF5"); STR_FAIL("\xF5\x80"); STR_FAIL("\xF5\x80\x80"); STR_FAIL("\xF5\x80\x80\x80"); STR_FAIL("\xF5\x80\x80\x80\x80"); /* Overlong encodings */ STR_FAIL("\xC0\x80"); /* Surrogate pairs */ STR_FAIL("\xED\xA0\x80"); /* U+D800 First high surrogate */ STR_FAIL("\xED\xAF\xBF"); /* U+DBFF Last high surrogate */ STR_FAIL("\xED\xB0\x80"); /* U+DC00 First low surrogate */ STR_FAIL("\xED\xBF\xBF"); /* U+DFFF Last low surrogate */ STR_FAIL("\xED\xA1\x8C\xED\xBE\xB4"); /* U+233B4 (invalid surrogate pair encoding) */ } static void test_write_string_utf16le(void) { struct spdk_json_write_ctx *w; /* All characters in BMP */ STR_UTF16LE_PASS(((uint8_t[]) { 'H', 0, 'e', 0, 'l', 0, 'l', 0, 'o', 0, 0x15, 0xFE, 0, 0 }), "Hello\\uFE15"); /* Surrogate pair */ STR_UTF16LE_PASS(((uint8_t[]) { 'H', 0, 'i', 0, 0x34, 0xD8, 0x1E, 0xDD, '!', 0, 0, 0 }), "Hi\\uD834\\uDD1E!"); /* Valid high surrogate, but no low surrogate */ STR_UTF16LE_FAIL(((uint8_t[]) { 0x00, 0xD8, 0, 0 /* U+D800 */ })); /* Invalid leading low surrogate */ STR_UTF16LE_FAIL(((uint8_t[]) { 0x00, 0xDC, 0x00, 0xDC, 0, 0 /* U+DC00 U+DC00 */ })); /* Valid high surrogate followed by another high surrogate (invalid) */ STR_UTF16LE_FAIL(((uint8_t[]) { 0x00, 0xD8, 0x00, 0xD8, 0, 0 /* U+D800 U+D800 */ })); } static void test_write_number_int32(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_INT32(0); END("0"); BEGIN(); VAL_INT32(1); END("1"); BEGIN(); VAL_INT32(123); END("123"); BEGIN(); VAL_INT32(-123); END("-123"); BEGIN(); VAL_INT32(2147483647); END("2147483647"); BEGIN(); VAL_INT32(-2147483648); END("-2147483648"); } static void test_write_number_uint32(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_UINT32(0); END("0"); BEGIN(); VAL_UINT32(1); END("1"); BEGIN(); VAL_UINT32(123); END("123"); BEGIN(); VAL_UINT32(2147483647); END("2147483647"); BEGIN(); VAL_UINT32(4294967295); END("4294967295"); } static int test_generate_string_uint128(char *buf, int buf_size, uint64_t low, uint64_t high) { char tmp_buf[256] = {0}; unsigned __int128 total; uint64_t seg; int count = 0; memset(buf, 0, buf_size); total = ((unsigned __int128)high << 64) + (unsigned __int128)low; while (total) { /* Use the different calculation to get the 128bits decimal value in UT */ seg = total % 1000000000000000; total = total / 1000000000000000; if (total) { snprintf(tmp_buf, buf_size, "%015" PRIu64 "%s", seg, buf); } else { snprintf(tmp_buf, buf_size, "%" PRIu64 "%s", seg, buf); } count = snprintf(buf, buf_size, "%s", tmp_buf); } return count; } static int test_generate_string_name_uint128(char *name, char *buf, int buf_size, uint64_t low, uint64_t high) { char tmp_buf[256] = {0}; int count = test_generate_string_uint128(buf, buf_size, low, high); memcpy(tmp_buf, buf, buf_size); count = snprintf(buf, 256, "\"%s\":%s", name, tmp_buf); return count; } static void test_write_number_uint128(void) { struct spdk_json_write_ctx *w; char buf[256] = {0}; int used_count = 0; BEGIN(); VAL_UINT128(0, 0); END("0"); BEGIN(); VAL_UINT128(1, 0); used_count = test_generate_string_uint128(buf, sizeof(buf), 1, 0); END_SIZE(buf, used_count); BEGIN(); VAL_UINT128(123, 0); used_count = test_generate_string_uint128(buf, sizeof(buf), 123, 0); END_SIZE(buf, used_count); BEGIN(); VAL_UINT128(2147483647, 0); used_count = test_generate_string_uint128(buf, sizeof(buf), 2147483647, 0); END_SIZE(buf, used_count); BEGIN(); VAL_UINT128(0, 1); used_count = test_generate_string_uint128(buf, sizeof(buf), 0, 1); END_SIZE(buf, used_count); BEGIN(); VAL_UINT128(4294967295, 1); used_count = test_generate_string_uint128(buf, sizeof(buf), 4294967295, 1); END_SIZE(buf, used_count); BEGIN(); VAL_UINT128(2147483647, 4294967295); used_count = test_generate_string_uint128(buf, sizeof(buf), 2147483647, 4294967295); END_SIZE(buf, used_count); BEGIN(); VAL_UINT128(4294967295, 4294967295); used_count = test_generate_string_uint128(buf, sizeof(buf), 4294967295, 4294967295); END_SIZE(buf, used_count); } static void test_write_string_number_uint128(void) { struct spdk_json_write_ctx *w; char buf[256] = {0}; int used_count = 0; BEGIN(); VAL_NAME_UINT128("case1", 0, 0); END("\"case1\":0"); BEGIN(); VAL_NAME_UINT128("case2", 1, 0); used_count = test_generate_string_name_uint128("case2", buf, sizeof(buf), 1, 0); END_SIZE(buf, used_count); BEGIN(); VAL_NAME_UINT128("case3", 123, 0); used_count = test_generate_string_name_uint128("case3", buf, sizeof(buf), 123, 0); END_SIZE(buf, used_count); BEGIN(); VAL_NAME_UINT128("case4", 2147483647, 0); used_count = test_generate_string_name_uint128("case4", buf, sizeof(buf), 2147483647, 0); END_SIZE(buf, used_count); BEGIN(); VAL_NAME_UINT128("case5", 0, 1); used_count = test_generate_string_name_uint128("case5", buf, sizeof(buf), 0, 1); END_SIZE(buf, used_count); BEGIN(); VAL_NAME_UINT128("case6", 4294967295, 1); used_count = test_generate_string_name_uint128("case6", buf, sizeof(buf), 4294967295, 1); END_SIZE(buf, used_count); BEGIN(); VAL_NAME_UINT128("case7", 2147483647, 4294967295); used_count = test_generate_string_name_uint128("case7", buf, sizeof(buf), 2147483647, 4294967295); END_SIZE(buf, used_count); BEGIN(); VAL_NAME_UINT128("case8", 4294967295, 4294967295); used_count = test_generate_string_name_uint128("case8", buf, sizeof(buf), 4294967295, 4294967295); END_SIZE(buf, used_count); } static void test_write_number_int64(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_INT64(0); END("0"); BEGIN(); VAL_INT64(1); END("1"); BEGIN(); VAL_INT64(123); END("123"); BEGIN(); VAL_INT64(-123); END("-123"); BEGIN(); VAL_INT64(INT64_MAX); END("9223372036854775807"); BEGIN(); VAL_INT64(INT64_MIN); END("-9223372036854775808"); } static void test_write_number_uint64(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_UINT64(0); END("0"); BEGIN(); VAL_UINT64(1); END("1"); BEGIN(); VAL_UINT64(123); END("123"); BEGIN(); VAL_UINT64(INT64_MAX); END("9223372036854775807"); BEGIN(); VAL_UINT64(UINT64_MAX); END("18446744073709551615"); } static void test_write_number_double(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_DOUBLE(0); END_SIZE("0.00000000000000000000e+00", 26); BEGIN(); VAL_DOUBLE(1.2); END_SIZE("1.19999999999999995559e+00", 26); BEGIN(); VAL_DOUBLE(1234.5678); END_SIZE("1.23456780000000003383e+03", 26); BEGIN(); VAL_DOUBLE(-1234.5678); END_SIZE("-1.23456780000000003383e+03", 27); } static void test_write_array(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_ARRAY_BEGIN(); VAL_ARRAY_END(); END("[]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_INT32(0); VAL_ARRAY_END(); END("[0]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_INT32(0); VAL_INT32(1); VAL_ARRAY_END(); END("[0,1]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_INT32(0); VAL_INT32(1); VAL_INT32(2); VAL_ARRAY_END(); END("[0,1,2]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_STRING("a"); VAL_ARRAY_END(); END("[\"a\"]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_STRING("a"); VAL_STRING("b"); VAL_ARRAY_END(); END("[\"a\",\"b\"]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_STRING("a"); VAL_STRING("b"); VAL_STRING("c"); VAL_ARRAY_END(); END("[\"a\",\"b\",\"c\"]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_TRUE(); VAL_ARRAY_END(); END("[true]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_TRUE(); VAL_FALSE(); VAL_ARRAY_END(); END("[true,false]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_TRUE(); VAL_FALSE(); VAL_TRUE(); VAL_ARRAY_END(); END("[true,false,true]"); } static void test_write_object(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_OBJECT_BEGIN(); VAL_OBJECT_END(); END("{}"); BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("a"); VAL_INT32(0); VAL_OBJECT_END(); END("{\"a\":0}"); BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("a"); VAL_INT32(0); VAL_NAME("b"); VAL_INT32(1); VAL_OBJECT_END(); END("{\"a\":0,\"b\":1}"); BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("a"); VAL_INT32(0); VAL_NAME("b"); VAL_INT32(1); VAL_NAME("c"); VAL_INT32(2); VAL_OBJECT_END(); END("{\"a\":0,\"b\":1,\"c\":2}"); } static void test_write_nesting(void) { struct spdk_json_write_ctx *w; BEGIN(); VAL_ARRAY_BEGIN(); VAL_ARRAY_BEGIN(); VAL_ARRAY_END(); VAL_ARRAY_END(); END("[[]]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_ARRAY_BEGIN(); VAL_ARRAY_BEGIN(); VAL_ARRAY_END(); VAL_ARRAY_END(); VAL_ARRAY_END(); END("[[[]]]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_INT32(0); VAL_ARRAY_BEGIN(); VAL_ARRAY_END(); VAL_ARRAY_END(); END("[0,[]]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_ARRAY_BEGIN(); VAL_ARRAY_END(); VAL_INT32(0); VAL_ARRAY_END(); END("[[],0]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_INT32(0); VAL_ARRAY_BEGIN(); VAL_INT32(1); VAL_ARRAY_END(); VAL_INT32(2); VAL_ARRAY_END(); END("[0,[1],2]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_INT32(0); VAL_INT32(1); VAL_ARRAY_BEGIN(); VAL_INT32(2); VAL_INT32(3); VAL_ARRAY_END(); VAL_INT32(4); VAL_INT32(5); VAL_ARRAY_END(); END("[0,1,[2,3],4,5]"); BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("a"); VAL_OBJECT_BEGIN(); VAL_OBJECT_END(); VAL_OBJECT_END(); END("{\"a\":{}}"); BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("a"); VAL_OBJECT_BEGIN(); VAL_NAME("b"); VAL_INT32(0); VAL_OBJECT_END(); VAL_OBJECT_END(); END("{\"a\":{\"b\":0}}"); BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("a"); VAL_ARRAY_BEGIN(); VAL_INT32(0); VAL_ARRAY_END(); VAL_OBJECT_END(); END("{\"a\":[0]}"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("a"); VAL_INT32(0); VAL_OBJECT_END(); VAL_ARRAY_END(); END("[{\"a\":0}]"); BEGIN(); VAL_ARRAY_BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("a"); VAL_OBJECT_BEGIN(); VAL_NAME("b"); VAL_ARRAY_BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("c"); VAL_INT32(1); VAL_OBJECT_END(); VAL_INT32(2); VAL_ARRAY_END(); VAL_NAME("d"); VAL_INT32(3); VAL_OBJECT_END(); VAL_NAME("e"); VAL_INT32(4); VAL_OBJECT_END(); VAL_INT32(5); VAL_ARRAY_END(); END("[{\"a\":{\"b\":[{\"c\":1},2],\"d\":3},\"e\":4},5]"); /* Examples from RFC 7159 */ BEGIN(); VAL_OBJECT_BEGIN(); VAL_NAME("Image"); VAL_OBJECT_BEGIN(); VAL_NAME("Width"); VAL_INT32(800); VAL_NAME("Height"); VAL_INT32(600); VAL_NAME("Title"); VAL_STRING("View from 15th Floor"); VAL_NAME("Thumbnail"); VAL_OBJECT_BEGIN(); VAL_NAME("Url"); VAL_STRING("http://www.example.com/image/481989943"); VAL_NAME("Height"); VAL_INT32(125); VAL_NAME("Width"); VAL_INT32(100); VAL_OBJECT_END(); VAL_NAME("Animated"); VAL_FALSE(); VAL_NAME("IDs"); VAL_ARRAY_BEGIN(); VAL_INT32(116); VAL_INT32(943); VAL_INT32(234); VAL_INT32(38793); VAL_ARRAY_END(); VAL_OBJECT_END(); VAL_OBJECT_END(); END( "{\"Image\":" "{" "\"Width\":800," "\"Height\":600," "\"Title\":\"View from 15th Floor\"," "\"Thumbnail\":{" "\"Url\":\"http://www.example.com/image/481989943\"," "\"Height\":125," "\"Width\":100" "}," "\"Animated\":false," "\"IDs\":[116,943,234,38793]" "}" "}"); } /* Round-trip parse and write test */ static void test_write_val(void) { struct spdk_json_write_ctx *w; struct spdk_json_val values[100]; char src[] = "{\"a\":[1,2,3],\"b\":{\"c\":\"d\"},\"e\":true,\"f\":false,\"g\":null}"; CU_ASSERT(spdk_json_parse(src, strlen(src), values, SPDK_COUNTOF(values), NULL, SPDK_JSON_PARSE_FLAG_DECODE_IN_PLACE) == 19); BEGIN(); VAL(values); END("{\"a\":[1,2,3],\"b\":{\"c\":\"d\"},\"e\":true,\"f\":false,\"g\":null}"); } int main(int argc, char **argv) { CU_pSuite suite = NULL; unsigned int num_failures; CU_initialize_registry(); suite = CU_add_suite("json", NULL, NULL); CU_ADD_TEST(suite, test_write_literal); CU_ADD_TEST(suite, test_write_string_simple); CU_ADD_TEST(suite, test_write_string_escapes); CU_ADD_TEST(suite, test_write_string_utf16le); CU_ADD_TEST(suite, test_write_number_int32); CU_ADD_TEST(suite, test_write_number_uint32); CU_ADD_TEST(suite, test_write_number_uint128); CU_ADD_TEST(suite, test_write_string_number_uint128); CU_ADD_TEST(suite, test_write_number_int64); CU_ADD_TEST(suite, test_write_number_uint64); CU_ADD_TEST(suite, test_write_number_double); CU_ADD_TEST(suite, test_write_array); CU_ADD_TEST(suite, test_write_object); CU_ADD_TEST(suite, test_write_nesting); CU_ADD_TEST(suite, test_write_val); num_failures = spdk_ut_run_tests(argc, argv, NULL); CU_cleanup_registry(); return num_failures; }
2.0625
2
2024-11-18T21:05:58.509886+00:00
2018-05-23T21:27:25
2b17f64c6897b876a1b8b51fd5b183d3933c7c9e
{ "blob_id": "2b17f64c6897b876a1b8b51fd5b183d3933c7c9e", "branch_name": "refs/heads/master", "committer_date": "2018-05-23T21:27:25", "content_id": "e4fe85bf96d416a7a730339c0abab5bf5484c3fc", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "51f8af248b0d2c6eb0207442f2e34a64e0ac666e", "extension": "c", "filename": "time.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 134437856, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 340, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/20 Domingo - Pure64/Kernel/time.c", "provenance": "stackv2-0083.json.gz:8607", "repo_name": "fermartin17/TP_Arqui", "revision_date": "2018-05-23T21:27:25", "revision_id": "90f18136450dd11f78b3f1b2fb96b1b9571a5cb5", "snapshot_id": "2d7f831b5d50d25e57e54b2658b98a2022d68099", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fermartin17/TP_Arqui/90f18136450dd11f78b3f1b2fb96b1b9571a5cb5/20 Domingo - Pure64/Kernel/time.c", "visit_date": "2020-03-18T07:11:07.106943" }
stackv2
#include <time.h> #include <naiveConsole.h> #include <keyboard.h> static unsigned long ticks = 0; static unsigned long next_time = 1; void timer_handler() { ticks++; if(seconds_elapsed() == next_time) { refreshScreen(); next_time += 1; } } int ticks_elapsed() { return ticks; } int seconds_elapsed() { return ticks / 18; }
2.078125
2
2024-11-18T21:05:59.279635+00:00
2021-07-13T17:59:57
a23cba36463053ad92a6f5de7a9cbca46901a5ff
{ "blob_id": "a23cba36463053ad92a6f5de7a9cbca46901a5ff", "branch_name": "refs/heads/main", "committer_date": "2021-07-13T17:59:57", "content_id": "41595f4646a83f20eec4c38bcea48cf4cce2b2bb", "detected_licenses": [ "MIT" ], "directory_id": "cb98afd4ec0522c91b9845a8f234bb065a7af1d0", "extension": "c", "filename": "Tute01.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 385610672, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 451, "license": "MIT", "license_type": "permissive", "path": "/Tute01.c", "provenance": "stackv2-0083.json.gz:9378", "repo_name": "SLIIT-FacultyOfComputing/tutorial-01b-IT21043932", "revision_date": "2021-07-13T17:59:57", "revision_id": "b543c4184afae0bc5cda1981827a84145863848a", "snapshot_id": "28cf0808ea480ac4d4ab96360a1222ebebce312b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SLIIT-FacultyOfComputing/tutorial-01b-IT21043932/b543c4184afae0bc5cda1981827a84145863848a/Tute01.c", "visit_date": "2023-06-15T15:25:07.777099" }
stackv2
/* Exercise 1 - Calculations Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */ #include <stdio.h> int main() { float mark1,mark2,total,average; printf("Enter marks for subject 1:"); scanf("%f",&mark1); printf("Enter marks for subject 2:"); scanf("%f",&mark2); total= mark1 + mark2; average= total / 2; printf("Display the average marks: %.2f",average); return 0; }
3.828125
4
2024-11-18T21:05:59.435811+00:00
2018-08-15T11:02:17
94b007e7ce74714099b1f5e07b57033a5a802194
{ "blob_id": "94b007e7ce74714099b1f5e07b57033a5a802194", "branch_name": "refs/heads/master", "committer_date": "2018-08-15T11:02:17", "content_id": "fa089b8e63ccf19ae9d9dd3b9267976935c178d7", "detected_licenses": [ "MIT" ], "directory_id": "c8ded86825a63069437d9eef630e5633f5fe967d", "extension": "c", "filename": "birarySearch.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 141395035, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 664, "license": "MIT", "license_type": "permissive", "path": "/dataStructure/chapter1/birarySearch.c", "provenance": "stackv2-0083.json.gz:9634", "repo_name": "jangseongwoo/TIL", "revision_date": "2018-08-15T11:02:17", "revision_id": "e86973ea78f50024c5f261bd671927068acc69d6", "snapshot_id": "e25f3b8cf52727a89409fcafa7dd2c718655aac8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jangseongwoo/TIL/e86973ea78f50024c5f261bd671927068acc69d6/dataStructure/chapter1/birarySearch.c", "visit_date": "2020-03-23T09:33:08.476311" }
stackv2
#include <stdio.h> int BSearch(int ar[], int len, int target) { int first = 0; int last = len - 1; int mid; while (first <= last) { mid = (first + last) / 2; if (target == ar[mid]) { return mid; } else { if (target < ar[mid]) last = mid - 1; else first = mid + 1; } } return -1; } int main() { int arr[] = {1, 2, 3, 6, 7, 8, 9, 11}; int index; index = BSearch(arr, sizeof(arr) / sizeof(int), 6); if (index == -1) printf("fail"); else printf("%d", index); return 0; }
3.46875
3
2024-11-18T21:05:59.503829+00:00
2021-07-12T14:03:16
f1daae3ba01bf8413e7aa885fb782774eb101ce8
{ "blob_id": "f1daae3ba01bf8413e7aa885fb782774eb101ce8", "branch_name": "refs/heads/master", "committer_date": "2021-07-12T14:03:16", "content_id": "651ade9d04be0ff93d4053082cd877ee8cb41fdf", "detected_licenses": [ "MIT" ], "directory_id": "777bb211f34ee8b4b81ddb90d738afd4c2d59f3f", "extension": "c", "filename": "solution.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 245548933, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1842, "license": "MIT", "license_type": "permissive", "path": "/src/moderate/double-trouble/solutions/c/solution.c", "provenance": "stackv2-0083.json.gz:9763", "repo_name": "rdtsc/codeeval-solutions", "revision_date": "2021-07-12T14:03:16", "revision_id": "d5c06baf89125e9e9f4b163ee57e5a8f7e73e717", "snapshot_id": "ef158af9fcf1a3548663386884e04d3a7aee05fe", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/rdtsc/codeeval-solutions/d5c06baf89125e9e9f4b163ee57e5a8f7e73e717/src/moderate/double-trouble/solutions/c/solution.c", "visit_date": "2021-07-19T05:31:49.871413" }
stackv2
#include <assert.h> #include <inttypes.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <string.h> int main(const int argc, const char* const argv[]) { // Getting away with no error checking throughout because CodeEval makes some // strong guarantees about our runtime environment. No need to pay when we're // being benchmarked. Don't forget to define NDEBUG prior to submitting! assert(argc >= 2 && "Expecting at least one command-line argument."); static char stdoutBuffer[256] = ""; // Turn on full output buffering for stdout. setvbuf(stdout, stdoutBuffer, _IOFBF, sizeof stdoutBuffer); FILE* inputStream = fopen(argv[1], "r"); assert(inputStream && "Failed to open input stream."); for(char lineBuffer[128] = ""; fgets(lineBuffer, sizeof lineBuffer, inputStream);) { // Kill trailing newline. { char* const cursor = strchr(lineBuffer, '\n'); if(cursor) *cursor = '\0'; } const size_t dataLength = strlen(lineBuffer); assert(!(dataLength & 1)); const char* const dataLeft = lineBuffer, * const dataRight = &lineBuffer[dataLength / 2]; const char* lhs = dataLeft, * rhs = dataRight; bool isValidInput = true; unsigned asteriskCount = 0; for(;lhs != dataRight; ++lhs, ++rhs) { // Wildcard pair. if((*lhs == '*') && (*rhs == '*')) ++asteriskCount; // Complete mismatch between letters. else if((*lhs != *rhs) && !(*lhs == '*' || *rhs == '*')) { isValidInput = false; break; } } if(!isValidInput) puts("0"); else { // |{A, B}| = 2. const uint_least64_t variantCount = pow(2, asteriskCount); printf("%" PRIuLEAST64 "\n", variantCount); } } // The CRT takes care of cleanup. }
2.765625
3
2024-11-18T21:06:00.221132+00:00
2019-05-14T14:36:54
638372fd3cefc71eacf0656595b45a62ff010257
{ "blob_id": "638372fd3cefc71eacf0656595b45a62ff010257", "branch_name": "refs/heads/master", "committer_date": "2019-05-14T14:36:54", "content_id": "0d2ab076fbef229c40e687e36b56caff03e84850", "detected_licenses": [ "MIT" ], "directory_id": "fde3ef8fc261aaf4156e240af7300ffd309379c8", "extension": "h", "filename": "led.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 638, "license": "MIT", "license_type": "permissive", "path": "/Lab4/APP_3/Utilities/LED/led.h", "provenance": "stackv2-0083.json.gz:10150", "repo_name": "Xiang-Pan/HUST_Sensor_Labs", "revision_date": "2019-05-14T14:36:54", "revision_id": "14b086ac6b41c88bfdbcdebe8dba576cd3195b37", "snapshot_id": "7c7de4a20bbe9ceacd4158dd7c0c088a7ec7c00a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Xiang-Pan/HUST_Sensor_Labs/14b086ac6b41c88bfdbcdebe8dba576cd3195b37/Lab4/APP_3/Utilities/LED/led.h", "visit_date": "2022-01-11T09:10:19.974971" }
stackv2
#ifndef _LED_H_ #define _LED_H_ #define LED_ALL_OFF GPIO_ResetBits(GPIOB, GPIO_Pin_5 |GPIO_Pin_6 |GPIO_Pin_7 |GPIO_Pin_8 |GPIO_Pin_9) #define LED_ALL_ON GPIO_SetBits(GPIOB, GPIO_Pin_5 |GPIO_Pin_6 |GPIO_Pin_7 |GPIO_Pin_8 |GPIO_Pin_9) /*! 枚举LED编号 */ typedef enum { LED1 = 1, LED2, LED3, LED4, LED5, }LED_e; /*! 枚举LED亮灭状态 */ typedef enum LED_status { LED_OFF = 0, //灯灭(对应低电平) LED_ON = 1 //灯亮(对应高电平) }LED_status; void led_init(void); void led_gpio_init(void); void led(LED_e ledn,LED_status status); #endif
2.40625
2
2024-11-18T21:06:00.805491+00:00
2019-12-24T11:42:08
4d8c0758028c4409a562839e13d9b347f610a027
{ "blob_id": "4d8c0758028c4409a562839e13d9b347f610a027", "branch_name": "refs/heads/master", "committer_date": "2019-12-24T11:42:08", "content_id": "05c0ccff30dd3e8e56a7a59febcfe14b38438ac9", "detected_licenses": [ "MIT" ], "directory_id": "614d24b76d8c9679c91dccefd16a8defff98ef99", "extension": "c", "filename": "sys.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 134716149, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2317, "license": "MIT", "license_type": "permissive", "path": "/STM32F10x/stm32/chx4 - 副本/System/sys.c", "provenance": "stackv2-0083.json.gz:10669", "repo_name": "zzccchen/review_note", "revision_date": "2019-12-24T11:42:08", "revision_id": "cdf0ba71e6fb08bb99137ce71f9cff5e8a0bc62f", "snapshot_id": "ebdeb1f2fd75506d444ab141eb747af7f8cc6ac3", "src_encoding": "GB18030", "star_events_count": 3, "url": "https://raw.githubusercontent.com/zzccchen/review_note/cdf0ba71e6fb08bb99137ce71f9cff5e8a0bc62f/STM32F10x/stm32/chx4 - 副本/System/sys.c", "visit_date": "2021-06-04T15:18:57.821445" }
stackv2
/** ****************************************************************************** * @file sys.c * @author 联航精英训练营 allen@unigress.com * @version V1.0 * @date 2013-10-20 * @brief 本源码中实现了系统中常用的功能函数。 ****************************************************************************** * @attention * * 本程序所提供的源代码均为本程序作者或由网络收集整理而来,仅供学习和研究使用。 * 如有侵犯的地方,请及时联系,我们会立即修改。使用本程序源码的用户必须明白, * 我们不能保证所提供的源码及其它资源的准确性、安全性和完整性,因此我们将不负责 * 承担任何直接,间接因使用这些源码对自己和他人造成任何形式的损失或伤害。任何人 * 在使用本代码时,应注明作者和出处。 * * <h2><center>版权所有(C) 2013 太原联航科技有限公司</center></h2> ****************************************************************************** */ #include "sys.h" #include <stdio.h> //默认的优先级设置 void NVIC_Configuration(void) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级 } /** * @brief 配置USART1、2、3的中断控制器 * @param None * @retval None */ void USARTx_NVIC_Configuration(void) { NVIC_InitTypeDef NVIC_InitStructure; /* Configure the NVIC Preemption Priority Bits */ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0); /* 使能USART1中断*/ NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* 使能USART2中断*/ NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* 使能USART3中断*/ NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } /******************* (C) 版权所有 2013 太原联航科技有限公司 *******************/
2.140625
2
2024-11-18T21:06:00.950271+00:00
2013-08-02T12:44:18
c742791ae4672f711701e35f90b5e4d26fb33eee
{ "blob_id": "c742791ae4672f711701e35f90b5e4d26fb33eee", "branch_name": "refs/heads/master", "committer_date": "2013-08-02T12:44:18", "content_id": "363e317d3d448d284d8814cb5f7678240e57aa9a", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "5e1cb34ab4330c3be818f3ca5b195471d16a5053", "extension": "h", "filename": "misc_instructions.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 34969722, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7200, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/VirtualSense/DJ_VirtualMachine.1.0/darjeeling.1.1/src/vm/common/execution/misc_instructions.h", "provenance": "stackv2-0083.json.gz:10798", "repo_name": "mikewen/virtual-sense", "revision_date": "2013-08-02T12:44:18", "revision_id": "c01de669737b791b81d75defeeab40a4ab63adf0", "snapshot_id": "0b958b0b3ce251ac79df8970af838ed29558d805", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mikewen/virtual-sense/c01de669737b791b81d75defeeab40a4ab63adf0/VirtualSense/DJ_VirtualMachine.1.0/darjeeling.1.1/src/vm/common/execution/misc_instructions.h", "visit_date": "2020-05-19T11:56:58.483925" }
stackv2
/* * misc_instructions.h * * Copyright (c) 2008 CSIRO, Delft University of Technology. * * This file is part of Darjeeling. * * Darjeeling is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Darjeeling is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Darjeeling. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __misc_instructions_h #define __misc_instructions_h static inline void LDS() { uint16_t i; // fetch and resolve the string id dj_local_id string_local_id = dj_fetchLocalId(); dj_global_id string_id = dj_global_id_resolve(dj_exec_getCurrentInfusion(), string_local_id); // get pointer to the ASCII string in program memory and the string length dj_di_pointer stringBytes = dj_di_stringtable_getElementBytes(string_id.infusion->stringTable, string_id.entity_id); uint16_t stringLength = dj_di_stringtable_getElementLength(string_id.infusion->stringTable, string_id.entity_id); // allocate memory to hold the string char *ret = (char*)dj_mem_alloc(stringLength+1, dj_vm_getSysLibClassRuntimeId(dj_exec_getVM(), BASE_CDEF_java_lang_String)); // throw OutOfMemoryError if(ret == NULL) { dj_exec_createAndThrow(BASE_CDEF_java_lang_OutOfMemoryError); return; } // copy the ASCII string from program space into memory for (i=0; i<stringLength; i++) ret[i] = dj_di_getU8(stringBytes++); // append a trailing zero ret[stringLength] = 0; pushRef(VOIDP_TO_REF(ret)); } static inline void NEW() { dj_di_pointer classDef; dj_local_id dj_local_id = dj_fetchLocalId(); dj_global_id dj_global_id = dj_global_id_resolve(dj_exec_getCurrentInfusion(), dj_local_id); // get class definition classDef = dj_global_id_getClassDefinition(dj_global_id); dj_object * object = dj_object_create( dj_global_id_getRuntimeClassId(dj_global_id), dj_di_classDefinition_getNrRefs(classDef), dj_di_classDefinition_getOffsetOfFirstReference(classDef) ); // if create returns null, throw out of memory error if (object==NULL) { dj_exec_createAndThrow(BASE_CDEF_java_lang_OutOfMemoryError); return; } pushRef(VOIDP_TO_REF(object)); } static inline void INSTANCEOF() { dj_local_id localClassId = dj_fetchLocalId(); ref_t ref = popRef(); dj_object * object = REF_TO_VOIDP(ref); DEBUG_ENTER_NEST("INSTANCEOF()"); // if the reference is null, result should be 0 (FALSE). // Else use dj_global_id_testType to dermine // if the ref on the stack is of the desired type if (ref==nullref) { pushShort(0); } else if (dj_object_getRuntimeId(object)==CHUNKID_INVALID) { dj_exec_createAndThrow(BASE_CDEF_javax_darjeeling_vm_ClassUnloadedException); return; } else if (dj_global_id_isJavaLangObject(dj_global_id_resolve(dj_exec_getCurrentInfusion(), localClassId))) { DEBUG_LOG("Ich bin a j.l.Object\n"); // a check against a non-null object for instanceof // java.lang.Object should always return true pushShort(1); } else { pushShort(dj_global_id_testType(object, localClassId)); } DEBUG_EXIT_NEST("INSTANCEOF()"); } static inline void CHECKCAST() { dj_local_id classLocalId = dj_fetchLocalId(); ref_t ref = peekRef(); dj_object * object = REF_TO_VOIDP(ref); // NULL passes checkcast if(object==NULL) return; if (dj_object_getRuntimeId(object) == CHUNKID_INVALID) { dj_exec_createAndThrow(BASE_CDEF_javax_darjeeling_vm_ClassUnloadedException); return; } if ( !dj_global_id_testType(object, classLocalId) ) dj_exec_createAndThrow(BASE_CDEF_java_lang_ClassCastException); } static inline void MONITORENTER() { dj_monitor * monitor; dj_object * obj; ref_t objRef = dj_exec_stackPopRef(); // check for null pointer if (objRef==nullref) { dj_exec_createAndThrow(BASE_CDEF_java_lang_NullPointerException); return; } DEBUG_ENTER_NEST_LOG("MONITORENTER() thread:%d, object%p\n", currentThread->id, REF_TO_VOIDP(objRef)); dj_mem_pushCompactionUpdateStack(objRef); // get the monitor for this object monitor = dj_vm_getMonitor(dj_exec_getVM(), (void*)REF_TO_VOIDP(objRef)); objRef = dj_mem_popCompactionUpdateStack(); // if the monitor didn't exist and could not be created, throw exception if (monitor==NULL) { dj_exec_createAndThrow(BASE_CDEF_java_lang_OutOfMemoryError); return; } obj = (dj_object*)REF_TO_VOIDP(objRef); // check if we can enter the monitor if (monitor->count==0) { DEBUG_LOG("Entering monitor %p\n",monitor); // we can enter the monitor, huzzaa monitor->count = 1; monitor->owner = currentThread; } else { if (monitor->owner==currentThread) { DEBUG_LOG("Reentering monitor %p. count is now %d\n",monitor,monitor->count+1); monitor->count++; } else { // we can't enter, so just block currentThread->status = THREADSTATUS_BLOCKED_FOR_MONITOR; currentThread->monitorObject = obj; monitor->waiting_threads++; DEBUG_LOG("monitor is already held by someone. let's block\n"); dj_exec_breakExecution(); } } DEBUG_EXIT_NEST_LOG("MONITORENTER()\n"); } static inline void MONITOREXIT() { dj_monitor * monitor; // Peek the object, don't pop it yet until after dj_vm_getMonitor is called. // This because dj_vm_getMonitor may require a memory allocation and thus may trigger // garbage compaction. By leaving the object on the operand stack for now we // are guaranteed that we can pop a valid reference after compaction. dj_object * obj = REF_TO_VOIDP(peekRef()); // check if the object is still valid if (dj_object_getRuntimeId(obj)==CHUNKID_INVALID) { dj_exec_createAndThrow(BASE_CDEF_javax_darjeeling_vm_ClassUnloadedException); return; } // check for null pointer if (obj==NULL) { dj_exec_createAndThrow(BASE_CDEF_java_lang_NullPointerException); return; } DEBUG_ENTER_NEST_LOG("MONITOREXIT() thread:%d, object:%p\n", currentThread->id, obj); // find the monitor associated with the object monitor = dj_vm_getMonitor(dj_exec_getVM(), obj); // if the monitor wasn't found, raise an error if(monitor == NULL) { dj_exec_createAndThrow(BASE_CDEF_java_lang_VirtualMachineError); return; } // safely pop the object obj = REF_TO_VOIDP(popRef()); dj_thread * thread = dj_exec_getCurrentThread(); // exit the monitor monitor->count--; monitor->owner = NULL; DEBUG_LOG("Exiting monitor %p, count is now %d\n", monitor, monitor->count); // remove the monitor if the count has reached 0 if ((monitor->count==0)&&(monitor->waiting_threads==0)) { DEBUG_LOG("Removing monitor\n"); dj_vm_removeMonitor(dj_exec_getVM(), monitor); } // clear thread's monitor object thread->monitorObject = NULL; DEBUG_EXIT_NEST_LOG("MONITOREXIT()\n"); } #endif /* __misc_instructions_h */
2.109375
2
2024-11-18T21:06:01.664479+00:00
2022-08-28T02:36:23
817c184b2601b17c196a2b1e6cf5bf4e8793e834
{ "blob_id": "817c184b2601b17c196a2b1e6cf5bf4e8793e834", "branch_name": "refs/heads/master", "committer_date": "2022-08-28T02:36:23", "content_id": "c1590bc7f1e9c9f509345b3dd656bdfb111d9ea5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e282df63ea4ed82c69541bcc65d619a0464d1826", "extension": "h", "filename": "unxs.h", "fork_events_count": 14, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 95415456, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3513, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/unxs.h", "provenance": "stackv2-0083.json.gz:11184", "repo_name": "hroptatyr/clob", "revision_date": "2022-08-28T02:36:23", "revision_id": "812137a3edca4e00f05ac8b3ff2212c5deb545a5", "snapshot_id": "8cb367bc9ad6cc6ea15c8aa596d4bc2fa6fcb7cf", "src_encoding": "UTF-8", "star_events_count": 25, "url": "https://raw.githubusercontent.com/hroptatyr/clob/812137a3edca4e00f05ac8b3ff2212c5deb545a5/src/unxs.h", "visit_date": "2022-09-30T06:59:32.109616" }
stackv2
/*** unxs.h -- uncrossing schemes * * Copyright (C) 2016-2022 Sebastian Freundt * * Author: Sebastian Freundt <freundt@ga-group.nl> * * This file is part of clob. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of any contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. * **/ #if !defined INCLUDED_unxs_h_ #define INCLUDED_unxs_h_ #include <stdint.h> #include "clob.h" #include "clob_val.h" typedef enum { /** don't keep track of parties */ MODE_NO = 0U, /** uncross with a single contra firm */ MODE_SC = 1U, /** uncross bilaterally */ MODE_BI = 2U, } unxs_mode_t; typedef struct { px_t prc; qx_t qty; } unxs_exe_t; typedef struct { qx_t base; qx_t term; } unxs_exa_t; typedef struct unxs_s { /** mode used for uncrossing */ const unxs_mode_t m; /** number of executions */ const size_t n; /** executions */ const unxs_exe_t *x; /** sides of executions from the maker point of view */ const uint_fast8_t *s; /** orders taking part in this match, (unxs_mode_t)M times N */ const clob_oid_t *o; /** remaining quantities, same dimension as O */ const qty_t *q; } *unxs_t; /** * Instantiate an uncrossing stream using uncrossing mode M. */ extern unxs_t make_unxs(unxs_mode_t); /** * Free resources associated with uncrossing stream. */ extern void free_unxs(unxs_t); /** * Clear execution stream. */ extern int unxs_clr(unxs_t); /** * Try crossing order O with book C at reference price R. * Executions will be tracked in C's exe-list. * The remainder of the order is returned. */ extern clob_ord_t unxs_order(clob_t c, clob_ord_t o, px_t r); /** * Uncross the book C at price P for a quantity of at most Q * and assuming a single contra firm. */ extern void unxs_auction(clob_t c, px_t p, qx_t q); /* convenience */ static inline __attribute__((pure, const)) unxs_exa_t unxs_exa(unxs_exe_t x, clob_side_t s) { switch (s) { case CLOB_SIDE_SELLER: /* maker is a seller */ return (unxs_exa_t){-x.qty, x.prc * x.qty}; case CLOB_SIDE_BUYER: /* maker is a buyer */ return (unxs_exa_t){x.qty, -x.prc * x.qty}; default: break; } return (unxs_exa_t){}; } #endif /* INCLUDED_unxs_h_ */
2.078125
2
2024-11-18T21:06:01.791782+00:00
2015-04-08T03:53:10
45282eea0ca27108764cbbcf2c77903b87863cce
{ "blob_id": "45282eea0ca27108764cbbcf2c77903b87863cce", "branch_name": "refs/heads/master", "committer_date": "2015-04-08T03:53:10", "content_id": "ac07996e4b2920edcc48413f13ccd5bc19307309", "detected_licenses": [ "MIT" ], "directory_id": "4fe4d248cfa56849199e91e088b9e838b8ad801e", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1048, "license": "MIT", "license_type": "permissive", "path": "/new/test.c", "provenance": "stackv2-0083.json.gz:11442", "repo_name": "JanChou/ui", "revision_date": "2015-04-08T03:53:10", "revision_id": "1d828c8debab274f7b058e3474e2494dfccb0c19", "snapshot_id": "f283502c18f7ac267df30d69aa235157422f3f42", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JanChou/ui/1d828c8debab274f7b058e3474e2494dfccb0c19/new/test.c", "visit_date": "2021-01-18T01:45:52.348246" }
stackv2
// 6 april 2015 #include "ui.h" #include <stdio.h> int onClosing(uiWindow *w, void *data) { printf("in closing!\n"); uiQuit(); return 1; } void onClicked(uiControl *b, void *data) { // TODO } void onClicked2(uiControl *b, void *data) { printf("button clicked!\n"); } int main(int argc, char *argv[]) { uiInitError *err; uiWindow *w; uiControl *stack; uiControl *button, *button2; err = uiInit(NULL); if (err != NULL) { fprintf(stderr, "error initializing ui: %s\n", uiInitErrorMessage(err)); uiInitErrorFree(err); return 1; } w = uiNewWindow("Hello", 320, 240); uiWindowOnClosing(w, onClosing, NULL); if (argc > 1) stack = uiNewHorizontalStack(); else stack = uiNewVerticalStack(); uiWindowSetChild(w, stack); button2 = uiNewButton("Change Me"); uiButtonOnClicked(button2, onClicked2, NULL); button = uiNewButton("Click Me"); uiButtonOnClicked(button, onClicked, button2); uiStackAdd(stack, button, 1); uiStackAdd(stack, button2, 0); uiWindowShow(w); uiMain(); printf("after uiMain()\n"); return 0; }
2.90625
3
2024-11-18T21:06:02.125595+00:00
2020-03-29T08:50:45
6908231468e7a5eb9eb00772b8a399d61099ac65
{ "blob_id": "6908231468e7a5eb9eb00772b8a399d61099ac65", "branch_name": "refs/heads/master", "committer_date": "2020-03-29T08:50:45", "content_id": "3f2ec4d3f5bbd783f6085aaa1f0150b2c8bd1e4c", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ea4e3ac0966fe7b69f42eaa5a32980caa2248957", "extension": "c", "filename": "print-lane.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 249169732, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3706, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/download/unzip/tcpdump/tcpdump-1/tcpdump/print-lane.c", "provenance": "stackv2-0083.json.gz:11956", "repo_name": "hyl946/opensource_apple", "revision_date": "2020-03-29T08:50:45", "revision_id": "e0f41fa0d9d535d57bfe56a264b4b27b8f93d86a", "snapshot_id": "36b49deda8b2f241437ed45113d624ad45aa6d5f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hyl946/opensource_apple/e0f41fa0d9d535d57bfe56a264b4b27b8f93d86a/download/unzip/tcpdump/tcpdump-1/tcpdump/print-lane.c", "visit_date": "2023-02-26T16:27:25.343636" }
stackv2
/* * Marko Kiiskila carnil@cs.tut.fi * * Tampere University of Technology - Telecommunications Laboratory * * Permission to use, copy, modify and distribute this * software and its documentation is hereby granted, * provided that both the copyright notice and this * permission notice appear in all copies of the software, * derivative works or modified versions, and any portions * thereof, that both notices appear in supporting * documentation, and that the use of this software is * acknowledged in any publications resulting from using * the software. * * TUT ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION AND DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS * SOFTWARE. * */ #ifndef lint static const char rcsid[] = "@(#) $Header: /cvs/Darwin/Commands/Other/tcpdump/tcpdump/print-lane.c,v 1.1.1.1 2001/07/07 00:50:54 bbraun Exp $ (LBL)"; #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <sys/param.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <pcap.h> #include "interface.h" #include "addrtoname.h" #include "ether.h" #include "lane.h" static inline void lane_print(register const u_char *bp, int length) { register const struct lecdatahdr_8023 *ep; ep = (const struct lecdatahdr_8023 *)bp; if (qflag) (void)printf("lecid:%d %s %s %d: ", ntohs(ep->le_header), etheraddr_string(ep->h_source), etheraddr_string(ep->h_dest), length); else (void)printf("lecid:%d %s %s %s %d: ", ntohs(ep->le_header), etheraddr_string(ep->h_source), etheraddr_string(ep->h_dest), etherproto_string(ep->h_type), length); } /* * This is the top level routine of the printer. 'p' is the points * to the ether header of the packet, 'h->tv' is the timestamp, * 'h->length' is the length of the packet off the wire, and 'h->caplen' * is the number of bytes actually captured. */ void lane_if_print(u_char *user, const struct pcap_pkthdr *h, const u_char *p) { int caplen = h->caplen; int length = h->len; struct lecdatahdr_8023 *ep; u_short ether_type; u_short extracted_ethertype; ts_print(&h->ts); if (caplen < sizeof(struct lecdatahdr_8023)) { printf("[|lane]"); goto out; } if (eflag) lane_print(p, length); /* * Some printers want to get back at the ethernet addresses, * and/or check that they're not walking off the end of the packet. * Rather than pass them all the way down, we set these globals. */ packetp = p; snapend = p + caplen; length -= sizeof(struct lecdatahdr_8023); caplen -= sizeof(struct lecdatahdr_8023); ep = (struct lecdatahdr_8023 *)p; p += sizeof(struct lecdatahdr_8023); ether_type = ntohs(ep->h_type); /* * Is it (gag) an 802.3 encapsulation? */ extracted_ethertype = 0; if (ether_type < ETHERMTU) { /* Try to print the LLC-layer header & higher layers */ if (llc_print(p, length, caplen, ep->h_source, ep->h_dest, &extracted_ethertype) == 0) { /* ether_type not known, print raw packet */ if (!eflag) lane_print((u_char *)ep, length + sizeof(*ep)); if (extracted_ethertype) { printf("(LLC %s) ", etherproto_string(htons(extracted_ethertype))); } if (!xflag && !qflag) default_print(p, caplen); } } else if (ether_encap_print(ether_type, p, length, caplen, &extracted_ethertype) == 0) { /* ether_type not known, print raw packet */ if (!eflag) lane_print((u_char *)ep, length + sizeof(*ep)); if (!xflag && !qflag) default_print(p, caplen); } if (xflag) default_print(p, caplen); out: putchar('\n'); }
2.09375
2
2024-11-18T21:06:02.203170+00:00
2021-02-16T01:51:47
c3b2230e1e9494be215e651121bb0b99b347d359
{ "blob_id": "c3b2230e1e9494be215e651121bb0b99b347d359", "branch_name": "refs/heads/main", "committer_date": "2021-02-16T01:51:47", "content_id": "46d1206ceb4fa3234011a0299caa011f5cc6450e", "detected_licenses": [ "MIT" ], "directory_id": "76579eed139f548395a67522bb9c95de1da09538", "extension": "c", "filename": "manipulatingcharfour.c", "fork_events_count": 0, "gha_created_at": "2021-01-14T14:30:40", "gha_event_created_at": "2021-01-22T16:05:00", "gha_language": null, "gha_license_id": "MIT", "github_id": 329640016, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 305, "license": "MIT", "license_type": "permissive", "path": "/Cprogramming/intermediate/manipulatingcharfour.c", "provenance": "stackv2-0083.json.gz:12084", "repo_name": "caramelmelmel/C_language_algorithms", "revision_date": "2021-02-16T01:51:47", "revision_id": "fe076b76d078933d45ec059f6411a2aa64954829", "snapshot_id": "236464077ab151ccb9eca84b4fef51ce87be5b29", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/caramelmelmel/C_language_algorithms/fe076b76d078933d45ec059f6411a2aa64954829/Cprogramming/intermediate/manipulatingcharfour.c", "visit_date": "2023-03-03T03:21:36.053147" }
stackv2
// use the do-while in the main char function //lopp through the inputs from the keyboard #include<stdio.h> #include<ctype.h> int main(){ int acter; do{ acter = getchar(); if(isalpha(acter)) { putchar(acter);} } while(acter != '\n'); return 1; }
3.1875
3
2024-11-18T21:06:03.086124+00:00
2018-09-27T16:15:31
946121b47a9d3248dd0c9daa2c218bf8164a5785
{ "blob_id": "946121b47a9d3248dd0c9daa2c218bf8164a5785", "branch_name": "refs/heads/master", "committer_date": "2018-09-27T16:15:31", "content_id": "9157503643f063aa5d541a4567ed50172673cf10", "detected_licenses": [ "MIT" ], "directory_id": "7225eb55476ef61991d7cd30aec5914931459812", "extension": "c", "filename": "austerity.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 23020, "license": "MIT", "license_type": "permissive", "path": "/austerity.c", "provenance": "stackv2-0083.json.gz:12729", "repo_name": "fatton139/Austerity", "revision_date": "2018-09-27T16:15:31", "revision_id": "233b6836b59a4f53c5fdf614b98a4387bdebca83", "snapshot_id": "d451283aaef522704405c393c91855e1f4f1d22a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fatton139/Austerity/233b6836b59a4f53c5fdf614b98a4387bdebca83/austerity.c", "visit_date": "2021-09-23T21:00:33.016572" }
stackv2
#include "austerity.h" /** * Frees memory allocated for the game. * @param game - The instance of the game. */ void free_game(Game *game) { if (game->deckTotal.amount < 8) { free(game->deckTotal.cards); } else { if (game->deckTotal.amount > 0) { free(game->deckTotal.cards); } if (game->deckFaceup.amount > 0) { free(game->deckFaceup.cards); } } for (int i = 0; i < game->playerAmount - 1; i++) { fclose(game->players[i].input); fclose(game->players[i].output); } free(game->players); } /** * Kills child processes in the game. * @param game - The instance of the game. */ void kill_children(Game *game) { for (int i = 0; i < game->playerAmount; i++) { if (game->players[i].pid != 0) { kill(game->players[i].pid, SIGKILL); } } } /** * Wait for children to exit and print the exit status. * @param game - The instance of the game. */ void wait_children(Game *game) { for (int i = 0; i < game->playerAmount; i++) { int status, id; waitpid(game->players[i].pid, &status, 0); id = game->players[i].id; if (WIFEXITED(status)) { if (WEXITSTATUS(status) > 0) { printf("Player %i ended with status %i\n", id, WEXITSTATUS(status)); } continue; } if (WIFSIGNALED(status)) { printf("Player %i shutdown after receiving signal %i\n", id, WTERMSIG(status)); } } } /** * Checks arguments to the start the hub. * @param argc - Argument counter. * @param argv - Argument vector. */ void check_args(int argc, char **argv) { if (argc < 6 || argc > 26) { exit_with_error(NULL, WRONG_ARG_NUM); } for (int i = 1; i < 3; i++) { if (!is_string_digit(argv[i])) { exit_with_error(NULL, BAD_ARG); } } } /** * Exit the hub with an error code. * @param game - The game instance. * @param error - The error code. */ void exit_with_error(Game *game, int error) { switch(error) { case (WRONG_ARG_NUM): fprintf(stderr, "Usage: austerity tokens points deck player "\ "player [player ...]\n"); break; case (BAD_ARG): fprintf(stderr, "Bad argument\n"); break; case (CANNOT_ACCESS_DECK_FILE): fprintf(stderr, "Cannot access deck file\n"); break; case (INVALID_DECK_FILE): fprintf(stderr, "Invalid deck file contents\n"); break; case (BAD_START): fprintf(stderr, "Bad start\n"); break; case (CLIENT_DISCONNECT): fprintf(stderr, "Client disconnected\n"); break; case (PROTOCOL_ERR): fprintf(stderr, "Protocol error by client\n"); break; case (SIGINT_RECIEVED): fprintf(stderr, "SIGINT caught\n"); break; } exit(error); } /** * Parse a deck and a array of string encoding of cards. * @param deck The deck to load the cards in to. * @param cardArr The array of cards to parse. */ void parse_deck(Deck deck, char **cardArr) { for (int i = 0; i < deck.amount; i++) { if (i != deck.amount - 1 || strcmp(cardArr[i], "") != 0) { if (!check_card(cardArr[i])) { exit_with_error(NULL, INVALID_DECK_FILE); } char **colSplit = split(cardArr[i], ":"); Card card; if (strcmp(colSplit[1], "") == 0) { exit_with_error(NULL, INVALID_DECK_FILE); } card.colour = colSplit[0][0]; card.value = atoi(colSplit[1]); char **commaSplit = split(colSplit[2], ","); for (int j = 0; j < 4; j++) { if (strcmp(commaSplit[j], "") == 0) { exit_with_error(NULL, INVALID_DECK_FILE); } card.cost[j] = atoi(commaSplit[j]); } deck.cards[i] = card; free(colSplit); free(commaSplit); } } } /** * Loads a deckfile. * @param fileName the name of the deckfile. * @return Deck a loaded deck struct. */ Deck load_deck(char *fileName) { FILE *file = fopen(fileName, "r"); if (file == NULL || !file) { exit_with_error(NULL, CANNOT_ACCESS_DECK_FILE); } char *content = malloc(sizeof(char)), character; int counter = 0, cards = 0; while((character = getc(file)) != EOF) { content = realloc(content, sizeof(char) * (counter + 1)); content[counter] = character; if (character == '\n') { cards++; } counter++; } fclose(file); content = realloc(content, sizeof(char) * (counter + 1)); content[counter] = '\0'; if (strcmp(content, "") == 0) { exit_with_error(NULL, INVALID_DECK_FILE); } char **cardArr = split(content, "\n"); Deck deck; deck.amount = cards + 1; deck.cards = malloc(sizeof(Card) * deck.amount); parse_deck(deck, cardArr); free(content); free(cardArr); return deck; } /** * Sets up the parent process to communicate with child. * @param game - The game instance. * @param id the - id of the player. * @param input - The input pipe. * @param output - The output pipe. * @param test - The test pipe. */ void setup_parent(Game *game, int id, int input[2], int output[2], int test[2]) { if (close(input[READ]) == -1 || close(output[WRITE]) == -1 || close(test[WRITE]) == -1) { exit_with_error(game, BAD_START); } game->players[id].input = fdopen(input[WRITE], "w"); game->players[id].output = fdopen(output[READ], "r"); FILE *testPipe = fdopen(test[READ], "r"); if (game->players[id].input == NULL || game->players[id].output == NULL || testPipe == NULL) { exit_with_error(game, BAD_START); } char *message = malloc(sizeof(char) * MAX_INPUT); if (fgets(message, MAX_INPUT, testPipe) != NULL) { fclose(testPipe); free(message); exit_with_error(game, BAD_START); } fclose(testPipe); free(message); } /** * Setup child process to communicate with parent. * @param game - The game instance. * @param id - id of the player. * @param input - The input pipe. * @param output - The output pipe. * @param test - The test pipe. * @param file - The file to execute for the child. */ void setup_child(Game *game, int id, int input[2], int output[2], int test[2], char *file) { if (close(input[WRITE]) == -1) { exit_with_error(game, BAD_START); } if (dup2(input[READ], STDIN_FILENO) == -1) { exit_with_error(game, BAD_START); } if (close(input[READ]) == -1) { exit_with_error(game, BAD_START); } if (close(output[READ]) == -1) { exit_with_error(game, BAD_START); } if (dup2(output[WRITE], STDOUT_FILENO) == -1) { exit_with_error(game, BAD_START); } if (close(output[WRITE]) == -1) { exit_with_error(game, BAD_START); } int devNull = open("/dev/null", O_WRONLY); if (devNull == -1) { exit_with_error(game, BAD_START); } if (dup2(devNull, STDERR_FILENO) == -1) { exit_with_error(game, BAD_START); } if (close(test[READ]) == -1) { exit_with_error(game, BAD_START); } int flags = fcntl(test[WRITE], F_GETFD); if (flags == -1) { exit_with_error(game, BAD_START); } if (fcntl(test[WRITE], F_SETFD, flags | FD_CLOEXEC) == -1) { exit_with_error(game, BAD_START); } char playerAmountArg[3], playerIdArg[3]; playerAmountArg[2] = '\0', playerIdArg[2] = '\0'; sprintf(playerAmountArg, "%d", game->playerAmount); sprintf(playerIdArg, "%d", id); execlp(file, file, playerAmountArg, playerIdArg, NULL); FILE *testPipe = fdopen(test[WRITE], "w"); fprintf(testPipe, "test\n"); fclose(testPipe); close(test[WRITE]); } /** * Sets up a single player in the game. * @param game - The game instance. * @param id - The player id. * @param file - The file name to execute. */ void setup_player(Game *game, int id, char *file) { int input[2], output[2], test[2]; if (pipe(input) != 0 || pipe(output) != 0 || pipe(test) != 0) { exit_with_error(game, BAD_START); } pid_t pid = fork(); if (pid < 0) { exit_with_error(game, BAD_START); } else if (pid > 0) { // Parent Process setup_parent(game, id, input, output, test); } else { // Child Process game->players[id].pid = pid; setup_child(game, id, input, output, test, file); } } /** * Sets up all the players in game. * @param game - The game instance. * @param playerPaths - An array of string of paths to the player. */ void setup_players(Game *game, char **playerPaths) { game->players = malloc(0); for (int i = 0; i < game->playerAmount; i++) { if (i != game->playerAmount) { game->players = realloc(game->players, sizeof(Player) * (i + 1)); } Player player; player.id = i; game->players[i] = player; set_player_values(&game->players[i]); setup_player(game, i, playerPaths[i]); } } /** * Sends an message to one player. * @param player - The player to send the message to. * @param message - the content to send */ void send_message(Player player, char *message, ...) { va_list args; va_start(args, message); vfprintf(player.input, message, args); va_end(args); fflush(player.input); } /** * Send an message to all the players. * @param game - The game instance. * @param message - The message to send. */ void send_all(Game *game, char *message, ...) { for (int i = 0; i < game->playerAmount; i++) { va_list args; va_start(args, message); vfprintf(game->players[i].input, message, args); fflush(game->players[i].input); va_end(args); } } /** * Determine whether if a new card can be flipped. * @param game - The game instance. * @return int - 1 if a new card can be flipped. * */ int has_next_card(Game *game) { return game->deckTotal.amount != game->deckIndex; } /** * Displays card detail to stdout. * @param c - The card to display. */ void display_card(Card c) { printf("New card = Bonus %c, worth %i, costs %i,%i,%i,%i\n", c.colour, c.value, c.cost[PURPLE], c.cost[BROWN], c.cost[YELLOW], c.cost[RED]); } /** * Draws the next card and places it in to the market. * @param game - The game instance. * @param deck - The deck to place in to. */ void draw_next(Game *game, Deck *deck) { if (has_next_card(game)) { Card card = game->deckTotal.cards[(game->deckIndex) - 1]; game->deckIndex++; deck->cards[7] = card; deck->amount++; display_card(card); send_all(game, "newcard%c:%i:%i,%i,%i,%i\n", card.colour, card.value, card.cost[PURPLE], card.cost[BROWN], card.cost[YELLOW], card.cost[RED]); } } /** * Draws cards and places them in to the market. * @param game - The game instance. */ void draw_cards(Game *game) { if (game->deckTotal.amount < 8) { //less than 8 cards total game->deckFaceup.cards = game->deckTotal.cards; game->deckFaceup.amount = game->deckTotal.amount; game->deckIndex = game->deckTotal.amount; } else { game->deckFaceup.cards = malloc(0); for (int i = game->deckIndex; i < game->deckTotal.amount; i++) { if (i != game->deckTotal.amount) { game->deckFaceup.cards = realloc(game->deckFaceup.cards, sizeof(Card) * (i + 1)); } game->deckFaceup.cards[i] = game->deckTotal.cards[i]; game->deckIndex++; if (i == 8) { break; } } game->deckFaceup.amount = 8; } for (int i = 0; i < game->deckFaceup.amount; i++) { display_card(game->deckFaceup.cards[i]); } } /** * Attempt to buy a card from the market. * @param game - The game instance. * @param player - The player which bought this card. * @param index - The index of the card bought. */ void buy_card(Game *game, Player *player, int index) { Deck newDeck; newDeck.cards = malloc(0); newDeck.amount = 0; for (int i = 0; i < (game->deckFaceup.amount - 1); i++) { newDeck.cards = realloc(newDeck.cards, sizeof(Card) * (i + 1)); if (i < index) { newDeck.cards[i] = game->deckFaceup.cards[i]; } else { newDeck.cards[i] = game->deckFaceup.cards[i + 1]; } newDeck.amount++; } if (!has_next_card(game)) { game->deckFaceup.amount--; } newDeck.cards = realloc(newDeck.cards, sizeof(Card) * (newDeck.amount + 1)); free(game->deckFaceup.cards); draw_next(game, &newDeck); game->deckFaceup.cards = newDeck.cards; } /** * Listen on an player's output pipe for an message. * @param player - The player to listen to. * @return char - The message sent by the player. */ char *listen(Player player) { char *message = malloc(sizeof(char) * MAX_INPUT); if (fgets(message, MAX_INPUT, player.output) == NULL) { // printf("MESSAGE FROM PLAYER IS NULL\n"); exit_with_error(NULL, PROTOCOL_ERR); } if (message[strlen(message) - 1] != '\0') { message[strlen(message) - 1] = '\0'; } return message; } /** * Use an player's tokens to purchase an card. * @param game - The game instance. * @param player - The player who used the tokens. * @param card - The card to apply the tokens to. * @param tokens - The amount of tokens spent. * @return int - 1 if successfully applied the tokens. */ int use_tokens(Game *game, Player *player, Card card, int tokens[5]) { int wild = tokens[WILD]; for (int i = 0; i < 4; i++) { if (player->tokens[i] < tokens[i]) { return 0; } } int usedWild = 0, discountedPrice; for (int i = 0; i < 4; i++) { discountedPrice = card.cost[i] - player->currentDiscount[i]; if (tokens[i] < discountedPrice) { int wildRequired = discountedPrice - tokens[i]; if (wildRequired > (wild - usedWild)) { return 0; } else { usedWild += wildRequired; } } } for (int i = 0; i < 4; i++) { player->tokens[i] -= tokens[i]; game->tokenPile[i] += tokens[i]; } player->wildTokens -= wild; return 1; } /** * Processes the purchase command from players. * @param game - The game instance. * @param player - The player who sent the command. * @param encoded - The encoded command which was sent. * @return int - 1 if successfully purchased. */ int process_purchase(Game *game, Player *player, char *encoded) { if (!match_seperators(encoded, 1, 4)) { return 0; } char **purchaseDetails = split(encoded, "e"); if (strcmp(purchaseDetails[0], "purchas") != 0 || strlen(purchaseDetails[1]) < 11) { return 0; } char **colSplit = split(purchaseDetails[1], ":"); char **commaSplit = split(colSplit[1], ","); if (!check_encoded(commaSplit, 5)) { return 0; } if (atoi(colSplit[0]) > 7) { return 0; } int index = atoi(colSplit[0]); int tokens[5]; for (int i = 0; i < 5; i++) { tokens[i] = atoi(commaSplit[i]); } Card card = game->deckFaceup.cards[index]; free(commaSplit); int status = use_tokens(game, player, card, tokens); free(colSplit); free(purchaseDetails); if (!status) { return 0; } update_discount(card.colour, player); player->points += card.value; printf("Player %c purchased %i using %i,%i,%i,%i,%i\n", player->id + 'A', index, tokens[PURPLE], tokens[BROWN], tokens[YELLOW], tokens[RED], tokens[WILD]); buy_card(game, player, index); send_all(game, "purchased%c:%i:%i,%i,%i,%i,%i\n", player->id + 'A', index, tokens[PURPLE], tokens[BROWN], tokens[YELLOW], tokens[RED], tokens[WILD]); return 1; } /** * Check whether if the take action is valid. * @param game - The game instance. * @param content - The content of the message. * @return int - 1 if the action is valid. */ int check_take(Game *game, char *content) { if (!match_seperators(content, 0, 3)) { return 0; } for (int i = 1; i < strlen(content); i++) { if (content[i] != ',' && content[i] != '\n' && !isdigit(content[i])) { return 0; } } char *contentCopy = malloc(sizeof(char) * (strlen(content) + 1)); strcpy(contentCopy, content); char **commaSplit = split(contentCopy, ","); for (int i = 0; i < 4; i++) { if (strcmp(commaSplit[i], "") == 0 || atoi(commaSplit[i]) != 0) { if (atoi(commaSplit[i]) > game->tokenPile[i]) { free(commaSplit); free(contentCopy); return 0; } } } free(commaSplit); free(contentCopy); return 1; } /** * Process an player taking tokens. * @param game - The game instance. * @param player - The player which is performing this action. * @param encoded - The content of the message. * @return int - 1 if the action is valid. */ int process_take(Game *game, Player *player, char *encoded) { char **takeDetails = split(encoded, "e"); if (strcmp(takeDetails[0], "tak") != 0 || !check_take(game, takeDetails[1])) { free(takeDetails); return 0; } char **commaSplit = split(takeDetails[1], ","); if (!check_encoded(commaSplit, 4)) { return 0; } int tokenPurple = 0, tokenBROWN = 0, tokenYellow = 0, tokenRed = 0; for (int i = 0; i < 4; i++) { game->tokenPile[i] -= atoi(commaSplit[i]); player->tokens[i] += atoi(commaSplit[i]); switch (i) { case (PURPLE): tokenPurple = atoi(commaSplit[i]); break; case (BROWN): tokenBROWN = atoi(commaSplit[i]); break; case (YELLOW): tokenYellow = atoi(commaSplit[i]); break; case (RED): tokenRed = atoi(commaSplit[i]); break; } } free(commaSplit); free(takeDetails); send_all(game, "took%c:%i,%i,%i,%i\n", player->id + 'A', tokenPurple, tokenBROWN, tokenYellow, tokenRed); printf("Player %c drew %i,%i,%i,%i\n", player->id + 'A', tokenPurple, tokenBROWN, tokenYellow, tokenRed); return 1; } /** * Process taking an while token * @param game - The game instance. * @param player - The player which is performing this action. * @param encoded - The content of the message. * @return int - 1 if the action is valid. */ int process_wild(Game *game, Player *player, char *encoded) { if (strlen(encoded) != 4) { return 0; } send_all(game, "wild%c\n", player->id + 'A'); printf("Player %c took a wild\n", player->id + 'A'); return 1; } /** * Process messages sent by the player. * @param game - The game instance. * @param player - The player which is performing this action. * @param encoded - The content of the message. * @return int - 1 if the action was successfully performed. */ int process(Game *game, Player *player, char *encoded) { if (strstr(encoded, "purchase") != NULL) { return process_purchase(game, player, encoded); } else if (strstr(encoded, "take") != NULL) { return process_take(game, player, encoded); } else if (strstr(encoded, "wild") != NULL) { process_wild(game, player, encoded); return 1; } else { return 0; } } /** * Initializes the game. * @param game - The game to initialize. */ void init_game(Game *game) { draw_cards(game); send_all(game, "tokens%i\n", game->tokenPile[PURPLE]); for (int i = 0; i < game->deckFaceup.amount; i++) { Card c = game->deckFaceup.cards[i]; send_all(game, "newcard%c:%i:%i,%i,%i,%i\n", c.colour, c.value, c.cost[0], c.cost[1], c.cost[2], c.cost[3]); } } /** * Check if the game is over. * @param game - The game instance to check if it is over. * @return int - 1 if the game has ended. */ int game_is_over(Game game) { for (int i = 0; i < game.playerAmount; i++) { if (game.players[i].points >= game.winPoints) { return 1; } } return 0; } /** * Begin playing the game. * @param game - The game instance to play. */ void play_game(Game *game) { init_game(game); int gameOver = 0; while (1) { if (gameOver) { break; } for (int i = 0; i < game->playerAmount; i++) { if (game->deckFaceup.amount == 0 || game_is_over(*game)) { send_all(game, "eog\n"); get_winners(game, get_highest_points(*game), TRUE); gameOver = 1; break; } send_message(game->players[i], "dowhat\n"); char *message = listen(game->players[i]); if (!process(game, &(game->players[i]), message)) { send_message(game->players[i], "dowhat\n"); char *reprompt = listen(game->players[i]); if (!process(game, &(game->players[i]), reprompt)) { free(reprompt); send_all(game, "eog\n"); printf("Game ended due to disconnect\n"); } } free(message); } } send_all(game, "eog\n"); } /** sigint handler */ void sigint_handle(int sig) { exit_with_error(NULL, NORMAL); } /** Setup signal handlers */ void setup_signal_action(void) { struct sigaction signalInt; signalInt.sa_handler = sigint_handle; sigaction(SIGINT, &signalInt, 0); struct sigaction signalPipe; signalPipe.sa_handler = SIG_IGN; sigaction(SIGPIPE, &signalPipe, 0); } /** Main */ int main(int argc, char **argv) { // setup_signal_action(); // Causes many memory leaks. check_args(argc, argv); Game game; game.winPoints = atoi(argv[WIN_POINTS]); for (int i = 0; i < 4; i++) { game.tokenPile[i] = atoi(argv[TOKENS]); } char **playersPaths = malloc(0); game.playerAmount = 0; game.deckFaceup.amount = 0; game.deckIndex = 0; for (int i = 4; i < argc; i++) { if (i != argc) { playersPaths = realloc(playersPaths, sizeof(char *) * (i - 3)); } playersPaths[i - 4] = argv[i]; game.playerAmount++; } setup_players(&game, playersPaths); free(playersPaths); game.deckTotal = load_deck(argv[DECK_FILE]); play_game(&game); // wait_children(&game); free_game(&game); }
2.546875
3
2024-11-18T21:06:03.447822+00:00
2015-03-02T07:39:23
fb40638fa2f218d85cdd04b5d06a77022e973ec8
{ "blob_id": "fb40638fa2f218d85cdd04b5d06a77022e973ec8", "branch_name": "refs/heads/master", "committer_date": "2015-03-02T07:39:23", "content_id": "77259bfe7c122a19ea1ab2016f6e0d9f42f76300", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f37c3546f39d7ebc4236c043e740d68bf826e8c1", "extension": "h", "filename": "FskTextConvert.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4261, "license": "Apache-2.0", "license_type": "permissive", "path": "/core/ui/FskTextConvert.h", "provenance": "stackv2-0083.json.gz:13116", "repo_name": "sandy-slin/kinomajs", "revision_date": "2015-03-02T07:39:23", "revision_id": "567b52be74ec1482e0bab2d370781a7188aeb0ab", "snapshot_id": "f08f60352b63f1d3fad3f6b0e9a5e4bc8025f082", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sandy-slin/kinomajs/567b52be74ec1482e0bab2d370781a7188aeb0ab/core/ui/FskTextConvert.h", "visit_date": "2020-12-24T22:21:05.506599" }
stackv2
/* Copyright (C) 2010-2015 Marvell International Ltd. Copyright (C) 2002-2010 Kinoma, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __FSKTEXTCONVERT__ #define __FSKTEXTCONVERT__ #include "Fsk.h" #ifdef __cplusplus extern "C" { #endif typedef struct { SInt32 size; UInt32 cmask; UInt32 cval; SInt32 shift; UInt32 lmask; UInt32 lval; } ftUTF8Sequence; FskAPI(FskErr) FskTextToPlatform(const char *text, UInt32 textLen, char **encodedText, UInt32 *encodedTextLen); FskAPI(FskErr) FskTextToUTF8(const char *text, UInt32 textLen, char **encodedText, UInt32 *encodedTextLen); FskAPI(FskErr) FskTextLatin1ToUTF8(const char *text, UInt32 textLen, char **encodedText, UInt32 *encodedTextLen); FskAPI(FskErr) FskTextUnicode16BEToUTF8(const UInt16 *text, UInt32 textByteCount, char **encodedText, UInt32 *encodedTextByteCount); FskAPI(FskErr) FskTextUnicode16LEToUTF8(const UInt16 *text, UInt32 textByteCount, char **encodedText, UInt32 *encodedTextByteCount); FskAPI(FskErr) FskTextUTF8ToUnicode16LE(const unsigned char *text, UInt32 textByteCount, UInt16 **encodedText, UInt32 *encodedTextByteCount); FskAPI(FskErr) FskTextUTF8ToUnicode16BE(const unsigned char *text, UInt32 textByteCount, UInt16 **encodedText, UInt32 *encodedTextByteCount); FskAPI(FskErr) FskTextUTF8ToUnicode16NE(const unsigned char *text, UInt32 textByteCount, UInt16 **encodedText, UInt32 *encodedTextByteCount); FskAPI(void) FskTextCharCodeToUTF8(UInt32 charCode, unsigned char *utf8); /** Convert UTF-8 to Unicode (UTF-16) in the native endian format, using memory supplied by the caller. ** \param[in] text The UTF-8 source text. ** \param[in] length The length, in bytes, of the UTF-8 source text. ** \param[in, out] encodedText Pointer to a place to store the Unicode-encoded text, without a terminating NULL character. ** If this is NULL, then no encoded text is returned. ** \param[in, out] encodedTextByteCount Pointer to a place to store the number of bytes needed to represent text as Unicode, ** regardless of whether or not encodedText was NULL or not. In this way, it is possible to query the amount of memory ** needed for the converted text, allocate it, then call it again to do the conversion. ** \return kFskErrNone if the operation was successful. **/ FskAPI(FskErr) FskTextUTF8ToUnicode16NENoAlloc(const unsigned char *text, UInt32 length, UInt16 *encodedText, UInt32 *encodedTextByteCount); FskAPI(void) FskTextUTF8DefaultWhitespaceProcessing(unsigned char *str); /* Remove newlines, convert tabs into spaces, strip off leading and trailing spaces, consolidate contiguous spaces */ FskAPI(Boolean) FskTextUTF8IsWhitespace(const unsigned char *text, UInt32 textLen, UInt32 *whiteSize); FskAPI(void) FskTextUnicode16SwapBytes(const UInt16 *fr, UInt16 *to, UInt32 nChars); /* Note: number of characters, not number of bytes */ FskAPI(UInt32) FskTextUTF8StrLen(const unsigned char *text); FskAPI(UInt32) FskTextUnicodeToUTF8Offset(const unsigned char *text, UInt32 theOffset); FskAPI(Boolean) FskTextUTF8IsValid(const unsigned char *theString, SInt32 theSize); FskAPI(SInt32) FskTextUTF8Advance(const unsigned char *theString, UInt32 theOffset, SInt32 direction); FskAPI(FskErr) FskTextUTF8ToUpper(const unsigned char *text, UInt32 textByteCount, unsigned char **upperText, UInt32 *upperTextByteCount); FskAPI(FskErr) FskTextUTF8ToLower(const unsigned char *text, UInt32 textByteCount, unsigned char **lowerText, UInt32 *lowerTextByteCount); #if TARGET_RT_LITTLE_ENDIAN #define FskTextUnicode16NEToUTF8 FskTextUnicode16LEToUTF8 #else #define FskTextUnicode16NEToUTF8 FskTextUnicode16BEToUTF8 #endif #ifdef __cplusplus } #endif #endif
2.328125
2
2024-11-18T21:06:07.113206+00:00
2017-10-22T07:15:46
3a33a642fc89ed1bdd1953988a187fabefe1c3b7
{ "blob_id": "3a33a642fc89ed1bdd1953988a187fabefe1c3b7", "branch_name": "refs/heads/master", "committer_date": "2017-10-22T07:23:52", "content_id": "20c2b4c7b984663baddcec7b47fb0ed057a12801", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "c0cbf3c93937e3d18732aa90ddd16574489e7327", "extension": "c", "filename": "hw_dut_api.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 107844374, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1166, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/sw_src_files/hw_dut_api.c", "provenance": "stackv2-0083.json.gz:14018", "repo_name": "arunjeevaraj/hls_vector_array", "revision_date": "2017-10-22T07:15:46", "revision_id": "e9068b07746a6c8ef467761d768dd4eb9f0c6503", "snapshot_id": "9fce10694958acc2b5c3355ce40cda5dd4ce9d41", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/arunjeevaraj/hls_vector_array/e9068b07746a6c8ef467761d768dd4eb9f0c6503/sw_src_files/hw_dut_api.c", "visit_date": "2021-07-16T03:05:51.417551" }
stackv2
/* * hw_dut_api.c * * Created on: Oct 15, 2017 * Author: arun */ #include "hw_dut_api.h" static XDut dut_inst; int setup_hw_dut() { XDut_Config* config_ptr; int status; config_ptr = XDut_LookupConfig(XPAR_XDUT_0_DEVICE_ID); if (!config_ptr) { xil_printf("Error Lookup config failed. \r\n"); return XST_FAILURE; } status = XDut_CfgInitialize(&dut_inst, config_ptr); if (status != XST_SUCCESS) { xil_printf("Failed to configure the XDUT \r\n"); } XDut_EnableAutoRestart(&dut_inst); XDut_Start(&dut_inst); return status; } void write_trans_mat_hw(void *trans_mat_buff) { data_type trans_mat_rb[36]; u8 matches = 0; data_type *trans_mat = (data_type*)trans_mat_buff; xil_printf("Write the trans matrix \r\n"); XDut_Write_trans_mat_V_Words(&dut_inst, 0, (int*)trans_mat, 36); // read back to see if the written to dut is same. XDut_Read_trans_mat_V_Words(&dut_inst, 0, (int*)trans_mat_rb, 36); for (unsigned i = 0; i < 6 ; i ++) { for (unsigned j = 0; j < 6 ; j++) { if (trans_mat_rb[6*i + j] == trans_mat[6*i + j]){ matches++; } } } if (matches !=36){ xil_printf("hw fault, trans mat read back failed\r\n"); } }
2.40625
2
2024-11-18T21:06:07.269120+00:00
2017-10-15T15:05:40
6800ddf57f110b98f787f4fcb058996afc265e74
{ "blob_id": "6800ddf57f110b98f787f4fcb058996afc265e74", "branch_name": "refs/heads/master", "committer_date": "2017-10-15T15:05:40", "content_id": "87815f5777392b857ac4ef083732195060c007bb", "detected_licenses": [ "MIT" ], "directory_id": "66bcd01db2ad818332ac4de809db37c1e873ba0e", "extension": "c", "filename": "bootmem.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3577, "license": "MIT", "license_type": "permissive", "path": "/kernel/kernel/mm/bootmem.c", "provenance": "stackv2-0083.json.gz:14274", "repo_name": "linpingchuan/Onyx", "revision_date": "2017-10-15T15:05:40", "revision_id": "bb22aa20c6e72a7fe11d8120cb790002f96e022b", "snapshot_id": "31e94c04ee002b559ea57a4e183c76a2c5af7676", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/linpingchuan/Onyx/bb22aa20c6e72a7fe11d8120cb790002f96e022b/kernel/kernel/mm/bootmem.c", "visit_date": "2021-07-17T12:44:39.950100" }
stackv2
/* * Copyright (c) 2016, 2017 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ /************************************************************************** * * * File: bootmem.c * * Description: Contains the implementation of the kernel's boot memory manager * * Date: 4/12/2016 * * **************************************************************************/ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <multiboot2.h> #include <onyx/bootmem.h> #include <onyx/paging.h> #include <onyx/vmm.h> #include <onyx/page.h> typedef struct stack_entry { uintptr_t base; size_t size; size_t magic; } stack_entry_t; typedef struct stack { stack_entry_t* next; } stack_t; /* size of physical memory */ static uint32_t pushed_blocks = 0; static uintptr_t pmm_memory_size = 0; /* Kernel addresses reserved for pmm stack */ static uintptr_t *pmm_stack_space = NULL; extern uint32_t end; stack_t *stack = NULL; size_t bootmem_get_memsize(void) { return pmm_memory_size; } void bootmem_push_page(uintptr_t page) { for(unsigned int i = 0; i < pushed_blocks + 1; i++) { if(stack->next[i].base == 0 && stack->next[i].size == 0) { stack->next[i].base = page; stack->next[i].size = PAGE_SIZE; stack->next[i].magic = 0xFDFDFDFD; break; } if(stack->next[i].base + stack->next[i].size == page) { stack->next[i].size += PAGE_SIZE; return; } } pushed_blocks++; } bool __check_used(uintptr_t page, uintptr_t start, uintptr_t end) { if(start == page) return true; if(start <= page && end > page) return true; return false; } bool was_said = false; extern uintptr_t kernel_end; #define KERNEL_START 0x100000 bool check_used(uintptr_t page, struct multiboot_tag_module *module) { if(page == 0) return true; if(__check_used(page, module->mod_start, module->mod_end) == true) return true; /* This part doesn't work, that's why we check for KERNEL_START - module->mod_end */ if(__check_used(page, KERNEL_START, 0x400000) == true) return true; return false; } void bootmem_push(uintptr_t base, size_t size, struct multiboot_tag_module *module) { if(!was_said) { was_said = true; printf("Module: %016x-%016x\n", module->mod_start, module->mod_end); } size &= -PAGE_SIZE; base = (uintptr_t) page_align_up((void*) base); for(uintptr_t p = base; p < base + size; p += PAGE_SIZE) { if(check_used(p, module) == false) bootmem_push_page(p); } } void bootmem_init(size_t memory_size, uintptr_t stack_space) { pmm_memory_size = memory_size * 1024; pmm_stack_space = (uintptr_t *) stack_space; stack = (stack_t *) stack_space; memset(stack, 0, 4096); __ksbrk(4096); stack->next = (stack_entry_t *) (stack_space + sizeof(stack_t)); } void *bootmem_alloc(size_t blocks) { uintptr_t ret_addr = 0; for (unsigned int i = pushed_blocks-1; i; i--) if (stack->next[i].base != 0 && stack->next[i].size != 0 && stack->next[i].size >= PMM_BLOCK_SIZE * blocks) { if (stack->next[i].size >= blocks * PMM_BLOCK_SIZE) { ret_addr = stack->next[i].base; stack->next[i].base += PMM_BLOCK_SIZE * blocks; stack->next[i].size -= PMM_BLOCK_SIZE * blocks; return (void *) ret_addr; } } return NULL; } void *bootmem_get_pstack(size_t *nentries) { *nentries = pushed_blocks; return stack; } void dump_bootmem(void) { for (unsigned int i = 0; i < pushed_blocks; i++) { printf("[%016lx - %016lx]\n", stack->next[i].base, stack->next[i].base + stack->next[i].size); } }
2.921875
3
2024-11-18T21:06:07.504186+00:00
2023-07-07T18:18:01
eb6f41d3b50a15dd2aa129e794ed98fc3bb2602d
{ "blob_id": "eb6f41d3b50a15dd2aa129e794ed98fc3bb2602d", "branch_name": "refs/heads/master", "committer_date": "2023-07-07T18:20:16", "content_id": "88a55c7922ac0b1948c76327eee19a0f6eb3e57f", "detected_licenses": [ "Zlib" ], "directory_id": "9c4ec01e04f7b0a1d213e1060c6b0a008dde7cbd", "extension": "c", "filename": "main_pg12.c", "fork_events_count": 212, "gha_created_at": "2018-01-09T20:13:39", "gha_event_created_at": "2021-06-17T20:12:04", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 116865771, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2501, "license": "Zlib", "license_type": "permissive", "path": "/series1/opamp/opamp_inverting/src/main_pg12.c", "provenance": "stackv2-0083.json.gz:14531", "repo_name": "SiliconLabs/peripheral_examples", "revision_date": "2023-07-07T18:18:01", "revision_id": "87b252e5a1bf5b36a548c121e8ffda085d3bcbc4", "snapshot_id": "edf5ee87cd0bcb2e7ad5066e278fa1ad3b92bd35", "src_encoding": "UTF-8", "star_events_count": 326, "url": "https://raw.githubusercontent.com/SiliconLabs/peripheral_examples/87b252e5a1bf5b36a548c121e8ffda085d3bcbc4/series1/opamp/opamp_inverting/src/main_pg12.c", "visit_date": "2023-07-26T22:20:57.916375" }
stackv2
/**************************************************************************//** * @main_pg12.c * @brief This project operates in EM3 and configures opamp 2 as an * inverting amplifier whose gain is given by the following equation: * * Vout = -(Vin - POS) * (R2 / R1) + POS. * * By default, this project selects the R2/R1 resistor ladder ratio to * be R2 = 3 * R1. This results in Vout = -3 * (Vin - POS) + POS = -3Vin + 4POS * @version 0.0.1 ****************************************************************************** * @section License * <b>Copyright 2018 Silicon Labs, Inc. http://www.silabs.com</b> ******************************************************************************* * * This file is licensed under the Silabs License Agreement. See the file * "Silabs_License_Agreement.txt" for details. Before using this software for * any purpose, you must agree to the terms of that agreement. * ******************************************************************************/ #include "em_device.h" #include "em_chip.h" #include "em_cmu.h" #include "em_emu.h" #include "em_opamp.h" // Note: change this to one of the OPAMP_ResSel_TypeDef type defines to select // the R2/R1 resistor ladder ratio. By default this is R2 = 3 * R1. This // results in Vout = -3Vin + 4POS #define RESISTOR_SELECT opaResSelR2eq3R1 /**************************************************************************//** * @brief * Main function * * @details * No signal is explicitly selected for the negative input of the opamp * because the default macro already takes care of routing it to the resistor * ladder taps. The input to the resistor ladder was chosen to come from the * negative pad (OPA2_N), but the positive pad (OPA2_P) could also be chosen. *****************************************************************************/ int main(void) { // Chip errata CHIP_Init(); // Turn on the VDAC clock CMU_ClockEnable(cmuClock_VDAC0, true); // Configure OPA2 OPAMP_Init_TypeDef init = OPA_INIT_INVERTING; init.resSel = RESISTOR_SELECT; // Choose the resistor ladder ratio init.posSel = opaPosSelAPORT3XCH2; // Choose opamp positive input to come from PD10 init.outMode = opaOutModeAPORT3YCH3; // Route opamp output to PD11 init.resInMux = opaResInMuxNegPad; // Route negative pad to resistor ladder // Enable OPA2 OPAMP_Enable(VDAC0, OPA2, &init); while (1) { EMU_EnterEM3(false); // Enter EM3 (won't exit) } }
2.578125
3
2024-11-18T21:06:07.826309+00:00
2016-10-17T02:09:59
9833c1d663502048eac0e2edd8651705cf18cf56
{ "blob_id": "9833c1d663502048eac0e2edd8651705cf18cf56", "branch_name": "refs/heads/master", "committer_date": "2016-10-17T02:09:59", "content_id": "a3c31aead76574a86aab7633b630b44c704a7b2c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3efe3003db51227b1eeb9ca0cafaca96429249ce", "extension": "c", "filename": "StdInOut.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6481678, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1590, "license": "Apache-2.0", "license_type": "permissive", "path": "/StOrbMain/arch/pc/StdInOut.c", "provenance": "stackv2-0083.json.gz:14789", "repo_name": "ohkawatks/orbe", "revision_date": "2016-10-17T02:09:59", "revision_id": "2f11a4fd88050dc5f2c5223437d5a9630732f22a", "snapshot_id": "e67d39890ffa6855b83670c26cb1f88075006a2f", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/ohkawatks/orbe/2f11a4fd88050dc5f2c5223437d5a9630732f22a/StOrbMain/arch/pc/StdInOut.c", "visit_date": "2020-04-04T20:10:34.653850" }
stackv2
/* * $Id: StdInOut.c 622 2008-08-15 01:03:13Z takaya $ * Copyright (C) 2008 AIST, National Institute of Advanced Industrial Science and Technology */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "xbasic_types.h" #include "Orbe.h" static FILE *in; static FILE *out; void StdInOut_initialize() { in = stdin; out = stdout; return; } unsigned int StdInOut_recv(u8* start, unsigned int length) { size_t len; len = fread(start, sizeof(u8), length, in); int i; DEBUG("RECV: size=%d\n", len); for (i = 0; i < len; i++) { DEBUG("%02x", start[i]); if ((i + 1) % 16 == 0) { DEBUG("\n"); } else if (i % 2 == 1) { DEBUG(" "); } } DEBUG("\n"); return len; } int Socket_eof() { return feof(in); } unsigned int StdInOut_send(u8* start, unsigned int length) { unsigned int len; len = fwrite(start, sizeof(u8), length, out); int i; DEBUG("SEND: size=%d\n", len); for (i = 0; i < len; i++) { DEBUG("%02x", start[i]); if ((i + 1) % 16 == 0) { DEBUG("\n"); } else if (i % 2 == 1) { DEBUG(" "); } } DEBUG("\n"); return len; } /* int main(int argc, char *argv[], char *env[]) { char *buf = (char *)malloc(sizeof(char) * 10); int i = 0; StdInOut_initilize(); StdInOut_recv(buf, 10); for (i = 0; i < 10; i++) { printf("%02x ", buf[i]); } buf[0] = 'x'; buf[1] = 'y'; buf[2] = 'z'; buf[3] = '\n'; buf[4] = '\0'; printf("\n"); StdInOut_send(buf, strlen(buf)); return 0; } */
2.65625
3
2024-11-18T21:06:08.128752+00:00
2023-07-08T14:00:54
8b81d302a72d82c346cef8166d3968fa25475e2d
{ "blob_id": "8b81d302a72d82c346cef8166d3968fa25475e2d", "branch_name": "refs/heads/master", "committer_date": "2023-07-08T22:17:15", "content_id": "f8e34bed454d4679cc56448be2d2634a23a6fea9", "detected_licenses": [ "ISC" ], "directory_id": "7b92efd7dfb60d9b0a498871d5ffa699d0cf7d9e", "extension": "c", "filename": "gfx_rgbmatrix.c", "fork_events_count": 20, "gha_created_at": "2017-12-25T23:06:04", "gha_event_created_at": "2023-07-08T22:17:17", "gha_language": "C", "gha_license_id": "ISC", "github_id": 115367599, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6580, "license": "ISC", "license_type": "permissive", "path": "/src/modules/gfx_rgbmatrix.c", "provenance": "stackv2-0083.json.gz:15048", "repo_name": "shinyblink/sled", "revision_date": "2023-07-08T14:00:54", "revision_id": "9d8e60ccbf6d8a30db83f41a8a4435d4c6b317a1", "snapshot_id": "854499be7c589b2d705050b41b8324ed66948e45", "src_encoding": "UTF-8", "star_events_count": 107, "url": "https://raw.githubusercontent.com/shinyblink/sled/9d8e60ccbf6d8a30db83f41a8a4435d4c6b317a1/src/modules/gfx_rgbmatrix.c", "visit_date": "2023-07-24T08:30:03.348039" }
stackv2
/* * rgbmatrix port, much stolen from sinematrix_rgb() at https://github.com/orithena/Arduino-LED-experiments/blob/master/MatrixDemo/MatrixDemo.ino * * This is an effect that basically paints a "base canvas" via a function and then defines a "camera" that * moves, rotates and zooms seemingly randomly over that canvas, showing what that "camera" sees. * This effect uses three such cameras, one for each RGB color, blending the result together. */ #include <types.h> #include <matrix.h> #include <timers.h> #include <stddef.h> #include <mathey.h> #include <math.h> #define FPS 60 #define FRAMETIME (T_SECOND / FPS) #define FRAMES (TIME_LONG * FPS) /*** management variables ***/ static int modno; static int frame = 0; static oscore_time nexttick; /*** matrix info (initialized in init()) ***/ static int mx, my; // matrix size static float fx, fy; // size-dependent factors // basic scale factor, determining how much of the "base image" is seen on average. // Higher numbers mean that the camera is farther away from the canvas. static const float scale_factor = 4*M_PI; /*** module run variables (internal state) ***/ // primary matrix coefficient run variables static float pangle = 0; // "proto-angle" static float angle = 0; // rotation angle static float sx = 0; // scale factor x static float sy = 0; // scale factor y static float tx = 0; // translation x static float ty = 0; // translation y static float cx = 0; // center offset x (used for rcx) static float cy = 0; // center offset y (used for rcy) static float rcx = 0; // rotation center offset x static float rcy = 0; // rotation center offset y // secondary set of matrix coefficient run variables (used for "shadow overlay" in sinematrix2) static float pangle2 = 0; // "proto-angle" static float angle2 = 0; // angle static float sx2 = 0; // scale factor x static float sy2 = 0; // scale factor y static float tx2 = 0; // translation x static float ty2 = 0; // translation y static float cx2 = 0; // center offset x (used for rcx) static float cy2 = 0; // center offset y (used for rcy) static float rcx2 = 0; // rotation center offset x static float rcy2 = 0; // rotation center offset y static float pangle3 = 0; // "proto-angle" static float angle3 = 0; // rotation angle static float sx3 = 0; // scale factor x static float sy3 = 0; // scale factor y static float tx3 = 0; // translation x static float ty3 = 0; // translation y static float cx3 = 0; // center offset x (used for rcx) static float cy3 = 0; // center offset y (used for rcy) static float rcx3 = 0; // rotation center offset x static float rcy3 = 0; // rotation center offset y static float basecol = 0; // base color offset to start from for each frame /*** module init ***/ int init(int moduleno, char* argstr) { mx = matrix_getx(); my = matrix_gety(); fx = mx / scale_factor; fy = my / scale_factor; if (mx < 2) return 1; if (my < 2) return 1; modno = moduleno; return 0; } /*** base "image" function ***/ static inline float halfsines3D(float x, float y) { float r = (cos(x) * sin(y)); return (r > 0.0 ? r : 0.0); } /*** math helper functions ***/ static inline float addmod(float x, float mod, float delta) { x = fmodf(x + delta, mod); x += x<0 ? mod : 0; return x; } static inline float addmodpi(float x, float delta) { return addmod(x, 2 * M_PI, delta); } /*** main drawing loop ***/ void reset(int _modno) { nexttick = udate(); frame = 0; } int draw(int _modno, int argc, char* argv[]) { nexttick = udate() + FRAMETIME; pangle = addmodpi( pangle, 0.00133 + (angle/256) ); angle = cos(pangle) * M_PI; pangle2 = addmodpi( pangle2, 0.00323 + (angle2/256) ); angle2 = cos(pangle2) * M_PI; pangle3 = addmodpi( pangle3, 0.00613 + (angle3/256) ); angle3 = cos(pangle3) * M_PI; sx = addmodpi( sx, 0.000673 ); sy = addmodpi( sy, 0.000437 ); sx2 = addmodpi( sx2, 0.000973 ); sy2 = addmodpi( sy2, 0.001037 ); sx3 = addmodpi( sx3, 0.00273 ); sy3 = addmodpi( sy3, 0.00327 ); tx = addmodpi( tx, 0.000239 ); ty = addmodpi( ty, 0.000293 ); tx2 = addmodpi( tx2, 0.000439 ); ty2 = addmodpi( ty2, 0.000193 ); tx3 = addmodpi( tx3, 0.000639 ); ty3 = addmodpi( ty3, 0.000793 ); cx = addmodpi( cx, 0.000347 ); cy = addmodpi( cy, 0.000437 ); rcx = (mx/2) + (sin(cx2) * mx); rcy = (my/2) + (sin(cy2) * my); cx2 = addmodpi( cx2, 0.000697 ); cy2 = addmodpi( cy2, 0.000727 ); rcx2 = (mx/2) + (sin(cx2) * mx); rcy2 = (my/2) + (sin(cy2) * my); cx3 = addmodpi( cx3, 0.000197 ); cy3 = addmodpi( cy3, 0.000227 ); rcx3 = (mx/2) + (sin(cx3) * mx); rcy3 = (my/2) + (sin(cy3) * my); basecol = addmod( basecol, 1.0, 0.007 ); matrix2_2 rotater = { .v1_1 = cos(angle), .v1_2 = -sin(angle), .v2_1 = sin(angle), .v2_2 = cos(angle) }; matrix2_2 rotateg = { .v1_1 = cos(angle2), .v1_2 = -sin(angle2), .v2_1 = sin(angle2), .v2_2 = cos(angle2) }; matrix2_2 rotateb = { .v1_1 = cos(angle3), .v1_2 = -sin(angle3), .v2_1 = sin(angle3), .v2_2 = cos(angle3) }; matrix2_2 scaler = { .v1_1 = (sin(sx) + 1.0)/fx, .v1_2 = 0, .v2_1 = 0, .v2_2 = (cos(sy) + 1.0)/fy }; matrix2_2 scaleg = { .v1_1 = (sin(sx2) + 1.0)/fx, .v1_2 = 0, .v2_1 = 0, .v2_2 = (cos(sy2) + 1.0)/fy }; matrix2_2 scaleb = { .v1_1 = (sin(sx3) + 1.0)/fx, .v1_2 = 0, .v2_1 = 0, .v2_2 = (cos(sy3) + 1.0)/fy }; vec2 translater = { .x = sin(tx) * mx, .y = sin(ty) * my }; vec2 translateg = { .x = sin(tx2) * mx, .y = sin(ty2) * my }; vec2 translateb = { .x = sin(tx3) * mx, .y = sin(ty3) * my }; for( int x = 0; x < mx; x++ ) { for( int y = 0; y < my; y++ ) { vec2 rc = { .x = x-rcx, .y = y-rcy }; vec2 rc2 = { .x = x-rcx2, .y = y-rcy2 }; vec2 rc3 = { .x = x-rcx3, .y = y-rcy3 }; vec2 cr = vadd(multm2v2( multm2(rotater, scaler), rc ), translater); vec2 cg = vadd(multm2v2( multm2(rotateg, scaleg), rc2 ), translateg); vec2 cb = vadd(multm2v2( multm2(rotateb, scaleb), rc3 ), translateb); RGB col = RGB( (halfsines3D(cr.x, cr.y))*255, (halfsines3D(cg.x, cg.y))*255, (halfsines3D(cb.x, cb.y))*255 ); matrix_set(x, y, col); } } // render it out matrix_render(); // manage framework variables if (frame >= FRAMES) { frame = 0; return 1; } frame++; timer_add(nexttick, modno, 0, NULL); return 0; } /*** module deconstructor ***/ void deinit(int _modno) {}
2.515625
3