text:
<?php
$TRANSLATIONS = array(
"Invalid value supplied for %s" => "El valor proporcionat no és vàlid per %s",
"Saved" => "Desat",
"test email settings" => "prova l'arranjament del correu",
"If you received this email, the settings seem to be correct." => "Si rebeu aquest correu sembla que l'arranjament del correu és correcte.",
"A problem occurred while sending the e-mail. Please revisit your settings." => "Hi ha hagut un problema en enviar el correu. Comproveu-ne l'arranjament.",
"Email sent" => "El correu electrónic s'ha enviat",
"You need to set your user email before being able to send test emails." => "Heu d'establir un nom d'usuari abans de poder enviar correus de prova.",
"Send mode" => "Mode d'enviament",
"Encryption" => "Xifrat",
"Authentication method" => "Mètode d'autenticació",
"Unable to load list from App Store" => "No s'ha pogut carregar la llista des de l'App Store",
"Authentication error" => "Error d'autenticació",
"Your full name has been changed." => "El vostre nom complet ha canviat.",
"Unable to change full name" => "No s'ha pogut canviar el nom complet",
"Group already exists" => "El grup ja existeix",
"Unable to add group" => "No es pot afegir el grup",
"Files decrypted successfully" => "Els fitxers s'han desencriptat amb èxit",
"Couldn't decrypt your files, please check your owncloud.log or ask your administrator" => "No es poden desencriptar els fitxers. Comproveu owncloud.log o demaneu-ho a l'administrador.",
"Couldn't decrypt your files, check your password and try again" => "No s'han pogut desencriptar els fitxers, comproveu la contrasenya i proveu-ho de nou",
"Encryption keys deleted permanently" => "Les claus d'encriptació s'han esborrat permanentment",
"Couldn't permanently delete your encryption keys, please check your owncloud.log or ask your administrator" => "No es poden esborrar les claus d'encriptació. Comproveu owncloud.log o demaneu-ho a l'administrador.",
"Couldn't remove app." => "No s'ha pogut eliminar l'aplicació",
"Email saved" => "S'ha desat el correu electrònic",
"Invalid email" => "El correu electrònic no és vàlid",
"Unable to delete group" => "No es pot eliminar el grup",
"Unable to delete user" => "No es pot eliminar l'usuari",
"Backups restored successfully" => "Les còpies de seguretat s'han restablert correctament",
"Couldn't restore your encryption keys, please check your owncloud.log or ask your administrator" => "No es poden restablir les claus d'encriptació. Comproveu owncloud.log o demaneu-ho a l'administrador.",
"Language changed" => "S'ha canviat l'idioma",
"Invalid request" => "Sol·licitud no vàlida",
"Admins can't remove themself from the admin group" => "Els administradors no es poden eliminar del grup admin",
"Unable to add user to group %s" => "No es pot afegir l'usuari al grup %s",
"Unable to remove user from group %s" => "No es pot eliminar l'usuari del grup %s",
"Couldn't update app." => "No s'ha pogut actualitzar l'aplicació.",
"Wrong password" => "Contrasenya incorrecta",
"No user supplied" => "No heu proporcionat cap usuari",
"Please provide an admin recovery password, otherwise all user data will be lost" => "Sisplau, proporcioneu una contrasenya de recuperació d'administrador, altrament totes les dades d'usuari es perdran",
"Wrong admin recovery password. Please check the password and try again." => "La contrasenya de recuperació d'administrador és incorrecta. Comproveu-la i torneu-ho a intentar.",
"Back-end doesn't support password change, but the users encryption key was successfully updated." => "El dorsal no permet canviar la contrasenya, però la clau d'encripació d'usuaris s'ha actualitzat correctament.",
"Unable to change password" => "No es pot canviar la contrasenya",
"Sending..." => "Enviant...",
"User Documentation" => "Documentació d'usuari",
"Admin Documentation" => "Documentació d'administrador",
"Update to {appversion}" => "Actualitza a {appversion}",
"Uninstall App" => "Desinstal·la l'aplicació",
"Disable" => "Desactiva",
"Enable" => "Habilita",
"Please wait...." => "Espereu...",
"Error while disabling app" => "Error en desactivar l'aplicació",
"Error while enabling app" => "Error en activar l'aplicació",
"Updating...." => "Actualitzant...",
"Error while updating app" => "Error en actualitzar l'aplicació",
"Error" => "Error",
"Update" => "Actualitza",
"Updated" => "Actualitzada",
"Uninstalling ...." => "Desintal·lant ...",
"Error while uninstalling app" => "Error en desinstal·lar l'aplicació",
"Uninstall" => "Desinstal·la",
"Select a profile picture" => "Seleccioneu una imatge de perfil",
"Very weak password" => "Contrasenya massa feble",
"Weak password" => "Contrasenya feble",
"So-so password" => "Contrasenya passable",
"Good password" => "Contrasenya bona",
"Strong password" => "Contrasenya forta",
"Decrypting files... Please wait, this can take some time." => "Desencriptant fitxers... Espereu, això pot trigar una estona.",
"Delete encryption keys permanently." => "Esborra les claus d'encriptació permanentment.",
"Restore encryption keys." => "Esborra les claus d'encripació.",
"Unable to delete {objName}" => "No es pot eliminar {objName}",
"Error creating group" => "Error en crear el grup",
"A valid group name must be provided" => "Heu de facilitar un nom de grup vàlid",
"deleted {groupName}" => "eliminat {groupName}",
"undo" => "desfés",
"Groups" => "Grups",
"Group Admin" => "Grup Admin",
"Delete" => "Esborra",
"never" => "mai",
"deleted {userName}" => "eliminat {userName}",
"add group" => "afegeix grup",
"A valid username must be provided" => "Heu de facilitar un nom d'usuari vàlid",
"Error creating user" => "Error en crear l'usuari",
"A valid password must be provided" => "Heu de facilitar una contrasenya vàlida",
"Warning: Home directory for user \"{user}\" already exists" => "Avís: la carpeta Home per l'usuari \"{user}\" ja existeix",
"__language_name__" => "Català",
"Everything (fatal issues, errors, warnings, info, debug)" => "Tot (problemes fatals, errors, avisos, informació, depuració)",
"Info, warnings, errors and fatal issues" => "Informació, avisos, errors i problemes fatals",
"Warnings, errors and fatal issues" => "Avisos, errors i problemes fatals",
"Errors and fatal issues" => "Errors i problemes fatals",
"Fatal issues only" => "Només problemes fatals",
"None" => "Cap",
"Login" => "Inici de sessió",
"Plain" => "Pla",
"NT LAN Manager" => "Gestor NT LAN",
"SSL" => "SSL",
"TLS" => "TLS",
"Security Warning" => "Avís de seguretat",
"You are accessing %s via HTTP. We strongly suggest you configure your server to require using HTTPS instead." => "Esteu accedint %s a través de HTTP. Us recomanem fermament que configureu el servidor perquè requereixi HTTPS.",
"Your data directory and your files are probably accessible from the internet. The .htaccess file is not working. We strongly suggest that you configure your webserver in a way that the data directory is no longer accessible or you move the data directory outside the webserver document root." => "La carpeta de dades i els vostres fitxersprobablement són accessibles des d'Internet. La fitxer .htaccess no funciona. Us recomanem que configureu el servidor web de tal manera que la carpeta de dades no sigui accessible o que moveu la carpeta de dades fora de l'arrel de documents del servidor web.",
"Setup Warning" => "Avís de configuració",
"Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken." => "El servidor web no està configurat correctament per permetre la sincronització de fitxers perquè la interfície WebDAV sembla no funcionar correctament.",
"Please double check the installation guides." => "Comproveu les guies d'instal·lació.",
"PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." => "Aparentment PHP està configurat per mostrar blocs en línia de documentació. Això farà que algunes aplicacions core siguin inaccessibles.",
"This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." => "Això probablement està provocat per una cau/accelerador com Zend OPcache o eAccelerator.",
"Database Performance Info" => "Informació del rendiment de la base de dades",
"SQLite is used as database. For larger installations we recommend to change this. To migrate to another database use the command line tool: 'occ db:convert-type'" => "S'utilitza SQLite com a base de dades. Per instal·lacions grans recomanem que la canvieu. per migrar a una altra base de dades useu l'eina d'intèrpret d'ordres 'occ db:convert-type'",
"Module 'fileinfo' missing" => "No s'ha trobat el mòdul 'fileinfo'",
"The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." => "El mòdul de PHP 'fileinfo' no s'ha trobat. Us recomanem que habiliteu aquest mòdul per obtenir millors resultats amb la detecció mime-type.",
"Your PHP version is outdated" => "La versió de PHP és obsoleta",
"Your PHP version is outdated. We strongly recommend to update to 5.3.8 or newer because older versions are known to be broken. It is possible that this installation is not working correctly." => "La versió de PHP és obsoleta. Us recomanem fermament que actualitzeu a la versió 5.3.8 o superior perquè les versions anteriors no funcionen. La instal·lació podria no funcionar correctament.",
"Locale not working" => "Locale no funciona",
"System locale can not be set to a one which supports UTF-8." => "No s'ha pogut establir cap localització del sistema amb suport per UTF-8.",
"This means that there might be problems with certain characters in file names." => "Això podria comportar problemes amb alguns caràcters en els noms dels fitxer.",
"We strongly suggest to install the required packages on your system to support one of the following locales: %s." => "Us recomanem que instal·leu els paquets necessaris en el sistema per donar suport a alguna de les localitzacions següents: %s",
"Internet connection not working" => "La connexió a internet no funciona",
"This server has no working internet connection. This means that some of the features like mounting of external storage, notifications about updates or installation of 3rd party apps don´t work. Accessing files from remote and sending of notification emails might also not work. We suggest to enable internet connection for this server if you want to have all features." => "Aquest servidor no té cap connexió a internet que funcioni. Això significa que algunes de les característiques com el muntatge d'emmagatzemament extern, les notificacions quant a actualitzacions o la instal·lació d'aplicacions de tercers no funcionarà. L'accés remot a fitxers i l'enviament de correus electrònics podria tampoc no funcionar. Us suggerim que habiliteu la connexió a internet per aquest servidor si voleu tenir totes les característiques.",
"Cron" => "Cron",
"Last cron was executed at %s." => "L'últim cron s'ha executat el %s",
"Last cron was executed at %s. This is more than an hour ago, something seems wrong." => "L'últim cron es va executar a %s. Fa més d'una hora, alguna cosa sembla que va malament.",
"Cron was not executed yet!" => "El cron encara no s'ha executat!",
"Execute one task with each page loaded" => "Executa una tasca per cada paquet carregat",
"cron.php is registered at a webcron service to call cron.php every 15 minutes over http." => "cron.php està registrat en un servei webcron que fa una crida a cron.php cada 15 minuts a través de http.",
"Use system's cron service to call the cron.php file every 15 minutes." => "Utilitza el servei cron del sistema per fer una crida al fitxer cron.php cada 15 minuts.",
"Sharing" => "Compartir",
"Allow apps to use the Share API" => "Permet que les aplicacions utilitzin l'API de compartir",
"Allow users to share via link" => "Permet als usuaris compartir a través d'enllaços",
"Enforce password protection" => "Reforça la protecció amb contrasenya",
"Allow public uploads" => "Permet pujada pública",
"Set default expiration date" => "Estableix la data de venciment",
"Expire after " => "Venciment després de",
"days" => "dies",
"Enforce expiration date" => "Força la data de venciment",
"Allow resharing" => "Permet compartir de nou",
"Restrict users to only share with users in their groups" => "Permet als usuaris compartir només amb usuaris del seu grup",
"Allow users to send mail notification for shared files" => "Permet als usuaris enviar notificacions de fitxers compartits per correu ",
"Exclude groups from sharing" => "Exclou grups de compartició",
"These groups will still be able to receive shares, but not to initiate them." => "Aquests fitxers encara podran rebre compartits, però no podran iniciar-los.",
"Security" => "Seguretat",
"Enforce HTTPS" => "Força HTTPS",
"Forces the clients to connect to %s via an encrypted connection." => "Força la connexió dels clients a %s a través d'una connexió encriptada.",
"Please connect to your %s via HTTPS to enable or disable the SSL enforcement." => "Connecteu a %s a través de HTTPS per habilitar o inhabilitar l'accés SSL.",
"Email Server" => "Servidor de correu",
"This is used for sending out notifications." => "S'usa per enviar notificacions.",
"From address" => "Des de l'adreça",
"mail" => "correu electrònic",
"Authentication required" => "Es requereix autenticació",
"Server address" => "Adreça del servidor",
"Port" => "Port",
"Credentials" => "Credencials",
"SMTP Username" => "Nom d'usuari SMTP",
"SMTP Password" => "Contrasenya SMTP",
"Test email settings" => "Prova l'arranjament del correu",
"Send email" => "Envia correu",
"Log" => "Registre",
"Log level" => "Nivell de registre",
"More" => "Més",
"Less" => "Menys",
"Version" => "Versió",
"Developed by the ownCloud community, the source code is licensed under the AGPL." => "Desenvolupat per la comunitat ownCloud, el codi font té llicència AGPL.",
"Add your App" => "Afegiu la vostra aplicació",
"More Apps" => "Més aplicacions",
"Select an App" => "Seleccioneu una aplicació",
"Documentation:" => "Documentació:",
"See application page at apps.owncloud.com" => "Mireu la pàgina d'aplicacions a apps.owncloud.com",
"See application website" => "Mostra la web de l'aplicació",
"-licensed by " => "-propietat de ",
"Enable only for specific groups" => "Activa només per grups específics",
"All" => "Tots",
"Administrator Documentation" => "Documentació d'administrador",
"Online Documentation" => "Documentació en línia",
"Forum" => "Fòrum",
"Bugtracker" => "Seguiment d'errors",
"Commercial Support" => "Suport comercial",
"Get the apps to sync your files" => "Obtingueu les aplicacions per sincronitzar els vostres fitxers",
"Show First Run Wizard again" => "Torna a mostrar l'assistent de primera execució",
"You have used %s of the available %s" => "Heu utilitzat %s d'un total disponible de %s",
"Password" => "Contrasenya",
"Your password was changed" => "La seva contrasenya s'ha canviat",
"Unable to change your password" => "No s'ha pogut canviar la contrasenya",
"Current password" => "Contrasenya actual",
"New password" => "Contrasenya nova",
"Change password" => "Canvia la contrasenya",
"Full Name" => "Nom complet",
"Email" => "Correu electrònic",
"Your email address" => "Correu electrònic",
"Fill in an email address to enable password recovery and receive notifications" => "Ompliu una adreça de correu per poder recuperar la contrasenya i rebre notificacions",
"Profile picture" => "Foto de perfil",
"Upload new" => "Puja'n una de nova",
"Select new from Files" => "Selecciona'n una de nova dels fitxers",
"Remove image" => "Elimina imatge",
"Either png or jpg. Ideally square but you will be able to crop it." => "Pot ser png o jpg. Idealment quadrada, però podreu retallar-la.",
"Your avatar is provided by your original account." => "El vostre compte original proporciona l'avatar.",
"Cancel" => "Cancel·la",
"Choose as profile image" => "Selecciona com a imatge de perfil",
"Language" => "Idioma",
"Help translate" => "Ajudeu-nos amb la traducció",
"The encryption app is no longer enabled, please decrypt all your files" => "L'aplicació d'encriptació ja no està activada, desencripteu tots els vostres fitxers",
"Log-in password" => "Contrasenya d'accés",
"Decrypt all Files" => "Desencripta tots els fitxers",
"Your encryption keys are moved to a backup location. If something went wrong you can restore the keys. Only delete them permanently if you are sure that all files are decrypted correctly." => "Les claus d'encriptació s'han mogut a una còpia de seguretat. Si alguna cosa va malament les podreu restablir. Esborreu-les permanentment només si esteu segur que tots els fitxers es desencripten correctament.",
"Restore Encryption Keys" => "Restableix les claus d'encriptació",
"Delete Encryption Keys" => "Esborra les claus d'encriptació",
"Login Name" => "Nom d'accés",
"Create" => "Crea",
"Admin Recovery Password" => "Recuperació de contrasenya d'administrador",
"Enter the recovery password in order to recover the users files during password change" => "Escriviu la contrasenya de recuperació per a poder recuperar els fitxers dels usuaris en canviar la contrasenya",
"Search Users and Groups" => "Cerca usuaris i grups",
"Add Group" => "Afegeix grup",
"Group" => "Grup",
"Everyone" => "Tothom",
"Admins" => "Administradors",
"Default Quota" => "Quota per defecte",
"Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" => "Escriviu la quota d'emmagatzemament (per ex.: \"512 MB\" o \"12 GB\")",
"Unlimited" => "Il·limitat",
"Other" => "Un altre",
"Username" => "Nom d'usuari",
"Quota" => "Quota",
"Storage Location" => "Ubicació de l'emmagatzemament",
"Last Login" => "Últim accés",
"change full name" => "canvia el nom complet",
"set new password" => "estableix nova contrasenya",
"Default" => "Per defecte"
);
$PLURAL_FORMS = "nplurals=2; plural=(n != 1);";


