text:
#include <sys/stat.h>
#include <time.h>
#include "configuration.h"
#include "utils.h"
#include "rules.h"
#include "index.h"
#include "cache.h"
#include "region.h"
#include "functions.h"
#include "filesystem.h"
#include "sharedmemory.h"
Cache ruleEngineConfig = {
    NULL, /* unsigned char *address */
    NULL, /* unsigned char *pointers */
    0, /* size_t dataSize */
    0, /* size_t cacheSize */
    UNINITIALIZED, /* RuleEngineStatus coreRuleSetStatus */
    UNINITIALIZED, /* RuleEngineStatus appRuleSetStatus */
    UNINITIALIZED, /* RuleEngineStatus extRuleSetStatus */
    UNINITIALIZED, /* RuleEngineStatus sysFuncDescIndexStatus */
    UNINITIALIZED, /* RuleEngineStatus coreFuncDescIndexStatus */
    UNINITIALIZED, /* RuleEngineStatus appFuncDescIndexStatus */
    UNINITIALIZED, /* RuleEngineStatus extFuncDescIndexStatus */
    UNINITIALIZED, /* RuleEngineStatus ruleEngineStatus */
    UNINITIALIZED, /* RuleEngineStatus cacheStatus */
    UNINITIALIZED, /* RuleEngineStatus sysRegionStatus */
    UNINITIALIZED, /* RuleEngineStatus regionCoreStatus */
    UNINITIALIZED, /* RuleEngineStatus regionAppStatus */
    UNINITIALIZED, /* RuleEngineStatus regionExtStatus */
    NULL, /* RuleSet *coreRuleSet */
    NULL, /* RuleSet *appRuleSet */
    NULL, /* RuleSet *extRuleSet */
    NULL, /* Env *sysFuncDescIndex */
    NULL, /* Env *coreFuncDescIndex */
    NULL, /* Env *appFuncDescIndex */
    NULL, /* Env *extFuncDescIndex */
    NULL, /* Region *sysRegion */
    NULL, /* Region *coreRegion */
    NULL, /* Region *appRegion */
    NULL, /* Region *extRegion */
    0, /* int tvarNumber */
    0, /* int clearDelayed */
    time_type_initializer, /* time_type timestamp */
    time_type_initializer, /* time_type updateTS */
    0, /* int version */
};

#ifdef DEBUG
int rSplitStr(char *all, char *head, int headLen, char *tail, int tailLen, char sep) {
    char *i = strchr(all, sep);
    if(i==NULL) {
        tail[0] = '\0';
        strcpy(head, all);
    } else {
        strcpy(tail, i+1);
        strncpy(head, all, i-all);
        head[i-all] = '\0';
    }
    return 0;
}
#endif

void removeRuleFromExtIndex(char *ruleName, int i) {
	if(isComponentInitialized(ruleEngineConfig.extFuncDescIndexStatus)) {
		FunctionDesc *fd = (FunctionDesc *)lookupFromHashTable(ruleEngineConfig.extFuncDescIndex->current, ruleName);
		RuleIndexList *rd = FD_RULE_INDEX_LIST(fd);
		removeNodeFromRuleIndexList2(rd, i);
		if(rd->head == NULL) {
			deleteFromHashTable(ruleEngineConfig.extFuncDescIndex->current, ruleName);
		}
	}

}
void appendRuleIntoExtIndex(RuleDesc *rule, int i, Region *r) {
	FunctionDesc *fd = (FunctionDesc *)lookupFromHashTable(ruleEngineConfig.extFuncDescIndex->current, RULE_NAME(rule->node));
	RuleIndexList *rd;
	if(fd == NULL) {
		rd = newRuleIndexList(RULE_NAME(rule->node), i, r);
		fd = newRuleIndexListFD(rd, NULL, r);

		insertIntoHashTable(ruleEngineConfig.extFuncDescIndex->current, RULE_NAME(rule->node), fd);
	} else {
		if(getNodeType(fd)==N_FD_RULE_INDEX_LIST) {
			rd = FD_RULE_INDEX_LIST(fd);
			appendRuleNodeToRuleIndexList(rd, i ,r);
		} else if(getNodeType(fd) == N_FD_EXTERNAL) {
			/* combine N_FD_EXTERNAL with N_FD_RULE_LIST */
			updateInHashTable(ruleEngineConfig.extFuncDescIndex->current, RULE_NAME(rule->node), newRuleIndexListFD(newRuleIndexList(RULE_NAME(rule->node), i, r),fd->exprType, r));
		} else {
			/* todo error handling */
		}
	}
}

void prependRuleIntoAppIndex(RuleDesc *rule, int i, Region *r) {
	RuleIndexList *rd;
	FunctionDesc *fd = (FunctionDesc *)lookupFromHashTable(ruleEngineConfig.appFuncDescIndex->current, RULE_NAME(rule->node));
	if(fd == NULL) {
		rd = newRuleIndexList(RULE_NAME(rule->node), i, r);
		fd = newRuleIndexListFD(rd, NULL, r);
		insertIntoHashTable(ruleEngineConfig.appFuncDescIndex->current, RULE_NAME(rule->node), fd);
	} else {
		rd = FD_RULE_INDEX_LIST(fd);
		prependRuleNodeToRuleIndexList(rd, i ,r);
	}
}
int checkPointExtRuleSet(Region *r) {
	ruleEngineConfig.extFuncDescIndex = newEnv(newHashTable2(100, r), ruleEngineConfig.extFuncDescIndex, NULL, r);
	return ruleEngineConfig.extRuleSet->len;
}
/*void appendAppRule(RuleDesc *rd, Region *r) {
	int i = ruleEngineConfig.appRuleSet->len++;
	ruleEngineConfig.appRuleSet->rules[i] = rd;
	appendRuleIntoIndex(rd, i, r);
}*/
void prependAppRule(RuleDesc *rd, Region *r) {
	int i = ruleEngineConfig.appRuleSet->len++;
	ruleEngineConfig.appRuleSet->rules[i] = rd;
	prependRuleIntoAppIndex(rd, i, r);
}
void popExtRuleSet(int checkPoint) {
	/*int i;
	for(i = checkPoint; i < ruleEngineConfig.extRuleSet->len; i++) {
		removeRuleFromExtIndex(RULE_NAME(ruleEngineConfig.extRuleSet->rules[i]->node), i);
	}*/
	Env *temp = ruleEngineConfig.extFuncDescIndex;
	ruleEngineConfig.extFuncDescIndex = temp->previous;
	/* deleteEnv(temp, 1); */
	ruleEngineConfig.extRuleSet->len = checkPoint;
}
RuleEngineStatus getRuleEngineStatus() {
    return ruleEngineConfig.ruleEngineStatus;
}
/* RuleEngineStatus getRuleEngineMemStatus() {
    return _ruleEngineMemStatus;
}
void setAppRuleSetStatus(RuleEngineStatus s) {
    _ruleEngineStatus = s;
}
RuleEngineStatus getAppRuleSetStatus() {
    return _ruleEngineStatus;
}
void setRuleEngineMemStatus(RuleEngineStatus s) {
	_ruleEngineMemStatus = s;
} */
int clearResources(int resources) {
	clearFuncDescIndex(APP, app);
	clearFuncDescIndex(SYS, sys);
	clearFuncDescIndex(CORE, core);
	clearFuncDescIndex(EXT, ext);
	clearRegion(APP, app);
	clearRegion(SYS, sys);
	clearRegion(CORE, core);
	clearRegion(EXT, ext);
	clearRuleSet(APP, app);
	clearRuleSet(CORE, core);
	clearRuleSet(EXT, ext);

	if((resources & RESC_CACHE) && isComponentAllocated(ruleEngineConfig.cacheStatus)) {
		free(ruleEngineConfig.address);
		ruleEngineConfig.address = NULL;
		ruleEngineConfig.cacheStatus = UNINITIALIZED;
	}
	return 0;
}
List hashtablesToClear = {NULL, NULL};
List envToClear = {NULL, NULL};
List regionsToClear = {NULL, NULL};
List memoryToFree = {NULL, NULL};

void delayClearResources(int resources) {
	/*if((resources & RESC_RULE_INDEX) && ruleEngineConfig.ruleIndexStatus == INITIALIZED) {
		listAppendNoRegion(hashtablesToClear, ruleEngineConfig.ruleIndex);
		ruleEngineConfig.ruleIndexStatus = UNINITIALIZED;
	}
	if((resources & RESC_COND_INDEX) && ruleEngineConfig.condIndexStatus == INITIALIZED) {
		listAppendNoRegion(hashtableToClear, ruleEngineConfig.condIndex);
		ruleEngineConfig.condIndexStatus = UNINITIALIZED;
	}*/
	delayClearRegion(APP, app);
	delayClearRegion(SYS, sys);
	delayClearRegion(CORE, core);
	delayClearRegion(EXT, ext);
	delayClearRuleSet(APP, app);
	delayClearRuleSet(CORE, core);
	delayClearRuleSet(EXT, ext);
	delayClearFuncDescIndex(APP, app);
	delayClearFuncDescIndex(SYS, sys);
	delayClearFuncDescIndex(CORE, core);
	delayClearFuncDescIndex(EXT, ext);

	if((resources & RESC_CACHE) && ruleEngineConfig.cacheStatus == INITIALIZED) {
		listAppendNoRegion(&memoryToFree, ruleEngineConfig.address);
		ruleEngineConfig.cacheStatus = UNINITIALIZED;
	}
}

void clearDelayed() {
	ListNode *n = envToClear.head;
	while(n!=NULL) {
		/* deleteEnv((Env *) n->value, 1); */
		listRemoveNoRegion(&envToClear, n);
		n = envToClear.head;
	}
	n = hashtablesToClear.head;
	while(n!=NULL) {
		deleteHashTable((Hashtable *) n->value, nop);
		listRemoveNoRegion(&hashtablesToClear, n);
		n = hashtablesToClear.head;
	}
	n = regionsToClear.head;
		while(n!=NULL) {
			region_free((Region *) n->value);
			listRemoveNoRegion(&regionsToClear, n);
			n = regionsToClear.head;
		}
		n = memoryToFree.head;
			while(n!=NULL) {
				free(n->value);
				listRemoveNoRegion(&memoryToFree, n);
				n = memoryToFree.head;
			}
}

void setCacheAddress(unsigned char *addr, RuleEngineStatus status, long size) {
    ruleEngineConfig.address = addr;
    ruleEngineConfig.cacheStatus = status;
    ruleEngineConfig.cacheSize = size;

}

