text:
#include "rsync.h"

#define POOL_DEF_EXTENT	(32 * 1024)

struct alloc_pool
{
	size_t			size;		/* extent size		*/
	size_t			quantum;	/* allocation quantum	*/
	struct pool_extent	*extents;	/* top extent is "live" */
	void			(*bomb)();	/* function to call if
						 * malloc fails		*/
	int			flags;

	/* statistical data */
	unsigned long		e_created;	/* extents created	*/
	unsigned long		e_freed;	/* extents detroyed	*/
	int64			n_allocated;	/* calls to alloc	*/
	int64			n_freed;	/* calls to free	*/
	int64			b_allocated;	/* cum. bytes allocated	*/
	int64			b_freed;	/* cum. bytes freed	*/
};

struct pool_extent
{
	void			*start;		/* starting address	*/
	size_t			free;		/* free bytecount	*/
	size_t			bound;		/* bytes bound by padding,
						 * overhead and freed	*/
	struct pool_extent	*next;
};

struct align_test {
	void *foo;
	int64 bar;
};

#define MINALIGN	offsetof(struct align_test, bar)

/* Temporarily cast a void* var into a char* var when adding an offset (to
 * keep some compilers from complaining about the pointer arithmetic). */
#define PTR_ADD(b,o)	( (void*) ((char*)(b) + (o)) )

alloc_pool_t
pool_create(size_t size, size_t quantum, void (*bomb)(const char *), int flags)
{
	struct alloc_pool	*pool;

	if (!(pool = new(struct alloc_pool)))
		return pool;
	memset(pool, 0, sizeof (struct alloc_pool));

	pool->size = size	/* round extent size to min alignment reqs */
	    ? (size + MINALIGN - 1) & ~(MINALIGN - 1)
	    : POOL_DEF_EXTENT;
	if (flags & POOL_INTERN) {
		pool->size -= sizeof (struct pool_extent);
		flags |= POOL_APPEND;
	}
	pool->quantum = quantum ? quantum : MINALIGN;
	pool->bomb = bomb;
	pool->flags = flags;

	return pool;
}

void
pool_destroy(alloc_pool_t p)
{
	struct alloc_pool *pool = (struct alloc_pool *) p;
	struct pool_extent	*cur, *next;

	if (!pool)
		return;

	for (cur = pool->extents; cur; cur = next) {
		next = cur->next;
		free(cur->start);
		if (!(pool->flags & POOL_APPEND))
			free(cur);
	}
	free(pool);
}

void *
pool_alloc(alloc_pool_t p, size_t len, const char *bomb_msg)
{
	struct alloc_pool *pool = (struct alloc_pool *) p;
	if (!pool)
		return NULL;

	if (!len)
		len = pool->quantum;
	else if (pool->quantum > 1 && len % pool->quantum)
		len += pool->quantum - len % pool->quantum;

	if (len > pool->size)
		goto bomb_out;

	if (!pool->extents || len > pool->extents->free) {
		void	*start;
		size_t	free;
		size_t	bound;
		size_t	skew;
		size_t	asize;
		struct pool_extent *ext;

		free = pool->size;
		bound = 0;

		asize = pool->size;
		if (pool->flags & POOL_APPEND)
			asize += sizeof (struct pool_extent);

		if (!(start = new_array(char, asize)))
			goto bomb_out;

		if (pool->flags & POOL_CLEAR)
			memset(start, 0, free);

		if (pool->flags & POOL_APPEND)
			ext = PTR_ADD(start, free);
		else if (!(ext = new(struct pool_extent)))
			goto bomb_out;
		if (pool->flags & POOL_QALIGN && pool->quantum > 1
		    && (skew = (size_t)PTR_ADD(start, free) % pool->quantum)) {
			bound  += skew;
			free -= skew;
		}
		ext->start = start;
		ext->free = free;
		ext->bound = bound;
		ext->next = pool->extents;
		pool->extents = ext;

		pool->e_created++;
	}

	pool->n_allocated++;
	pool->b_allocated += len;

	pool->extents->free -= len;

	return PTR_ADD(pool->extents->start, pool->extents->free);

  bomb_out:
	if (pool->bomb)
		(*pool->bomb)(bomb_msg);
	return NULL;
}

/* This function allows you to declare memory in the pool that you are done
 * using.  If you free all the memory in a pool's extent, that extent will
 * be freed. */
void
pool_free(alloc_pool_t p, size_t len, void *addr)
{
	struct alloc_pool *pool = (struct alloc_pool *)p;
	struct pool_extent *cur, *prev;

	if (!pool)
		return;

	if (!len)
		len = pool->quantum;
	else if (pool->quantum > 1 && len % pool->quantum)
		len += pool->quantum - len % pool->quantum;

	pool->n_freed++;
	pool->b_freed += len;

	for (prev = NULL, cur = pool->extents; cur; prev = cur, cur = cur->next) {
		if (addr >= cur->start
		    && addr < PTR_ADD(cur->start, pool->size))
			break;
	}
	if (!cur)
		return;

	if (!prev) {
		/* The "live" extent is kept ready for more allocations. */
		if (cur->free + cur->bound + len >= pool->size) {
			size_t skew;

			if (pool->flags & POOL_CLEAR) {
				memset(PTR_ADD(cur->start, cur->free), 0,
				       pool->size - cur->free);
			}
			cur->free = pool->size;
			cur->bound = 0;
			if (pool->flags & POOL_QALIGN && pool->quantum > 1
			    && (skew = (size_t)PTR_ADD(cur->start, cur->free) % pool->quantum)) {
				cur->bound += skew;
				cur->free -= skew;
			}
		} else if (addr == PTR_ADD(cur->start, cur->free)) {
			if (pool->flags & POOL_CLEAR)
				memset(addr, 0, len);
			cur->free += len;
		} else
			cur->bound += len;
	} else {
		cur->bound += len;

		if (cur->free + cur->bound >= pool->size) {
			prev->next = cur->next;
			free(cur->start);
			if (!(pool->flags & POOL_APPEND))
				free(cur);
			pool->e_freed++;
		} else if (prev != pool->extents) {
			/* Move the extent to be the first non-live extent. */
			prev->next = cur->next;
			cur->next = pool->extents->next;
			pool->extents->next = cur;
		}
	}
}

/* This allows you to declare that the given address marks the edge of some
 * pool memory that is no longer needed.  Any extents that hold only data
 * older than the boundary address are freed.  NOTE: You MUST NOT USE BOTH
 * pool_free() and pool_free_old() on the same pool!! */
void
pool_free_old(alloc_pool_t p, void *addr)
{
	struct alloc_pool *pool = (struct alloc_pool *)p;
	struct pool_extent *cur, *prev, *next;

	if (!pool || !addr)
		return;

	for (prev = NULL, cur = pool->extents; cur; prev = cur, cur = cur->next) {
		if (addr >= cur->start
		    && addr < PTR_ADD(cur->start, pool->size))
			break;
	}
	if (!cur)
		return;

	if (addr == PTR_ADD(cur->start, cur->free)) {
		if (prev) {
			prev->next = NULL;
			next = cur;
		} else {
			size_t skew;

			/* The most recent live extent can just be reset. */
			if (pool->flags & POOL_CLEAR)
				memset(addr, 0, pool->size - cur->free);
			cur->free = pool->size;
			cur->bound = 0;
			if (pool->flags & POOL_QALIGN && pool->quantum > 1
			    && (skew = (size_t)PTR_ADD(cur->start, cur->free) % pool->quantum)) {
				cur->bound += skew;
				cur->free -= skew;
			}
			next = cur->next;
			cur->next = NULL;
		}
	} else {
		next = cur->next;
		cur->next = NULL;
	}

	while ((cur = next) != NULL) {
		next = cur->next;
		free(cur->start);
		if (!(pool->flags & POOL_APPEND))
			free(cur);
		pool->e_freed++;
	}
}