text:
@implementation CIExhibition (Helpers)

+ (NSString*)entityName {
    return NSStringFromClass(self);
}

+ (CIExhibition*)findFirstOrCreateByAttribute:(NSString*)attribute withValue:(id)value usingData:(NSDictionary*)data {
    CIExhibition *exhibition = [CIExhibition MR_findFirstByAttribute:attribute withValue:value];
    if (exhibition == nil) {
        exhibition = [CIExhibition MR_createEntity];
        // Reset download status for new objects
        exhibition.bgDownloaded = @NO;
    } else {
        // If either of the dates is different, reset download status
        NSDate *iphoneUpdatedAt = [CIData dateValueOrNilForKey:@"bg_iphone_updated_at" data:data];
        NSDate *ipadUpdatedAt = [CIData dateValueOrNilForKey:@"bg_ipad_updated_at" data:data];
        if (([exhibition.bgIphoneUpdatedAt compare:iphoneUpdatedAt] != NSOrderedSame) ||
            ([exhibition.bgIpadUpdatedAt compare:ipadUpdatedAt] != NSOrderedSame)) {
            // Reset download status for new objects
            exhibition.bgDownloaded = @NO;
        }
    }

    // Parse the rest of the data and update the model object
    exhibition.uuid = [data objectForKey:@"uuid"];
    exhibition.createdAt = [CIData dateValueOrNilForKey:@"created_at" data:data];
    exhibition.updatedAt = [CIData dateValueOrNilForKey:@"updated_at" data:data];
    exhibition.deletedAt = [CIData dateValueOrNilForKey:@"deleted_at" data:data];

    exhibition.title = [CIData objValueOrNilForKey:@"title" data:data];
    exhibition.subtitle = [CIData objValueOrNilForKey:@"subtitle" data:data];
    exhibition.sponsor = [CIData objValueOrNilForKey:@"sponsor" data:data];
    exhibition.isLive = [CIData objValueOrNilForKey:@"is_live" data:data];
    exhibition.position = [CIData objValueOrNilForKey:@"position" data:data];

    exhibition.bgIphoneNormal = [CIData objValueOrNilForKey:@"bg_iphone_normal" data:data];
    exhibition.bgIphoneRetina = [CIData objValueOrNilForKey:@"bg_iphone_retina" data:data];
    exhibition.bgIphoneUpdatedAt = [CIData dateValueOrNilForKey:@"bg_iphone_updated_at" data:data];
    exhibition.bgIphoneFileSize = [CIData objValueOrNilForKey:@"bg_iphone_file_size" data:data];
    exhibition.bgIpadNormal = [CIData objValueOrNilForKey:@"bg_ipad_normal" data:data];
    exhibition.bgIpadRetina = [CIData objValueOrNilForKey:@"bg_ipad_retina" data:data];
    exhibition.bgIpadUpdatedAt = [CIData dateValueOrNilForKey:@"bg_ipad_updated_at" data:data];
    exhibition.bgIpadFileSize = [CIData objValueOrNilForKey:@"bg_ipad_file_size" data:data];

    // Mark as 'not changed'
    exhibition.syncStatus = [NSNumber numberWithInteger:CISyncStatusNotChanged];

    return exhibition;
}