int generateLocalCache() {
    unsigned char *buf = NULL;
	if(ruleEngineConfig.cacheStatus == INITIALIZED) {
		free(ruleEngineConfig.address);
	}
	buf = (unsigned char *)malloc(SHMMAX);
	if(buf == NULL) {
		return RE_OUT_OF_MEMORY;
	}
	setCacheAddress(buf, INITIALIZED, SHMMAX);
	return 0;
}
int generateFunctionDescriptionTables() {
	createFuncDescIndex(SYS, sys);
	createFuncDescIndex(CORE, core);
    createFuncDescIndex(APP, app);
    if(!isComponentInitialized(ruleEngineConfig.extFuncDescIndexStatus)) {
    	createFuncDescIndex(EXT, ext);
    	ruleEngineConfig.extFuncDescIndex->previous = ruleEngineConfig.appFuncDescIndex;
    } else {
    	Env *extEnv = ruleEngineConfig.extFuncDescIndex;
    	while(extEnv->previous!= NULL) {
    		extEnv = extEnv->previous;
    	}
    	extEnv->previous = ruleEngineConfig.appFuncDescIndex;
    }
    ruleEngineConfig.appFuncDescIndex->previous = ruleEngineConfig.coreFuncDescIndex;
    ruleEngineConfig.coreFuncDescIndex->previous = ruleEngineConfig.sysFuncDescIndex;

	return 0;
}
void generateRuleSets() {
	createRuleSet(APP, app);
	createRuleSet(CORE, core);
	createRuleSet(EXT, ext);
}
void generateRegions() {
	createRegion(APP, app);
	createRegion(CORE, core);
	createRegion(SYS, sys);
	createRegion(EXT, ext);
}
int unlinkFuncDescIndex() {
	Env *extEnv = ruleEngineConfig.extFuncDescIndex;
	while(extEnv->previous != ruleEngineConfig.appFuncDescIndex) {
		extEnv = extEnv->previous;
	}
	extEnv->previous = NULL;
	ruleEngineConfig.appFuncDescIndex->previous = NULL;
	ruleEngineConfig.coreFuncDescIndex->previous = NULL;
	return 0;
}
int clearRuleIndex(ruleStruct_t *inRuleStruct) {
	if(inRuleStruct == &coreRuleStrct) {
		clearResources(RESC_CORE_FUNC_DESC_INDEX);
	} else if(inRuleStruct == &appRuleStrct) {
		clearResources(RESC_APP_FUNC_DESC_INDEX);
	}
	return 0;
}

int createRuleIndex(ruleStruct_t *inRuleStruct) {
	if(inRuleStruct == &coreRuleStrct) {
		createRuleNodeIndex(ruleEngineConfig.coreRuleSet, ruleEngineConfig.coreFuncDescIndex->current, CORE_RULE_INDEX_OFF, ruleEngineConfig.coreRegion);
		createCondIndex(ruleEngineConfig.coreRegion);
	} else if(inRuleStruct == &appRuleStrct) {
		createRuleNodeIndex(ruleEngineConfig.appRuleSet, ruleEngineConfig.appFuncDescIndex->current, APP_RULE_INDEX_OFF, ruleEngineConfig.appRegion);
	}
	return 0;

}
int loadRuleFromCacheOrFile(int processType, char *irbSet, ruleStruct_t *inRuleStruct) {
    char r1[NAME_LEN], r2[RULE_SET_DEF_LENGTH], r3[RULE_SET_DEF_LENGTH];
    strcpy(r2,irbSet);
    int res = 0;

#ifdef DEBUG
    /*Cache *cache;*/
#endif

    /* get max timestamp */
    char fn[MAX_NAME_LEN];
    time_type timestamp = time_type_initializer, mtim;
	while (strlen(r2) > 0) {
		rSplitStr(r2,r1,NAME_LEN,r3,RULE_SET_DEF_LENGTH,',');
		getRuleBasePath(r1, fn);
		if((res = getModifiedTime(fn, &mtim))!=0) {
			return res;
		}
		if(time_type_gt(mtim, timestamp)) {
			time_type_set(timestamp, mtim);
		}
#if defined(DEBUG) && !defined(USE_BOOST)
		printf("last modified time, %ld\n", timestamp);
#endif
		strcpy(r2,r3);
	}
	strcpy(r2,irbSet);

	#ifdef CACHE_ENABLE

	Cache *cache;
    int update = 0;
    unsigned char *buf = NULL;
	/* try to find shared memory cache */
    if(processType == RULE_ENGINE_TRY_CACHE && inRuleStruct == &coreRuleStrct) {
    	buf = prepareNonServerSharedMemory();
    	if(buf != NULL) {
            cache = restoreCache(buf);
	        detachSharedMemory();

	        if(cache == NULL) {
	        	rodsLog(LOG_ERROR, "Failed to restore cache.");
	        } else if(time_type_gt(timestamp, cache->timestamp)) {
	        	 update = 1;
	        	 free(cache->address);
	        	 rodsLog(LOG_DEBUG, "Rule file modified, force refresh.");
	        } else {

	        cache->cacheStatus = INITIALIZED;
            ruleEngineConfig = *cache;
            /* generate extRuleSet */
        	generateRegions();
        	generateRuleSets();
        	generateFunctionDescriptionTables();
        	if(inRuleStruct == &coreRuleStrct && ruleEngineConfig.ruleEngineStatus == UNINITIALIZED) {
        		getSystemFunctions(ruleEngineConfig.sysFuncDescIndex->current, ruleEngineConfig.sysRegion);
        	}
            /* ruleEngineConfig.extRuleSetStatus = LOCAL;
            ruleEngineConfig.extFuncDescIndexStatus = LOCAL; */
            /* createRuleIndex(inRuleStruct); */
            RETURN;
	        }
    	} else {
    		rodsLog(LOG_DEBUG, "Cannot open shared memory.");
    	}
    }
#endif

    if(ruleEngineConfig.ruleEngineStatus == INITIALIZED) {
		/* Reloading rule set, clear previously generated rule set */
		unlinkFuncDescIndex();
		clearRuleIndex(inRuleStruct);
    }

	generateRegions();
	generateRuleSets();
	generateFunctionDescriptionTables();
	if(inRuleStruct == &coreRuleStrct && ruleEngineConfig.ruleEngineStatus == UNINITIALIZED) {
		getSystemFunctions(ruleEngineConfig.sysFuncDescIndex->current, ruleEngineConfig.sysRegion);
	}
    /*ruleEngineConfig.extRuleSetStatus = LOCAL;
    ruleEngineConfig.extFuncDescIndexStatus = LOCAL;*/
	while (strlen(r2) > 0) {
		int i = rSplitStr(r2,r1,NAME_LEN,r3,RULE_SET_DEF_LENGTH,',');
		if (i == 0)
			i = readRuleStructAndRuleSetFromFile(r1, inRuleStruct);
#ifdef DEBUG
		printf("%d rules in core rule set\n", ruleEngineConfig.coreRuleSet->len);
#endif
		if (i != 0) {
			res = i;
			RETURN;
		}
		strcpy(r2,r3);
	}

	createRuleIndex(inRuleStruct);
	/* set max timestamp */
	time_type_set(ruleEngineConfig.timestamp, timestamp);

#ifdef CACHE_ENABLE
	if((processType == RULE_ENGINE_INIT_CACHE || update) && inRuleStruct == &coreRuleStrct) {
		unsigned char *shared = prepareServerSharedMemory();

		if(shared != NULL) {
			int ret = updateCache(shared, SHMMAX, &ruleEngineConfig, processType);
			detachSharedMemory();
			if(ret != 0) {
				removeSharedMemory();
			}
		} else {
			rodsLog(LOG_ERROR, "Cannot open shared memory.");
		}
	}
#endif

ret:
    ruleEngineConfig.ruleEngineStatus = INITIALIZED;

    return res;
}
int readRuleStructAndRuleSetFromFile(char *ruleBaseName, ruleStruct_t *inRuleStrct)
{
  int i;
/*  char l0[MAX_RULE_LENGTH]; */
/*  char l1[MAX_RULE_LENGTH]; */
/*  char l2[MAX_RULE_LENGTH]; */
/*  char l3[MAX_RULE_LENGTH]; */
   char rulesFileName[MAX_NAME_LEN];
/*   FILE *file; */
/*   char buf[MAX_RULE_LENGTH]; */
   char *configDir;
/*   char *t; */
   i = inRuleStrct->MaxNumOfRules;

   if (ruleBaseName[0] == '/' || ruleBaseName[0] == '\\' ||
       ruleBaseName[1] == ':') {
     snprintf (rulesFileName,MAX_NAME_LEN, "%s",ruleBaseName);
   }
   else {
     configDir = getConfigDir ();
     snprintf (rulesFileName,MAX_NAME_LEN, "%s/reConfigs/%s.re", configDir,ruleBaseName);
   }
   /*file = fopen(rulesFileName, "r");
   if (file == NULL) {
#ifndef DEBUG
       rodsLog(LOG_NOTICE,
	     "readRuleStructFromFile() could not open rules file %s\n",
	     rulesFileName);
#endif
     return(RULES_FILE_READ_ERROR);
   }
   buf[MAX_RULE_LENGTH-1]='\0';
   while (fgets (buf, MAX_RULE_LENGTH-1, file) != NULL) {
     if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0';
     if (buf[0] == '#' || strlen(buf) < 4)
       continue;
		char *l0, *l2, *l3;
		// rSplitStr(buf, l1, MAX_RULE_LENGTH, l0, MAX_RULE_LENGTH, '|');
		l0 = nextRuleSection(buf, l1);
     inRuleStrct->action[i] = strdup(l1);
     inRuleStrct->ruleHead[i] = strdup(l1);
     if ((t = strstr(inRuleStrct->action[i],"(")) != NULL) {
       *t = '\0';
     }
     inRuleStrct->ruleBase[i] = strdup(ruleBaseName);
		// rSplitStr(l0, l1, MAX_RULE_LENGTH, l3, MAX_RULE_LENGTH,'|');
		l3 = nextRuleSection(l0, l1);
     inRuleStrct->ruleCondition[i] = strdup(l1);
		// rSplitStr(l3, l1, MAX_RULE_LENGTH, l2, MAX_RULE_LENGTH, '|');
		l2 = nextRuleSection(l3, l1);
     inRuleStrct->ruleAction[i] = strdup(l1);
     inRuleStrct->ruleRecovery[i] = strdup(l2);
     i++;
   }
   fclose (file);
   inRuleStrct->MaxNumOfRules = i;*/
	int errloc;
	rError_t errmsgBuf;
        errmsgBuf.errMsg = NULL;
        errmsgBuf.len = 0;

        char *buf = (char *) malloc(ERR_MSG_LEN*1024*sizeof(char));
        int res = 0;
	if(inRuleStrct == &coreRuleStrct) {
		if((res = readRuleSetFromFile(ruleBaseName,ruleEngineConfig.coreRuleSet,ruleEngineConfig.coreFuncDescIndex,&errloc,&errmsgBuf, ruleEngineConfig.coreRegion))==0) {
		} else {
			errMsgToString(&errmsgBuf, buf, ERR_MSG_LEN*1024);
			rodsLog(LOG_ERROR, "%s", buf);
		}
	} else if(inRuleStrct == &appRuleStrct) {
		if((res = readRuleSetFromFile(ruleBaseName,ruleEngineConfig.appRuleSet, ruleEngineConfig.appFuncDescIndex,&errloc,&errmsgBuf, ruleEngineConfig.appRegion))==0) {
		} else {
			errMsgToString(&errmsgBuf, buf, ERR_MSG_LEN*1024);
			rodsLog(LOG_ERROR, "%s", buf);
		}
	}
	free(buf);
	freeRErrorContent(&errmsgBuf);
	return res;
}