/* If the current extent doesn't have "len" free space in it, mark it as full
 * so that the next alloc will start a new extent.  If len is (size_t)-1, this
 * bump will always occur.  The function returns a boundary address that can
 * be used with pool_free_old(), or a NULL if no memory is allocated. */
void *
pool_boundary(alloc_pool_t p, size_t len)
{
	struct alloc_pool *pool = (struct alloc_pool *)p;
	struct pool_extent *cur;

	if (!pool || !pool->extents)
		return NULL;

	cur = pool->extents;

	if (cur->free < len) {
		cur->bound += cur->free;
		cur->free = 0;
	}

	return PTR_ADD(cur->start, cur->free);
}

#define FDPRINT(label, value) \
	do { \
		int len = snprintf(buf, sizeof buf, label, value); \
		if (write(fd, buf, len) != len) \
			ret = -1; \
	} while (0)

#define FDEXTSTAT(ext) \
	do { \
		int len = snprintf(buf, sizeof buf, "  %12ld  %5ld\n", \
				   (long)ext->free, (long)ext->bound); \
		if (write(fd, buf, len) != len) \
			ret = -1; \
	} while (0)

int
pool_stats(alloc_pool_t p, int fd, int summarize)
{
	struct alloc_pool *pool = (struct alloc_pool *) p;
	struct pool_extent	*cur;
	char buf[BUFSIZ];
	int ret = 0;

	if (!pool)
		return ret;

	FDPRINT("  Extent size:       %12ld\n",	(long)	pool->size);
	FDPRINT("  Alloc quantum:     %12ld\n",	(long)	pool->quantum);
	FDPRINT("  Extents created:   %12ld\n",		pool->e_created);
	FDPRINT("  Extents freed:     %12ld\n",		pool->e_freed);
	FDPRINT("  Alloc count:       %12.0f\n", (double) pool->n_allocated);
	FDPRINT("  Free Count:        %12.0f\n", (double) pool->n_freed);
	FDPRINT("  Bytes allocated:   %12.0f\n", (double) pool->b_allocated);
	FDPRINT("  Bytes freed:       %12.0f\n", (double) pool->b_freed);

	if (summarize)
		return ret;

	if (!pool->extents)
		return ret;

	if (write(fd, "\n", 1) != 1)
		ret = -1;

	for (cur = pool->extents; cur; cur = cur->next)
		FDEXTSTAT(cur);

	return ret;
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Class representing the Dailymotion player.
 */

import { NgZone, Injectable } from "@angular/core";
import { isUndefined } from "util";

import { PlayerConfig } from "./playerconfig.interface";
import { DailymotionApiService } from "./dailymotion-api.service";

@Injectable()
export class Dailymotionplayer {
    private defaultWidth: number = 320;
    private defaultHeight: number = 240;

    constructor( private zone: NgZone, private dailmyotionApiService: DailymotionApiService ) {}

    /**
     * (Wrapper function to) Load a new player using the dailymotion JS api
     */
    load( playerConfig: PlayerConfig ) {

        if( isUndefined(window.DM) ) {
            // Subscribe to the emitter who emits the window.DM OBJECT AS SOON AS IT IS LOADED/AVAILABLE.
            // "data = window.DM" => We actually don't need to use it here, just make sure the function is called AFTER
            // the OBJECT is available
            this.dailmyotionApiService.apiEmitter.subscribe(
                data => {
                    // Using this.zone.run() causes Angular to perform change detection which will update the view
                    this.zone.run(() => this.newPlayer( playerConfig ) );
                }
            );
        } else {
            // The DM class is already loaded, no need to wait for it to get streamed
            this.zone.run(() => this.newPlayer( playerConfig ) );

        }

    }

    /**
     * For cleaner code: load new DM player within that private function.
     * See https://developer.dailymotion.com/tools/sdks for documentation
     */
    private newPlayer(playerConfig: PlayerConfig) {
        let player = new window.DM.player(playerConfig.elementId, {
           width: playerConfig.width || this.defaultWidth,
           height: playerConfig.height || this.defaultHeight,
           video: playerConfig.videoId,
           params : {
               'autoplay' : false,
           }
        });

        // Emit player only after the API is really really _really_ ready
        player.addEventListener('apiready', function() {
            playerConfig.playerStream.emit(player);
        });

    }

    /**
     * Generate a unique ID.
     * It's needed when working with multiple players.
     * Source: http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript/8809472#8809472
     *
     * @return {string}
     */
    generateUUID () {
        var d = new Date().getTime();
        if(window.performance && typeof window.performance.now === "function"){
            d += performance.now(); // use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random()*16)%16 | 0;
            d = Math.floor(d/16);
            return (c=='x' ? r : (r&0x3|0x8)).toString(16);
        });

        return uuid;
    }
}


text:
<?php

namespace Intersvyaz\Bootstrap;

\Yii::import('zii.widgets.grid.CGridView');

/**
 * Bootstrap styled Yii's {@link \CGridView}.
 */
class GridView extends \CGridView
{
	/**
	 * @inheritdoc
	 */
	public $pager = ['class' => '\Intersvyaz\Bootstrap\LinkPager'];

	/**
	 * @inheritdoc
	 */
	public $pagerCssClass = 'pagination';

	/**
	 * @inheritdoc
	 */
	public $cssFile = false;

	/**
	 * @inheritdoc
	 */
	public $itemsCssClass = 'items table';
}


text:
var Util = require("util");

function ClientsManager() {
    var clients = {};
    this.addClient = function(client) {
        clients[client.id] = client;
    };
    this.getPlayer = function(id) {
        return clients[id];
    };
    this.removePlayer = function(id) {
        delete clients.id;
    };
};

var manager = new ClientsManager();

module.exports = manager;


text:
extern crate rand;
extern crate serde;
extern crate serde_json;

mod sidekiq;
pub use crate::sidekiq::{
    create_async_redis_pool, create_redis_pool, Client, ClientError, ClientOpts, Job, JobOpts,
    RedisPool,
};
pub use serde_json::value::Value;


text:
/**
 * @jest-environment node
 */
/* @flow */
import flexExamples from '../../../website/app/demos/Flex/Flex/examples';
import flexItemExamples from '../../../website/app/demos/Flex/FlexItem/examples';
import testDemoExamples from '../../../../utils/testDemoExamples';

const examples = [...flexExamples, ...flexItemExamples];

describe('Flex', () => {
  testDemoExamples(examples, {
    mode: 'ssr'
  });
});


text:
using System.Collections.Generic;
using System.Linq;
using LASI.Utilities;

namespace LASI.Core
{
    /// <summary>
    /// Represents a paragraph.
    /// </summary>
    public sealed class Paragraph : IReifiedTextual
    {
        /// <summary>
        /// Initializes a new instance of the Paragraph class.
        /// </summary>
        /// <param name="kind">Indicates the kind of Paragraph.</param>
        /// <param name="sentences">The sentences which comprise the Paragraph.</param>
        public Paragraph(ParagraphKind kind, IEnumerable<Sentence> sentences)
        {
            ParagraphKind = kind;
            Sentences = sentences;
        }
        /// <summary>
        /// Initializes a new instance of the Paragraph class.
        /// </summary>
        /// <param name="kind">Indicates the kind of Paragraph.</param>
        /// <param name="first">The first sentence of the Paragraph</param>
        /// <param name="rest">The rest of sentences which comprise the Paragraph.</param>
        public Paragraph(ParagraphKind kind, Sentence first, params Sentence[] rest) : this(kind, rest.Prepend(first)) { }

        /// <summary>
        /// Establish the nested links between the Paragraph, its parent Document, and the sentences comprising it.
        /// </summary>
        /// <param name="parentDocument">The document instance to identified as the Paragraph's parent.</param>
        public void EstablishTextualLinks(Document parentDocument)
        {
            Document = parentDocument;
            foreach (var sentence in Sentences)
            {
                sentence.EstablishTextualLinks(this);
            }
        }
        /// <summary>
        /// Returns the sequence of Phrases which come after the given phrase through to the end of the Paragraph.
        /// </summary>
        /// <param name="startAfter">The Phrase which bounds the sequence.</param>
        /// <returns>The sequence of Phrases which come after the given phrase through to the end of the Paragraph.</returns>
        public IEnumerable<Phrase> GetPhrasesAfter(Phrase startAfter) => Phrases.SkipWhile(p => p != startAfter).Skip(1);