+ (NSArray *)liveExhibitionUuids {
    NSMutableArray *liveExhibitionsUUIDs = [[NSMutableArray alloc] init];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deletedAt = nil) AND (isLive = YES)"];

    for (CIExhibition *exhibition in [CIExhibition MR_findAllWithPredicate:predicate]) {
        [liveExhibitionsUUIDs addObject:exhibition.uuid];
    }

    return liveExhibitionsUUIDs;
}

+ (CIExhibition*)randomLiveExhibition {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deletedAt = nil) AND (isLive = YES)"];
    NSArray *exhibitions = [CIExhibition MR_findAllSortedBy:@"position" ascending:YES withPredicate:predicate];

    NSUInteger totalExhibitions = [exhibitions count];

    if (totalExhibitions == 0) {
        return nil;
    }

    NSUInteger randomNumber = arc4random() % totalExhibitions;

    return [exhibitions objectAtIndex:randomNumber];
}

- (NSDictionary*)toDictionary {
    return @{
             @"uuid" : self.uuid,
             @"created_at" : [CIData dateOrNSNull:self.createdAt],
             @"updated_at" : [CIData dateOrNSNull:self.updatedAt],
             @"deleted_at" : [CIData dateOrNSNull:self.deletedAt],

             @"title" : [CIData objOrNSNull:self.title],
             @"subtitle" : [CIData objOrNSNull:self.subtitle],
             @"sponsor" : [CIData objOrNSNull:self.sponsor],
             @"is_live" : [CIData objOrNSNull:self.isLive],
             @"position" : [CIData objOrNSNull:self.position],

             @"bg_iphone_normal" : [CIData objOrNSNull:self.bgIphoneNormal],
             @"bg_iphone_retina" : [CIData objOrNSNull:self.bgIphoneRetina],
             @"bg_iphone_updated_at" : [CIData dateOrNSNull:self.bgIphoneUpdatedAt],
             @"bg_iphone_file_size" : [CIData objOrNSNull:self.bgIphoneFileSize],
             @"bg_ipad_normal" : [CIData objOrNSNull:self.bgIpadNormal],
             @"bg_ipad_retina" : [CIData objOrNSNull:self.bgIpadRetina],
             @"bg_ipad_updated_at" : [CIData dateOrNSNull:self.bgIpadUpdatedAt],
             @"bg_ipad_file_size" : [CIData objOrNSNull:self.bgIpadFileSize]
             };
}

#pragma mark - Paths

- (NSString*)getDirectoryPath {
    // Local path structure: /Documents/Exhibitions/:uuid
    NSString *documentDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *path = [[documentDirectory stringByAppendingPathComponent:@"Media"] stringByAppendingPathComponent:self.uuid];
    return path;
}

- (NSString*)getBackgroundFilePath {
    // Local path structure: /Documents/Exhibitions/:uuid/bg.png (or bg@2x.png)
    NSString *fileName;
    if (IS_RETINA) {
        fileName = @"bg@2x.png";
    } else {
        fileName = @"bg.png";
    }
    NSString *documentDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *path = [[[documentDirectory stringByAppendingPathComponent:@"Media"]
                      stringByAppendingPathComponent:self.uuid]
                      stringByAppendingPathComponent:fileName];
    return path;
}

- (NSString*)getBlurredBackgroundFilePath {
    // Local path structure: /Documents/Exhibitions/:uuid/bg_blur.png (or bg_blur@2x.png)
    NSString *fileName;
    if (IS_RETINA) {
        fileName = @"bg_blur@2x.png";
    } else {
        fileName = @"bg_blur.png";
    }
    NSString *documentDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *path = [[[documentDirectory stringByAppendingPathComponent:@"Media"]
                       stringByAppendingPathComponent:self.uuid]
                      stringByAppendingPathComponent:fileName];
    return path;
}

#pragma mark - Relationships

- (NSArray*)artists {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deletedAt = nil) AND (exhibitionUuid == %@)", self.uuid];
    NSArray *artists = [CIArtist MR_findAllWithPredicate:predicate];

    // Return results sorted
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];
    return [artists sortedArrayUsingDescriptors:@[sort]];
}

- (NSArray*)artistArtworks {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deletedAt = nil) AND (exhibitionUuid == %@)", self.uuid];
    return [CIArtistArtwork MR_findAllWithPredicate:predicate];
}

- (NSArray*)artworks {
    // Default sorting by code
    return [self artworksSortedBy:@"code" ascending:YES];
}

- (NSArray*)artworksSortedBy:(NSString *)sortedBy ascending:(BOOL)ascending {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deletedAt = nil) AND (exhibitionUuid == %@)", self.uuid];
    return [CIArtwork MR_findAllSortedBy:sortedBy ascending:ascending withPredicate:predicate];
}

- (NSArray*)media {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deletedAt = nil) AND (exhibitionUuid == %@)", self.uuid];
    return [CIMedium MR_findAllWithPredicate:predicate];
}

- (NSArray*)tours {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deletedAt = nil) AND (exhibitionUuid == %@)", self.uuid];
    NSArray *tours = [CITour MR_findAllWithPredicate:predicate];

    // Return results sorted
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
    return [tours sortedArrayUsingDescriptors:@[sort]];
}

- (NSArray*)tourArtworks {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deletedAt = nil) AND (exhibitionUuid == %@)", self.uuid];
    return [CITourArtwork MR_findAllWithPredicate:predicate];
}

@end

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Ivesia unguiculata Gray

### Remarks
null


text:
#import <Foundation/Foundation.h>

#import "UAInbox.h"

@interface UAInboxDefaultJSDelegate : NSObject <UAInboxJavaScriptDelegate> {

}

@end


text:
var express = require('express');
var util = require('util');
var es = require('event-stream');
var BaucisError = require('../../BaucisError');

// __Private Module Members__
var validOperators = [ '$set', '$push', '$pull' ];

// __Module Definition__
var decorator = module.exports = function (options, protect) {
  var controller = this;

  function checkBadUpdateOperatorPaths (operator, paths) {
    var bad = false;
    var whitelisted = controller.operators(operator);
    var parts;

    if (!whitelisted) return true;

    parts = whitelisted.split(/\s+/);

    paths.forEach(function (path) {
      if (parts.indexOf(path) !== -1) return;
      bad = true;
    });

    return bad;
  }

  // If there's a body, send it through any user-added streams.
  controller.query('instance', 'put', function (request, response, next) {
    var parser;
    var count = 0;
    var operator = request.headers['x-baucis-update-operator'];
    var versionKey = controller.schema().get('versionKey');
    var pipeline = protect.pipeline();
    // Check if the body was parsed by some external middleware e.g. `express.json`.
    // If so, create a one-document stream from the parsed body.
    if (request.body) {
      pipeline(es.readArray([ request.body ]));
    }
    // Otherwise, stream and parse the request.
    else {
      parser = request.baucis.api.parser(request.get('content-type'));
      if (!parser) return next(BaucisError.UnsupportedMediaType());
      pipeline(request);
      pipeline(parser);
    }
    // Set up the stream context.
    pipeline(function (body, callback) {
      var context = { doc: undefined, incoming: body };
      callback(null, context);
    });
    // Load the Mongoose document and add it to the context, unless this is a
    // special update operator.
    if (!operator) {
      pipeline(function (context, callback) {
        var query = controller.model().findOne(request.baucis.conditions);
        query.exec(function (error, doc) {
          if (error) return callback(error);
          if (!doc) return callback(BaucisError.NotFound());
          // Add the Mongoose document to the context.
          callback(null, { doc: doc, incoming: context.incoming });
        });
      });
    }
    // Pipe through user streams, if any.
    pipeline(request.baucis.incoming());
    // If the document ID is present, ensure it matches the ID in the URL.
    pipeline(function (context, callback) {
      var bodyId = context.incoming[controller.findBy()];
      if (bodyId === undefined) return callback(null, context);
      if (bodyId === request.params.id) return callback(null, context);
      callback(BaucisError.BadRequest("The ID of the update document did not match the URL's document ID"));
    });
    // Ensure the request includes a finite object version if locking is enabled.
    if (controller.locking()) {
      pipeline(function (context, callback) {
        var updateVersion = context.incoming[versionKey];
        if (updateVersion === undefined || !Number.isFinite(Number(updateVersion))) {
          return callback(BaucisError.BadRequest('Locking is enabled, so the target version must be provided in the request body using path "%s"', versionKey));
        }
        callback(null, context);
      });
      // Add some locking checks only applicable to the default update operator.
      if (!operator) {
        // Make sure the version key was selected.
        pipeline(function (context, callback) {
          if (!context.doc.isSelected(versionKey)) {
            callback(BaucisError.BadRequest('The version key "%s" must be selected', versionKey));
            return;
          }
          // Pass through.
          callback(null, context);
        });
        pipeline(function (context, callback) {
          var updateVersion = Number(context.incoming[versionKey]);
          // Update and current version have been found.  Check if they're equal.
          if (updateVersion !== context.doc[versionKey]) return callback(BaucisError.LockConflict());
          // One is not allowed to set __v and increment in the same update.
          delete context.incoming[versionKey];
          context.doc.increment();
          // Pass through.
          callback(null, context);
        });
      }
    }
    // Ensure there is exactly one update document.
    pipeline(es.through(
      function (context) {
        count += 1;
        if (count === 2) {
          next(BaucisError.BadRequest('The request body contained more than one update document'));
          return;
        }
        if (count > 1) return;

        this.emit('data', context);
      },
      function () {
        if (count === 0) {
          next(BaucisError.BadRequest('The request body did not contain an update document'));
        }
        this.emit('end');
      }
    ));
    // Finish up for the default update operator.
    if (!operator) {
      // Update the Mongoose document with the request body.
      pipeline(function (context, callback) {
        context.doc.set(context.incoming);
        // Pass through.
        callback(null, context);
      });
      // Save the Mongoose document.
      pipeline(function (context, callback) { context.doc.save(callback); });
    }
    // Finish up for a non-default update operator (bypasses validation).
    else {
      pipeline(function (context, callback) {
        var wrapper = {};

        if (validOperators.indexOf(operator) === -1) {
          callback(BaucisError.BadRequest('The requested update operator "%s" is not supported', operator));
          return;
        }
        // Ensure that some paths have been enabled for the operator.
        if (!controller.operators(operator)) {
          callback(BaucisError.Forbidden('The requested update operator "%s" is not enabled for this resource', operator));
          return;
        }
        // Make sure paths have been whitelisted for this operator.
        if (checkBadUpdateOperatorPaths(operator, Object.keys(context.incoming))) {
          callback(BaucisError.Forbidden('This update path is forbidden for the requested update operator "%s"', operator));
          return;
        }

        wrapper[operator] = context.incoming;
        if (controller.locking()) {
          request.baucis.conditions[versionKey] = Number(context.incoming[versionKey]);
        }
        // Update the doc using the supplied operator and bypassing validation.
        controller.model().update(request.baucis.conditions, wrapper, callback);
      });
    }

    var s = pipeline();
    s.on('end', next);
    s.on('error', next);
    s.resume();
  });
};