int availableRules() {
	return (isComponentInitialized(ruleEngineConfig.appRuleSetStatus) ? ruleEngineConfig.coreRuleSet->len : 0) + (isComponentInitialized(ruleEngineConfig.appRuleSetStatus) == INITIALIZED? ruleEngineConfig.appRuleSet->len : 0);
}


text:
Joshfire.define(['joshfire/class'], function(Class) {

  return Class(
      /**
      * @lends utils_delayedswitch.prototype
      */
      {

        /**
        * @constructs
        * @class A on/off switch with delay and reset
        * @param {Function} stateON callback when ON.
        * @param {Function} stateOFF callback when OFF.
        * @param {Integer} delayON delay before calling stateON.
        */
        __constructor: function(stateON, stateOFF, delayON /*, todo delayOFF*/ ) {
          this._on = stateON;
          this._off = stateOFF;
          this.delayON = delayON;
          this.timer = false;
        },

        /**
        * @function on
        *
        */
        on: function() {
          if (!this.delayON) {
            if (this._on) this._on();
          } else if (!this.timer) {
            var self = this;
            this.timer = setTimeout(function() {
              self.timer = false;
              if (self._on) self._on();
            }, this.delayON);
          }
        },

        /**
        * @function off
        *
        */
        off: function() {
          if (this.timer) {
            clearTimeout(this.timer);
            this.timer = false;
          }
          if (this._off) this._off();
        },

        /**
        * @function reset
        *
        */
        reset: function() {
          this.off();
          this.on();
        }
      });

});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Aisel\ProductBundle\Tests\Controller\Admin;

use Aisel\MediaBundle\Tests\Controller\UploadControllerTest;

/**
 * ApiImageControllerTest
 *
 * @author Ivan Proskuryakov <volgodark@gmail.com>
 */
class ApiImageControllerTest extends UploadControllerTest
{

    public function testPostImageAction()
    {
        $product = $this
            ->dm
            ->getRepository('Aisel\ProductBundle\Document\Product')
            ->findOneBy(['locale' => 'en']);

        foreach ($product->getImages() as $image) {
            $product->removeImage($image);
        }

        $this->assertEquals(0, count($product->getImages()));

        foreach ($this->filenames['files'] as $file) {
            $filename = $this->upload($product->getId(), $file);

            // Create Product Image entity
            $data = [
                'filename' => $filename,
                'title' => 'title',
                'description' => 'description',
            ];

            $this->client->request(
                'POST',
                '/' . $this->api['backend'] .
                '/media/image/',
                [],
                [],
                ['CONTENT_TYPE' => 'application/json'],
                json_encode($data)
            );

            $response = $this->client->getResponse();
            $content = $response->getContent();

            $statusCode = $response->getStatusCode();
            $result = json_decode($content, true);

            $parts = explode('/', $response->headers->get('location'));
            $id = array_pop($parts);
            $this->assertEquals($statusCode, 201);
            $this->assertEquals($result, '');
            $this->assertNotNull($id);

            $images[] = ['id' => $id];
        }

        // Patching product
        $data = [
            'images' => $images,
        ];

        $this->client->request(
            'PUT',
            '/' . $this->api['backend'] . '/product/' . $product->getId(),
            [],
            [],
            ['CONTENT_TYPE' => 'application/json'],
            json_encode($data)
        );

        $response = $this->client->getResponse();
        $content = $response->getContent();
        $statusCode = $response->getStatusCode();

//        var_dump($product->getId());
//        var_dump($product->getPrice());
//        var_dump($content);
//        exit();

        $this->assertEmpty($content);
        $this->assertTrue(204 === $statusCode);
        $this->dm->clear();

        //Checking
        $product = $this
            ->dm
            ->getRepository('Aisel\ProductBundle\Document\Product')
            ->find($product->getId());

        $this->assertEquals(count($this->filenames['files']), count($product->getImages()));
    }

    public function testPutImageAction()
    {
        $product = $this
            ->dm
            ->getRepository('Aisel\ProductBundle\Document\Product')
            ->findOneBy(['locale' => 'en']);

        $image = $product->getImages()[0];
        $data = [
            'title' => time(),
            'description' => time(),
        ];

        $this->client->request(
            'PUT',
            '/' . $this->api['backend'] .
            '/media/image/' . $image->getId(),
            [],
            [],
            ['CONTENT_TYPE' => 'application/json'],
            json_encode($data)
        );

        $response = $this->client->getResponse();
        $content = $response->getContent();
        $statusCode = $response->getStatusCode();
        $result = json_decode($content, true);

        $this->assertEquals($statusCode, 204);
        $this->assertEquals($result, '');

        $this->dm->clear();

        $product = $this
            ->dm
            ->getRepository('Aisel\ProductBundle\Document\Product')
            ->findOneBy(['locale' => 'en']);
        $image = $product->getImages()[0];

        $this->assertEquals($image->getTitle(), $data['title']);
        $this->assertEquals($image->getDescription(), $data['description']);
    }

    public function testGetImageAction()
    {
        $product = $this
            ->dm
            ->getRepository('Aisel\ProductBundle\Document\Product')
            ->findOneBy(['locale' => 'en']);

        $this->assertEquals(count($this->filenames['files']), count($product->getImages()));

        foreach ($product->getImages() as $image) {
            $this->client->request(
                'GET',
                '/' . $this->api['backend'] .
                '/media/image/' . $image->getId(),
                [],
                [],
                ['CONTENT_TYPE' => 'application/json']
            );

            $response = $this->client->getResponse();
            $content = $response->getContent();
            $statusCode = $response->getStatusCode();
            $result = json_decode($content, true);

            $this->assertEquals($statusCode, 200);
            $this->assertNotNull($result['filename']);
            $this->assertNotNull($result['main_image']);
            $this->assertNotNull($result['updated_at']);
            $this->assertNotNull($result['updated_at']);
        }
    }

    public function testDeleteImageAction()
    {
        $product = $this
            ->dm
            ->getRepository('Aisel\ProductBundle\Document\Product')
            ->findOneBy(['locale' => 'en']);

        $this->assertEquals(count($this->filenames['files']), count($product->getImages()));

        foreach ($product->getImages() as $image) {
            $this->client->request(
                'DELETE',
                '/' . $this->api['backend'] .
                '/media/image/' . $image->getId(),
                [],
                [],
                ['CONTENT_TYPE' => 'application/json']
            );

            $response = $this->client->getResponse();
            $content = $response->getContent();
            $statusCode = $response->getStatusCode();

            $this->assertEquals($statusCode, 204);
            $this->assertEmpty($content);
        }

        $data['images'] = [];
        $this->client->request(
            'PUT',
            '/'. $this->api['backend'] . '/product/' . $product->getId(),
            [],
            [],
            ['CONTENT_TYPE' => 'application/json'],
            json_encode($data)
        );

        $response = $this->client->getResponse();
        $content = $response->getContent();
        $statusCode = $response->getStatusCode();

        $this->dm->clear();

        $product = $this
            ->dm
            ->getRepository('Aisel\ProductBundle\Document\Product')
            ->findOneBy(['locale' => 'en']);

        $this->assertEquals(0, count($product->getImages()->toArray()));
    }

}


text:
class ApiController < ApplicationController
  before_action :check_token

  def check_token
    render body: nil, status: :unauthorized unless App.api_token == params[:token]
  end
end


text:
<link href="../../../../../../../../../Mainpage/summaries.css" rel="stylesheet" />
<title>Linebreak2 with sentences</title>

So let's see if we can take the derivative of this expression right over here, if we can find capital F prime of x.

And once again, it looks like you might be able to use the fundamental theorem of calculus. A big giveaway is that you're taking the derivative of a definite integral that gives you a function of x. But here I have x on both the upper and the lower boundary, and the fundamental theorem of calculus, is at least from what we've seen, is when we have x's only on the upper boundary. And then, of course, it's an x squared, but we've seen examples of that already when we used the chain rule to do it. But how can we break this up and put this in a form that's a little bit closer to what we're familiar with when we apply the fundamental theorem of calculus? And to realize that, we really just have to attempt to graph what this is representing.

So let's say that this is our lowercase f of x, or I should say f of t. So let's call this lowercase f of t.

And let's graph it over the interval between x and x squared.

So let's say this is my y-axis. This is my t-axis. And let's say that this right over here is y is equal to f of t.

I'm drawing it generally. I don't know what this exactly looks like. And we're going to talk about the interval between x and x squared.

So if we're going to talk about the interval between x, which is right over here, it's the lower bound, so x and x squared.

It's the lower bound, at least for this definite integral. We don't know for sure. It depends on what x you choose on which one is actually smaller.

But let's just say that for the sake of visualizing, we'll draw x right over here, and we will draw x squared right over here.

So this whole expression, this entire definite integral, is essentially asking for, is essentially representing this entire area, the entire area under the curve.

But what we could do is introduce a constant that's someplace in between x and x squared.

Let's say that constant is c, and break this area into two different areas with c as the divider.

So that same exact whole area we can now write it as two separate integrals.

So one integral that represents this area right over here, and then another integral that represents this area right over there, and where we just say c is some constant between x and x squared.