        /// <summary>
        /// Returns a string representation of the Paragraph.
        /// </summary>
        /// <returns>A string representation of the Paragraph.</returns>
        public override string ToString() => $"{base.ToString()}: {Sentences.Count()} sentences\n\"{Text}\"";

        /// <summary>
        /// The collection of Sentences which comprise the Paragraph.
        /// </summary>
        public IEnumerable<Sentence> Sentences { get; }

        /// <summary>
        /// The collection of Words which comprise the Paragraph.
        /// </summary>
        public IEnumerable<Word> Words => Sentences.SelectMany(s => s.Words);

        /// <summary>
        /// The collection of Phrases which comprise the Paragraph.
        /// </summary>
        public IEnumerable<Phrase> Phrases => Sentences.SelectMany(s => s.Phrases);

        /// <summary>
        /// The collection of Clauses which comprise the Paragraph.
        /// </summary>
        public IEnumerable<Clause> Clauses => Sentences.SelectMany(s => s.Clauses);

        /// <summary>
        /// The Document the Paragraph belongs to.
        /// </summary>
        public Document Document { get; private set; }
        /// <summary>
        /// The ParagraphKind of the Paragraph.
        /// </summary>
        public ParagraphKind ParagraphKind { get; }

        /// <summary>
        /// The textual content of the Paragraph.
        /// </summary>
        public string Text => text ?? (text = string.Join(" ", Sentences.Select(s => s.Text)));

        /// <summary>
        /// Returns an enumeration of all constituent Lexical structures of the Paragraph.
        /// Lexical structures that contain other Lexical structures, such as Clauses, will be followed by their constituents.
        /// </summary>
        public IEnumerable<ILexical> Lexicals => Sentences.SelectMany(c => c.Phrases.SelectMany(p => p.Words));
        /// <summary>
        /// Gets all of the Entities in the Paragraph.
        /// </summary>
        public IEnumerable<IEntity> Entities => Lexicals.OfEntity();
        /// <summary>
        /// Gets all of the Verbals in the Paragraph.
        /// </summary>
        public IEnumerable<IVerbal> Verbals => Lexicals.OfVerbal();

        private string text;
    }
    /// <summary>
    /// Defines the Various Kinds of Paragraphs which a document may contain.
    /// </summary>
    public enum ParagraphKind
    {
        /// <summary>
        /// A paragraph containing one or more complete sentences.
        /// </summary>
        Default,
        /// <summary>
        /// A paragraph containing numbered or bulleted content.
        /// </summary>
        Enumeration,
        /// <summary>
        /// A paragraph containing a heading.
        /// </summary>
        Heading,
    }
}


text:
title: Thunderbolt 3 Woes
tags: ["thunderbolt", "mac"]
date: 2020-04-27
draft: true
---

It feels like for every 1 thing a piece of new technology enables it makes 2 other things more painful.

Recently this new piece of technology has been Thunderbolt 3, specifically cable length.

<!-- more -->

Copper Thunderbolt 3 cables – the ones you might have to connect 2 devices – have a length limit of 2m. My home office setup has a desktop computer under a sit/stand desk with an LG 5k UltraFine monitor clamped to it.


text:
package com.proteus.peach.common.util

import java.util.Comparator
import java.util.function.BiConsumer
import java.util.function.Consumer
import java.util.function.Function
import java.util.function.Predicate

/**
 * Conversions between scala functions and Java 8 stream related functions.
 */
object JavaCollectionsConversions {

  /**
   * Transform a given scala function into a Java one.
   * @param f The scala function.
   * @tparam A Input generic type.
   * @tparam B Output generic type.
   * @return A Java function.
   */
  implicit def scalaToJavaFunction[A, B](f: (A) => B): Function[A, B] = {
    new Function[A, B] {
      override def apply(t: A): B = f(t)
    }
  }

  /**
   * Transform a given scala function into a Java Consumer.
   * @param f The scala function.
   * @tparam A Input generic type.
   * @tparam B Output parameter of the Scala function. The returning value is ignored.
   * @return A Java Consumer.
   */
  implicit def scalaToJavaConsumer[A, B](f: A => B): Consumer[A] = {
    new Consumer[A]() {
      override def accept(t: A): Unit = f(t)
    }
  }

  /**
   * Transform a given scala function into a Java Predicate.
   * @param f The scala function.
   * @tparam A Input generic type.
   * @return A Java Predicate.
   */
  implicit def scalaToJavaPredicate[A](f: A => Boolean): Predicate[A] = {
    new Predicate[A] {
      override def test(t: A): Boolean = f(t)
    }
  }

  /**
   * Transform a given scala function into a Java Comparator.
   * @param f The scala function.
   * @tparam A The input generic type.
   * @return A Java Comparator.
   */
  implicit def scalaToJavaComparator[A](f: (A, A) => Int): Comparator[A] = {
    new Comparator[A] {
      override def compare(o1: A, o2: A): Int = f(o1, o2)
    }
  }

  /**
   * Transform a given scala function into a Java BiConsumer
   * @param f The scala function.
   * @tparam A Input generic type.
   * @tparam B Input generic type.
   * @tparam C Output parameter of the Scala function. The returning value is ignored.
   * @return A Java BiConsumer.
   */
  implicit def scalaToJavaBiConsumer[A, B, C](f: (A, B) => C): BiConsumer[A, B] = {
    new BiConsumer[A, B]() {
      override def accept(t: A, d: B): Unit = f(t, d)
    }
  }

}


text:
from unittest import TestCase
from app import matematica

class TestSumar(TestCase):
    def test_sumar(self):
        resultado = matematica.sumar(1, 2)
        self.assertEqual(resultado, 3)


text:
require 'spec_helper'

describe 'Line' do

  it 'paints a line on canvas ' do
    graphics = double("graphics")
    line = Line.new(Color.red,0,0,100,100)
    expect(graphics).to receive(:setColor).with(Color.red)
    expect(graphics).to receive(:drawLine).with(0,0,100,100)
    line.render(graphics)
  end
end


text:
package org.sagebionetworks.repo.model.dbo.dao.table;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Callback for a writer to an output stream.
 *
 * @author jhill
 *
 */
public interface WriterCallback {

	/**
	 * Write the data to the given output stream.
	 * @param out
	 * @throws IOException
	 */
	void write(OutputStream out) throws IOException;

}


text:
from __future__ import unicode_literals

# Authentication and Authorisation
from functools import wraps

from . import http

def permit(test_func, response_class=http.Forbidden):
    '''Decorate a handler to control access'''
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(self, *args, **kwargs):
            if test_func(self, *args, **kwargs):
                return view_func(self, *args, **kwargs)
            return response_class()
        return _wrapped_view
    return decorator

# Helpers for people wanting to control response class
def test_logged_in(self, *args, **kwargs):
    return self.request.user.is_authenticated()

def test_staff(self, *args, **kwargs):
    return self.request.user.is_staff

permit_logged_in = permit(test_logged_in)
permit_staff = permit(test_staff)

def permit_groups(response_class=http.Forbidden, *groups):
    def in_groups(self, *args, **kwargs):
        return self.request.user.groups.filter(name__in=groups).exists()
    return permit(in_groups, response_class=response_class)


text:
> not available in anSript for Web

Open and run anScript code from file.

---
#### `runtimeRunFromCharArray(var.s script)`
Run anScript code from `script`'s value.

---
#### `runtimeExit()`
Exit interpreter.

---
#### `runtimeError(var error, ...)`
Throw _executionError_ (`error` could be `var.i`, `var.f` or `var.s`).

## Example:

### main.ans

    runtimeRun(<path>sayHello.ans.s)
	instructionCreate(ins)
	    variableCreate(key, var.i)
	    logicLoop(1.i)
	        windowGetKeyInput(key)
	        consolePrintLine(key)
	        logicSwitch(key)
	            logicCase(27.i)
	                runtimeEnd()
	            }
	            logicCase(logicDefault)
	                timeWait(100.i)
	            }
	        }
	    }
	}
	ins()

### sayHello.ans

	consolePrint(Hello!.s)
	consoleNewLine()


text:
/**
 * Tag.js
 *
 * @description :: Tag names for startups
 * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

module.exports = {

  adapter: 'mysql',

  attributes: {

      id: {
          type: 'integer',
          primaryKey: true,
          autoIncrement: true
      },

      name: {
          type: 'string',
          required: true,
          unique: true
      },

      startups: {
          collection: 'startup',
          via: 'tag',
          through: 'startuptag'
      }
  }
};


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
<!-- 		<mapping class="com.security.domain.User"/> -->
	</session-factory>

</hibernate-configuration>


text:
import { moduleForComponent, test } from 'ember-qunit';
import DS from 'ember-data';
import Branchable from '@cardstack/tools/mixins/branch-adapter';
import AdapterMixin from 'ember-resource-metadata/adapter-mixin';
import RSVP from 'rsvp';
import Ember from 'ember';

let requests, answers;

moduleForComponent('branch-adapter', 'Integration | Adapter | branch-adapter', {
  integration: true,
  beforeEach() {
    requests = [];
    answers = [];
    this.register('service:cardstack-routing', Ember.Service.extend({
      defaultBranch: 'a'
    }));
    this.register('adapter:post', DS.JSONAPIAdapter.extend(Branchable, AdapterMixin, {
      shouldBackgroundReloadRecord() {
        return false;
      },
      ajax(url, type, options) {
        requests.push({ url, type, options });
        if (answers.length === 0) {
          throw new Error("more requests than expected");
        }
        return RSVP.resolve(answers.shift());
      }
    }));
    this.register('model:post', DS.Model.extend());
    this.inject.service('store');
    this.inject.service('resource-metadata', { as: 'meta' });
  }
});

test('findRecord on default branch', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => this.get('store').findRecord('post', 1))
    .then(record => {
      assert.equal(record.id, 1);
      assert.deepEqual(requests[0].url, '/posts/1');
    });
});

test('findRecord on a branch', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'x' } }))
    .then(record => {
      assert.equal(record.id, 1);
      assert.deepEqual(requests[0].url, '/posts/1?branch=x');
    });
});

test('findRecord leaves off explicitly requested default branch', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'a' } }))
    .then(record => {
      assert.equal(record.id, 1);
      assert.deepEqual(requests[0].url, '/posts/1');
    });
});

test('findRecord caches on same branch', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'x' } }))
    .then(() => {
      assert.equal(requests.length, 1);
      return this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'x' } });
    }).then(() => {
      assert.equal(requests.length, 1, "no additional request");
    });
});

test('findRecord does not cache when branch changes', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'x' } }))
    .then(() => {
      assert.equal(requests.length, 1);
      return this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'y' } });
    }).then(() => {
      assert.equal(requests.length, 2, "saw a new request");
    });
});

test('queryRecord with default branch', function(assert) {
  answers.push({
    data: [{
      id: 1,
      type: 'posts'
    }]
  });
  return RSVP.resolve()
    .then(() => this.get('store').queryRecord('post', { filter: { slug: 'hi' } } ))
    .then(record => {
      assert.equal(record.id, 1);
      assert.equal(requests.length, 1);
      assert.equal(requests[0].url, '/posts');
      assert.deepEqual(requests[0].options, {
        data: {
          filter: { slug: 'hi' },
          page: { size: 1 }
        } });
    });
});

test('queryRecord with explicit branch', function(assert) {
  answers.push({
    data: [{
      id: 1,
      type: 'posts'
    }]
  });
  return RSVP.resolve()
    .then(() => this.get('store').queryRecord('post', { branch: 'x', filter: { slug: 'hi' } } ))
    .then(record => {
      assert.equal(record.id, 1);
      assert.equal(requests.length, 1);
      assert.equal(requests[0].url, '/posts');
      assert.deepEqual(requests[0].options, {
        data: {
          branch: 'x',
          filter: { slug: 'hi' },
          page: { size: 1 }
        } });
    });
});

test('queryRecord with explicit branch matching default', function(assert) {
  answers.push({
    data: [{
      id: 1,
      type: 'posts'
    }]
  });
  return RSVP.resolve()
    .then(() => this.get('store').queryRecord('post', { branch: 'a', filter: { slug: 'hi' } } ))
    .then(record => {
      assert.equal(record.id, 1);
      assert.equal(requests.length, 1);
      assert.equal(requests[0].url, '/posts');
      assert.deepEqual(requests[0].options, {
        data: {
          filter: { slug: 'hi' },
          page: { size: 1 }
        } });
    });
});

test('createRecord with directly provided branch', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => {
      let model = this.get('store').createRecord('post');
      return model.save({ adapterOptions: { branch: 'b' } });
    }).then(() => {
      assert.equal(requests.length, 1);
      assert.equal(requests[0].url, '/posts?branch=b');
      assert.equal(requests[0].type, 'POST');
    });
});

test('createRecord with branch from resource meta', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => {
      let model = this.get('store').createRecord('post');
      this.get('meta').write(model, { branch: 'b' });
      return model.save();
    }).then(() => {
      assert.equal(requests.length, 1);
      assert.equal(requests[0].url, '/posts?branch=b');
      assert.equal(requests[0].type, 'POST');
    });
});

test('updateRecord maintains branch', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => {
      return this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'b' }});
    }).then(record => record.save())
    .then(() => {
      assert.equal(requests.length, 2);
      assert.equal(requests[1].url, '/posts/1?branch=b');
      assert.equal(requests[1].type, 'PATCH');
    })
});

test('deleteRecord maintains branch', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  answers.push({
    data: {
      id: 1,
      type: 'posts'
    }
  });
  return RSVP.resolve()
    .then(() => {
      return this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'b' }});
    }).then(record => record.destroyRecord())
    .then(() => {
      assert.equal(requests.length, 2);
      assert.equal(requests[1].url, '/posts/1?branch=b');
      assert.equal(requests[1].type, 'DELETE');
    })
});

test('deleteRecord provides if-match header', function(assert) {
  answers.push({
    data: {
      id: 1,
      type: 'posts',
      meta: {
        version: 'my-version'
      }
    }
  });
  answers.push(null);
  return RSVP.resolve()
    .then(() => {
      return this.get('store').findRecord('post', 1, { adapterOptions: { branch: 'b' }});
    }).then(record => record.destroyRecord())
    .then(() => {
      assert.deepEqual(requests[1].options, {headers: { 'if-match': 'my-version' } });
    })
});


text:
package com.icegreen.greenmail.test;

import com.icegreen.greenmail.user.GreenMailUser;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.GreenMailUtil;
import com.icegreen.greenmail.util.Retriever;
import com.icegreen.greenmail.util.ServerSetupTest;
import org.junit.Test;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author Wael Chatila
 * @version $Id: $
 * @since Jan 29, 2006
 */
public class GreenMailUtilTest {
    @Test
    public void testMimeMessageLoading() throws MessagingException {
        MimeMessage message = GreenMailUtil.newMimeMessage(SAMPLE_EMAIL);
        assertThat(message.getSubject()).isEqualTo("wassup");
    }

    @Test
    public void testGetBody() {
        MimeMessage message = GreenMailUtil.newMimeMessage(SAMPLE_EMAIL);
        String body = GreenMailUtil.getBody(message);
        assertThat(body.trim()).isEqualTo("Yo wassup Bertil");
    }