text:
import { A } from "mod";
const x: typeof A = 0;


text:
[assembly: Elmah.Scc("$Id: ComparisonResults.cs 566 2009-05-11 10:37:10Z azizatif $")]

namespace Elmah.Assertions
{
    #region Import

    using System;

    #endregion

    public delegate bool ComparisonResultPredicate(int result);

    public sealed class ComparisonResults
    {
        public readonly static ComparisonResultPredicate Equal = new ComparisonResultPredicate(MeansEqual);
        public readonly static ComparisonResultPredicate Lesser = new ComparisonResultPredicate(MeansLesser);
        public readonly static ComparisonResultPredicate LesserOrEqual = new ComparisonResultPredicate(MeansLessOrEqual);
        public readonly static ComparisonResultPredicate Greater = new ComparisonResultPredicate(MeansGreater);
        public readonly static ComparisonResultPredicate GreaterOrEqual = new ComparisonResultPredicate(MeansGreaterOrEqual);

        private static bool MeansEqual(int result) { return result == 0; }
        private static bool MeansLesser(int result) { return result < 0; }
        private static bool MeansLessOrEqual(int result) { return result <= 0; }
        private static bool MeansGreater(int result) { return result > 0; }
        private static bool MeansGreaterOrEqual(int result) { return result >= 0; }

        private ComparisonResults()
        {
            throw new NotSupportedException();
        }
    }
}


text:
<?php

namespace Spf\Shift\Repositories;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Laracasts\Flash\Flash;
use Spf\Shift\Entities\Missing;
use Spf\User;

class MissingRepository extends BaseRepo
{
    /**
     * @return Missing
     */
    public function getModel()
    {
        return new Missing();
    }

    /**
     * Create missing
     *
     * @param $request
     * @return mixed
     */
    public function createMissing($request)
    {
        $missing = new Missing();

        $fileName = $this->setNamePhoto($request->photo);

        $missing->fill($request->all());
        $missing->status = 'desaparecido';
        $missing->photo  = $fileName;

        $findUser = User::where('email', '=', $request->email)->first();

        if($findUser) {
            $user = $findUser;
        } else {
            $user            = new User();
            $user->name      = $request->name;
            $user->last_name = $request->last_nameR;
            $user->email     = $request->email;
            $user->phone     = $request->phone;
            $user->policy    = 1;
        }

        $user->save();
        $user->missings()->save($missing);

        return Flash::success('El registro se creó correctamente!');
    }

    /**
     * Get missing person by id
     *
     * @param $id
     * @return mixed
     */
    public function getMissing($id)
    {
        return Missing::with('user')->findOrFail($id);
    }

    /**
     * Update missing person
     *
     * @param $request
     * @param $id
     * @return mixed
     */
    public function updateMissing($request, $id)
    {
        $findUser = User::where('email', '=', $request->email)->first();

        if($findUser) {
            $missing = Missing::findOrFail($id);

            $fileName = $this->setNamePhoto($request->photo);

            $missing->fill($request->all());
            $missing->photo  = $fileName;

            $user = $findUser;

            $user->save();
            $user->missings()->save($missing);

            return Flash::success('El registro se actualizó correctamente!');
        } else {
            return Flash::error('El registro no se puedo actualizar ya que tu no eres el creador del registro');
        }

    }

    /**
     * @param $photoRequest
     * @return string
     */
    public function setNamePhoto($photoRequest) {

        if ($photoRequest) {
            $photo     = $photoRequest;
            $path = public_path() . '/uploads';
            $extension = $photo->getClientOriginalExtension();
            $fileName  = time() . '-' . rand(100, 10000) . '.' . $extension;

            $photo= Image::make($photo->getRealPath())->resize('150','150')->save($path . '/' . $fileName);

            //Storage::disk('local')->put($fileName, File::get($photo));
        } else {
            $fileName = 'avatar.jpg';
        }

        return 'uploads/'. $fileName;
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles, Theme } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Typography from '@material-ui/core/Typography';

interface TabContainerProps {
  children?: React.ReactNode;
}

function TabContainer(props: TabContainerProps) {
  return (
    <Typography component="div" style={{ padding: 8 * 3 }}>
      {props.children}
    </Typography>
  );
}

TabContainer.propTypes = {
  children: PropTypes.node.isRequired,
};

interface LinkTabProps {
  label?: string;
  href?: string;
}

function LinkTab(props: LinkTabProps) {
  return (
    <Tab
      component="a"
      onClick={(event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
        event.preventDefault();
      }}
      {...props}
    />
  );
}

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper,
  },
}));

function NavTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  function handleChange(event: React.ChangeEvent<{}>, newValue: number) {
    setValue(newValue);
  }

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Tabs variant="fullWidth" value={value} onChange={handleChange}>
          <LinkTab label="Page One" href="/drafts" />
          <LinkTab label="Page Two" href="/trash" />
          <LinkTab label="Page Three" href="/spam" />
        </Tabs>
      </AppBar>
      {value === 0 && <TabContainer>Page One</TabContainer>}
      {value === 1 && <TabContainer>Page Two</TabContainer>}
      {value === 2 && <TabContainer>Page Three</TabContainer>}
    </div>
  );
}

export default NavTabs;


text:
package org.bridje.web.view.controls;

import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.bridje.el.ElEnvironment;
import org.bridje.ioc.thls.Thls;

/**
 * The data for the events of the control that can be render in a WebView.
 */
@XmlTransient
@XmlJavaTypeAdapter(UIEventAdapter.class)
public class UIEvent
{
    private final String expression;

    private final String parameter;

    UIEvent(String expression)
    {
        this.expression = expression;
        parameter = "__ev." + ParamsContext.createParam(expression);
    }

    /**
     * Gets the event´s expression.
     *
     * @return The event´s expression.
     */
    public String getExpression()
    {
        return expression;
    }

    /**
     * The parameter for the event.
     *
     * @return The parameter for the event.
     */
    public String getParameter()
    {
        return parameter;
    }