Well, how can we denote this area in purple? Well, that's going to be-- So this thing is going to be equal to the sum of these two areas. The purple area we can show is the definite integral from x to c of our function of t, cosine t over t dt. And then to that we're going to add the green area.

And then we'll get the original area.

So for the green area, our lower bound of integration is now our constant c, and our upper bound of integration is x squared, and it's going to be of cosine t over t dt. And this is a form where, if we know how to apply the chain rule, we can apply the fundamental theorem of calculus.

And this is almost in a form. We're used to seeing it where the x is the upper bound. And, well, we already know what happens. We can swap these two bounds, but it'll just be the negative of that integral.

So this is going to be equal to-- let me rewrite it-- the negative of the definite integral from c to x of cosine t over t dt. And then we have plus the definite integral that goes from c to x squared of cosine t over t dt.

So all we've done is we've rewritten this thing in a way that we're used to applying the fundamental theorem of calculus.

So if we want to find F prime of x, well, applying the derivative operator over here, we're going to have a negative out front. It's going to be equal to negative cosine x over x. Once again, just the fundamental theorem of calculus. And then plus-- we're first going to take the derivative of this thing with respect to x squared, and that's going to give you cosine of x squared over x squared.

Wherever you saw t, you replace it with an x squared. And then you're going to multiply that times the derivative of x squared with respect to x.

So that's just going to be-- derivative of x squared with respect to x is just 2x.

And we're done. We just need to simplify this thing.

So all of this is going to be equal to negative cosine x over x plus-- well, this is going to cancel out with just one of those-- plus 2 cosine x squared over x. And I guess we could simplify it even more as being equal to-- and we can swap these-- everything over x 2 cosine of x squared minus cosine of x.

And we are done.


text:
using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Collections.Generic;
using System.Linq;
using Partner.Data;

namespace Partner.Service {