    @Test
    public void testGetEmptyBodyAndHeader() throws Exception {
        GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
        try {
            greenMail.start();

            String subject = GreenMailUtil.random();
            String body = ""; // Provokes https://github.com/greenmail-mail-test/greenmail/issues/151
            String to = "test@localhost";
            final byte[] gifAttachment = {0, 1, 2};
            GreenMailUtil.sendAttachmentEmail(to, "from@localhost", subject, body, gifAttachment,
                    "image/gif", "testimage_filename", "testimage_description",
                    greenMail.getSmtp().getServerSetup());
            greenMail.waitForIncomingEmail(5000, 1);

            try (Retriever retriever = new Retriever(greenMail.getImap())) {
                MimeMultipart mp = (MimeMultipart) retriever.getMessages(to)[0].getContent();
                BodyPart bp;
                bp = mp.getBodyPart(0);
                assertThat(body).isEqualTo(GreenMailUtil.getBody(bp).trim());
                assertThat(
                        "Content-Type: text/plain; charset=us-ascii\r\n" +
                        "Content-Transfer-Encoding: 7bit").isEqualTo(
                        GreenMailUtil.getHeaders(bp).trim());

                bp = mp.getBodyPart(1);
                assertThat("AAEC").isEqualTo(GreenMailUtil.getBody(bp).trim());
                assertThat(
                        "Content-Type: image/gif; name=testimage_filename\r\n" +
                        "Content-Transfer-Encoding: base64\r\n" +
                        "Content-Disposition: attachment; filename=testimage_filename\r\n" +
                        "Content-Description: testimage_description").isEqualTo(GreenMailUtil.getHeaders(bp).trim());

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                GreenMailUtil.copyStream(bp.getInputStream(), bout);
                assertThat(bout.toByteArray()).isEqualTo(gifAttachment);
            }
        } finally {
            greenMail.stop();
        }
    }

    @Test
    public void testSendTextEmailTest() throws Exception {
        GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
        try {
            greenMail.setUser("foo@localhost", "pwd");
            greenMail.start();
            GreenMailUtil.sendTextEmail("\"Foo, Bar\" <foo@localhost>", "\"Bar, Foo\" <bar@localhost>",
                    "Test subject", "Test message", ServerSetupTest.SMTP);
            greenMail.waitForIncomingEmail(1);

            Store store = greenMail.getImap().createStore();
            store.connect("foo@localhost", "pwd");
            try {
                Folder folder = store.getFolder("INBOX");
                folder.open(Folder.READ_ONLY);
                Message[] msgs = folder.getMessages();
                assertThat(null != msgs && msgs.length == 1).isTrue();
                Message m = msgs[0];
                assertThat(m.getSubject()).isEqualTo("Test subject");
                Address[] a = m.getRecipients(Message.RecipientType.TO);
                assertThat(null != a && a.length == 1
                        && a[0].toString().equals("\"Foo, Bar\" <foo@localhost>")).isTrue();
                a = m.getFrom();
                assertThat(null != a && a.length == 1
                        && a[0].toString().equals("\"Bar, Foo\" <bar@localhost>")).isTrue();
                assertThat(m.getContentType().toLowerCase().startsWith("text/plain")).isTrue();
                assertThat(m.getContent()).isEqualTo("Test message");
            } finally {
                store.close();
            }
        } finally {
            greenMail.stop();
        }
    }

    @Test
    public void testSetAndGetQuota() throws MessagingException {
        GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
        try {
            greenMail.start();

            final GreenMailUser user = greenMail.setUser("foo@localhost", "pwd");

            Store store = greenMail.getImap().createStore();
            store.connect("foo@localhost", "pwd");

            Quota testQuota = new Quota("INBOX");
            testQuota.setResourceLimit("STORAGE", 1024L * 42L);
            testQuota.setResourceLimit("MESSAGES", 5L);

            assertThat(0).isEqualTo(GreenMailUtil.getQuota(user, testQuota.quotaRoot).length);
            GreenMailUtil.setQuota(user, testQuota);

            final Quota[] quota = GreenMailUtil.getQuota(user, testQuota.quotaRoot);
            assertThat(quota.length).isEqualTo(1);
            assertThat(quota[0].resources.length).isEqualTo(2);

            store.close();
        } finally {
            greenMail.stop();
        }
    }

    final static String SAMPLE_EMAIL = "From - Thu Jan 19 00:30:34 2006\r\n"
            + "X-Account-Key: account245\r\n"
            + "X-UIDL: 11332317636080.2607.mail5,S=833\r\n"
            + "X-Mozilla-Status: 0001\r\n"
            + "X-Mozilla-Status2: 00000000\r\n"
            + "Return-Path: <bertil@surstomming.com>\r\n"
            + "Delivered-To: eivar@blastigen.com\r\n"
            + "Received: (qmail 2376 invoked from network); 19 Jan 2006 02:01:05 -0000\r\n"
            + "Received: from unknown (HELO [192.168.0.5]) (hej@66.245.216.76)\r\n"
            + "\tby mail5.hotmail.com with (RC4-MD5 encrypted) SMTP; Wed, 18 Jan 2006 18:01:05 -0800\r\n"
            + "Message-ID: <43CEF322.7080702@hotmail.com>\r\n"
            + "Date: Wed, 18 Jan 2006 18:02:10 -0800\r\n"
            + "From: Wael Chatila <wael@localhost>\r\n"
            + "User-Agent: Mozilla Thunderbird 1.0.7 (Windows/20050923)\r\n"
            + "X-Accept-Language: en-us, en\r\n" + "MIME-Version: 1.0\r\n"
            + "To: Bertil <bertil@localhost>\r\n" + "Subject: wassup\r\n"
            + "Content-Type: text/plain; charset=ISO-8859-1; format=flowed\r\n"
            + "Content-Transfer-Encoding: 7bit\r\n" + "\r\n"
            + "Yo wassup Bertil\r\n";
}


text:
/**
 * TypeLinking:
 * - Tests whether it is allowed to use a package name that clashes
 * with the identifier of a singletype import.
 */
package List;

import java.util.List;

public class A{

    public A(){}
}


text:
package hu.supercluster.paperwork.integration.test;

import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;

import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;

import java.util.concurrent.TimeUnit;

import hu.supercluster.paperwork.integration.*;
import hu.supercluster.paperwork.integration.matcher.BuildTimeMatcher;
import hu.supercluster.paperwork.integration.matcher.GitShaMatcher;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.CoreMatchers.any;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.core.IsNot.not;

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
    public static final long TIMESTAMP_THRESHOLD = TimeUnit.MINUTES.toMillis(10);
    public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String TIMEZONE_ID_1 = "GMT";
    public static final String TIMEZONE_ID_2 = "Pacific/Honolulu";

    @Rule
    public TestRule rule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void shouldHaveCorrectValueForSimpleKey() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.simpleKey)).check(matches(withText(is("simpleValue"))));
    }

    @Test
    public void shouldDisplayGitSha() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.gitSha)).check(matches(withText(new GitShaMatcher())));
    }

    @Test
    public void shouldDisplayGitTag() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.gitTag)).check(matches(not(withText(isEmptyString()))));
    }

    @Test
    public void shouldDisplayGitInfo() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.gitInfo)).check(matches(not(withText(isEmptyString()))));
    }

    @Test
    public void shouldDisplayGitBranch() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.gitBranch)).check(matches(not(withText(isEmptyString()))));
    }

    @Test
    public void shouldHaveRelevantBuildTime1() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.buildTime1)).check(matches(withText(new BuildTimeMatcher(TIMESTAMP_THRESHOLD))));
    }

    @Test
    public void shouldDisplayBuildTime2() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.buildTime2)).check(matches(withText("AD")));
    }

    @Test
    public void shouldHaveRelevantBuildTime3() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.buildTime3)).check(matches(withText(new BuildTimeMatcher(TIMESTAMP_THRESHOLD, DATETIME_FORMAT, TIMEZONE_ID_1))));
    }

    @Test
    public void shouldHaveRelevantBuildTime4() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.buildTime4)).check(matches(withText(new BuildTimeMatcher(TIMESTAMP_THRESHOLD, DATETIME_FORMAT, TIMEZONE_ID_2))));
    }

    @Test
    public void shouldHaveCorrectValueForShell() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.shell)).check(matches(withText("String output of test.sh")));
    }

    @Test
    public void shouldDisplayEnv() {
        onView(ViewMatchers.withId(hu.supercluster.paperwork.integration.R.id.env)).check(matches(not(withText(isEmptyString()))));
    }
}