    /**
     * Invokes the method defined by this event.
     *
     * @return The object returned when invoking the method of the event.
     */
    public Object invoke()
    {
        return Thls.get(ElEnvironment.class).get("${" + expression + "}", Object.class);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>glm::gtx::vector_access Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Modules

Namespaces

Classes

Files

Namespace List

Namespace Members

glm

gtx

vector_access

Functions

glm::gtx::vector_access Namespace Reference

GLM_GTX_vector_access extension: Function to set values to vectors.
More...

Functions

template<typename valType >

void 	set (detail::tvec2< valType > &v, valType const &x, valType const &y)

 	Set values to a 2 components vector.

template<typename valType >

void 	set (detail::tvec4< valType > &v, valType const &x, valType const &y, valType const &z, valType const &w)

 	Set values to a 4 components vector.

template<typename valType >

void 	set (detail::tvec3< valType > &v, valType const &x, valType const &y, valType const &z)

 	Set values to a 3 components vector.

Detailed Description

GLM_GTX_vector_access extension: Function to set values to vectors.

<address class="footer">Generated by

 1.7.3 </address>


text:
using namespace ouro::windows;

namespace ouro { namespace gui {

mru::mru(const info& _Info)
	: Info(_Info)
	, NumMRUs(_Info.last_id-_Info.first_id+1)
{
	if (_Info.prefix.empty())
		oThrow(std::errc::invalid_argument, "A prefix must be specified");
	if (0 > snprintf(KeyFormat, "%s%%02d", _Info.prefix))
		oThrow(std::errc::invalid_argument, "the prefix is too long");
}

sstring mru::entry_name(int _Index)
{
	sstring n;
	snprintf(n, n.capacity(), "MRU%02d", _Index);
	return n;
}

void mru::get_entries(std::vector<uri_string>& _Entries)
{
	uri_string Entry;
	_Entries.clear();
	_Entries.reserve(NumMRUs);
	for (int i = 0; i < NumMRUs; i++)
	{
		sstring EntryName = entry_name(i);
		registry::get(Entry, registry::hkey::current_user, Info.registry_key, EntryName);
		_Entries.push_back(Entry);
	}
}

void mru::add(const char* _Entry)
{
	sstring EntryName;
	std::vector<uri_string> Entries;
	get_entries(Entries);

	// Remove any duplicates of the incoming URI
	auto it = std::find_if(Entries.begin(), Entries.end(), [&](const uri_string& x)->bool { return !_stricmp(x, _Entry); });
	while (it != Entries.end())
	{
		Entries.erase(it);
		it = std::find_if(Entries.begin(), Entries.end(), [&](const uri_string& x)->bool { return !_stricmp(x, _Entry); });
	}

	// Insert this as the front of the list
	Entries.insert(Entries.begin(), _Entry);

	// Write the list back out
	int i = 0;
	const int n = (int)Entries.size();
	for (; i < n; i++)
		registry::set(registry::hkey::current_user, Info.registry_key, entry_name(i), Entries[i]);

	// and delete any extra stale entries that remain as a result of the Entries
	// list getting shorter
	const int NumIDs = Info.last_id-Info.first_id+1;
	for (; i < NumMRUs; i++)
		registry::delete_value(registry::hkey::current_user, Info.registry_key, entry_name(i));

	refresh();
}

char* mru::get(char* _StrDestination, size_t _SizeofStrDestination, int _ID)
{
	if (_ID >= Info.first_id && _ID <= Info.last_id)
		return registry::get(_StrDestination, _SizeofStrDestination, registry::hkey::current_user, Info.registry_key, entry_name(_ID - Info.first_id));
	return nullptr;
}

void mru::refresh()
{
	menu::remove_all(Info.menu);
	uri_string Entry;
	for (int i = 0; i < NumMRUs; i++)
	{
		registry::get(Entry, registry::hkey::current_user, Info.registry_key, entry_name(i));
		menu::append_item(Info.menu, Info.first_id + i, Entry);
	}
}

}}


text:
"""The tests for the demo light component."""
# pylint: disable=protected-access
import unittest

from homeassistant.setup import setup_component
import homeassistant.components.light as light

from tests.common import get_test_home_assistant

ENTITY_LIGHT = 'light.bed_light'

class TestDemoLight(unittest.TestCase):
    """Test the demo light."""

    # pylint: disable=invalid-name
    def setUp(self):
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        self.assertTrue(setup_component(self.hass, light.DOMAIN, {'light': {
            'platform': 'demo',
        }}))

    # pylint: disable=invalid-name
    def tearDown(self):
        """Stop down everything that was started."""
        self.hass.stop()

    def test_state_attributes(self):
        """Test light state attributes."""
        light.turn_on(
            self.hass, ENTITY_LIGHT, xy_color=(.4, .6), brightness=25)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_LIGHT)
        self.assertTrue(light.is_on(self.hass, ENTITY_LIGHT))
        self.assertEqual((.4, .6), state.attributes.get(light.ATTR_XY_COLOR))
        self.assertEqual(25, state.attributes.get(light.ATTR_BRIGHTNESS))
        self.assertEqual(
            (76, 95, 0), state.attributes.get(light.ATTR_RGB_COLOR))
        self.assertEqual('rainbow', state.attributes.get(light.ATTR_EFFECT))
        light.turn_on(
            self.hass, ENTITY_LIGHT, rgb_color=(251, 252, 253),
            white_value=254)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_LIGHT)
        self.assertEqual(254, state.attributes.get(light.ATTR_WHITE_VALUE))
        self.assertEqual(
            (251, 252, 253), state.attributes.get(light.ATTR_RGB_COLOR))
        light.turn_on(self.hass, ENTITY_LIGHT, color_temp=400, effect='none')
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_LIGHT)
        self.assertEqual(400, state.attributes.get(light.ATTR_COLOR_TEMP))
        self.assertEqual(154, state.attributes.get(light.ATTR_MIN_MIREDS))
        self.assertEqual(500, state.attributes.get(light.ATTR_MAX_MIREDS))
        self.assertEqual('none', state.attributes.get(light.ATTR_EFFECT))
        light.turn_on(self.hass, ENTITY_LIGHT, kelvin=3000, brightness_pct=50)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_LIGHT)
        self.assertEqual(333, state.attributes.get(light.ATTR_COLOR_TEMP))
        self.assertEqual(127, state.attributes.get(light.ATTR_BRIGHTNESS))

    def test_turn_off(self):
        """Test light turn off method."""
        light.turn_on(self.hass, ENTITY_LIGHT)
        self.hass.block_till_done()
        self.assertTrue(light.is_on(self.hass, ENTITY_LIGHT))
        light.turn_off(self.hass, ENTITY_LIGHT)
        self.hass.block_till_done()
        self.assertFalse(light.is_on(self.hass, ENTITY_LIGHT))

    def test_turn_off_without_entity_id(self):
        """Test light turn off all lights."""
        light.turn_on(self.hass, ENTITY_LIGHT)
        self.hass.block_till_done()
        self.assertTrue(light.is_on(self.hass, ENTITY_LIGHT))
        light.turn_off(self.hass)
        self.hass.block_till_done()
        self.assertFalse(light.is_on(self.hass, ENTITY_LIGHT))


text:
Glob-Copy
=========

Glob-aware `cp` for node.

Usage
-----
`cp(src, dest, cb)`