  // The service is stateful, as it is only a Proof of Concept.
  // Services should be stateless, this is for demonstration purpose only.
  [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
  public class PaymentService : IPaymentService
  {
    private const string MagicKey = "896983"; // ASCII code for "YES"

    private Dictionary<int, Payment> accounts = new Dictionary<int, Payment>();
    private int counter;

    public int ReceiveRequest(PaymentRequest request)
    {
      Console.WriteLine("ReceiveRequest: " + request);
      var payment = BuildPayment(request);
      accounts.Add(counter, payment);
      return counter;
    }

    public Payment FindPaymentById(int identifier)
    {
      if(!accounts.ContainsKey(identifier)) {
        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
        return null;
      }
      return accounts[identifier];
    }

    public List<int> GetAllPaymentIds()
    {
      return accounts.Keys.ToList();
    }

    private Payment BuildPayment(PaymentRequest request)
    {
      var payment = new Payment();
      payment.Identifier = counter++;
      payment.CreditCard = request.CreditCard;
      payment.Amount = request.Amount;
      if (request.CreditCard.Contains(MagicKey)) {
        payment.Status = PaymentStatus.Ok;
      } else {
        payment.Status = PaymentStatus.Ko;
      }
      payment.Date = DateTime.Now.ToString();
      return payment;
    }

  }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NuGetGallery.Monitoring
{
    public static class SqlConnectionExtensions
    {
        public static object ExecuteScalar(this SqlConnection self, string query)
        {
            SqlCommand cmd = self.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = query;
            return cmd.ExecuteScalar();
        }
    }
}


text:
package com.xbit.engine.base;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

public class Window
{
	public static void createWindow(int width, int height, String title)
	{
		Display.setTitle(title);
		try
		{
			Display.setDisplayMode(new DisplayMode(width, height));
			Display.create();
			Keyboard.create();
			Mouse.create();
		}
		catch (LWJGLException exception)
		{
			exception.printStackTrace();
		}
	}

	public static void render()
	{
		Display.update();
	}

	public static void Dispose()
	{
		Display.destroy();
		Keyboard.destroy();
		Mouse.destroy();
	}

	public static boolean isCloseRequested()
	{
		return Display.isCloseRequested();
	}

	public static int getWidth()
	{
		return Display.getDisplayMode().getWidth();
	}

	public static int getHeight()
	{
		return Display.getDisplayMode().getHeight();
	}
}


text:
<?php

class Recurring_Payment_Method implements Payment_Method
{
	private $_params;

	private $_descrip = "A transaction which repeats on a defined interval.  Some gateways allow a trial interval as well.";

	public function __construct()
	{
		$this->_params = array(
			'profile_start_date'		=>	'2012-05-31', //Required.  The subscription start date.
			'profile_reference'			=>	'REF-NUM', //A reference from your own subscription / invoicing system for the subscriber.
			'desc'						=>	'This is my description',	//Required.  A description for the recurring bill.
			'max_failed_payments'		=>	'3', //Maximum # of failed payments before subscription is cancelled
			'auto_bill_amt'				=>	'5.00', // ?
			'billing_period'			=>	'Year', //Required.  Year, month, week
			'billing_frequency'			=>	'1',	//Required.  Number of times to bill per period
			'total_billing_cycles'		=>	'3', //Total # of times the customer will be billed.
			'amt'						=>	'25.00',	//Required.  Amount to bill on a recurring basis.
			'trial_billing_frequency'	=>	'Year', //Set this if you want a trial.  Year, month, week.
			'trial_billing_cycles'		=>	'1', //Total # of times you want the customer to be billed at the trial rate.
			'trial_amt'					=>	'5.00',	//The trial rate.
			'currency_code'				=>	'USD', //ie USD
			'shipping_amt'				=>	'0.00', //Total of shipping alone.
			'tax_amt'					=>	'0.00', //Total of tax alone.
			'initial_amt'				=>	'0.00',	//billed immediately upon profile creation
			'failed_init_action'		=>	'Continue',	//What to do if the initial bill failes.  Continue or Cancel.
			'inv_num'					=>	'INV-NUM',
			'ship_to_first_name'		=>	'Calvin', //Name of person being shipped to
			'ship_to_last_name'			=>	'Froedge',
			'ship_to_street'			=>	'151 Somewhere Street',
			'ship_to_street2'			=>	'Suite A',
			'ship_to_city'				=>	'Somewhere',
			'ship_to_state'				=>	'KY',
			'ship_to_zip'				=>	'42167',
			'ship_to_country'			=>	'United States',
			'ship_to_phone_num'			=>	'(801) 754 4466',
			'ship_to_company'			=>	'Some Company',
			'cc_type'					=>	'Visa',	//Required.  Credit card type.
			'cc_number'					=>	'4111111111111111',	//Required.  Credit card number.
			'cc_exp'					=>	'022015',	//Required.  Credit card expiration date.
			'cc_code'					=>	'203',	//Required.  Credit Card CVV code.
			'email'						=>	'calvinsemail@gmail.com',
			'identifier'				=>	'YOUR-IDENTIFIER',
			'country'					=>	'US',	//Required.  Buyer's country code.
			'business_name'				=>	'The Business Name',
			'salutation'				=>	'Mr.',
			'first_name'				=>	'Calvin',
			'middle_name'				=>	'P',
			'last_name'					=>	'Froedge',
			'suffix'					=>	'PIMP',
			'street'					=>	'317 Kublashayev',  //Required.  Buyer's street address.
			'street2'					=>	'',
			'city'						=>	'Simferople',	//Required.  Buyer's city.
			'state'						=>	'CR',	//Required.  Buyer's state or province.
			'postal_code'				=>	'UKR',	//Required.  Buyer's postal code.
			'phone'						=>	'(801) 754 4466',
			'fax'						=>	'(801) 754 4466',
		);
	}

	public function get_params()
	{
		return $this->_params;
	}

	public function get_description()
	{
		return $this->_descrip();
	}
}


text:
<!doctype html>

<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<link rel="stylesheet" type="text/css" href="css/foundation.min.css"/>
<link rel="stylesheet" type="text/css" href="css/styles.css"/>

NPR player

Player

Related content

{{ s.caption }}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>DatabaseService</title>
    <meta name="date" content="2015-03-27">
    <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

de.crawcial.twitter.database

Class DatabaseService

java.lang.Object

de.crawcial.twitter.database.DatabaseService

public class DatabaseService
extends java.lang.Object

This singleton class handles all database activities of Crawcial for Twitter.

Author:

Sebastian Lauber

Field Summary

Fields

                                Modifier and Type
                                Field and Description

                                (package private) java.util.concurrent.LinkedBlockingQueue<java.lang.Runnable>

                                attachmentExecutors

Method Summary

All Methods Static
                                Methods Instance Methods Concrete Methods

                                Modifier and Type
                                Method and Description

                                void
                                forceShutdown()

Forces a shutdown (clears queues and shuts down all workers).

                                org.lightcouch.CouchDbProperties
                                getDbProperties()

Returns the current database connection properties.

                                java.lang.String
                                getImgSize()

Returns the configured image download size.

                                static DatabaseService
                                getInstance()

Returns the Crawcial for Twitter DatabaseService singleton.

                                java.util.Vector<com.google.gson.JsonObject>

                                getJsonObjectVector()

Returns the current outgoing vector to the database.

                                int
                                getWarningCnt()

Returns the warning count, that indicates the number of warning
                                        messages received from Twitter.

                                void
                                increaseWarnings()

This method must be called, if a message from Twitter does not
                                        contain a valid Tweet.

                                void
                                init(boolean downloadMedia,
                                    org.lightcouch.CouchDbProperties dbProperties,
                                    java.lang.String imgSize,
                                    boolean mediaHttps)

Configures the DatabaseService singleton, must be called before
                                        the crawling process starts.

                                boolean
                                isDownloadMedia()

Returns true, if the media downloader is enabled.

                                boolean
                                isMediaHttps()

Returns true, if https should be used for media downloads.

                                (package private) void
                                loadAttachment(com.google.gson.JsonObject status)

Triggers an attachment download of the status.

                                void
                                shutdown()

Initiates a proper shutdown.

Methods inherited from class java.lang.Object

                                clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait,
                                    wait, wait

Field Detail

attachmentExecutors

java.util.concurrent.LinkedBlockingQueue<java.lang.Runnable> attachmentExecutors

Method Detail

forceShutdown

public void forceShutdown()

Forces a shutdown (clears queues and shuts down all workers).

getDbProperties

public org.lightcouch.CouchDbProperties getDbProperties()

Returns the current database connection properties.

Returns:

current CouchDB connection properties

getImgSize

public java.lang.String getImgSize()

Returns the configured image download size.

Returns:

current configured image download size (thumb, small, medium, large)

getInstance

public static DatabaseService getInstance()

Returns the Crawcial for Twitter DatabaseService singleton.

Returns:

Crawcial for Twitter DatabaseService singleton

getJsonObjectVector

public java.util.Vector<com.google.gson.JsonObject> getJsonObjectVector()

Returns the current outgoing vector to the database.

Returns:

outgoing JSON vector

getWarningCnt

public int getWarningCnt()

Returns the warning count, that indicates the number of warning
                                    messages received from Twitter.

Returns:

warning count

increaseWarnings

public void increaseWarnings()

This method must be called, if a message from Twitter does not
                                    contain a valid Tweet.

init

public void init(boolean downloadMedia,
                 org.lightcouch.CouchDbProperties dbProperties,
                 java.lang.String imgSize,
                 boolean mediaHttps)

Configures the DatabaseService singleton, must be called before the
                                    crawling process starts.

Parameters:

downloadMedia - true, if media downloader enabled, false to disable
                                        media downloads

dbProperties - CouchDB properties for the Crawcial Twitter Database

imgSize - requested image size (thumb, small, medium, large)

mediaHttps - true if https should be used for media downloads

isDownloadMedia

public boolean isDownloadMedia()

Returns true, if the media downloader is enabled.

Returns:

true, if the media downloader is enabled

isMediaHttps

public boolean isMediaHttps()

Returns true, if https should be used for media downloads.

Returns:

true, if https should be used for media downloads

loadAttachment

void loadAttachment(com.google.gson.JsonObject status)

Triggers an attachment download of the status.

Parameters:

status - Tweet for attachment download

shutdown

public void shutdown()
              throws java.lang.InterruptedException

Initiates a proper shutdown.

Throws:

java.lang.InterruptedException - if interrupted

Skip navigation links

Overview

Package

Class

Tree

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
@interface JEPWorkout : MTLModel

@property (nonatomic, copy) NSString *identifier;

@property (nonatomic, strong) NSDate *date;

@property (nonatomic, copy) NSString *originalText;
@property (nonatomic, copy) NSArray *exercises;

- (NSString *)title;

@end


text:
This is the master index of packages in [Roost](https://github.com/dirk/Roost).
Package definition Roostfiles can be submitted here; they are then compiled
down into efficient binaries to be downloaded by users.

## License

Licensed under the MIT license. See [LICENSE](LICENSE) for details.


text:
'use strict'

angular.module('app.nav')
    .directive('navToggle', navToggle)

function navToggle ($timeout, $mdUtil, NavService) {
  return {
    restrict: 'E',
    scope: {
      section: '='
    },
    template: require('./nav-toggle.html'),
    link: navToggleLink
  }
  function navToggleLink (scope, element) {
    scope.getTargetHeight = getTargetHeight
    scope.isOpen = function () {
      return NavService.isSectionOpen(scope.section)
    }
    scope.toggle = function () {
      NavService.toggleOpenSection(scope.section)
    }
    scope.menu = element.find('ul')
    $mdUtil.nextTick(function () {
      scope.$watch(
              function () {
                return scope.isOpen()
              },
              function (open) {
                var targetHeight = open ? scope.getTargetHeight(scope.menu) : 0
                $timeout(function () {
                  scope.menu.css({height: targetHeight})
                })
              }
            )
    })
  }
  function getTargetHeight (list) {
    var clientHeight = list.prop('childElementCount') * 40
    return clientHeight + 'px'
  }
}


text:
require 'concurrent'

require 'rackstash/buffer_stack'
require 'rackstash/formatter'
require 'rackstash/message'
require 'rackstash/flows'

module Rackstash
  # The Logger is the main entry point for Rackstash. It provides an interface
  # very similar to the Logger class in Ruby's Standard Library but extends it
  # with facilities for structured logging.
  class Logger
    # Logging formatter, a `Proc`-like object which take four arguments and
    # returns the formatted message. The arguments are:
    #
    # * `severity` - The severity of the log message as a String.
    # * `time` - A Time instance representing when the message was logged.
    # * `progname` - The progname passed to the logger method (or the default
    #   {#progname}).
    # * `msg` - The `Object` the user passed to the log message; not necessarily
    #   a String.
    #
    # The formatter should return a String. When no formatter is set, an
    # instance of {Formatter} is used.
    #
    # @return [#call] the log formatter for each individual buffered line
    attr_accessor :formatter

    # @return [Integer] a numeric log level. Normally you'd use one of the
    #   {SEVERITIES} constants, i.e., an integer between 0 and 5. We will only
    #   log messages with a severity above the configured level.
    attr_reader :level

    # @return [String] the logger's progname, used as the default for log
    #   messages if none is passed to {#add} and passed to the {#formatter}.
    #   By default we use {PROGNAME}.
    attr_accessor :progname

    # @return [Flows] the list of defined {Flow} objects which are responsible
    #   for transforming, encoding, and persisting the log events.
    attr_reader :flows

    # Create a new Logger instance.
    #
    # We mostly follow the common interface of Ruby's core Logger class with the
    # exception that you can give one or more flows to write logs to. Each
    # {Flow} is responsible to write a log event (e.g. to a file, STDOUT, a TCP
    # socket, ...). Each log event is written to all defined {#flows}.
    #
    # When giving the flows here, you can given them in one of varous
    # representations, all of which we will transform into an actual {Flow}:
    #
    # * A {Rackstash::Flow} object. For the most control over the flow, you can
    #   create the {Flow} object on your own and pass it here
    # * A {Rackstash::Adapter::Adapter}. When passing an adapter, we will
    #   create a new {Flow} from this adapter, using its default encoder and
    #   without any defined filters.
    # * An log device from which we can create an adapter. In this case, we
    #   first attempt to build an adapter from it using {Rackstash::Adapter.[]}.
    #   After that, we use it to create a {Flow} as above.
    #
    # When passing a block to this initializer, we will yield the last created
    # flow object to it. If you pass multiple log devices / adapters / flows,
    # only the last one will be yielded. If the block doesn't expect an argument,
    # we run the block in the instance scope of the flow.
    #
    # The following three example to create a custom Logger are thus equivalent:
    #
    #     logger = Rackstash::Logger.new(STDOUT) do
    #       encoder Rackstash::Encoder::Message.new
    #     end
    #
    #     logger = Rackstash::Logger.new(Rackstash::Adapter::IO.new(STDOUT)) do
    #       encoder Rackstash::Encoder::Message.new
    #     end
    #
    #     adapter = Rackstash::Adapter::IO.new(STDOUT)
    #     flow = Rackstash::Flows.new(adapter) do
    #       encoder Rackstash::Encoder::Message.new
    #     end
    #     logger = Rackstash::Logger.new(flow)
    #
    # To create a simple Logger which logs to `STDOUT` using the default JSON
    # format, you can just use
    #
    #     logger = Rackstash::Logger.new(STDOUT)
    #
    # @param flows [Array<Flow, Object>, Flow, Adapter::Adapter, Object]
    #   an array of {Flow}s or a single {Flow}, respectivly object which can be
    #   used as a {Flow}'s adapter. See {Flow#initialize}.
    # @param level [Integer] a numeric log level. Normally you'd use one of the
    #   {SEVERITIES} constants, i.e., an integer between 0 and 5. We will only
    #   log messages with a severity above the configured level.
    # @param progname [String] the logger's progname, used as the default for
    #   log messages if none is passed to {#add} and passed to the {#formatter}.
    #   By default we use {PROGNAME}.
    # @param formatter [#call] the log formatter for each individual buffered
    #   line. See {#formatter} for details.
    # @yieldparam flow [Rackstash::Flow] if the given block accepts an argument,
    #   we yield the last {Flow} as a parameter. Without an expected argument,
    #   the block is directly executed in the context of the last {Flow}.
    def initialize(*flows, level: DEBUG, progname: PROGNAME, formatter: Formatter.new, &block)
      @buffer_stack = Concurrent::ThreadLocalVar.new

      @flows = Rackstash::Flows.new(*flows)
      self.level = level
      self.progname = progname
      self.formatter = formatter

      if block_given? && (flow = @flows.last)
        if block.arity == 0
          flow.instance_eval(&block)
        else
          yield flow
        end
      end
    end

    # Add a message to the current {Buffer} without any further formatting. If
    # the current buffer is bufering, the message will just be added. Else,
    # it will be flushed to the configured {#flows} directly.
    #
    # @param msg [Object]
    # @return [String] the passed `msg`
    def <<(msg)
      buffer.add_message Message.new(
        msg,
        time: Time.now.utc.freeze,
        progname: @progname,
        severity: UNKNOWN
      )
      msg
    end

    # Retrieve a stored value from a given `key` in the current Buffer's fields.
    # This is strictly equivalent to calling `logger.fields[key]`.
    #
    # @param (see Fields::Hash#[])
    # @return (see Fields::Hash#[])
    def [](key)
      buffer.fields[key]
    end

    # Set the value of a key in the current Buffer's fields to the supplied
    # value. You can set nested hashes and arrays here. The hash keys will be
    # normalized as strings.
    # This is strictly equivalent to calling `logger.fields[key] = value`.
    #
    # @param (see Fields::Hash#[]=)
    # @raise [ArgumentError] if you attempt to set one of the forbidden fields,
    #   namely any of {Buffer::FORBIDDEN_FIELDS}
    # @return (see Fields::Hash#[]=)
    def []=(key, value)
      buffer.fields[key] = value
    end

    # (see Flows#close)
    def close
      @flows.close
    end

    # Set the base log level as either one of the {SEVERITIES} or a
    # String/Symbol describing the level. When logging a message, it will only
    # be added if its log level is at or above the base level defined here
    #
    # @param severity [Integer, String, Symbol] one of the {SEVERITIES} or its
    #   name
    def level=(severity)
      @level = Rackstash.severity(severity)
    end

    # (see Buffer#fields)
    def fields
      buffer.fields
    end

    # (see Flows#reopen)
    def reopen
      @flows.reopen
    end

    # (see Buffer#tag)
    def tag(*new_tags)
      buffer.tag(*new_tags)
    end

    # (see Buffer#tags)
    def tags
      buffer.tags
    end

    # (see Buffer#timestamp)
    def timestamp(time = nil)
      buffer.timestamp(time)
    end

    # Log a message at the DEBUG log level.
    #
    # @param msg (see #add)
    # @yield (see #add)
    # @return (see #add)
    def debug(msg = nil)
      if block_given?
        add(DEBUG, msg) { yield }
      else
        add(DEBUG, msg)
      end
    end

    # @return [Boolean] `true` if messages on the DEBUG level will be logged
    def debug?
      @level <= DEBUG
    end

    # Log a message at the INFO log level.
    #
    # @param msg (see #add)
    # @yield (see #add)
    # @return (see #add)
    def info(msg = nil)
      if block_given?
        add(INFO, msg) { yield }
      else
        add(INFO, msg)
      end
    end

    # @return [Boolean] `true` if messages on the INFO level will be logged
    def info?
      @level <= INFO
    end

    # Log a message at the WARN log level.
    #
    # @param msg (see #add)
    # @yield (see #add)
    # @return (see #add)
    def warn(msg = nil)
      if block_given?
        add(WARN, msg) { yield }
      else
        add(WARN, msg)
      end
    end

    # @return [Boolean] `true` if messages on the WARN level will be logged
    def warn?
      @level <= WARN
    end

    # Log a message at the ERROR log level.
    #
    # @param msg (see #add)
    # @yield (see #add)
    # @return (see #add)
    def error(msg = nil)
      if block_given?
        add(ERROR, msg) { yield }
      else
        add(ERROR, msg)
      end
    end

    # @return [Boolean] `true` if messages on the ERROR level will be logged
    def error?
      @level <= ERROR
    end

    # Log a message at the FATAL log level.
    #
    # @param msg (see #add)
    # @yield (see #add)
    # @return (see #add)
    def fatal(msg = nil)
      if block_given?
        add(FATAL, msg) { yield }
      else
        add(FATAL, msg)
      end
    end

    # @return [Boolean] `true` if messages on the FATAL level will be logged
    def fatal?
      @level <= FATAL
    end

    # Log a message at the UNKNOWN log level.
    #
    # @param msg (see #add)
    # @yield (see #add)
    # @return (see #add)
    def unknown(msg = nil)
      if block_given?
        add(UNKNOWN, msg) { yield }
      else
        add(UNKNOWN, msg)
      end
    end

    # @return [Boolean] `true` if messages on the UNKNOWN level will be logged
    def unknown?
      @level <= UNKNOWN
    end

    # Log a message if the given severity is high enough. This is the generic
    # logging method. Users will be more inclined to use {#debug}, {#info},
    # {#warn}, {#error}, or {#fatal}.
    #
    # The message will be added to the current log buffer. If we are currently
    # buffering (i.e. if we are inside a {#capture} block), the message is
    # merely added but not flushed to the underlying logger. Else, the message
    # along with any previously defined fields and tags will be flushed to the
    # base logger immediately.
    #
    # @param severity [Integer] The log severity. One of the {SEVERITIES}
    #   constants.
    # @param msg [#to_s, ::Hash, Exception, nil] The log message. If unset, we
    #   try, to use the return value of the optional block. If we get a `String`
    #   or `Exception`, we log a new {Message}. If it's a Hash, we deep_merge it
    #   into the current buffer's fields instead.
    # @param progname [String, nil] The program name. Can be omitted. It's
    #   treated as a message if no `msg` and `block` are given.
    # @yield If `message` is `nil`, we yield to the block to get a message
    #   string.
    # @return [Message, ::Hash, nil] The merged Hash, or the resolved {Message}
    #   or `nil` if nothing was logged
    def add(severity, msg = nil, progname = nil)
      severity = severity ? Integer(severity) : UNKNOWN
      return if @level > severity

      progname ||= @progname
      if msg.nil?
        if block_given?
          msg = yield
        else
          msg = progname
          progname = @progname
        end
      end

      case msg
      when Hash, Rackstash::Fields::Hash
        buffer.add_fields(msg)
      else
        time = Time.now.utc.freeze
        buffer.add_message Message.new(
          formatter.call(Rackstash.severity_label(severity), time, progname, msg),
          time: time,
          progname: progname,
          severity: severity
        )
      end
    end
    alias log add

    # (see Buffer#add_exception)
    def add_exception(exception, force: true)
      buffer.add_exception(exception, force: force)
    end
    alias add_error add_exception

    # Create a new {Buffer} and put it on the {BufferStack} for the current
    # Thread. Until it is poped again with {#pop_buffer}, all newly logged
    # messages and any access to fields or tags will be sent to this new Buffer.
    # Previous Buffers will only be visible after it was poped. You should make
    # sure that the Buffer is only ever used by the calling Thread to retain the
    # thread-safety guarantees of Rackstash.
    #
    # Most of the time, you should use {#capture} instead to ensure that the
    # Buffer is reliably removed again when the execution leaves the block.
    # The only sensible use of the manual buffer management is when you need
    # to flush the Buffer outside of its active scope after it was poped.
    #
    # When using this method, it is crucial that you manually pop and flush the
    # buffer in all cases. This can look like this:
    #
    #     logger.push_buffer(buffering: true)
    #     begin
    #       logger.fields['key'] = 'value'
    #       logger.info 'performing some work...'
    #     ensure
    #       buffer = logger.pop_buffer
    #       buffer.flush if buffer
    #     end
    #
    # By using the `begin ... ensure` block, you can enforce that the buffer is
    # actually poped and flushed after the execution leaves your environment,
    # even if an Exception is raised. If you omit to pop the Buffer from the
    # stack, weird things can happen and your logs will probably end up not
    # being consistent or not even flushed at all.
    #
    # @see #pop_buffer
    #
    # @param buffer_args [Hash<Symbol => Object>] optional arguments for the new
    #   {Buffer}. See {Buffer#initialize} for allowed values.
    # @return [Buffer] the newly pushed {Buffer} instance
    def push_buffer(**buffer_args)
      buffer_stack.push(**buffer_args)
    end

    # Remove a previously pushed {Buffer} from the {BufferStack} for the current
    # Thread.
    #
    # You should only call this method after having called {#push_buffer} before
    # in the very same Thread and only exactly as many times as you have called
    # {#push_buffer} in that Thread. If you call this method too many times or
    # without first calling {#push_buffer}, it will destroy the consistency of
    # BufferStack causing undefined (i.e. weird) behavior.
    #
    # Since the Buffer is not flushed before returning, it is possible to still
    # modify the buffer before eventually flushing it on your own.
    #
    # Should it happen that there is no Buffer on the {BufferStack} (which can
    # only happen if the code execution was non-linear and stepped outside the
    # block scope), we return `nil` and not change the BufferStack.
    #
    # @note In contrast to {#capture}, the poped Buffer is not flushed
    #   automatically. You *MUST* call `buffer.flush` yourself to write the
    #   buffered log data to the log adapter(s).
    # @see #push_buffer
    #
    # @return [Buffer, nil] the removed {Buffer} from the current Thread's
    #   {BufferStack} or `nil` if no {Buffer} could be found on the stack.
    def pop_buffer
      buffer_stack.pop
    end

    # Capture all messages and fields logged for the duration of the provided
    # block in the current thread.
    #
    # Create a new {Buffer} and put in on the {BufferStack} for the current
    # thread. For the duration of the block, all new logged messages and any
    # access to fields and tags will be sent to this new buffer. Previous
    # buffers created in the same thread will only be visible after the
    # execution left the block.
    #
    # Note that the created {Buffer} is only valid for the current thread. In
    # other threads, it not visible and will thus not be used.
    #
    # @param buffer_args [Hash<Symbol => Object>] optional arguments for the new
    #   {Buffer}. See {Buffer#initialize} for allowed values.
    # @yield During the duration of the block, all logged messages, fields and
    #   tags are set on the new buffer. After the block returns, the {Buffer} is
    #   removed from the {BufferStack} again and is always flushed
    #   automatically.
    # @return [Object] the return value of the block
    def capture(**buffer_args)
      raise ArgumentError, 'block required' unless block_given?

      buffer_stack.push(**buffer_args)
      begin
        yield
      ensure
        buffer_stack.flush_and_pop
      end
    end

    # TODO: This alias should be deprecated
    alias with_buffer capture

    private

    def buffer_stack
      @buffer_stack.value ||= BufferStack.new(@flows)
    end

    def buffer
      buffer_stack.current
    end
  end
end


text:
layout: update
date: 2015-05-12
title: AppVeyor update on May 12, 2015
---

AppVeyor 2.6.3

## What's new

* [#266](https://github.com/appveyor/ci/issues/266) Fixed: Display friendly message on artifact upload error.
* [#263](https://github.com/appveyor/ci/issues/263) Fixed: Assembly patching is not picking up a new build version set by Update-AppveyorBuild.

## Build worker updates

* Azure SDK 2.6 installed to `Visual Studio 2015 RC` image.
* AWS CLI 1.7.25 installed to all build worker images.
* AWS SDK updated to 3.7.606.0 on all images.
* io.js 2.0.0 and 2.0.1 added to all images. Use `Install-Product node ''` to switch to the latest 2.x io.js version.
* [Windows Management Framework 5.0 Preview April 2015](https://www.microsoft.com/en-us/download/details.aspx?id=46889) installed to `unstable` image.

## Previous worker images

There are build worker images available from previous deployment. You can use them in case of any issues with the current images:

- `Previous Windows Server 2012 R2`
- `Previous Unstable`
- `Previous Visual Studio 2014 CTP4`
- `Previous Visual Studio 2015 CTP`
- `Previous Visual Studio 2015 CTP 6`
- `Previous Visual Studio 2015 Preview`
- `Previous MinGW`

You can select build worker image in OS dropdown on Environment tab of project settings or if you use `appveyor.yml`:

    os: Previous Windows Server 2012 R2

> **Note to "Pro" customers:** Whenever custom build worker image is chosen the build will run on Azure, so there is about 3-4 minutes delay before build starts to provision build worker virtual machine.


text:
package com.sun.jini.test.impl.norm;

import java.util.logging.Level;

// Test harness specific classes
import com.sun.jini.qa.harness.TestException;
import com.sun.jini.qa.harness.QAConfig;

import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.List;
import java.util.Iterator;

import net.jini.core.lease.Lease;

import net.jini.lease.LeaseRenewalService;
import net.jini.lease.LeaseRenewalSet;

import com.sun.jini.test.share.TestBase;

/**
 * Test creates a number leases, places it in a lease renewal set, uses
 * getLeases to ensure that they are all still there, removes one, makes
 * sure that the other ones are still in the set and the removed one is not.
 * Finally, it lets the membership expiration elapse on one of the leases
 * still in the set and then calls getLeases again to ensure that all the other
 * leases are still present.
 */
public class GetLeasesTest extends TestBase {

    /** Membership duration for short lease */
    private long membershipDuration;

    /** Should we try shuting down the service under test? */
    private boolean tryShutdown;

    /** The set of leases we think are in the renewal set */
    final private Set leases = new HashSet();

    public void setup(QAConfig sysConfig) throws Exception {
	super.setup(sysConfig);
	this.parse();
    }

    /**
     * com.sun.jini.test.impl.norm.membership_duration (long):
     *     number of milliseconds the short lease should be in the set
     * <p>
     * com.sun.jini.test.impl.norm.tryShutdown (boolean):
     *     if used the test will kill the VM the service
     *     is running in after adding the client lease to the set and again
     *     after removing the lease from the set.
     */
    protected void parse() throws Exception {
	super.parse();
	membershipDuration = getConfig().getLongConfigVal(
            "com.sun.jini.test.impl.norm.membership_duration", 60 * 1000);
	tryShutdown = getConfig().getBooleanConfigVal(
            "com.sun.jini.test.impl.norm.tryShutdown", false);
    }

    private void check(List fromRenewalSet,String msg) throws TestException {
	if (!fromRenewalSet.containsAll(leases) ||
	    !leases.containsAll(fromRenewalSet))
	{
	    logger.log(Level.INFO, "Renewal set does not have what it should have");
	    logger.log(Level.INFO, "What it should have");
	    for (final Iterator i = leases.iterator(); i.hasNext(); ) {
		logger.log(Level.INFO, "     " + i.next());
	    }

	    logger.log(Level.INFO, "What it does have");
	    for (final Iterator i = fromRenewalSet.iterator(); i.hasNext(); ) {
		logger.log(Level.INFO, "     " + i.next());
	    }

	    throw new TestException(msg);
	}
    }

    public void run() throws Exception {
	specifyServices(new Class[]{LeaseRenewalService.class});
	LeaseRenewalService lrs = (LeaseRenewalService)services[0];

	// Create the lease
	// The leases that will remain in the set the whole time
	final long now = System.currentTimeMillis();
	leases.add(LocalLease.getLocalLease(
            (4 * membershipDuration) + now, 60 * 1000, 0, 0));
	leases.add(LocalLease.getLocalLease(
            (4 * membershipDuration) + now, 60 * 1000, 1, 1));

	// The lease we will remove
	final Lease toRemove = LocalLease.getLocalLease(
            (4 * membershipDuration) + now, 60 * 1000, 2, 2);
	leases.add(toRemove);

	// The lease who's membership expiration we will let expire
	final Lease toExpire = LocalLease.getLocalLease(
            (4 * membershipDuration) + now, 60 * 1000, 3, 3);
	leases.add(toExpire);

	LeaseRenewalSet set =
	    lrs.createLeaseRenewalSet(4 * membershipDuration);
	set = prepareSet(set);
	addLease(prepareNormLease(set.getRenewalSetLease()), false);

	logger.log(Level.INFO, "Adding leases to renewal set");

	for (final Iterator i=leases.iterator(); i.hasNext(); ) {
	    final Lease toAdd = (Lease)i.next();
	    if (toAdd.equals(toExpire)) {
		set.renewFor(toAdd, membershipDuration);
	    } else {
		set.renewFor(toAdd, Lease.FOREVER);
	    }
	}

	final long start = System.currentTimeMillis();

	if (tryShutdown) {
            logger.log(Level.INFO, "Shuting down at: " + start + " milliseconds");
	    shutdown(0);
        }

	logger.log(Level.INFO, "Calling getLeases(), looking for all 4 leases");
	check(Arrays.asList(set.getLeases()),
	      "Set is missing or holding leases it should not");

	logger.log(Level.INFO, "Removing 1 lease from the set");
	final Lease removed = set.remove(toRemove);
	if (removed == null || !removed.equals(toRemove)) {
	    throw new TestException("Could not remove lease");
        }
	leases.remove(toRemove);

	if (tryShutdown) {
            logger.log(Level.INFO, "Shuting down at: "
                + System.currentTimeMillis() + " milliseconds");
	    shutdown(0);
        }

	logger.log(Level.INFO, "Calling getLeases(), looking for 3 leases");
	check(Arrays.asList(set.getLeases()),"Set is missing or "
            + "holding leases it should not after removing one");

	// Wait for expiration to be reached on toExpire
	final long sleepTime =
	    (membershipDuration - (System.currentTimeMillis() - start))
            + 10000;
	if (sleepTime > 0) {
	    logger.log(Level.INFO, "Sleeping for: " + sleepTime + " milliseconds");
	    Thread.sleep(sleepTime);
	}
	leases.remove(toExpire);

	if (tryShutdown) {
            logger.log(Level.INFO, "Shuting down at: "
                + System.currentTimeMillis() + " milliseconds");
	    shutdown(0);
        }

	logger.log(Level.INFO, "Calling getLeases(), looking for 2 leases");
	check(Arrays.asList(set.getLeases()),
	    "Set is missing or holding leases it should not after expire");
    }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Options Page</title>

			File Size Limit:
			<input id="fileSizeLimit" style="width: 400px; margin-top: 5px;" type="text">

			Lower limit of the file size in bytes to trigger the download

			Include File Type:
			<textarea id="typeFilterA" placeholder="application/pdf" rows="2" cols="50"></textarea>

			Regular Expressions: Matches MIME type

			Exclude File Type:
			<textarea id="typeFilterB" rows="2" cols="50"></textarea>

			Regular Expressions: Matches MIME type

			Include URL:
			<textarea id="urlFilterA" placeholder="https://addons\.mozilla\.org/firefox/addon/aria2-integration/" rows="2" cols="50"></textarea>

			Regular Expressions: Matches URL

			Exclude URL:
			<textarea id="urlFilterB" rows="2" cols="50"></textarea>

			Regular Expressions: Matches URL

			<button data-message="OP_save" id="save">Save</button>


text:
printServer
===========

print server


text:
import { l8 as s, t, bL as t$1 } from './_virtual_index-1ea2035a.js';
import { e } from './centroid-205dc6cf.js';

const i={getObjectId:t=>t.objectId,getAttributes:t=>t.attributes,getAttribute:(t,e)=>t.attributes[e],cloneWithGeometry:(t,e)=>new s(e,t.attributes,null,t.objectId),getGeometry:t=>t.geometry,getCentroid:(r,i)=>(t(r.centroid)&&(r.centroid=e(new t$1,r.geometry,i.hasZ,i.hasM)),r.centroid)};

export { i };


text:
using Messaging.Interfaces.Common;

namespace Messaging.Interfaces.Notifications
{
    public interface INotificationManager
    {
        void Notify(IMessagingContent messageContent);
    }
}


text:
import xxxx.ddd;
import com.XXX;
import yyy.com.*;
import static zzz.yyy.com.AAA.*;
import static zzz.yyy.com.BBB;

class Foo {
  {

  }
}


text: require_relative 'multidb'


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Voy. Uranie 457. 1829; t. 77. 1828

#### Original name
null

### Remarks
null


text:
module Propellor.Property.Postfix where

import Propellor
import qualified Propellor.Property.Apt as Apt

installed :: Property
installed = Apt.serviceInstalledRunning "postfix"

-- | Configures postfix as a satellite system, which
-- relats all mail through a relay host, which defaults to smtp.domain.
--
-- The smarthost may refuse to relay mail on to other domains, without
-- futher coniguration/keys. But this should be enough to get cron job
-- mail flowing to a place where it will be seen.
satellite :: Property
satellite = setup `requires` installed
  where
	setup = trivial $ property "postfix satellite system" $ do
		hn <- asks hostName
		ensureProperty $ Apt.reConfigure "postfix"
			[ ("postfix/main_mailer_type", "select", "Satellite system")
			, ("postfix/root_address", "string", "root")
			, ("postfix/destinations", "string", " ")
			, ("postfix/mailname", "string", hn)
			]


text:
.class Landroid/opengl/GLSurfaceView$DefaultWindowSurfaceFactory;
.super Ljava/lang/Object;
.source "GLSurfaceView.java"

# interfaces
.implements Landroid/opengl/GLSurfaceView$EGLWindowSurfaceFactory;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/opengl/GLSurfaceView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "DefaultWindowSurfaceFactory"
.end annotation

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 797
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/opengl/GLSurfaceView$1;)V
    .locals 0
    .param p1, "x0"    # Landroid/opengl/GLSurfaceView$1;

    .prologue
    .line 797
    invoke-direct {p0}, Landroid/opengl/GLSurfaceView$DefaultWindowSurfaceFactory;-><init>()V

    return-void
.end method

# virtual methods
.method public createWindowSurface(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLConfig;Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLSurface;
    .locals 4
    .param p1, "egl"    # Ljavax/microedition/khronos/egl/EGL10;
    .param p2, "display"    # Ljavax/microedition/khronos/egl/EGLDisplay;
    .param p3, "config"    # Ljavax/microedition/khronos/egl/EGLConfig;
    .param p4, "nativeWindow"    # Ljava/lang/Object;

    .prologue
    .line 801
    const/4 v1, 0x0

    .line 803
    .local v1, "result":Ljavax/microedition/khronos/egl/EGLSurface;
    const/4 v2, 0x0

    :try_start_0
    invoke-interface {p1, p2, p3, p4, v2}, Ljavax/microedition/khronos/egl/EGL10;->eglCreateWindowSurface(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLConfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;
    :try_end_0
    .catch Ljava/lang/IllegalArgumentException; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v1

    .line 813
    :goto_0
    return-object v1

    .line 804
    :catch_0
    move-exception v0

    .line 811
    .local v0, "e":Ljava/lang/IllegalArgumentException;
    const-string v2, "GLSurfaceView"

    const-string v3, "eglCreateWindowSurface"

    invoke-static {v2, v3, v0}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0
.end method

.method public destroySurface(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSurface;)V
    .locals 0
    .param p1, "egl"    # Ljavax/microedition/khronos/egl/EGL10;
    .param p2, "display"    # Ljavax/microedition/khronos/egl/EGLDisplay;
    .param p3, "surface"    # Ljavax/microedition/khronos/egl/EGLSurface;

    .prologue
    .line 818
    invoke-interface {p1, p2, p3}, Ljavax/microedition/khronos/egl/EGL10;->eglDestroySurface(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSurface;)Z

    .line 819
    return-void
.end method


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Yort.Ntp
{
	/// <summary>
	/// Event arguments for the <see cref="NtpClient.ErrorOccurred"/> event, containing details of the error that occurred.
	/// </summary>
	public class NtpNetworkErrorEventArgs : EventArgs
	{
		private readonly Exception _Exception;

		/// <summary>
		/// Full constructor.
		/// </summary>
		/// <param name="exception">A <see cref="Exception"/> containing details of the network or socket error that occurred.</param>
		public NtpNetworkErrorEventArgs(Exception exception)
		{
			_Exception = exception;
		}

		/// <summary>
		/// Returns a <see cref="Exception"/> containing details of the network or socket error that occurred.
		/// </summary>
		public Exception Exception
		{
			get
			{
				return _Exception;
			}
		}
	}
}


text:
class ConnectionsController < ApplicationController
  before_action :ensure_feature_enabled_for_district!

  def show_json
    params.require(:school_id)
    params.permit(:time_now)
    time_now = time_now_or_param(params[:time_now])
    school_id = (School.find_by_slug(params[:school_id]) || School.find_by_id(params[:school_id])).id

    students_with_2020_survey_data_json = students_with_2020_survey_data(current_educator, school_id, time_now)
    render json: {
      students_with_2020_survey_data: students_with_2020_survey_data_json
    }
  end

  private
  # Use time from value or fall back to Time.now
  def time_now_or_param(params_time_now)
    if params_time_now.present?
      Time.at(params_time_now.to_i)
    else
      Time.now
    end
  end

  def ensure_feature_enabled_for_district!
    raise Exceptions::EducatorNotAuthorized unless PerDistrict.new.enabled_high_school_levels?
  end

  def students_with_2020_survey_data(educator, school_id, time_now)
    # query for students, enforce authorization
    students = Authorizer.new(educator).authorized do
      Student.active
        .where(school_id: school_id)
    end
    unsafe_students_with_2020_survey_data_json(students, time_now)
  end

  # At present, similar to the data needed for the levels page, without the level
  # calculation itself. Inlcudes specific answer to 2020 survey
  # These queries have no auth checks, so authorization must be established when
  # getting the students list
  def unsafe_students_with_2020_survey_data_json(students, time_now)
    cutoff_time = time_now - 45.days

    # Only include relevant survey answer
    survey_responses = StudentVoiceCompleted2020Survey
      .where('created_at >= ?', cutoff_time)
      .select(:id, :student_id, :shs_adult, :created_at)
      .group_by(&:student_id)

    student_ids = survey_responses.keys & students.map(&:id) #Only authorized students with completed surveys

    # query for absences and discipline events in batch
    absence_counts_by_student_id = Absence
      .where(student_id: student_ids)
      .where('occurred_at >= ?', cutoff_time)
      .group(:student_id)
      .count
    discipline_incident_counts_by_student_id = DisciplineIncident
      .where(student_id: student_ids)
      .where('occurred_at >= ?', cutoff_time)
      .group(:student_id)
      .count

    # query for sections within the current term
    section_ids = Section
      .where(term_local_id: SchoolYear.current_term_local_ids(time_now))
      .pluck(:id)
    student_section_assignments_by_student_id = StudentSectionAssignment
      .includes(section: :course)
      .where(student_id: student_ids)
      .where(section_id: section_ids)
      .group_by(&:student_id)

    # Optimized batch query for latest event_notes
    notes_by_student_id = most_recent_event_notes_by_student_id(student_ids, cutoff_time, notes_query_map)

    students_with_surveys = Student.where(id: student_ids)

    # Serialize student fields
    students_json = students_with_surveys.as_json(only: [
      :id,
      :first_name,
      :last_name,
      :grade,
      :limited_english_proficiency,
      :house,
      :counselor,
      :sped_placement,
      :program_assigned
    ])

    # Merge it all back together
    students_with_2020_survey_data = students_json.map do |student_json|
      student_id = student_json['id']
      student_section_assignments_right_now = student_section_assignments_by_student_id.fetch(student_id, [])
      surveys = survey_responses.fetch(student_id, "") # Should always find this
      student_json.merge({
        survey_response: surveys.max_by {|survey| survey[:created_at]},
        absences_count_in_period: absence_counts_by_student_id.fetch(student_id, 0),
        discipline_incident_count_in_period: discipline_incident_counts_by_student_id.fetch(student_id, 0),
        section_assignments_right_now: student_section_assignments_by_student_id.fetch(student_id, []),
        notes: notes_by_student_id[student_id],
        student_section_assignments_right_now: student_section_assignments_right_now.as_json({
          only: [:id, :grade_letter, :grade_numeric],
          include: {
            section: {
              only: [:id, :section_number],
              methods: [:course_description]
            }
          }
        })
      })
    end
    students_with_2020_survey_data.as_json
  end

  def notes_query_map
    sst_event_note_type_ids = [300]
    experience_event_note_type_ids = [305, 306, 307]
    counselor_event_note_type_ids = [308]
    other_event_note_type_ids = EventNoteType.all.pluck(:id) - sst_event_note_type_ids - experience_event_note_type_ids
    {
      last_sst_note: sst_event_note_type_ids,
      last_experience_note: experience_event_note_type_ids,
      last_counselor_note: counselor_event_note_type_ids,
      last_other_note: other_event_note_type_ids
    }
  end

  # query_map is {:result_key => [event_note_type_id]}
  def most_recent_event_notes_by_student_id(student_ids, cutoff_time, query_map)
    notes_by_student_id = {}

    # query across all students and note types
    all_event_note_type_ids = query_map.values.flatten.uniq
    partial_event_notes = EventNote
      .where(student_id: student_ids)
      .where('recorded_at >= ?', cutoff_time)
      .where(event_note_type_id: all_event_note_type_ids)
      .where(is_restricted: false)
      .select('student_id, event_note_type_id, max(recorded_at) as most_recent_recorded_at')
      .group(:student_id, :event_note_type_id)

    # merge them together and serialize
    sorted_partial_event_notes = partial_event_notes.sort_by(&:most_recent_recorded_at).reverse
    student_ids.each do |student_id|
      notes_for_student = {}
      query_map.each do |key, event_note_type_ids|
        # find the most recent note for this kind, we can use find because the list is sorted
        matching_partial_note = sorted_partial_event_notes.find do |partial_event_note|
          matches_student_id = partial_event_note.student_id == student_id
          matches_event_note_type_id = event_note_type_ids.include?(partial_event_note.event_note_type_id)
          matches_student_id && matches_event_note_type_id
        end

        # serialize notes for a student
        if matching_partial_note.nil?
          notes_for_student[key] = {}
        else
          notes_for_student[key] = {
            event_note_type_id: matching_partial_note.event_note_type_id,
            recorded_at: matching_partial_note.most_recent_recorded_at
          }
        end
      end
      notes_by_student_id[student_id] = notes_for_student
    end
    notes_by_student_id
  end

end


text:
package marubinotto.piggydb.model.fragments;

import static marubinotto.piggydb.model.Assert.assertClassificationEquals;
import static marubinotto.util.CollectionUtils.list;
import static marubinotto.util.CollectionUtils.map;

import java.util.HashMap;

import marubinotto.piggydb.model.Fragment;
import marubinotto.piggydb.model.FragmentRepository;
import marubinotto.piggydb.model.Tag;
import marubinotto.piggydb.model.TagRepository;

import org.junit.Before;
import org.junit.Test;

public class RefreshClassificationsTest extends FragmentRepositoryTestBase {

	private Fragment fragment1;
	private Fragment fragment2;

	public RefreshClassificationsTest(RepositoryFactory<FragmentRepository> factory) {
		super(factory);
	}

	@Before
	public void given() throws Exception {
		super.given();

		this.fragment1 = newFragmentWithTitleAndTags("Adaptive Design", "agile");
		this.object.register(this.fragment1);

		this.fragment2 = newFragmentWithTitleAndTags("The New Methodology", "agile");
		this.object.register(this.fragment2);
	}

	@Test
	public void tagAdded() throws Exception {
		// Given
		Fragment fragment = this.object.get(this.fragment1.getId());
		fragment.addTagByUser("software", this.object.getTagRepository(), getPlainUser());
		this.object.update(fragment);

		// When
		this.object.refreshClassifications(list(this.fragment1));

		// Then
		assertClassificationEquals(
			map("agile", null).map("software", null),
			this.fragment1.getClassification());
	}

	@Test
	public void grandparentTagAdded() throws Exception {
		// Given
		TagRepository tagRepository = this.object.getTagRepository();
		Tag tag = tagRepository.getByName("agile");
		tag.addTagByUser("methodology", tagRepository, getPlainUser());
		tagRepository.update(tag);

		// When
		this.object.refreshClassifications(list(this.fragment1));

		// Then
		assertClassificationEquals(
			map("agile", map("methodology", null)),
			this.fragment1.getClassification());
	}

	@Test
	public void grandparentTagAdded_refreshTwo() throws Exception {
		// Given
		TagRepository tagRepository = this.object.getTagRepository();
		Tag tag = tagRepository.getByName("agile");
		tag.addTagByUser("methodology", tagRepository, getPlainUser());
		tagRepository.update(tag);

		// When
		this.object.refreshClassifications(list(this.fragment1, this.fragment2));

		// Then
		assertClassificationEquals(
			map("agile", map("methodology", null)),
			this.fragment1.getClassification());
		assertClassificationEquals(
			map("agile", map("methodology", null)),
			this.fragment2.getClassification());
	}

	@Test
	@SuppressWarnings("rawtypes")
	public void tagRemoved() throws Exception {
		// Given
		Fragment fragment = this.object.get(this.fragment1.getId());
		fragment.removeTagByUser("agile", getPlainUser());
		this.object.update(fragment);

		// When
		this.object.refreshClassifications(list(this.fragment1));

		// Then
		assertClassificationEquals(
			new HashMap(),
			this.fragment1.getClassification());
	}

	@Test
	public void refreshTwoWithSameIds() throws Exception {
		// Given
		Fragment fragment = this.object.get(this.fragment1.getId());
		fragment.addTagByUser("software", this.object.getTagRepository(), getPlainUser());
		this.object.update(fragment);

		// When
		Fragment f1 = this.fragment1.copyForUpdate();
		Fragment f2 = this.fragment1.copyForUpdate();
		this.object.refreshClassifications(list(f1, f2));

		// Then
		assertClassificationEquals(
			map("agile", null).map("software", null), f1.getClassification());
		assertClassificationEquals(
			map("agile", null).map("software", null), f2.getClassification());
	}
}