text:
package org.neo4j.driver.internal.handlers;

import static java.lang.String.format;

import java.util.Map;
import java.util.Objects;
import org.neo4j.driver.AccessMode;
import org.neo4j.driver.Value;
import org.neo4j.driver.exceptions.ClientException;
import org.neo4j.driver.exceptions.ServiceUnavailableException;
import org.neo4j.driver.exceptions.SessionExpiredException;
import org.neo4j.driver.exceptions.TransientException;
import org.neo4j.driver.internal.BoltServerAddress;
import org.neo4j.driver.internal.RoutingErrorHandler;
import org.neo4j.driver.internal.spi.ResponseHandler;
import org.neo4j.driver.internal.util.Futures;

public class RoutingResponseHandler implements ResponseHandler {
    private final ResponseHandler delegate;
    private final BoltServerAddress address;
    private final AccessMode accessMode;
    private final RoutingErrorHandler errorHandler;

    public RoutingResponseHandler(
            ResponseHandler delegate,
            BoltServerAddress address,
            AccessMode accessMode,
            RoutingErrorHandler errorHandler) {
        this.delegate = delegate;
        this.address = address;
        this.accessMode = accessMode;
        this.errorHandler = errorHandler;
    }

    @Override
    public void onSuccess(Map<String, Value> metadata) {
        delegate.onSuccess(metadata);
    }

    @Override
    public void onFailure(Throwable error) {
        Throwable newError = handledError(error);
        delegate.onFailure(newError);
    }

    @Override
    public void onRecord(Value[] fields) {
        delegate.onRecord(fields);
    }

    @Override
    public boolean canManageAutoRead() {
        return delegate.canManageAutoRead();
    }

    @Override
    public void disableAutoReadManagement() {
        delegate.disableAutoReadManagement();
    }

    private Throwable handledError(Throwable receivedError) {
        Throwable error = Futures.completionExceptionCause(receivedError);

        if (error instanceof ServiceUnavailableException) {
            return handledServiceUnavailableException(((ServiceUnavailableException) error));
        } else if (error instanceof ClientException) {
            return handledClientException(((ClientException) error));
        } else if (error instanceof TransientException) {
            return handledTransientException(((TransientException) error));
        } else {
            return error;
        }
    }

    private Throwable handledServiceUnavailableException(ServiceUnavailableException e) {
        errorHandler.onConnectionFailure(address);
        return new SessionExpiredException(format("Server at %s is no longer available", address), e);
    }

    private Throwable handledTransientException(TransientException e) {
        String errorCode = e.code();
        if (Objects.equals(errorCode, "Neo.TransientError.General.DatabaseUnavailable")) {
            errorHandler.onConnectionFailure(address);
        }
        return e;
    }

    private Throwable handledClientException(ClientException e) {
        if (isFailureToWrite(e)) {
            // The server is unaware of the session mode, so we have to implement this logic in the driver.
            // In the future, we might be able to move this logic to the server.
            switch (accessMode) {
                case READ:
                    return new ClientException("Write queries cannot be performed in READ access mode.");
                case WRITE:
                    errorHandler.onWriteFailure(address);
                    return new SessionExpiredException(format("Server at %s no longer accepts writes", address));
                default:
                    throw new IllegalArgumentException(accessMode + " not supported.");
            }
        }
        return e;
    }

    private static boolean isFailureToWrite(ClientException e) {
        String errorCode = e.code();
        return Objects.equals(errorCode, "Neo.ClientError.Cluster.NotALeader")
                || Objects.equals(errorCode, "Neo.ClientError.General.ForbiddenOnReadOnlyDatabase");
    }
}


text:
/**
 * @file    tcell_store.c
 * @brief   Store a file on the tcell.
 * @author  Loudet Julien
 * @version 1.1
 * @date    2015-09
 */

#include <time.h> /* localtime, struct tm, time */
#include <stdio.h> /* fprintf */
#define _GNU_SOURCE /* strtok_r */
#include <string.h> /* strtok_r, strcpy, strcat */

#include "../core/beans/my_info.h"
#include "../core/message/message.h"
#include "../core/crypto/rsa_encryption.h"
#include "../core/network/connection.h"
#include "../core/network/transfer_file.h"
#include "../database/database.h"
#include "tcell.h"

void tcell_store(MyInfo_t *my_info, int sock_fd, char *store_msg)
{
    FileDesc_t file_desc;
    char *msg_part, *field, *value, *msg_end;

    msg_part = strtok_r(store_msg, MSG_SEP, &msg_end);

    /* Get the file description from the store message */
    while(msg_part != NULL)
    {
        char *field_end;
        field = strtok_r(msg_part, FIELD_VALUE_SEP, &field_end);

        if(field == NULL)
        {
            fprintf(stderr, "[ERROR] An error occurred while decrypting the "
                    "        message. Unable to process it.\n");
            exit(-1);
        }

        /* The field is not null we cant get a value */
        value = strtok_r(NULL, FIELD_VALUE_SEP, &field_end);

        if(value == NULL)
        {
            fprintf(stderr, "[WARNING] The value of the field < %s > \n"
                            "          was not provided.\n", field);
        }

        /* Fill in the correct field of the file descriptor */
        if(strcmp(field, FIELD_FILE_GID) == 0)
        {
            strcpy(file_desc.file_gid, value);
        }
        else if(strcmp(field, FIELD_FILE_ID) == 0)
        {
            strcpy(file_desc.file_id, value);
        }
        else if(strcmp(field, FIELD_SIZE) == 0)
        {
            strcpy(file_desc.size, value);
        }
        else if(strcmp(field, FIELD_TYPE) == 0)
        {
            strcpy(file_desc.type, value);
        }
        else if(strcmp(field, FIELD_DESC) == 0)
        {
            strcpy(file_desc.description, value);
        }
        else if(strcmp(field, FIELD_SYM_KEY) == 0)
        {
            strcpy(file_desc.symmetric_key, value);
        }
        else if(strcmp(field, FIELD_IV) == 0)
        {
            strcpy(file_desc.initialisation_vector, value);
        }

        msg_part = strtok_r(NULL, MSG_SEP, &msg_end);
    }

    /* Update the file gid to add the time */
    char strtime[ARR_SIZE];
    time_t t = time(NULL);
    struct tm s_tm = *localtime(&t);
    sprintf(strtime, "%d%d%d%d%d%d", s_tm.tm_year + 1900, s_tm.tm_mon + 1,
                                     s_tm.tm_mday, s_tm.tm_hour, s_tm.tm_min,
                                     s_tm.tm_sec);

    strcat(file_desc.file_gid, "-");
    strcat(file_desc.file_gid, strtime);

    /* Set the path of the file on the tcell */
    char *tcell_files_path = get_tcell_files_path();
    char buf_path[ARR_SIZE];
    sprintf(buf_path, "%s/%s", tcell_files_path, file_desc.file_gid);
    strcpy(file_desc.path, buf_path);
    free(tcell_files_path);

    /* Insert a new entry in the database */
    if(insertFile(&file_desc) != 1)
    {
        fprintf(stderr, "[ERROR] Could not insert file into the database.\n");
        exit(-1);
    }

    /* Everyting went well, send an ack to start the file transfer */
    send_msg_to(sock_fd, rsa_encrypt_msg(my_info->my_public_key, MSG_ACK));

    /* File transfer! */
    recv_file_from(sock_fd, file_desc.size, file_desc.path);

    /* Send an ack to end the transaction */
    send_msg_to(sock_fd, rsa_encrypt_msg(my_info->my_public_key, MSG_ACK));

    fprintf(stdout, "[INFO] File successfully transfered!\n");
}


text:
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.us.Common;