`src` can be a string or an array of strings with a glob pattern.
(see [minimatch patterns](https://github.com/isaacs/minimatch#usage) and
[examples](https://github.com/sindresorhus/globby#globbing-patterns))

`dest` is a string.

`cb` is optional.

Example
-------
```
var cp = require('glob-copy');

cp('./app/*.html', './public', function(err, files) {
  console.log("copied " + files.length + " files to ./public");
});

cp.sync('./app/*.html', './public');
```


text:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace Spect.Net.VsPackage.ToolWindows.TestExplorer
{
    /// <summary>
    /// Resturns the visibility value for non-conclusion
    /// </summary>
    public class ConclusionVisibleConverter: IValueConverter
    {
        /// <summary>Converts a value. </summary>
        /// <param name="value">The value produced by the binding source.</param>
        /// <param name="targetType">The type of the binding target property.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>A converted value. If the method returns <see langword="null" />, the valid null value is used.</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value is TestState state
                ? (state == TestState.Aborted || state == TestState.Inconclusive
                    ? Visibility.Collapsed
                    : Visibility.Visible)
                : value;
        }

        /// <summary>Converts a value. </summary>
        /// <param name="value">The value that is produced by the binding target.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>A converted value. If the method returns <see langword="null" />, the valid null value is used.</returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateForumTopicsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('forum_topics', function(Blueprint $table)
		{
			$table->increments('id');
                        $table->integer('forum_id')->unsigned();
                        $table->string('topic_titre', 60);
                        $table->integer('user_id')->unsigned();
                        $table->mediumInteger('topic_vu');
                        $table->integer('topic_genre')->unsigned();
                        $table->integer('topic_last_post')->unsigned();
                        $table->integer('topic_first_post')->unsigned();
                        $table->mediumInteger('topic_post');
                        $table->boolean('topic_locked');
			$table->timestamps();
                        $table->unique('topic_last_post', 'topic_last_post');

		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('forum_topics');
	}

}


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

namespace Godiva
{
    public class RouteTemplate
    {
        public string Template { get; set;  }
        public RouteTemplate()
        {

        }

        internal string[] GetSegments()
        {
            return this.Template.Split(RouteParser.Separator , StringSplitOptions.RemoveEmptyEntries);
        }
    }
}


text:
package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;

import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;
import static com.github.tomakehurst.wiremock.testsupport.NoFileSource.noFileSource;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class HandlebarsSoapHelperTest extends HandlebarsHelperTestBase {

    private HandlebarsSoapHelper helper;
    private ResponseTemplateTransformer transformer;

    @Before
    public void init() {
        this.helper = new HandlebarsSoapHelper();
        this.transformer = new ResponseTemplateTransformer(true);
    }

    @Test
    public void extractsASimpleBodyValue() throws IOException {
        testHelper(this.helper, "<Envelope><Body><test>success</test></Body></Envelope>", "/test/text()", "success");
    }

    @Test
    public void rendersASimpleValue() {
        final ResponseDefinition responseDefinition = this.transformer.transform(
                mockRequest()
                    .url("/soap")
                    .body("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope/\"><soap:Body><m:a><m:test>success</m:test></m:a></soap:Body></soap:Envelope>"),
                aResponse()
                    .withBody("<test>{{soapXPath request.body '/a/test/text()'}}</test>").build(),
                noFileSource(),
                Parameters.empty());

        assertThat(responseDefinition.getBody(), is("<test>success</test>"));
    }

    @Test
    public void negativeTestResponseTemplate(){
        final ResponseDefinition responseDefinition = this.transformer.transform(
                mockRequest()
                    .url("/soap")
                    .body("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope/\"><soap:Body><m:a><m:test>success</m:test></m:a></soap:Body></soap:Envelope>"),
                aResponse()
                    .withBody("<test>{{soapXPath request.body '/b/test'}}</test>").build(),
                noFileSource(),
                Parameters.empty());

        assertThat(responseDefinition.getBody(), is("<test></test>"));
    }
}


text:
class CWindow : public CAbstractWindow
{
    // CAbstractWindow interface
protected:
    void OnWindowEvent(const SDL_Event &event) override;
    void OnUpdateWindow(float deltaSeconds) override;
    void OnDrawWindow(const glm::ivec2 &size) override;

private:
    void PrintOpenGLInfo();
};


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping">

    <mapped-superclass name="Sylius\Bundle\SettingsBundle\Model\Parameter" table="sylius_settings_parameter">
        <id name="id" column="id" type="integer">
            <generator strategy="AUTO" />
        </id>

        <field name="namespace" column="namespace" type="string" />
        <field name="name" column="name" type="string" />
        <field name="value" column="value" type="object" nullable="true" />
    </mapped-superclass>

</doctrine-mapping>


text:
#include "config.h"
#include "public/web/WebDOMMouseEvent.h"

#include "core/events/MouseEvent.h"

namespace blink {

int WebDOMMouseEvent::screenX() const
{
    return constUnwrap<MouseEvent>()->screenX();
}

int WebDOMMouseEvent::screenY() const
{
    return constUnwrap<MouseEvent>()->screenY();
}

int WebDOMMouseEvent::clientX() const
{
    return constUnwrap<MouseEvent>()->clientX();
}

int WebDOMMouseEvent::clientY() const
{
    return constUnwrap<MouseEvent>()->clientY();
}

int WebDOMMouseEvent::offsetX()
{
    return unwrap<MouseEvent>()->offsetX();
}

int WebDOMMouseEvent::offsetY()
{
    return unwrap<MouseEvent>()->offsetY();
}

int WebDOMMouseEvent::pageX() const
{
    return constUnwrap<MouseEvent>()->pageX();
}

int WebDOMMouseEvent::pageY() const
{
    return constUnwrap<MouseEvent>()->pageY();
}

int WebDOMMouseEvent::x() const
{
    return constUnwrap<MouseEvent>()->x();
}

int WebDOMMouseEvent::y() const
{
    return constUnwrap<MouseEvent>()->y();
}

int WebDOMMouseEvent::button() const
{
    return constUnwrap<MouseEvent>()->button();
}

bool WebDOMMouseEvent::buttonDown() const
{
    return constUnwrap<MouseEvent>()->buttonDown();
}

} // namespace blink


text:
package com.gooddata.connector;

import com.gooddata.Constants;
import com.gooddata.exception.HttpMethodException;
import com.gooddata.exception.ProcessingException;
import com.gooddata.modeling.model.SourceColumn;
import com.gooddata.modeling.model.SourceSchema;
import com.gooddata.processor.CliParams;
import com.gooddata.processor.Command;
import com.gooddata.processor.ProcessingContext;
import com.gooddata.transform.Transformer;
import com.gooddata.util.CSVWriter;
import com.gooddata.util.FileUtil;
import com.gooddata.util.NetUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * GoodData Facebook Insights connector
 *
 * @author zd <zd@gooddata.com>
 * @version 1.0
 */
public class FacebookInsightsConnector extends AbstractConnector implements Connector {

    private static Logger l = Logger.getLogger(FacebookInsightsConnector.class);

    private String oauthToken;
    private DateTime startDate;
    private DateTime endDate;
    private String baseUrl;
    private HttpClient client;

    private final DateTimeFormatter baseFmt = DateTimeFormat.forPattern(Constants.DEFAULT_DATETIME_FMT_STRING);
    private final DateTime base = baseFmt.parseDateTime("1900-01-01 00:00:00");

    protected FacebookInsightsConnector() {
        client = new HttpClient();

        NetUtil.configureHttpProxy(client);

    }

    /**
     * Creates a new Facebook connector
     *
     * @return a new instance of the FacebookConnector
     */
    public static FacebookInsightsConnector createConnector() {
        return new FacebookInsightsConnector();
    }

    /**
     * Saves a template of the config file
     *
     * @param name           new schema name
     * @param configFileName config file name
     * @throws java.io.IOException   if there is a problem with writing the config file
     * @throws java.sql.SQLException if there is a problem with the db
     */
    public static void saveConfigTemplate(String name, String configFileName, String folder)
            throws IOException {
        l.debug("Saving Facebook config template.");
        final SourceSchema s = SourceSchema.createSchema(name);

        SourceColumn o = new SourceColumn("objectid", SourceColumn.LDM_TYPE_DATE, "FAcebook Object ID");
        if (folder != null && folder.length() > 0)
            o.setFolder(folder);
        s.addColumn(o);

        SourceColumn dt = new SourceColumn("date", SourceColumn.LDM_TYPE_DATE, "date");
        dt.setFormat(Constants.DEFAULT_DATE_FMT_STRING);
        if (folder != null && folder.length() > 0)
            dt.setFolder(folder);
        s.addColumn(dt);

        SourceColumn metric = new SourceColumn("metric", SourceColumn.LDM_TYPE_ATTRIBUTE, "metric");
        if (folder != null && folder.length() > 0)
            metric.setFolder(folder);
        s.addColumn(metric);

        SourceColumn value = new SourceColumn("value", SourceColumn.LDM_TYPE_FACT, "fact");
        if (folder != null && folder.length() > 0)
            value.setFolder(folder);
        s.addColumn(value);

        s.writeConfig(new File(configFileName));
        l.debug("Saved Facebook Insights config template.");
    }

    private String fetchData(String uri) {
        try {
            GetMethod method = new GetMethod(uri);
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                return method.getResponseBodyAsString();
            } else {
                String msg = method.getStatusCode() + " " + method.getStatusText();
                l.debug("Exception executing " + method.getName() + " on " + method.getPath() + ": " + msg);
                throw new HttpMethodException(msg);
            }
        } catch (HttpException e) {
            l.debug("Error invoking Facebook REST API.", e);
            throw new HttpMethodException("Error invoking Facebook REST API.", e);
        } catch (IOException e) {
            l.debug("Error invoking GoodData REST API.", e);
            throw new HttpMethodException("Error invoking Facebook REST API.", e);
        }
    }

    private JSONObject fetchJSON(String uri) {
        return JSONObject.fromObject(fetchData(uri));
    }

    private String constructInsightsApiUrl(String baseUrlWithTime) {
        return baseUrlWithTime + "&access_token=" + URLEncoder.encode(oauthToken);
    }

    private String constructInsightsApiUrl(String baseUrl, DateTime startDate, DateTime endDate) {
        return baseUrl + "?since=" + (startDate.getMillis() / 1000) + "&until=" + (endDate.getMillis() / 1000) + "&access_token=" + URLEncoder.encode(oauthToken);
    }

    private final DateTimeFormatter isoFmt = ISODateTimeFormat.dateTimeParser();
    private final DateTimeFormatter defFmt = DateTimeFormat.forPattern(Constants.DEFAULT_DATE_FMT_STRING);

    private class InsightsRecord {

        private DateTime date;
        private String objectId;
        private String metric;
        private Number value;

        public InsightsRecord(String o, DateTime d, String m, Number v) {
            setObjectId(o);
            setDate(d);
            setMetric(m);
            setValue(v);
        }

        public InsightsRecord(String o, String d, String m, Number v) {
            setObjectId(o);
            setDate(isoFmt.parseDateTime(d));
            setMetric(m);
            setValue(v);
        }

        public InsightsRecord(String o, DateTime d, String m, String v) {
            setObjectId(o);
            setDate(d);
            setMetric(m);
            try {
                Number n = Double.parseDouble(v);
                setValue(n);
            } catch (NumberFormatException e) {
                l.debug("Invalid Facebook Insights value: " + v);
            }
        }

        public InsightsRecord(String o, String d, String m, String v) {
            setObjectId(o);
            setDate(isoFmt.parseDateTime(d));
            setMetric(m);
            try {
                Number n = Double.parseDouble(v);
                setValue(n);
            } catch (NumberFormatException e) {
                l.debug("Invalid Facebook Insights value: " + v);
            }
        }

        public String[] getRecord() {
            return new String[]{getObjectId(), defFmt.print(getDate()), getMetric(), (getValue() != null) ? (getValue().toString()) : ("0")};
        }

        public DateTime getDate() {
            return date;
        }

        public void setDate(DateTime date) {
            this.date = date;
        }

        public String getMetric() {
            return metric;
        }

        public void setMetric(String metric) {
            this.metric = metric;
        }

        public Number getValue() {
            return value;
        }

        public void setValue(Number value) {
            this.value = value;
        }

        public String getObjectId() {
            return objectId;
        }

        public void setObjectId(String objectId) {
            this.objectId = objectId;
        }

    }

    private String fetchInsightsRecords(String uri, List<InsightsRecord> ret) {
        String nextUri = null;
        JSONObject data = fetchJSON(uri);
        if (data != null) {
            JSONArray dt = data.getJSONArray("data");
            if (dt != null && !dt.isEmpty() && dt.size() > 0) {
                for (int i = 0; i < dt.size(); i++) {
                    JSONObject metricData = dt.getJSONObject(i);
                    if (metricData != null && !metricData.isNullObject() && !metricData.isEmpty()) {
                        String id = metricData.getString("id");
                        String metricName = metricData.getString("name");
                        if (id != null && id.length() > 0 && metricName != null && metricName.length() > 0) {
                            if (id.indexOf("/") > 0) {
                                String oid = id.split("/")[0];
                                JSONArray dataPoints = metricData.getJSONArray("values");
                                if (dataPoints != null && !dataPoints.isEmpty() && dataPoints.size() > 0) {
                                    for (int j = 0; j < dataPoints.size(); j++) {
                                        JSONObject dataPoint = dataPoints.getJSONObject(j);
                                        if (dataPoint != null && !dataPoint.isNullObject() && !dataPoint.isEmpty()) {
                                            String d = dataPoint.getString("end_time");
                                            Object v = dataPoint.get("value");
                                            if (d != null && v != null && d.length() > 0) {
                                                String value = "0";
                                                if (v instanceof Number || v instanceof String) {
                                                    value = v.toString();
                                                } else if (v instanceof JSONArray) {
                                                    Object vl = ((JSONArray) v).get(0);
                                                    if (vl != null) {
                                                        value = vl.toString();
                                                    }
                                                } else {
                                                    value = v.toString();
                                                }
                                                ret.add(new InsightsRecord(oid, d, metricName, value));
                                            }
                                        }
                                    }
                                }
                            } else {
                                l.debug("Invalid format of the Facebook Insights id: " + id);
                            }
                        } else {
                            l.debug("Invalid format of the Facebook Insights id: " + id + " or metric: " + metricName);
                        }
                    }
                }
            }
            JSONObject paging = data.getJSONObject("paging");
            if (paging != null && !paging.isNullObject() && !paging.isEmpty()) {
                nextUri = paging.getString("next");
            }
        }
        return nextUri;
    }

    /**
     * {@inheritDoc}
     */
    public void extract(String file, final boolean transform) throws IOException {
        File dataFile = new File(file);
        l.debug("Extracting Facebook data to file=" + dataFile.getAbsolutePath());
        CSVWriter cw = FileUtil.createUtf8CsvEscapingWriter(dataFile);
        Transformer t = Transformer.create(schema);
        String[] header = t.getHeader(transform);
        cw.writeNext(header);

        String url = constructInsightsApiUrl(getBaseUrl(), getStartDate(), getEndDate());
        List<InsightsRecord> result = new ArrayList<InsightsRecord>();
        url = fetchInsightsRecords(url, result);
        int cnt = 0;

        while (result != null && result.size() > 0) {
            cnt += result.size();
            l.debug("Started retrieving Facebook data.");
            for (InsightsRecord o : result) {
                String[] record = o.getRecord();
                String[] row = new String[record.length];
                for (int i = 0; i < record.length; i++) {
                    row[i] = record[i];
                }
                if (transform)
                    row = t.transformRow(row, DATE_LENGTH_UNRESTRICTED);
                cw.writeNext(row);
                cw.flush();
            }
            result.clear();
            url = fetchInsightsRecords(url, result);
        }

        l.debug("Retrieved " + cnt + " rows of Facebook data.");
        cw.close();
    }

    /**
     * {@inheritDoc}
     */
    public boolean processCommand(Command c, CliParams cli, ProcessingContext ctx) throws ProcessingException {
        try {
            if (c.match("GenerateFacebookInsightsConfig")) {
                generateConfig(c, cli, ctx);
            } else if (c.match("LoadFacebookInsights") || c.match("UseFacebookInsights")) {
                load(c, cli, ctx);
            } else
                return super.processCommand(c, cli, ctx);
        } catch (IOException e) {
            throw new ProcessingException(e);
        }
        return true;
    }

    /**
     * Loads new Facebook file command processor
     *
     * @param c   command
     * @param p   command line arguments
     * @param ctx current processing context
     * @throws java.io.IOException in case of IO issues
     */
    private void load(Command c, CliParams p, ProcessingContext ctx) throws IOException {

        String configFile = c.getParamMandatory("configFile");
        setBaseUrl(c.getParamMandatory("baseUrl"));
        setStartDate(defFmt.parseDateTime(c.getParamMandatory("startDate")));
        setEndDate(defFmt.parseDateTime(c.getParamMandatory("endDate")));
        String auth = c.getParamMandatory("authToken");
        c.paramsProcessed();

        File conf = FileUtil.getFile(configFile);
        initSchema(conf.getAbsolutePath());
        setOauthToken(auth);
        // sets the current connector
        ctx.setConnector(this);
        setProjectId(ctx);
        l.info("Facebook Insights Connector successfully loaded.");
    }

    /**
     * Generate new config file from CSV command processor
     *
     * @param c   command
     * @param p   command line arguments
     * @param ctx current processing context
     * @throws java.io.IOException in case of IO issues
     */
    private void generateConfig(Command c, CliParams p, ProcessingContext ctx) throws IOException {
        String name = c.getParamMandatory("name");
        String configFile = c.getParamMandatory("configFile");
        String folder = c.getParam("folder");
        c.paramsProcessed();

        FacebookInsightsConnector.saveConfigTemplate(name, configFile, folder);
        l.info("Facebook Insights Connector configuration successfully generated. See config file: " + configFile);
    }

    public DateTime getStartDate() {
        return startDate;
    }

    public void setStartDate(DateTime startDate) {
        this.startDate = startDate;
    }

    public DateTime getEndDate() {
        return endDate;
    }

    public void setEndDate(DateTime endDate) {
        this.endDate = endDate;
    }

    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String getOauthToken() {
        return oauthToken;
    }

    public void setOauthToken(String oauthToken) {
        this.oauthToken = oauthToken;
    }

}


text: This example should detect copying content into different commits


text:
package net.jxta.impl.xindice.core.filer;

import net.jxta.impl.xindice.core.DBException;
import net.jxta.impl.xindice.core.DBObject;
import net.jxta.impl.xindice.core.data.Key;
import net.jxta.impl.xindice.core.data.Record;
import net.jxta.impl.xindice.core.data.RecordSet;
import net.jxta.impl.xindice.core.data.Value;
import net.jxta.impl.xindice.util.Named;

/**
 * Filer is the low-level file management interface for Xindice.  A Filer object
 * is implemented in order to provide a data source to the Xindice Collection
 * class.  Filers are developed to perform transparent storage and retrieval to
 * and from heterogenous data sources (such as FTP, HTTP, RDBMS, etc...)
 */
public interface Filer extends Named, DBObject {

    /**
     * readRecord returns a Record from the Filer based on the specified
     * Key.
     *
     * @param key The Record's Key
     * @return The returned Record
     * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs
     */
    Record readRecord(Key key) throws DBException;

    /**
     * readRecord returns a Record from the Filer at the specified
     * position. The Record's Key will be set to null.
     *
     * @param pos The Record's position
     * @return The returned Record
     * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs
     */
    Record readRecord(long pos) throws DBException;

    /**
     * writeRecord writes a Value to the Filer based on the specified Key.
     *
     * @param key The Record's Key
     * @param value The Record's Value
     * @return 0 if the Record could not be written, the starting
     * offset of the Record otherwise (used for indexing)
     * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs
     */
    long writeRecord(Key key, Value value) throws DBException;

    /**
     * deleteRecord removes a Record from the Filer based on the
     * specified Key.
     *
     * @param key The Record's Key
     * @return Whether or not the Record was deleted
     * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs
     */
    boolean deleteRecord(Key key) throws DBException;

    /**
     * getRecordCount returns the number of Records in the Filer.
     *
     * @return The Record count
     * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs
     */
    long getRecordCount() throws DBException;

    /**
     * getRecordSet returns a RecordSet object for the current Filer.
     *
     * @return The Filer Enumerator
     * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs
     */
    RecordSet getRecordSet() throws DBException;

    /**
     * flush forcefully flushes any unwritten buffers to disk.
     * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs
     */
    void flush() throws DBException;
}


text:
Welcome to ###SITE_NAME_UFC###

Page not found. It may be in under construction. Click here go to previous page.


text:
Check your delivery!

Protocols implemented:

 - SMTP and IMAP4
 - IRC and IRC/TLS
 - FTP and FTP/TLS
 - Flat file

Outputs available:

 - Nagios + perfdata
 - JSON

Possible scenarios:

 - Send and check from and to your "internal" servers
 - Send from your servers, check from external servers
 - Send from external servers, check from internal servers
 - Send and check from external servers \o/

# Install

Requirements:

 - `Python >= 3.2`, NO PYTHON 2

```
# From local clone
pip install -e .
pip install -e .[irc] # with IRC delivery

# Or from GitHub
pip install -e "git+https://github.com/Leryan/check_delivery.git#egg=check_delivery"
pip install -e "git+https://github.com/Leryan/check_delivery.git#egg=check_delivery[irc]"
```

# Use

```
check_delivery \
    --recv 'sendmethod://senduser:sendpassword@sendhost:port' \
    --send 'recvmethod://recvuser:recvpassword@recvhost:port' \
    --wait X
```

 - `--wait` : wait X seconds before checking the inbox.
 - There is **no** port auto-detection and I don't want to code such thing. I prefer to keep simpler code and more explicit configuration.
 - `--doc` : list all senders and receivers, with their documentation.
 - `--play` : allows you to use `scenarios`, defined in the configuration (`--conf <file>`). See `player.sample.ini`.

## Examples

```
# This example shows you how to send a mail from `usersmtp@smtpdomain.tld`
# to `userimap@imapdomain.tld`, using different servers.
check_delivery \
    --send 'smtpstarttls://usersmtp%40smtpdomain.tld:BadPassword@smtp.smtpdomain.tld:587' \
    --recv 'imapstarttls://userimap%40imapdomain.tld:OtherBadPassword@imap.domain.tld:143' \

# This example shows you how to send a mail from `usersmtp@smtpdomain.tld`
# to `userimap@imapdomain.tld`, using the same, local server.
check_delivery \
    --send 'smtp://usersmtp%40smtpdomain.tld@localhost:587' \
    --recv 'imapstarttls://userimap%40imapdomain.tld:OtherBadPassword@localhost:143/INBOX' \

# Check that a file is copied by some black magic from /dropin/sendfile to /checkout/sendfile
check_delivery --send="filerecv:///dropin/sendfile" --recv="filesend:///checkout/sendfile"
```

Or you can use an INI file containing your URLs:

```ini
[creds]
user1 = user%40domain.tld:password
user2 = user%40otherdomain.tld:password

[senders]
domain = smtpstarttls://${creds:user1}@domain.tld:port
otherdomain = smtp://${creds:user2}@otherdomain.tld:port

[receivers]
domain = imapstarttls://${creds:user1}@domain.tld:port
otherdomain = imap://${creds:user2}@otherdomain.tld:port/Unsorted

[scenarios]
domain.to.otherdomain.send = ${senders:domain}
domain.to.otherdomain.recv = ${receivers:otherdomain}

[expects]
; This section must be present, even if empty.
; See player.sample.ini to see how to use expects.
```

```
check_delivery --conf config.ini --play domain.to.otherdomain
```

Note: the INI file is read by Python's `ConfigParser`, with the `ExtendedInterpolation` string interpolation enabled.

Documentation: https://docs.python.org/3/library/configparser.html#configparser.ExtendedInterpolation

## Send methods

 - `smtp`: clear SMTP
 - `smtps`: TLS SMTP
 - `smtpstarttls`: SMTP + STARTTLS
 - `file`: flat file
 - `irc`
 - `irctls`
 - `ftp`
 - `ftps`

## Receive methods

 - `imap`: clear IMAP
 - `imaps`: TLS IMAP
 - `imapstarttls`: IMAP + STARTTLS
 - `file`: flat file
 - `irc`
 - `irctls`
 - `ftp`
 - `ftps`

## Special parameters

A parameter is sent through URL's query. Here is the list of parameters:

 - `ssl_verify`: `NONE`, `OPTIONAL` or `REQUIRED`

# Extending

Look at the `delivery_file.py` code, and the entry point `check_delivery` function in `__init__.py`.

The `launch()` function runs in this order:

 - `token_generate()`
 - `receiver.connect_early()`
 - `sender.connect()`
 - `sender.send()`: send the token
 - `sender.clean()`
 - `sender.close()`
 - `time.sleep(wait)`: wait `--wait seconds` seconds
 - `receiver.connect()`
 - `receiver.recv()`: check for the token to be received. This function **MUST** raise a `CheckDeliveryException` exception.
 - `receiver.clean()`
 - `receiver.close()`
 - `sender.close_late()`

The `connect_early()` function may be useful, for example, with an IRC delivery check, while the `close_late()` function may be useful for something asking for an ACK to work properly.

If you use those functions, you will probably want to override `connect()` and `close()` with `pass`.

Want your sender/receiver into [the core](http://www.imdb.com/title/tt0298814/)? Send a pull request.

# Tests

 - Tests done with `Python 3.5.2/ArchLinux` and `Python 3.4.3/CentOS 7`
 - Postfix 2.10.1 (plus rmilter/rspamd)
 - Dovecot 2.2.10
 - Zimbra 8.6
 - ngircd-21
 - vsftpd 3.0.3

# TODO

 - tests
 - send url parameters to each Method implementation. Could be useful, for example, to exit with an OK status even if send/recv has failed. Is case of SMTP, you'd be able to check you're not in an open relay configuration.


text:
"""
Add local_user_id.

Revision ID: 57bbf0c387c
Revises: 13391c68750
Create Date: 2016-04-02 09:54:09.643644
"""
from __future__ import unicode_literals

import sqlalchemy as sa
from alembic import op
from sqlalchemy.sql import table

# Revision identifiers, used by Alembic.
# pylint: disable=C0103,invalid-name  # revision control variables not uppercase
revision = "57bbf0c387c"
down_revision = "13391c68750"

def upgrade():
    conn = op.get_bind()
    op.add_column("external_identities", sa.Column("local_user_id", sa.Integer()))

    external_identities_t = table("external_identities",
                                  sa.Column("local_user_name", sa.Unicode(50)),
                                  sa.Column("local_user_id", sa.Integer))
    users_t = table("users",
                    sa.Column("user_name", sa.Unicode(50)),
                    sa.Column("id", sa.Integer))

    stmt = external_identities_t.update().values(local_user_id=users_t.c.id).where(
        users_t.c.user_name == external_identities_t.c.local_user_name
    )
    conn.execute(stmt)
    op.drop_constraint("pk_external_identities", "external_identities", type="primary")
    op.drop_constraint("fk_external_identities_local_user_name_users", "external_identities", type="foreignkey")
    op.drop_column("external_identities", "local_user_name")
    op.create_primary_key("pk_external_identities", "external_identities",
                          cols=["external_id", "local_user_id", "provider_name"])
    op.create_foreign_key(None, "external_identities", "users",
                          remote_cols=["id"], local_cols=["local_user_id"], onupdate="CASCADE", ondelete="CASCADE")

def downgrade():
    pass


text:
require 'rubygems'
require 'tegu_gears'

Dir.glob("#{File.dirname(__FILE__)}/ext/*.rb").each { |file| require file }
Dir.glob("#{File.dirname(__FILE__)}/kmeans/*.rb").each { |file| require file }


text:
<?php

namespace app\models;

use yii\db\ActiveRecord;

class Printers extends ActiveRecord
{
}


text:
starter-project
===============

Project template which includes the basic setup for frameworks and tools such as AngularJs, NodeJs, GruntJs and Karma


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Chalé</logradouro><bairro>Guabiraba</bairro><cidade>Recife</cidade><uf>PE</uf><cep>52291411</cep></feed>


text:
_.extend(Mart.Subscription, {
  spawn: function(cartId) {
    var cart = Mart.Carts.findOne(cartId)
    console.log("Cart starts: ");
    console.log(moment(cart.firstBookingStarts()).format());
    var startSubscription = moment(cart.firstBookingStarts()).add(1, 'months').toDate();
    console.log(startSubscription);

    return Mart.Subscriptions.insert({
      originalCartId: cartId,
      storefrontName: cart.storefrontNameAtCheckout,
      productName: cart.productNameAtCheckout,
      merchantId: cart.merchantId,
      userId: cart.userId,
      subtotal: cart.subtotalAtCheckout,
      serviceFee: cart.serviceFeeAtCheckout,
      tax: cart.taxAtCheckout,
      total: cart.recurringTotal(),
      merchantCut: cart.merchantCutAtCheckout,
      connectionFee: cart.connectionFeeAtCheckout,
      name: cart.storefrontNameAtCheckout,
      startAt: startSubscription,
      state: Mart.Subscription.STATES.SPAWNED,
      createdAt: new Date()
    })
  }
})

Meteor.methods({
  'mart/subscription/cancel': function(subscriptionId) {
    check(subscriptionId, String);

    var stateTo, subscription

    if(Mart._isMerchant(this.userId)) {
      subscription = Mart.Subscriptions.findOne({merchantId: this.userId, _id: subscriptionId})

      if(subscription)
        stateTo = Mart.Subscription.STATES.CANCELLED_BY_MERCHANT
    }

    if(!subscription)
      subscription = Mart.Subscriptions.findOne({userId: this.userId, _id: subscriptionId})

    if(!subscription)
      throw new Meteor.Error('unauthorized', 'You cannot do that')

    if(!stateTo)
      stateTo = Mart.Subscription.STATES.CANCELLED_BY_SHOPPER

    console.log('Cancelling in ' + subscription.state);
    if(subscription.state === Mart.Subscription.STATES.ACTIVE) {
      var Stripe = StripeAPI(Meteor.settings.STRIPE_SECRET_KEY);
      var cancelSubscription = Meteor.wrapAsync(Stripe.customers.cancelSubscription, Stripe.customers);
      console.log(subscription);
      var cart = subscription.cart()
      var customer = Mart.GatewayTypes.Stripe.Customers.findOne({userId: cart.userId})

      try {
        console.log('About to cancel');
        console.log(subscription);
        cancelSubscription(customer.stripeToken, subscription.gatewayToken)
        return Mart.Subscriptions.update(subscriptionId, {$set: {
          state: stateTo
        }})
      } catch (error) {
        throw new Meteor.Error("stripe-cancel-subscription-error", error.message);
      }
    } else if(subscription.state === Mart.Subscription.STATES.SPAWNED) {
      return Mart.Subscriptions.update(subscriptionId, {$set: {
        state: stateTo
      }})
    }

  }
});


text:
/* Author: Christine Xu, University of North Carolina at Chapel Hill*/

#ifndef _COMPUTE_VOLUME_OVERLAP_PROTO
#define _COMPUTE_VOLUME_OVERLAP_PROTO

#ifdef __cplusplus
#define BEGIN_DECL extern "C" {
#define END_DECL }
#else
#define BEGIN_DECL
#define END_DECL
#endif

BEGIN_DECL
#undef BEGIN_DECL

//This is an overarching function that will call GetVolumeOverlap 3 times, one for
//each projection (x,y,z).  That way it's a bit more robust to degenerate or axis-
//aligned byus.
void ComputeRobustVolumeOverlap(double * L1, double * L2, int numVertices1, int numVertices2, int * T1, int * T2, int numTriangles1, int numTriangles2, double dice[], double int_union_ratio[] );

END_DECL
#undef END_DECL

#endif /*_COMPUTE_VOLUME_OVERLAP_PROTO*/


text:
using System;

namespace CabFromHell.Mobile
{
	public delegate void AccellerometerUpdate(double x, double y, double z);

	public interface IAccellerometer
	{
		void AddHandler(AccellerometerUpdate handler);
	}
}


text:
.class public interface abstract Lmf/org/w3c/dom/html/HTMLScriptElement;
.super Ljava/lang/Object;
.source "HTMLScriptElement.java"

# interfaces
.implements Lmf/org/w3c/dom/html/HTMLElement;

# virtual methods
.method public abstract getCharset()Ljava/lang/String;
.end method

.method public abstract getDefer()Z
.end method

.method public abstract getEvent()Ljava/lang/String;
.end method

.method public abstract getHtmlFor()Ljava/lang/String;
.end method

.method public abstract getSrc()Ljava/lang/String;
.end method

.method public abstract getText()Ljava/lang/String;
.end method

.method public abstract getType()Ljava/lang/String;
.end method

.method public abstract setCharset(Ljava/lang/String;)V
.end method

.method public abstract setDefer(Z)V
.end method

.method public abstract setEvent(Ljava/lang/String;)V
.end method

.method public abstract setHtmlFor(Ljava/lang/String;)V
.end method

.method public abstract setSrc(Ljava/lang/String;)V
.end method

.method public abstract setText(Ljava/lang/String;)V
.end method

.method public abstract setType(Ljava/lang/String;)V
.end method


text:
module.exports = call;
call.usage = "fhc call <url> [<method> <params>]";
call.desc = "Call a FeedHenry system URL";

var util = require('util');
var fhc = require("../../fhc");
var fhreq = require("../../utils/request");

// Get FeedHenry platform call
function call (argv, cb) {
  var args = argv._;
  var host = fhreq.getFeedHenryUrl();

  if (args.length === 0) {
    return cb(call.usage);
  }

  var url = args[0];
  var method = args[1] || 'GET';
  var data = args[2] || '{}';

//function GET (url, where, etag, nofollow, cb) {
  fhreq.requestFunc(host, method, url, data, function (err, remoteData, raw, response) {
    if (err) return cb(err);
    if (response.statusCode === 200) {
      if ('object' === typeof remoteData) {
        remoteData.status = "ok";
        remoteData.statusCode = 200;
      } else {
        remoteData = {
          "body" : raw,
          "status" : "ok",
          "statusCode" : response.statusCode
        };
      }
      call.message = raw;
      return cb(err, remoteData);
    }
    return cb(undefined, {status: 'error', error: remoteData, statusCode: response.statusCode});
  });
}


text:
'use strict'

const apemanScff = require('apeman-scff')
const scff = require('apeman-scff-demo')

apemanScff(scff, 'project/my-awesome-project', {
  silent: false,
  force: false
}).then(() => {
  /* ... */
})


text:
<sprite styles="loading-scene-bg">
    <sprite styles="loading-scene-progressbg">
        <sprite styles="loading-scene-progressbar" :width="loadedPercent * 400 -4"/>
    </sprite>
</sprite>


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.program.model.symbol;

/**
 * Class to define reference types for data.
 */
public final class DataRefType extends RefType {

	// memory access type
	protected static final int READX    =  1;
	protected static final int WRITEX   =  2;
	protected static final int INDX     =  4;

	private int      access = 0;

	/**
	 * Constructs a DataRefType with the given type.
	 */
    protected DataRefType(byte type, String name, int access) {
        super(type, name);
        this.access = access;
	}

    @Override
	public boolean isData() {
		return true;
	}

	@Override
	public boolean isRead() {
		return (access & READX) == READX;
	}

	@Override
	public boolean isWrite() {
		return (access & WRITEX) == WRITEX;
	}

	@Override
	public boolean isIndirect() {
		return (access & INDX) == INDX;
	}

}