namespace OpenADK.Library.us.Assessment{

/// A Sif3Assessment
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.6</para>
/// </remarks>
[Serializable]
public class Sif3Assessment : SifDataObject
{
	///
	/// Creates an instance of a Sif3Assessment
	///
	public Sif3Assessment() : base( Adk.SifVersion, AssessmentDTD.SIF3ASSESSMENT ){}

	///
	/// Constructor that accepts values for all mandatory fields
	///
	///<param name="refId">The GUID that uniquely identifies this object.</param>
	///<param name="name">Name of the test.</param>
	///
	public Sif3Assessment( string refId, string name ) : base( Adk.SifVersion, AssessmentDTD.SIF3ASSESSMENT )
	{
		this.RefId = refId;
		this.Name = name;
	}

	///
	/// Constructor used by the .Net Serialization formatter
	///
	[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
	protected Sif3Assessment( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	///
	/// Gets the metadata fields that make up the key of this object
	///
	/// <value>
	/// an array of metadata fields that make up the object's key
	/// </value>
	public override IElementDef[] KeyFields {
		get { return new IElementDef[] { AssessmentDTD.SIF3ASSESSMENT_REFID }; }
	}

	///
	/// Gets or sets the value of the <c>RefId</c> attribute.
	///
	/// <value> The <c>RefId</c> attribute of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this attribute as: "The GUID that uniquely identifies this object."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public override string RefId
	{
		get
		{
			return (string) GetSifSimpleFieldValue( AssessmentDTD.SIF3ASSESSMENT_REFID ) ;
		}
		set
		{
			SetFieldValue( AssessmentDTD.SIF3ASSESSMENT_REFID, new SifString( value ), value );
		}
	}

	///
	/// Gets or sets the value of the <c><Name></c> element.
	///
	/// <value> The <c>Name</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "Name of the test."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public string Name
	{
		get
		{
			return (string) GetSifSimpleFieldValue( AssessmentDTD.SIF3ASSESSMENT_NAME ) ;
		}
		set
		{
			SetFieldValue( AssessmentDTD.SIF3ASSESSMENT_NAME, new SifString( value ), value );
		}
	}

	///Sets the value of the <c><AssessmentIdentifiers></c> element.
	/// <param name="AssessmentIdentifier">A list of all assessment identifiers that may be associated with this assessment.</param>
	///<remarks>
	/// <para>This form of <c>setAssessmentIdentifiers</c> is provided as a convenience method
	/// that is functionally equivalent to the <c>AssessmentIdentifiers</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public void SetAssessmentIdentifiers( AssessmentIdentifier AssessmentIdentifier ) {
		RemoveChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTIDENTIFIERS);
		AddChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTIDENTIFIERS, new AssessmentIdentifiers( AssessmentIdentifier ) );
	}

	///
	/// Gets or sets the value of the <c><AssessmentIdentifiers></c> element.
	///
	/// <value> An AssessmentIdentifiers </value>
	/// <remarks>
	/// <para>To remove the <c>AssessmentIdentifiers</c>, set <c>AssessmentIdentifiers</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public AssessmentIdentifiers AssessmentIdentifiers
	{
		get
		{
			return (AssessmentIdentifiers)GetChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTIDENTIFIERS);
		}
		set
		{
			RemoveChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTIDENTIFIERS);
			if( value != null)
			{
				AddChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTIDENTIFIERS, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><AssessmentPackageRefId></c> element.
	///
	/// <value> The <c>AssessmentPackageRefId</c> element of this object.</value>
	/// <remarks>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public string AssessmentPackageRefId
	{
		get
		{
			return (string) GetSifSimpleFieldValue( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTPACKAGEREFID ) ;
		}
		set
		{
			SetFieldValue( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTPACKAGEREFID, new SifString( value ), value );
		}
	}

	///
	/// Gets or sets the value of the <c><AssessmentDescriptors></c> element.
	///
	/// <value> An AssessmentDescriptors </value>
	/// <remarks>
	/// <para>To remove the <c>AssessmentDescriptors</c>, set <c>AssessmentDescriptors</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public AssessmentDescriptors AssessmentDescriptors
	{
		get
		{
			return (AssessmentDescriptors)GetChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTDESCRIPTORS);
		}
		set
		{
			RemoveChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTDESCRIPTORS);
			if( value != null)
			{
				AddChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTDESCRIPTORS, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><AssessmentProvider></c> element.
	///
	/// <value> The <c>AssessmentProvider</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "Identifies the provider or publisher of the assessment."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public string AssessmentProvider
	{
		get
		{
			return (string) GetSifSimpleFieldValue( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTPROVIDER ) ;
		}
		set
		{
			SetFieldValue( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTPROVIDER, new SifString( value ), value );
		}
	}

	///Sets the value of the <c><AssessmentItemBanks></c> element.
	/// <param name="AssessmentItemBank">A wrapper for the Item Bank elements.</param>
	///<remarks>
	/// <para>This form of <c>setAssessmentItemBanks</c> is provided as a convenience method
	/// that is functionally equivalent to the <c>AssessmentItemBanks</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public void SetAssessmentItemBanks( AssessmentItemBank AssessmentItemBank ) {
		RemoveChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTITEMBANKS);
		AddChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTITEMBANKS, new AssessmentItemBanks( AssessmentItemBank ) );
	}

	///
	/// Gets or sets the value of the <c><AssessmentItemBanks></c> element.
	///
	/// <value> An AssessmentItemBanks </value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this null as: "Assessments may be part of one or more item banks."</para>
	/// <para>To remove the <c>AssessmentItemBanks</c>, set <c>AssessmentItemBanks</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public AssessmentItemBanks AssessmentItemBanks
	{
		get
		{
			return (AssessmentItemBanks)GetChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTITEMBANKS);
		}
		set
		{
			RemoveChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTITEMBANKS);
			if( value != null)
			{
				AddChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTITEMBANKS, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><AssessmentSubjects></c> element.
	///
	/// <value> A SubjectAreaList </value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this null as: "The assessment may be designed to measure specific subject areas. Note that grade levels are also
	///                 included in the Assessment Form object. Specific forms of an assessment may have more granularity.
	///             "</para>
	/// <para>To remove the <c>SubjectAreaList</c>, set <c>AssessmentSubjects</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public SubjectAreaList AssessmentSubjects
	{
		get
		{
			return (SubjectAreaList)GetChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTSUBJECTS);
		}
		set
		{
			RemoveChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTSUBJECTS);
			if( value != null)
			{
				AddChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTSUBJECTS, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><AssessmentGradeLevels></c> element.
	///
	/// <value> A GradeLevels </value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this null as: "The assessment may be designed for specific grade levels. Note that grade levels are also included in
	///                 the Assessment Form object. Specific forms of an assessment may have more granularity.
	///             "</para>
	/// <para>To remove the <c>GradeLevels</c>, set <c>AssessmentGradeLevels</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public GradeLevels AssessmentGradeLevels
	{
		get
		{
			return (GradeLevels)GetChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTGRADELEVELS);
		}
		set
		{
			RemoveChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTGRADELEVELS);
			if( value != null)
			{
				AddChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTGRADELEVELS, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><AssessmentLanguages></c> element.
	///
	/// <value> A LanguageList </value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this null as: "The assessment may be available in multiple languages. This list will indicate which languages are
	///                 available.
	///             "</para>
	/// <para>To remove the <c>LanguageList</c>, set <c>AssessmentLanguages</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public LanguageList AssessmentLanguages
	{
		get
		{
			return (LanguageList)GetChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTLANGUAGES);
		}
		set
		{
			RemoveChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTLANGUAGES);
			if( value != null)
			{
				AddChild( AssessmentDTD.SIF3ASSESSMENT_ASSESSMENTLANGUAGES, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><LearningStandardItemRefIds></c> element.
	///
	/// <value> A LearningStandardItemRefIds </value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this null as: "This list identifies all learning standards that may be measured by this assessment"</para>
	/// <para>To remove the <c>LearningStandardItemRefIds</c>, set <c>LearningStandardItemRefIds</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public LearningStandardItemRefIds LearningStandardItemRefIds
	{
		get
		{
			return (LearningStandardItemRefIds)GetChild( AssessmentDTD.SIF3ASSESSMENT_LEARNINGSTANDARDITEMREFIDS);
		}
		set
		{
			RemoveChild( AssessmentDTD.SIF3ASSESSMENT_LEARNINGSTANDARDITEMREFIDS);
			if( value != null)
			{
				AddChild( AssessmentDTD.SIF3ASSESSMENT_LEARNINGSTANDARDITEMREFIDS, value );
			}
		}
	}

}}


text:
package com.vaadin.shared.ui.grid;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.vaadin.shared.Connector;
import com.vaadin.shared.ui.ContentMode;

/**
 * Shared state for Grid headers and footers.
 *
 * @author Vaadin Ltd
 * @since 8.0
 */
public class SectionState implements Serializable {

    /** The state of a header or footer row. */
    public static class RowState implements Serializable {

        /** The map from column ids to the cells in this row. */
        public Map<String, CellState> cells = new HashMap<>();

        /** The map from a joint cell to column id sets in this row. */
        public Map<CellState, Set<String>> cellGroups = new HashMap<>();

        /**
         * Whether this row is the default header row. Always false for footer
         * rows.
         */
        public boolean defaultHeader = false;

        /**
         * The style name for the row. Null if none.
         */
        public String styleName = null;
    }

    /** The state of a header or footer cell. */
    public static class CellState implements Serializable {

        public GridStaticCellType type = GridStaticCellType.TEXT;

        /** The style name for this cell. Null if none. */
        public String styleName = null;

        /** The textual caption of this cell. */
        public String text;

        /** The html content of this cell. */
        public String html;

        /**
         * The connector for the component that is set to be displayed in this
         * cell. Null if none.
         */
        public Connector connector = null;

        /** The id of the column that this cell belongs to. */
        public String columnId;

        /** The tooltip for the cell */
        public String description;

        /** The content mode for the tooltip for the cell */
        public ContentMode descriptionContentMode = ContentMode.TEXT;
    }

    /** The rows in this section. */
    public List<RowState> rows = new ArrayList<>();

    /**
     * Visibility of this section.
     *
     * @since 8.1.1
     */
    public boolean visible = true;
}


text:
namespace Google.Cloud.Translate.V3.Snippets
{
    // [START translate_v3_generated_TranslationService_DetectLanguage_async]
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Translate.V3;
    using System.Threading.Tasks;

    public sealed partial class GeneratedTranslationServiceClientSnippets
    {
        /// <summary>Snippet for DetectLanguageAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task DetectLanguageRequestObjectAsync()
        {
            // Create client
            TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();
            // Initialize request argument(s)
            DetectLanguageRequest request = new DetectLanguageRequest
            {
                Content = "",
                MimeType = "",
                Model = "",
                ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
                Labels = { { "", "" }, },
            };
            // Make the request
            DetectLanguageResponse response = await translationServiceClient.DetectLanguageAsync(request);
        }
    }
    // [END translate_v3_generated_TranslationService_DetectLanguage_async]
}


text:
class NamespaceValidator < ActiveModel::EachValidator
  RESERVED = %w[
    .well-known
    admin
    all
    assets
    ci
    dashboard
    files
    groups
    help
    hooks
    issues
    merge_requests
    new
    notes
    profile
    projects
    public
    repository
    robots.txt
    s
    search
    services
    snippets
    teams
    u
    unsubscribes
    users
    system
  ].freeze

  WILDCARD_ROUTES = %w[tree commits wikis new edit create update logs_tree
                       preview blob blame raw files create_dir find_file
                       artifacts graphs refs badges].freeze

  STRICT_RESERVED = (RESERVED + WILDCARD_ROUTES).freeze

  def self.valid?(value)
    !reserved?(value) && follow_format?(value)
  end

  def self.reserved?(value, strict: false)
    if strict
      STRICT_RESERVED.include?(value.to_s.downcase)
    else
      RESERVED.include?(value.to_s.downcase)
    end
  end

  def self.follow_format?(value)
    value =~ Gitlab::Regex.namespace_regex
  end

  delegate :reserved?, :follow_format?, to: :class

  def validate_each(record, attribute, value)
    unless follow_format?(value)
      record.errors.add(attribute, Gitlab::Regex.namespace_regex_message)
    end

    strict = record.is_a?(Group) && record.parent_id

    if reserved?(value, strict: strict)
      record.errors.add(attribute, "#{value} is a reserved name")
    end
  end
end


text:
import axios from 'axios'
import { ROOT_URL, HEADERS, PARAMETERS } from './config_service'

export default class AuthService {
  constructor() {
    this.instanceService = null
  }

  static setInstance(instanceService) {
    this.instanceService = instanceService
  }

  static getInstance() {
    if (!this.instanceService) {
      this.instanceService = new AuthService()
    }
    return this.instanceService
  }

  signIn({ email, password }, next, err) {
    axios.post(`${ROOT_URL}/auth/signin?${PARAMETERS()}`, { email, password })
    .then(response => {
      console.log(response.data.token)
      next(response.data.token, response.data.name);
    })
    .catch(response => {
      err(response.data)
    });
  }

  signUp({ email, password, name }, next, err) {
    axios.post(`${ROOT_URL}/auth/signup?${PARAMETERS()}`, { email, password, name })
    .then(response => {
      console.log(response.data.token)
      next(response.data.token, name);
    })
    .catch(response => err(response.data));
  }

  setAuthorizations(next, err) {
    axios.get(`${ROOT_URL}/api/actions?${PARAMETERS()}`, HEADERS())
    .then(response => {
      next(response.data)
    })
    .catch(response => {
      err(response.data)
    })
  }
}


text:
const { assert } = require('chai');
const { once } = require('events');
const sinon = require('sinon');
const Users = require('../../../../src');

const { nockCfApi, restoreCfApi } = require('../../../helpers/cloudflare/api-stub');

describe('#cloudflare access-list worker', () => {
  const Timeout = (setTimeout(() => {}, 0).unref()).constructor;
  const createService = (config) => {
    this.users = new Users(config);
  };

  beforeEach('start', () => {
    nockCfApi();
  });

  afterEach('stop', async () => {
    if (this.users) {
      await global.clearRedis.call(this, false);
    }
    restoreCfApi();
  });

  it('should set interval job', async () => {
    createService({
      cfAccessList: {
        enabled: true,
        worker: {
          enabled: true,
          cleanupInterval: 2000,
        },
      },
    });

    await this.users.connect();
    await this.users.cfAccessList.cfApi.createList('test_worker_test_list');

    const { cfWorker } = this.users;
    const startSpy = sinon.spy(cfWorker, 'start');
    assert(cfWorker.next instanceof Timeout);

    await once(cfWorker, 'done');
    await once(cfWorker, 'done');

    assert(startSpy.callCount === 2, 'should be called twice');
  });
});


text:
import com.webdriver.concrete.WebDriverType;
import com.webdriver.contracts.WebDriverFactory;
import com.webdriver.contracts.WebDriverWrapper;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;

import static org.junit.Assert.assertTrue;

public class WebdriverFactoryTest {

    @Test
    public void startDriverAndNavigate() {
        WebDriverWrapper wrapper = WebDriverFactory.getDriver(WebDriverType.CHROME);
        WebDriver driver = wrapper.getDriver();

        driver.get("http://google.com");
        Google google = PageFactory.initElements(driver, Google.class);
        assertTrue("Search Bar is missing", google.isSearchBarExists());
        wrapper.closeDriver();

    }

}


text:
package com.flowci.core.agent.event;

import com.flowci.core.agent.domain.AgentHost;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;

/**
 * Agent status change event
 */
@Getter
public class AgentHostStatusEvent extends ApplicationEvent {

    private final AgentHost host;

    public AgentHostStatusEvent(Object source, AgentHost host) {
        super(source);
        this.host = host;
    }
}


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

namespace FactoryMethod
{
    public abstract class Equipment
    {
        public string Name { get; protected set; }
    }
}