text
stringlengths
2
100k
meta
dict
ul.thumbnails.image_picker_selector { overflow: auto; list-style-image: none; list-style-position: outside; list-style-type: none; padding: 0px; margin: 0px; } ul.thumbnails.image_picker_selector ul { overflow: auto; list-style-image: none; list-style-position: outside; list-style-type: none; padding: 0px; margin: 0px; } ul.thumbnails.image_picker_selector li.group {width:100%;} ul.thumbnails.image_picker_selector li.group_title { float: none; } ul.thumbnails.image_picker_selector li { margin: 0px 12px 12px 0px; float: left; } ul.thumbnails.image_picker_selector li .thumbnail { padding: 6px; border: 1px solid #dddddd; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; } ul.thumbnails.image_picker_selector li .thumbnail img { -webkit-user-drag: none; } ul.thumbnails.image_picker_selector li .thumbnail.selected { background: #0088cc; }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2001-2002 Andre Hedrick <[email protected]> * Portions (C) Copyright 2002 Red Hat Inc * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * For the avoidance of doubt the "preferred form" of this code is one which * is in an open non patent encumbered format. Where cryptographic key signing * forms part of the process of creating an executable the information * including keys needed to generate an equivalently functional executable * are deemed to be part of the source code. */ #include <linux/types.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/pci.h> #include <linux/ide.h> #include <linux/init.h> #define DRV_NAME "ide_pci_generic" static bool ide_generic_all; /* Set to claim all devices */ module_param_named(all_generic_ide, ide_generic_all, bool, 0444); MODULE_PARM_DESC(all_generic_ide, "IDE generic will claim all unknown PCI IDE storage controllers."); static void netcell_quirkproc(ide_drive_t *drive) { /* mark words 85-87 as valid */ drive->id[ATA_ID_CSF_DEFAULT] |= 0x4000; } static const struct ide_port_ops netcell_port_ops = { .quirkproc = netcell_quirkproc, }; #define DECLARE_GENERIC_PCI_DEV(extra_flags) \ { \ .name = DRV_NAME, \ .host_flags = IDE_HFLAG_TRUST_BIOS_FOR_DMA | \ extra_flags, \ .swdma_mask = ATA_SWDMA2, \ .mwdma_mask = ATA_MWDMA2, \ .udma_mask = ATA_UDMA6, \ } static const struct ide_port_info generic_chipsets[] = { /* 0: Unknown */ DECLARE_GENERIC_PCI_DEV(0), { /* 1: NS87410 */ .name = DRV_NAME, .enablebits = { {0x43, 0x08, 0x08}, {0x47, 0x08, 0x08} }, .host_flags = IDE_HFLAG_TRUST_BIOS_FOR_DMA, .swdma_mask = ATA_SWDMA2, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, }, /* 2: SAMURAI / HT6565 / HINT_IDE */ DECLARE_GENERIC_PCI_DEV(0), /* 3: UM8673F / UM8886A / UM8886BF */ DECLARE_GENERIC_PCI_DEV(IDE_HFLAG_NO_DMA), /* 4: VIA_IDE / OPTI621V / Piccolo010{2,3,5} */ DECLARE_GENERIC_PCI_DEV(IDE_HFLAG_NO_AUTODMA), { /* 5: VIA8237SATA */ .name = DRV_NAME, .host_flags = IDE_HFLAG_TRUST_BIOS_FOR_DMA | IDE_HFLAG_OFF_BOARD, .swdma_mask = ATA_SWDMA2, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, }, { /* 6: Revolution */ .name = DRV_NAME, .port_ops = &netcell_port_ops, .host_flags = IDE_HFLAG_CLEAR_SIMPLEX | IDE_HFLAG_TRUST_BIOS_FOR_DMA | IDE_HFLAG_OFF_BOARD, .swdma_mask = ATA_SWDMA2, .mwdma_mask = ATA_MWDMA2, .udma_mask = ATA_UDMA6, } }; /** * generic_init_one - called when a PIIX is found * @dev: the generic device * @id: the matching pci id * * Called when the PCI registration layer (or the IDE initialization) * finds a device matching our IDE device tables. */ static int generic_init_one(struct pci_dev *dev, const struct pci_device_id *id) { const struct ide_port_info *d = &generic_chipsets[id->driver_data]; int ret = -ENODEV; /* Don't use the generic entry unless instructed to do so */ if (id->driver_data == 0 && ide_generic_all == 0) goto out; switch (dev->vendor) { case PCI_VENDOR_ID_UMC: if (dev->device == PCI_DEVICE_ID_UMC_UM8886A && !(PCI_FUNC(dev->devfn) & 1)) goto out; /* UM8886A/BF pair */ break; case PCI_VENDOR_ID_OPTI: if (dev->device == PCI_DEVICE_ID_OPTI_82C558 && !(PCI_FUNC(dev->devfn) & 1)) goto out; break; case PCI_VENDOR_ID_JMICRON: if (dev->device != PCI_DEVICE_ID_JMICRON_JMB368 && PCI_FUNC(dev->devfn) != 1) goto out; break; case PCI_VENDOR_ID_NS: if (dev->device == PCI_DEVICE_ID_NS_87410 && (dev->class >> 8) != PCI_CLASS_STORAGE_IDE) goto out; break; } if (dev->vendor != PCI_VENDOR_ID_JMICRON) { u16 command; pci_read_config_word(dev, PCI_COMMAND, &command); if (!(command & PCI_COMMAND_IO)) { printk(KERN_INFO "%s %s: skipping disabled " "controller\n", d->name, pci_name(dev)); goto out; } } ret = ide_pci_init_one(dev, d, NULL); out: return ret; } static const struct pci_device_id generic_pci_tbl[] = { { PCI_VDEVICE(NS, PCI_DEVICE_ID_NS_87410), 1 }, { PCI_VDEVICE(PCTECH, PCI_DEVICE_ID_PCTECH_SAMURAI_IDE), 2 }, { PCI_VDEVICE(HOLTEK, PCI_DEVICE_ID_HOLTEK_6565), 2 }, { PCI_VDEVICE(UMC, PCI_DEVICE_ID_UMC_UM8673F), 3 }, { PCI_VDEVICE(UMC, PCI_DEVICE_ID_UMC_UM8886A), 3 }, { PCI_VDEVICE(UMC, PCI_DEVICE_ID_UMC_UM8886BF), 3 }, { PCI_VDEVICE(HINT, PCI_DEVICE_ID_HINT_VXPROII_IDE), 2 }, { PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_82C561), 4 }, { PCI_VDEVICE(OPTI, PCI_DEVICE_ID_OPTI_82C558), 4 }, #ifdef CONFIG_BLK_DEV_IDE_SATA { PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_8237_SATA), 5 }, #endif { PCI_VDEVICE(TOSHIBA, PCI_DEVICE_ID_TOSHIBA_PICCOLO_1), 4 }, { PCI_VDEVICE(TOSHIBA, PCI_DEVICE_ID_TOSHIBA_PICCOLO_2), 4 }, { PCI_VDEVICE(TOSHIBA, PCI_DEVICE_ID_TOSHIBA_PICCOLO_3), 4 }, { PCI_VDEVICE(TOSHIBA, PCI_DEVICE_ID_TOSHIBA_PICCOLO_5), 4 }, { PCI_VDEVICE(NETCELL, PCI_DEVICE_ID_REVOLUTION), 6 }, /* * Must come last. If you add entries adjust * this table and generic_chipsets[] appropriately. */ { PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE << 8, 0xFFFFFF00UL, 0 }, { 0, }, }; MODULE_DEVICE_TABLE(pci, generic_pci_tbl); static struct pci_driver generic_pci_driver = { .name = "PCI_IDE", .id_table = generic_pci_tbl, .probe = generic_init_one, .remove = ide_pci_remove, .suspend = ide_pci_suspend, .resume = ide_pci_resume, }; static int __init generic_ide_init(void) { return ide_pci_register_driver(&generic_pci_driver); } static void __exit generic_ide_exit(void) { pci_unregister_driver(&generic_pci_driver); } module_init(generic_ide_init); module_exit(generic_ide_exit); MODULE_AUTHOR("Andre Hedrick"); MODULE_DESCRIPTION("PCI driver module for generic PCI IDE"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
package com.mesosphere.sdk.offer; import org.apache.mesos.Protos; import org.apache.mesos.SchedulerDriver; import com.mesosphere.sdk.framework.Driver; import com.mesosphere.sdk.testutils.ResourceTestUtils; import com.mesosphere.sdk.testutils.TestConstants; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import static org.mockito.Mockito.*; public class OfferAccepterTest { private static final Protos.Offer OFFER_A = Protos.Offer.newBuilder(Protos.Offer.getDefaultInstance()) .setHostname("hostA") .setSlaveId(Protos.SlaveID.newBuilder().setValue("agentA").build()) .setId(Protos.OfferID.newBuilder().setValue("offerA")) .setFrameworkId(Protos.FrameworkID.newBuilder().setValue("fwkA")) .build(); private static final Protos.Offer OFFER_B = Protos.Offer.newBuilder(Protos.Offer.getDefaultInstance()) .setHostname("hostB") .setSlaveId(Protos.SlaveID.newBuilder().setValue("agentB").build()) .setId(Protos.OfferID.newBuilder().setValue("offerB")) .setFrameworkId(Protos.FrameworkID.newBuilder().setValue("fwkB")) .build(); private static final DestroyOfferRecommendation DESTROY_A = new DestroyOfferRecommendation(OFFER_A, ResourceTestUtils.getUnreservedCpus(1.0)); private static final DestroyOfferRecommendation DESTROY_B = new DestroyOfferRecommendation(OFFER_B, ResourceTestUtils.getUnreservedCpus(2.0)); // Should be dropped from accept calls to Mesos: private static final StoreTaskInfoRecommendation STORETASK_A = new StoreTaskInfoRecommendation( OFFER_A, TestConstants.TASK_INFO, Protos.ExecutorInfo.newBuilder().setExecutorId(TestConstants.EXECUTOR_ID).build()); private static final StoreTaskInfoRecommendation STORETASK_B = new StoreTaskInfoRecommendation( OFFER_B, TestConstants.TASK_INFO, Protos.ExecutorInfo.newBuilder().setExecutorId(TestConstants.EXECUTOR_ID).build()); private static final UnreserveOfferRecommendation UNRESERVE_A = new UnreserveOfferRecommendation(OFFER_A, ResourceTestUtils.getUnreservedCpus(1.1)); private static final UnreserveOfferRecommendation UNRESERVE_B = new UnreserveOfferRecommendation(OFFER_B, ResourceTestUtils.getUnreservedCpus(2.1)); private static final List<OfferRecommendation> ALL_RECOMMENDATIONS = Arrays.asList(DESTROY_A, DESTROY_B, STORETASK_A, STORETASK_B, UNRESERVE_A, UNRESERVE_B); private static final OfferAccepter ACCEPTER = new OfferAccepter(); @Mock private SchedulerDriver mockDriver; @Captor private ArgumentCaptor<Collection<Protos.OfferID>> offerIdCaptor; @Captor private ArgumentCaptor<Collection<Protos.Offer.Operation>> operationCaptor; @Before public void beforeEach() { MockitoAnnotations.initMocks(this); } @Test public void testAcceptEmptyList() { Driver.setDriver(mockDriver); ACCEPTER.accept(Collections.emptyList()); verifyZeroInteractions(mockDriver); } @Test public void testGroupRecommendationsByAgent() { final Map<String, List<OfferRecommendation>> group = OfferAccepter.groupByAgent(ALL_RECOMMENDATIONS); Assert.assertEquals(2, group.size()); List<OfferRecommendation> recs = group.get("agentA"); Assert.assertEquals(Arrays.asList(DESTROY_A, STORETASK_A, UNRESERVE_A), recs); recs = group.get("agentB"); Assert.assertEquals(Arrays.asList(DESTROY_B, STORETASK_B, UNRESERVE_B), recs); } @Test public void testAcceptRecommendationsByAgent() { Driver.setDriver(mockDriver); ACCEPTER.accept(ALL_RECOMMENDATIONS); // Separate calls for each agent: verify(mockDriver, times(2)).acceptOffers(offerIdCaptor.capture(), operationCaptor.capture(), any()); // Offer ids should be deduped within each agent. Also the ordering should be alphabetical based on agent id. List<Collection<Protos.OfferID>> offerIdCalls = offerIdCaptor.getAllValues(); Assert.assertEquals(2, offerIdCalls.size()); Assert.assertEquals(Collections.singleton(OFFER_A.getId()), offerIdCalls.get(0)); Assert.assertEquals(Collections.singleton(OFFER_B.getId()), offerIdCalls.get(1)); List<Collection<Protos.Offer.Operation>> operationCalls = operationCaptor.getAllValues(); Assert.assertEquals(2, operationCalls.size()); Assert.assertEquals(Arrays.asList(DESTROY_A.getOperation().get(), UNRESERVE_A.getOperation().get()), operationCalls.get(0)); Assert.assertEquals(Arrays.asList(DESTROY_B.getOperation().get(), UNRESERVE_B.getOperation().get()), operationCalls.get(1)); } }
{ "pile_set_name": "Github" }
# This file is automatically generated. Please do not edit this file. If you'd like to change the content please use crowdin. AutoUpdate.NoPermissions=, mas o UMS n\u00e3o pode escrever na pasta de perfil. AutoUpdate.UnableToRunUpdate=N\u00e3o \u00e9 poss\u00edvel atualizar. Poder\u00e1 ter de fazer o download manualmente. AutoUpdate.VersionXIsAvailable=A vers\u00e3o %s est\u00e1 dispon\u00edvel AutoUpdate.0=Atualiza\u00e7\u00e3o autom\u00e1tica do Universal Media Server AutoUpdate.1=Verifica\u00e7\u00e3o de actualiza\u00e7\u00f5es n\u00e3o iniciada AutoUpdate.2=Transfer\u00eancia conclu\u00edda AutoUpdate.3=Download em progresso AutoUpdate.4=Nenhuma actualiza\u00e7\u00e3o dispon\u00edvel AutoUpdate.5=A conectar ao servidor AutoUpdate.8=Estado desconhecido AutoUpdate.9=Sem actualiza\u00e7\u00e3o autom\u00e1tica AutoUpdate.10=Download AutoUpdate.11=Agora n\u00e3o AutoUpdate.13=Tente executar UMS como administrador. AviSynthMEncoder.3=Permitir o AviSynth mudar de framerate vari\u00e1vel para framerate constante (convertfps = true) AviSynthMEncoder.4=O script AviSynth \u00e9 totalmente personaliz\u00e1vel \n AviSynthMEncoder.5=As seguintes vari\u00e1veis est\u00e3o dispon\u00edveis:\n AviSynthMEncoder.6=<movie>: A instru\u00e7\u00e3o completa de DirectShowSource, p.ex. DirectShowSource (nome de ficheiro, converterfps)\n AviSynthMEncoder.7=<sub>: Instru\u00e7\u00e3o completa de legendas se houver alguma detectada (SRT/SUB/IDX/ASS/SSA)\n AviSynthMEncoder.8=<moviefilename>: Nome do ficheiro de v\u00eddeo se deseja fazer tudo voc\u00ea mesmo AviSynthMEncoder.13=Activar interpola\u00e7\u00e3o de movimento True Motion via InterFrame AviSynthMEncoder.15=Permitir o uso GPU com True Motion. Melhor qualidade, mas mais lento. AviSynthMEncoder.16=Esta caracter\u00edstica aumenta a utiliza\u00e7\u00e3o de CPU e pode causar lentid\u00e3o. Voc\u00ea pode fazer \u00e9 correr mais r\u00e1pido, permitindo a op\u00e7\u00e3o multithreading nesta p\u00e1gina. CharacterSet.Big5=Big5 Chin\u00eas Tradicional CharacterSet.EUC-JP=EUC-JP Japon\u00eas CharacterSet.EUC-KR=EUC-KR Coreano CharacterSet.GB18030=GB18030 Padr\u00e3o Nacional Chin\u00eas CharacterSet.IBM420=IBM420 Ar\u00e1bico CharacterSet.IBM424=IBM424 Hebraico CharacterSet.KOI8-R=KOI8-R Russo e B\u00falgaro CharacterSet.ShiftJIS=Shift Japanese Industrial Standards CharacterSet.TIS-620=Padr\u00e3o Industrial Tailand\u00eas TIS-620 CharacterSet.874=Windows CodePage 874 - Tailand\u00eas CharacterSet.932=Windows CodePage 932 - Japon\u00eas CharacterSet.936=Windows CodePage 936 - Chin\u00eas Simplificado CharacterSet.949=Windows CodePage 949 - Coreano CharacterSet.950=Windows CodePage 950 - Chin\u00eas Tradicional CharacterSet.1250=Windows CodePage 1250 - Centro-Leste Europeu CharacterSet.1251=Windows CodePage 1251 - Cir\u00edlico CharacterSet.1252=Windows CodePage 1252 - Europeu Ocidental CharacterSet.1253=Windows CodePage 1253 - Grego CharacterSet.1254=Windows CodePage 1254 - Turco CharacterSet.1255=Windows CodePage 1255 - Hebraico CharacterSet.1256=Windows CodePage 1256 - Ar\u00e1bico CharacterSet.1257=Windows CodePage 1257 - B\u00e1ltico CharacterSet.1258=Windows CodePage 1258 - Vietnamita CharacterSet.2022-JP=ISO-2022-JP Japon\u00eas CharacterSet.2022-KR=ISO-2022-KR Coreano CharacterSet.2022-CN=ISO-2022-CN Chin\u00eas Simplificado CharacterSet.8859-10=ISO-8859-10 L\u00ednguas N\u00f3rdicas CharacterSet.8859-14=ISO-8859-14 Celta CharacterSet.8859-13=ISO-8859-13 L\u00ednguas B\u00e1lticas CharacterSet.8859-11=ISO-8859-11 Tailand\u00eas CharacterSet.8859-16=ISO-8859-16 Sudeste Europeu CharacterSet.8859-15=ISO-8859-15 Europa Ocidental com o s\u00edmbolo do euro CharacterSet.8859-8=ISO-8859-8 Hebraico CharacterSet.8859-9=ISO-8859-9 Turco CharacterSet.8859-6=ISO-8859-6 Ar\u00e1bico CharacterSet.8859-7=ISO-8859-7 Grego CharacterSet.8859-4=ISO-8859-4 Norte da Europa CharacterSet.8859-5=ISO-8859-5 Cir\u00edlico CharacterSet.8859-2=ISO-8859-2 Europa Central e Leste CharacterSet.8859-3=ISO-8859-3 Sul da Europa CharacterSet.8859-1=ISO-8859-1 Europa Ocidental DLNAMediaDatabase.ConnectionError=<html>A cache local n\u00e3o foi inicializada.<br>Reiniciar o programa ou o equipamento pode resolver a quest\u00e3o.</html> DLNAMediaDatabase.1=A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z DLNAMediaDatabase.2=Limpar base de dados... DLNAMediaDatabase.4=Procurar na pasta: DLNAMediaDatabase.5=Cache danificada n\u00e3o pode ser apagada. Parar o programa e apague a pasta %s manualmente. DLNAResource.0=[Sem transcodifica\u00e7\u00e3o] DLNAResource.2=Legenda: DLNAResource.3=Fluxo DLNAResource.4=Visto DLNAResource.5=Reproduzido DLNAResource.6=Visto DVDISOTitle.1=T\u00edtulo DbgPacker.1=Criar DbgPacker.2=Compactar os ficheiros selecionados DbgPacker.3=Abrir local do ficheiro zip DbgPacker.4=Substituir o ficheiro existente? DbgPacker.5=N\u00e3o foi poss\u00edvel abrir o visualizador externo, por favor, verifique a associa\u00e7\u00e3o de tipo de ficheiro. O erro foi:\n DbgPacker.6=N\u00e3o foi poss\u00edvel abrir o visualizador externo. O erro foi:\n DbgPacker.7=N\u00e3o \u00e9 poss\u00edvel abrir "%s", n\u00e3o encontrado! Dialog.Apply=Aplicar altera\u00e7\u00f5es Dialog.Close=Fechar\t Dialog.Confirm=Confirmar Dialog.Error=Erro Dialog.Information=Informa\u00e7\u00e3o Dialog.NO=N\u00e3o Dialog.OK=OK Dialog.Options=Op\u00e7\u00f5es Dialog.PermissionsError=Erro nas permiss\u00f5es Dialog.Question=Pergunta Dialog.Restart=%s precisa de ser reiniciado para aplicar as altera\u00e7\u00f5es. Quer reiniciar agora? Dialog.Select=Seleccionar Dialog.Warning=Aviso Dialog.YES=Sim Engine.AviSynthNotFound=O mecanismo de transcodifica\u00e7\u00e3o %s n\u00e3o est\u00e1 dispon\u00edvel pois o AviSynth n\u00e3o foi encontrado. Engine.Disabled=Mecanismo de transcodifica\u00e7\u00e3o %s est\u00e1 desativado. Engine.Enabled=Mecanismo de transcodifica\u00e7\u00e3o %s est\u00e1 ativado. Engine.EnabledVersion=Mecanismo de transcodifica\u00e7\u00e3o %1$s (%2$s) est\u00e1 ativado. Engine.Error=Mecanismo de transcodifica\u00e7\u00e3o %s indispon\u00edvel, devido a falha com o seguinte erro: %d. Engine.ErrorShort=H\u00e1 um problema com o mecanismo de transcodifica\u00e7\u00e3o %s Engine.ExecutableNotDefined=O execut\u00e1vel %1$s para o mecanismo %2$s \u00e9 indefinido. Engine.ExecutableNotFound=A execu\u00e7\u00e3o "%1$s" para transcodifica\u00e7\u00e3o %2$s n\u00e3o foi encontrada. Engine.ExecutablePlatformIncompatible=O mecanismo de transcodifica\u00e7\u00e3o %s n\u00e3o est\u00e1 dispon\u00edvel para este sistema operacional. Engine.ExitCode=Mecanismo de transcodifica\u00e7\u00e3o %s indispon\u00edvel, devido a falha com o seguinte erro: %d. Engine.MissingExecutePermission=Permiss\u00f5es insuficientes para executar "%1$s" para o mecanismo de transcodifica\u00e7\u00e3o %2$s. Engine.NotTested=Mecanismo de transcodifica\u00e7\u00e3o %s n\u00e3o est\u00e1 dispon\u00edvel porque n\u00e3o p\u00f4de ser validado. Engine.Undefined=O execut\u00e1vel %s n\u00e3o est\u00e1 definido. Engine.UnknownStatus=O estado do motor de transcodifica\u00e7\u00e3o %s \u00e9 desconhecido. Engine.VersionTooLow=Apenas as vers\u00f5es %1$s e superiores de %2$s s\u00e3o suportadas. Engine.tsMuxerErrorLinux=Certifique-se de que as bibliotecas de 32 bits necess\u00e1rias est\u00e3o instaladas. FFmpeg.GPUDecodingAccelerationDisabled=nenhum FFmpeg.GPUDecodingAccelerationMethod=M\u00e9todo de acelera\u00e7\u00e3o da descodifica\u00e7\u00e3o por GPU: FFmpeg.GPUDecodingAccelerationMethodTooltip=<html><strong>Por defeito:</strong> "auto"<br><strong>Notas:</strong> A defini\u00e7\u00e3o recomendada \u00e9 "auto" porque os outros m\u00e9todos n\u00e3o permitem que o sistema mude para o modo de descodifica\u00e7\u00e3o via software quando surgem erros.<br>Tamb\u00e9m aceita op\u00e7\u00f5es personalizadas, ex:<br>-hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -hwaccel_output_format vaapi<br>para descodifica\u00e7\u00e3o e tamb\u00e9m para codifica\u00e7\u00e3o por GPU.<br>-init_hw_device vaapi=amd:/dev/dri/renderD129 -hwaccel vaapi -hwaccel vaapi -hwaccel_device amd<br>pra utilizar o dispositivo AMD quando um sistema tem GPUs Intel e AMD.<br>Consulte https://trac.ffmpeg.org/wiki/HWAccelIntro</html> FFmpeg.GPUDecodingThreadCount=Contagem da thread de descodifica\u00e7\u00e3o por GPU: FFmpeg.GPUDecodingThreadCountTooltip=<html><strong>Por defeito:</strong> "1"<br><strong>Notas:</strong> O n\u00famero de threads do GPU a utilizar quando estiver a ser descodificado v\u00eddeo.<br>Valores diferentes de "1" podem ser inst\u00e1veis ou o FFmpeg pode parar devido a erros.<br>"0" ir\u00e1 permitir que o FFmpeg escolha automaticamente.</html> FFmpeg.Sox=Utilizar SoX para uma reamostragem \u00e1udio de maior qualidade FFmpeg.SoxTooltip=<html><strong>Por defeito:</strong> Falso<br><strong>Notas:</strong> Isto pode melhorar a qualidade do som, quando a reamostragem estiver conclu\u00edda.</html> FFmpeg.0=<html>Configura\u00e7\u00e3o de fonte \u00e9 aplicada a legendas baseadas em texto incorporadas e externas, excepto para legendas ASS/SSA.</html> FFmpeg.1=Preferir MEncoder ao transcodificar legendas problem\u00e1ticas FFmpeg.2=<html>MEncoder \u00e9 mais est\u00e1vel do que FFmpeg para transcodificar alguns tipos de legendas. Permitir a escolha autom\u00e1tica da op\u00e7\u00e3o mais est\u00e1vel para cada v\u00eddeo.</html> FFmpeg.3=Usar a configura\u00e7\u00e3o de fonte (tamanho, cor...) FileTranscodeVirtualFolder.1=Cap\u00edtulo: %s FoldTab.ShowLiveSubtitlesFolder=Mostrar a pasta "Legendas ao Vivo" FoldTab.ShowMediaLibraryFolder=Mostrar a pasta "Biblioteca de media" FoldTab.ShowMediaLibraryFolderTooltip=<html><strong>Defeito:</strong> Activo<br><strong>Notas:</strong> Se activo, ser\u00e1 criada e guardada uma cache de media, a qual \u00e9 acess\u00edvel pela biblioteca de media. <br>Resulta no carregamento mais r\u00e1pido quando se usam pastas fora da biblioteca.</html> FoldTab.ShowNewMediaFolder=Mostrar a pasta "Novas Multimedia" FoldTab.ShowRecentlyPlayedFolder=Mostrar a pasta "Vistos Recentemente" FoldTab.ShowServerSettingsFolder=Mostrar a pasta de "Defini\u00e7\u00f5es do Servidor" FoldTab.ShowTranscodeFolder=Mostrar a pasta "#--TRANSCODE--#" FoldTab.addSubtitlesInfo=Adicionar informa\u00e7\u00f5es das legendas aos nomes dos v\u00eddeos: FoldTab.addSubtitlesInfoToolTip=<html><strong>Padr\u00e3o:</strong> B\u00e1sico<br><string>Notas:</strong> Adiciona informa\u00e7\u00f5es sobre as legendas selecionadas ao nome do v\u00eddeo. Exemplo b\u00e1sico:<br>SomeVideo &#123;legendas em ingl\u00eas&#125;<br>Exemplo Completo:<br>SomeVideo &#123;Ext. Sub:SubRip/Ingl\u00eas&#125;</html> FoldTab.showEngineNamesAfterFilenames=Adicionar nome do motor no fim do nome do ficheiro FoldTab.showEngineNamesAfterFilenamesToolTip=<html><strong>Padr\u00e3o:</strong> Desativado<br><strong>Notas:</strong> Se ativado, o nome do mecanismo ser\u00e1 exibido ap\u00f3s o nome do ficheiro.<br><strong>Exemplo:</strong>Este \u00e9 o nome do arquivo [FFmpeg]</html> FoldTab.2=Pesquisar todas as pastas partilhadas FoldTab.5=Esconder extens\u00e3o dos ficheiros FoldTab.7=Pastas Partilhadas FoldTab.8=Esconder nomes dos motores de transcodifica\u00e7\u00e3o FoldTab.9=Adicionar Pasta FoldTab.10=Deseja terminar a pesquisa?\n\n FoldTab.13=Miniaturas FoldTab.14=Usar o MPlayer para miniaturas de V\u00eddeo FoldTab.15=Alfab\u00e9tica (A-Z) FoldTab.16=Por data, mais recentes primeiro FoldTab.17=Por data, mais antigos primeiro FoldTab.18=M\u00e9todo de ordena\u00e7\u00e3o de ficheiros: FoldTab.19=Miniaturas DVD ISO FoldTab.20=ASCIIb\u00e9ticamente FoldTab.21=Miniaturas de imagens FoldTab.22=Alfanum\u00e9rico FoldTab.26=Miniaturas de \u00c1udio: FoldTab.27=Pasta alternativa para capas de v\u00eddeo FoldTab.28=Escolha uma pasta FoldTab.29=Mostrar biblioteca do iPhoto FoldTab.30=Mostrar biblioteca do iTunes FoldTab.31=Esconder pastas vazias/n\u00e3o media (Cuidado: navega\u00e7\u00e3o mais lenta) FoldTab.34=Mostrar biblioteca do Aperture FoldTab.35=Nenhum FoldTab.36=Remover pasta(s) selecionada(s) FoldTab.37=Limite m\u00ednimo antes de utilizar pastas A-Z: FoldTab.39=Ignorar palavra "the" ao ordenar FoldTab.40=Cancelar a verifica\u00e7\u00e3o de pastas compartilhadas FoldTab.41=A cancelar pesquisa... FoldTab.43=Melhorar nomes de ficheiros (n\u00e3o renomeia) FoldTab.44=<html><strong>Por defeito:</strong> Ativado<br><strong>Notas:</strong> Se ativado, os ficheiros ser\u00e3o ordenados assim: <ol><li>Apple</li><li>The Banana</li><li>Carrot</li></ol> Se desativado, os ficheiros ser\u00e3o ordenados assim: <ol><li>Apple</li><li>Carrot</li> <li>The Banana</li></ol></html> FoldTab.45=<html><strong>Por defeito:</strong> Desativado<br><strong>Notas:</strong> Se ativado, os ficheiros aparecer\u00e3o assim:<ol><li>Apple - 10</li><li>Banana - 213 - The Cake Special</li><li>Carrot (2002)</li></ol>Se desativado, os ficheiros aparecer\u00e3o assim:<ol><li>[SomeFans] Apple - 10 (1280x720 Blu-Ray FLAC) [44A36D20]</li><li>Banana.S02E13.The.Cake.Special.720p.HDTV.x264-SomeFans</li><li>Carrot.2002.LIMITED.720p.BluRay.x264-SomeFans</li></ol></html> FoldTab.47=<html><strong>Por defeito:</strong> Desativado<br><strong>Notas:</strong> Se ativado, 3 pastas virtuais novas aparecer\u00e3o nos dispositivos para permitir o acesso \u00e0 sua m\u00fasica iTunes:<ul><li>Navegar por Artista</li><li>Navegar por \u00c1lbum</li><li>Navegar por G\u00e9nero</li></ul></html> FoldTab.49=<html><strong>Por defeito:</strong> 10000<br><strong>Notas:</strong> Se o n\u00famero de itens numa pasta exceder este n\u00famero, eles ser\u00e3o divididos em subpastas virtuais pela sua primeira letra/n\u00famero</html> FoldTab.50=Navegar por Artista FoldTab.51=Navegar por \u00c1lbum FoldTab.52=Navegar por G\u00e9nero FoldTab.54=Esconder a pasta "Novas Multimedia" FoldTab.55=Esconder a pasta "Ouviu Recentemente " FoldTab.56=Diret\u00f3rio FoldTab.57=Incluir na Nova Pasta Multimedia FoldTab.58=Aleat\u00f3rio FoldTab.59=<html><strong>Padr\u00e3o:</strong> desativado <br><strong>notas:</strong> isto torna a navega\u00e7\u00e3o mais lenta</html> FoldTab.60=<html><strong>Padr\u00e3o:</strong> desativado <br><strong>notas:</strong> pastas devem ter "Incluir na Nova Pasta de Multimedia" habilitado para ter seu conte\u00fado inclu\u00eddo na pasta Nova Multimedia.</html> FoldTab.61=<html><strong>Padr\u00e3o:</strong> desativado <br><strong>notas:</strong> quando essa configura\u00e7\u00e3o estiver desabilitada, o FFmpeg \u00e9 usado para gerar thumbnails. <br> MPlayer faz miniaturas na propor\u00e7\u00e3o correta (FFmpeg miniaturas s\u00e3o sempre em widescreen) mas pode ser ligeiramente mais lento</html> FoldTab.62=Nenhuma Classifica\u00e7\u00e3o FoldTab.64=<html><strong>Omiss\u00e3o:</strong> Ativado se estiver ativo o melhoramento de nomes de ficheiros<br><strong>Notas:</strong> Se ativado, os ficheiros ser\u00e3o mostrados assim:<ol><li>Show Name - 213 - Episode Title</li><li>Movie Name (2014)</li></ol>Se desativado, os ficheiros ser\u00e3o mostrados assim:<ol><li>Show.Name.S02E13.HDTV-GroupName</li><li>Movie.Name.720p.BluRay.x264-GroupName</ol></html> FoldTab.65=Monitorizar o estado de reprodu\u00e7\u00e3o dos ficheiros FoldTab.66=<html><strong>Omiss\u00e3o:</strong>Desativado<br><strong>Nota:</strong>As pastas devem ter ativo "Monitorizar estado dos ficheiros" para terem os seus conte\u00fados inclu\u00eddos na pasta de Novos M\u00e9dia.</html> FoldTab.67=N\u00e3o fazer nada FoldTab.68=Marcar ficheiro FoldTab.69=Esconder v\u00eddeo FoldTab.70=Mover o ficheiro para uma pasta diferente FoldTab.71=Mover o ficheiro para a reciclagem FoldTab.72=A\u00e7\u00e3o para totalmente reproduzido: FoldTab.73=Descarregar do Arquivo Capas de Arte FoldTab.74=Utilizar info de www.OpenSubtitles.org FoldTab.75=Marcar o conte\u00fado como; J\u00e1 Visto FoldTab.76=Marcar o conte\u00fado como: J\u00e1 Visto FontFileFilter.3=Fontes TrueType General.Unknown=Desconhecido General.3=Erro desconhecido GeneralTab.ForceDefaultRenderer=For\u00e7ar o renderizador pr\u00e9-definido GeneralTab.ForceDefaultRendererTooltip=<html><strong>Por defeito:</strong> Desativado<br><strong>Notas:</strong> Desativa a dete\u00e7\u00e3o autom\u00e1tica</html> GeneralTab.StartWithWindows=Iniciar com o Windows GeneralTab.2=Desinstalar servi\u00e7o do Windows GeneralTab.3=Servi\u00e7o do Windows desinstalado GeneralTab.5=Selecionar renderizadores GeneralTab.9=Execute o assistente de configura\u00e7\u00e3o (necessidades de reinicializa\u00e7\u00e3o do aplicativo) GeneralTab.10=Executar apenas uma inst\u00e2ncia do UMS GeneralTab.11=<html><strong>UMS deve ser executado como administrador para funcionar numa \u00fanica inst\u00e2ncia.</strong></html> GeneralTab.12=Usar a largura de banda m\u00e1xima autom\u00e1ticamente GeneralTab.13=Marcar/Desmarcar todos os renderizadores GeneralTab.14=Idioma: Generic.AutoDetect=Dete\u00e7\u00e3o autom\u00e1tica Generic.Basic=B\u00e1sico Generic.Copy=Copiar Generic.Folder=Pasta Generic.Full=Completo Generic.None=Nenhum Generic.Unknown=Desconhecido GenericIcons.DVDVideo=Video DVD KeyedComboBoxModel.1=Valor personalizado "%s" Language.af=Afric\u00e2ner Language.ar=\u00c1rabe Language.bg=B\u00falgaro Language.bn=Bengal\u00eas Language.ca=Catal\u00e3o Language.cs=Checo Language.da=Dinamarqu\u00eas Language.de=Alem\u00e3o Language.el=Grego Language.en-GB=Ingl\u00eas, Reino Unido Language.en-US=Ingl\u00eas, Estados Unidos Language.es=Espanhol Language.fa=Persa (Farsi) Language.fi=Finland\u00eas Language.fr=Franc\u00eas Language.hr=Croata Language.hu=H\u00fangaro Language.is=Island\u00eas Language.it=Italiano Language.iw=Hebreu Language.ja=Japon\u00eas Language.ko=Coreano Language.nl=Holand\u00eas Language.no=Noruegu\u00eas Language.pl=Polaco Language.pt-BR=Portugu\u00eas do Brasil Language.pt=Portugu\u00eas Language.ro=Romeno Language.ru=Russo Language.sk=Eslovaco Language.sl=Esloveno Language.sr=S\u00e9rvio (Cir\u00edlico) Language.sv=Sueco Language.th=Tailand\u00eas Language.tr=Turco Language.uk=Ucraniano Language.vi=Vietnamita Language.zh-Hant=Chin\u00eas (Tradicional) Language.zh-Hans=Chin\u00eas (Simplificado) LanguageSelection.1=Seleccione o idioma LanguageSelection.2=Por favor selecione um idioma para %s. Isso pode ser alterado mais tarde sob "%s". LanguageSelection.3=%s s\u00f3 \u00e9 %d%% traduzido. Tradu\u00e7\u00f5es em falta ser\u00e3o exibidas em ingl\u00eas. Se voc\u00ea quiser nos ajudar a melhorar nossas tradu\u00e7\u00f5es %s, por favor, veja abaixo. LanguageSelection.4=Sobre as tradu\u00e7\u00f5es LanguageSelection.5=Se o seu idioma est\u00e1 ausente ou incompleto, voc\u00ea pode contribuir tradu\u00e7\u00f5es. \u00c9 f\u00e1cil e voc\u00ea pode faz\u00ea-lo de seu web browser. Basta visitar <a href="%s"> nossa site crowdin</a> e come\u00e7ar a traduzir. LanguageSelection.6=N\u00e3o foi poss\u00edvel abrir o hiperlink, por favor visite "%s" manualmente LanguageSelection.7=Por favor selecione um idioma para %s. LinksTab.5=Links relacionados: LinksTab.6=Data de vers\u00e3o: LinksTab.7=projeto crowdin %s LooksFrame.BrowserError=Ocorreu um erro ao tentar iniciar o browser pr\u00e9-definido: LooksFrame.TabGeneralSettings=Defini\u00e7\u00f5es Gerais LooksFrame.TabNavigationSettings=Configura\u00e7\u00f5es de Navega\u00e7\u00e3o LooksFrame.TabSharedContent=Conte\u00fado Partilhado LooksFrame.URIError=N\u00e3o foi poss\u00edvel formar uma URL v\u00e1lida para a interface web. Consulte o registo para mais informa\u00e7\u00e3o. LooksFrame.5=Sair LooksFrame.6=Painel Principal LooksFrame.9=Guardar LooksFrame.12=Reiniciar Servidor LooksFrame.13=O servidor tem que ser reiniciado devido a uma altera\u00e7\u00e3o de configura\u00e7\u00e3o LooksFrame.18=Estado LooksFrame.19=Registo LooksFrame.21=Defini\u00e7\u00f5es de Transcoding LooksFrame.24=FAQ / Ajuda LooksFrame.25=Sobre LooksFrame.26=, \u00daNICAMENTE PARA TESTAR, POSSIVELMENTE INST\u00c1VEL LooksFrame.28=Isto reinicia o servidor HTTP, n\u00e3o o aplicativo LooksFrame.29=Interface Web LooksFrame.30=Corre a nossa Interface Web no navegador por defeito. MEncoderVideo.0=N\u00e3o usar loop filter deblocking para H.264: Pode degradar a qualidade, desactive se o CPU for suficientemente r\u00e1pido! MEncoderVideo.2=M\u00e9todo alternativo de sincroniza\u00e7\u00e3o A/V MEncoderVideo.3=Usar par\u00e2metros padr\u00e3o dos codecs (Recomendado!\n) MEncoderVideo.4=For\u00e7ar framerate analizado pelo FFmpeg MEncoderVideo.6=Op\u00e7\u00f5es personalizadas: MEncoderVideo.7=Prioridade da linguagem \u00e1udio: MEncoderVideo.8=Defini\u00e7\u00f5es de Legendas MEncoderVideo.9=Prioridade de Linguagem para Legendas: MEncoderVideo.10=Prioridade de Linguagem \u00e1udio/Legendas (exemplo: en,off;eng,off) MEncoderVideo.12=Defini\u00e7\u00f5es de fonte ASS: MEncoderVideo.13=Contorno da Fonte MEncoderVideo.14=Sombra da Fonte MEncoderVideo.15=Margem da Fonte MEncoderVideo.16=Defini\u00e7\u00f5es padr\u00e3o de fontes: MEncoderVideo.17=Contorno da Fonte MEncoderVideo.18=Borr\u00e3o da Fonte MEncoderVideo.19=Margem da Fonte MEncoderVideo.20=Legendas ASS/SSA MEncoderVideo.21=Fontconfig/Fontes incorporadas MEncoderVideo.22=Auto carregar legendas *.srt/*.sub com o mesmo nome do ficheiro MEncoderVideo.23=Modo de FriBiDi MEncoderVideo.24=Fonte TrueType espec\u00edfica (para l\u00ednguas asi\u00e1ticas): MEncoderVideo.25=Seleccionar Fonte TrueType MEncoderVideo.26=Filtro Deinterlace MEncoderVideo.27=Usar v\u00eddeo scaler: MEncoderVideo.28=Largura MEncoderVideo.29=Defini\u00e7\u00f5es avan\u00e7adas: Par\u00e2metros espec\u00edficos de Codecs MEncoderVideo.30=Altura MEncoderVideo.31=C\u00f4r MEncoderVideo.33=Par\u00e2metros personalizados: MEncoderVideo.34=Editar par\u00e2metros personalizados de codecs MEncoderVideo.35=Suporte multicore melhorado para conte\u00fado H.264 HD MEncoderVideo.36=Usar estilo ASS original MEncoderVideo.37=Pasta alternativa para legendas MEncoderVideo.38=Trocar para tsMuxeR quando o v\u00eddeo em H.264 \u00e9 compat\u00edvel com a ps3 e n\u00e3o h\u00e1 legendas configuradas [TS/M2T/MOV/MP4/AVI/MKV] MEncoderVideo.39=Remuxar faixa de video DVD ISO (sem reencode) MEncoderVideo.68=#Aqui pode usar par\u00e2metros espec\u00edficos para algumas combina\u00e7\u00f5es de codecs.\n MEncoderVideo.70=#Considerar como defini\u00e7\u00f5es avan\u00e7adas, n\u00e3o devendo ser usado se n\u00e3o souber exactamente como\n MEncoderVideo.71=#A sintaxe \u00e9 {java condition} :: {MEncoder options} ; Pode acumular diversas op\u00e7\u00f5es\n MEncoderVideo.72=#Tokens autorizados: filename srtfile container vcodec acodec samplerate framerate width height channels duration\n MEncoderVideo.75=#Op\u00e7\u00f5es especiais:\n MEncoderVideo.76=# -noass: desactiva definitivamente legendas ASS/SSA visto poderem interferir com a sincroniza\u00e7\u00e3o A/V\n MEncoderVideo.77=# -nosync: desactiva definitivamente m\u00e9todo alternativo de sincroniza\u00e7\u00e3o A/V para esta condi\u00e7\u00e3o (-mc far\u00e1 o mesmo)\n MEncoderVideo.78=# -quality: sobrepor defini\u00e7\u00f5es de quailidade de v\u00eddeo\n MEncoderVideo.87=#Pode usar aqui as suas pr\u00f3prias condi\u00e7\u00f5es/op\u00e7\u00f5es!\n Alguns exemplos: para activar o build mt do MEncoder\n MEncoderVideo.89=#para remover 24p judder numa TV de 50hz: framerate == 23.976 :: -speed 1.042709376 -ofps 25\n MEncoderVideo.91=#para remux quando o v\u00eddeo for MPEG-2 e n\u00e3o houver legendas: vcodec == mpeg2 && srtfile == null :: -ovc copy -nosync MEncoderVideo.92=DVD/VOBsub legendas de qualidade (0-4) (maior \u00e9 melhor): MEncoderVideo.93=Adicione bordas para compensa\u00e7\u00e3o do overscan: MEncoderVideo.94=For\u00e7ar Idioma: MEncoderVideo.95=For\u00e7ar etiquetas: MEncoderVideo.125=Escolher cor das legendas MEncoderVideo.126=eng,fre,jpn,ger,und MEncoderVideo.127=eng, fre, jpn, ger, und MEncoderVideo.128=eng, off; *, eng; *, und MEncoderVideo.133=Escala de Fonte MEncoderVideo.134=Normalizar o volume de \u00e1udio MEncoderVideo.135=# -nomux: Desativar multiplexa\u00e7\u00e3o via tsMuxeR\n MEncoderVideo.136=<html><strong>Omiss\u00e3o:</strong> Desativado<br><strong>Notas:</strong> Pode degradar a qualidade</html> MediaLibrary.98=Por Letra MediaLibrary.99=Por Ano NetworkTab.EmptyMediaLibrary=Esvaziar a Biblioteca de Media NetworkTab.EnableMediaLibrary=Activar a Biblioteca de Media NetworkTab.MediaLibraryEmptiedExceptFullyPlayed=A Biblioteca de Media ser\u00e1 esvaziada, excepto os totalmente visualizados. NetworkTab.PreventSleepDuringPlayback=Durante a reprodu\u00e7\u00e3o NetworkTab.PreventSleepLabel=Inibir Suspens\u00e3o: NetworkTab.PreventSleepNever=Nunca NetworkTab.PreventSleepToolTip=<html><strong>Defeito:</strong> Durante a reprodu\u00e7\u00e3o<br><br>Esta op\u00e7\u00e3o do UMS impede o sistema de entrar em suspens\u00e3o.</html> NetworkTab.PreventSleepWhileRunning=Durante a execu\u00e7\u00e3o NetworkTab.StartupScan=Verificar pastas partilhadas ao Iniciar NetworkTab.StartupScanTooltip=<html>por Defeito:</strong> true <br><br>Esta op\u00e7\u00e3o controla se as pastas partilhadas UMS s\u00e3o verificadas ao Iniciar. <br> \u00c9 recomend\u00e1vel para manter a biblioteca actualizada. <strong></html> NetworkTab.0=L\u00edngua [tem de reiniciar a aplica\u00e7\u00e3o]: NetworkTab.1=Navegar nos ficheiros .RAR/.ZIP/.CBR NetworkTab.2=Gerar miniaturas NetworkTab.3=Iniciar minimizado NetworkTab.4=Instalar como Servi\u00e7o do Windows NetworkTab.5=Defini\u00e7\u00f5es Gerais NetworkTab.8=Procurar por atualiza\u00e7\u00f5es NetworkTab.9=Verificar atualiza\u00e7\u00f5es automaticamente NetworkTab.11=Instalou o servi\u00e7o no Windows ! Para usar, tem de sair da aplica\u00e7\u00e3o,\n NetworkTab.12=depois iniciar (e configurar) o servi\u00e7o pelo painel de gest\u00e3o do Windows.\n\n NetworkTab.14=Erro na instala\u00e7\u00e3o do servi\u00e7o do Windows!\n NetworkTab.16=Posi\u00e7\u00e3o de procura de miniatura (em segundos): NetworkTab.19=Tem a certeza? NetworkTab.20=For\u00e7ar rede no interface: NetworkTab.22=Defini\u00e7\u00f5es de Rede, mude apenas se tiver problemas NetworkTab.23=For\u00e7ar IP do servidor: NetworkTab.24=For\u00e7ar porta do servidor (5001 por defeito): NetworkTab.30=Usar filtro IP: NetworkTab.31=Defini\u00e7\u00f5es avan\u00e7adas de HTTP e do sistema NetworkTab.32=Motor HTTP V2 NetworkTab.34=Sistema de Plugins NetworkTab.35=Largura de banda m\u00e1xima em Mb/s (0 significa sem limite): NetworkTab.36=Renderizador por omiss\u00e3o quando a dete\u00e7\u00e3o autom\u00e1tica falhar: NetworkTab.37=Renderizador desconhecido NetworkTab.40=Os Plugins ainda n\u00e3o est\u00e3o carregados. Aguarde. NetworkTab.41=Nome NetworkTab.42=Classifica\u00e7\u00e3o NetworkTab.43=Autores / Desenvolvedores NetworkTab.45=Cancelar NetworkTab.46=Instalar Plugins NetworkTab.47=A Transferir NetworkTab.48=Executando p\u00f3s-instala\u00e7\u00e3o de NetworkTab.49=est\u00e1 carregado e funcionando NetworkTab.50=Instalando NetworkTab.51=Editar manualmente o arquivo de configura\u00e7\u00e3o do UMS NetworkTab.52=Erro ao salvar o arquivo de configura\u00e7\u00e3o NetworkTab.53=Descri\u00e7\u00e3o NetworkTab.54=Editar o arquivo do Plugin de credencial NetworkTab.55=Erro ao salvar o arquivo da credencial do plugin NetworkTab.56=Habilitar a rede externa NetworkTab.58=UMS deve ser executado como administrador para alterar esta defini\u00e7\u00e3o. NetworkTab.59=Arquivo classifica\u00e7\u00e3o / nomea\u00e7\u00e3o NetworkTab.60=Pastas virtuais / arquivos NetworkTab.61=Ocultar op\u00e7\u00f5es avan\u00e7adas (necessidades de reinicializa\u00e7\u00e3o do aplicativo) NetworkTab.62=Habilitado para renderizadores: (precisa reiniciar o aplicativo) NetworkTab.63=N\u00e3o recomendado, basta selecionar "Iniciar minimizado" para o mesmo efeito. NetworkTab.64=<html>Se o servidor n\u00e3o pode encontrar seu renderer, pode ser porque a porta j\u00e1 est\u00e1 sendo utilizada por outro programa. <br>Nesse caso, voc\u00ea deve inserir uma porta n\u00e3o utilizada aqui.</html> NetworkTab.65=<html><strong>Padr\u00e3o:</strong> 90 <br><strong>notas:</strong> recomenda-se um valor de 90 para 100 Mbit conex\u00f5es, 30 para wireless e 0 para Gigabit</html> NetworkTab.67=<html><strong>Omiss\u00e3o:</strong> Ativado<br><strong>Notas:</strong> Controla se o UMS tentar\u00e1 aceder uma rede externa como a Internet</html> NetworkTab.68=Habilitar resumo do video NetworkTab.69=<html><strong>Omiss\u00e3o:</strong> Ativado<br><strong>Notas:</strong> Quando for ativado, se voc\u00ea assistir parcialmente um v\u00eddeo e ent\u00e3o reiniciar o UMS, ser\u00e1 criado um novo ficheiro virtual e mostrado juntamente com o ficheiro de v\u00eddeo na lista do renderizador.<br>A reprodu\u00e7\u00e3o desse novo ficheiro virtual recome\u00e7ar\u00e1 de onde tinha parado anteriormente, enquanto a reprodu\u00e7\u00e3o do ficheiro original come\u00e7ar\u00e1 do in\u00edcio como normalmente.<br><br>\u00c9 normal que o v\u00eddeo recomece at\u00e9 20 segundos antes de quando tinha parado.</html> NetworkTab.71=Nome do Servidor: NetworkTab.72=Acrescentar o nome do perfil NetworkTab.73=<html><strong>Omiss\u00e3o:</strong> Falso<br><strong>Notas:</strong> Quando estiver ativada, o nome do perfil do UMS (por omiss\u00e3o, o nome do seu computador) \u00e9 adicionado ao nome do servidor quando mostrado no renderizador.</html> NetworkTab.74=Ativar imagem de abertura PMS.MediaLibrary=Biblioteca de M\u00e9dia PMS.0=N\u00e3o foram encontrados renderizadores PMS.1=\u00c1udio PMS.3=M\u00e9todo alternativo para sincroniza\u00e7\u00e3o A/V PMS.4=Filtro de Deinterlace PMS.8=Legendas PMS.9=Todas as Playlists de \u00e1udio PMS.11=Todas as faixas \u00e1udio PMS.12=Por Data PMS.13=Por Artista PMS.14=Default H.264 Remux com MEncoder PMS.16=Por Album PMS.17=Renderizador desconhecido PMS.18=Ligado PMS.19=Por G\u00e9nero PMS.22=Por Artista/Album PMS.26=Por G\u00e9nero/Artista/Album PMS.27=Guardar configura\u00e7\u00e3o PMS.28=Por Letra/Artista/\u00c1lbum PMS.31=Foto PMS.32=Todas as Fotos PMS.34=V\u00eddeo PMS.35=Todos os V\u00eddeos PMS.36=V\u00eddeos HD PMS.37=#- Defini\u00e7\u00f5es de V\u00eddeo -# PMS.39=V\u00eddeos SD PMS.40=Imagens de DVD PMS.42=Erro ao iniciar UMS PMS.130=Procurando renderizadores... PMS.131=Configura\u00e7\u00f5es do Servidor PMS.132=Scripts PMS.133=#--LEGENDAS AO VIVO--# PMS.134=Resumir PMS.135=Gerir ficheiros de continua\u00e7\u00e3o PMS.136=Apagar todos os ficheiros PMS.141=Porta bloqueada. Alterar em Configura\u00e7\u00e3o geral. PMS.142=Cliente Web PMS.143=Procurar pastas de disco PMS.144=Pesquisar PMS.146=Lista de reprodu\u00e7\u00e3o din\u00e2mica PMS.147=#--PLAYLIST DIN\u00c2MICA--# PMS.148=para playlist din\u00e2mica PMS.149=Reiniciar a UMS PMS.150=Marcar todos como assistido PlayerControlPanel.0=Mostrar/ocultar detalhes PlayerControlPanel.1=Adicionar \u00e0 lista de reprodu\u00e7\u00e3o PlayerControlPanel.2=Remover da lista de reprodu\u00e7\u00e3o PlayerControlPanel.3=Limpar playlist PluginTab.0=Plugins instalados PluginTab.4=Propriet\u00e1rio PluginTab.5=Etiqueta PluginTab.6=Nome de utilizador PluginTab.7=Palavra Chave PluginTab.8=Credenciais PluginTab.9=Acrescentar PluginTab.10=Acrescentar/Editar credencial PluginTab.11=Editar PluginTab.12=Apagar PluginTab.13=Voc\u00ea tem certeza que quer apagar as credenciais selecionadas? PluginTab.14=Mostrar palavras chave PluginTab.16=Voc\u00ea n\u00e3o tem permiss\u00e3o para modificar a pasta de plugins. PluginTab.17=Pasta de plugins "%s" n\u00e3o encontrada. ProfileChooser.1=Seletor de perfis do Universal Media Server ProfileChooser.2=Selecionar ProfileChooser.3=Arquivo de perfil (.conf) ou diretoria ProgramExecutableType.Bundled=junto ProgramExecutableType.Custom=personalizado ProgramExecutableType.Installed=instalado RendererPanel.1=Controlos RendererPanel.2=Iniciar um novo ficheiro de configura\u00e7\u00e3o RendererPanel.3=Abrir a configura\u00e7\u00e3o pai RendererPanel.4=Sem configura\u00e7\u00e3o pai RendererPanel.5=Personalizar este dispositivo RendererPanel.6=Substituir o ficheiro existente? RendererPanel.7=O ficheiro existe RendererPanel.8=Forne\u00e7a um nome de ficheiro RendererPanel.9=Forne\u00e7a um ficheiro de refer\u00eancia RendererPanel.10=Nome RendererPanel.11=Endere\u00e7o SharedContentTab.AddNewWebContent=Adicionar novo conte\u00fado web SharedContentTab.ArrowDown=Mover a pasta selecionada para baixo SharedContentTab.ArrowUp=Mover a pasta selecionada para cima SharedContentTab.AudioFeed=Podcast SharedContentTab.AudioStream=Transmiss\u00e3o de \u00e1udio SharedContentTab.ConfirmRemove=Isto ir\u00e1 remover %d pastas. Tem certeza? SharedContentTab.FolderName=Nome da Pasta SharedContentTab.FoldersColon=Pastas: (separadas por v\u00edrgula): SharedContentTab.ImageFeed=Feed de imagem SharedContentTab.MoveSelectedWebContentDown=Mover conte\u00fado web para baixo SharedContentTab.MoveSelectedWebContentUp=Mover conte\u00fado web para cima SharedContentTab.RemoveSelectedWebContent=Remover conte\u00fado web selecionado SharedContentTab.Source=Origem SharedContentTab.SourceURLColon=Origem/URL: SharedContentTab.Type=Tipo SharedContentTab.TypeColon=Tipo: SharedContentTab.VideoFeed=Feed de v\u00eddeo SharedContentTab.VideoStream=Transmiss\u00e3o de v\u00eddeo SharedContentTab.WebContent=Conte\u00fado web SleepManager.PostponeSleepName=Repor o contador inactivo do Universal Media Server SleepManager.PreventSleepPlaybackDetails=Durante a reprodu\u00e7\u00e3o, a Suspens\u00e3o do sistema fica inactiva SleepManager.PreventSleepPlaybackName=Universal Media Server em reprodu\u00e7\u00e3o SleepManager.PreventSleepRunningDetails=Durante a reprodu\u00e7\u00e3o do Universal Media Server, a Suspens\u00e3o do sistema fica inactiva SleepManager.PreventSleepRunningName=Universal Media Server em reprodu\u00e7\u00e3o Splash.1=Desativar a imagem de abertura durante a inicializa\u00e7\u00e3o? Splash.2=Configura\u00e7\u00e3o de ecr\u00e3 de entrada StatusTab.2=Estado StatusTab.3=A aguardar... StatusTab.5=Vazio StatusTab.6=Buffer: StatusTab.9=Media renderers detectados StatusTab.11=Mb/s StatusTab.12=MB StatusTab.13=Bitrate: StatusTab.14=Atual: StatusTab.15=Pico: Subtitles.ExternalShort=Ext. Subtitles.InternalShort=Int. Subtitles.LiveSubtitles=Legendas online Subtitles.LowerCase=legendas Subtitles.UnknownShort=Desc. TrTab2.DeleteLiveSubtitles=Eliminar legendas descarregadas ap\u00f3s uso TrTab2.DeleteLiveSubtitlesTooltip=<html><strong>por Defeiro:</strong> False <br>Determina se o Download de Legendas online s\u00e3o exclu\u00eddas do disco quando a reprodu\u00e7\u00e3o termina. Manter as legendas permitir\u00e1 a reutiliza\u00e7\u00e3o e requer muito pouco espa\u00e7o em disco.</html> TrTab2.LiveSubtitlesLimit=Limitar o numero de legendas descarregadas, em: TrTab2.LiveSubtitlesLimitTooltip=<html><strong>por Defeiro:</strong> 20 <br>Define o n\u00famero m\u00e1ximo de legendas descarregadas por v\u00eddeo. A legenda, considerada melhore \u00e9 real\u00e7ada, se existirem v\u00e1rias.</html> TrTab2.0=Activar/desactivar um motor de transcoding TrTab2.1=Sem defini\u00e7\u00f5es para configurar por agora TrTab2.5=Defini\u00e7\u00f5es comuns de transcode TrTab2.6=Ordenar a lista de motores de transcoding. O primeiro ir\u00e1 aparecer na pasta original de v\u00eddeo TrTab2.7=V\u00e1rias op\u00e7\u00f5es TrTab2.8=Saltar transcode para as seguintes extens\u00f5es (separadas por v\u00edrgulas): TrTab2.9=For\u00e7ar transcode para as seguintes extens\u00f5es (separadas por v\u00edrgulas): TrTab2.11=Motores TrTab2.14=Motores de ficheiros de v\u00eddeo TrTab2.15=Motores de ficheiros de \u00e1udio TrTab2.16=Motores de streaming de v\u00eddeo web TrTab2.17=Motores de streaming de \u00e1udio Web TrTab2.18=Motores v\u00e1rios TrTab2.19=Motor a negrito ser\u00e1 o priorit\u00e1rio TrTab2.20=e ir\u00e1 substituir o v\u00eddeo original TrTab2.21=AviSynth n\u00e3o suportado. TrTab2.22=Reamostragem autom\u00e1tica de \u00e1udio para 44.1 ou 48Khz TrTab2.23=Tamanho m\u00e1ximo do transcode buffer em MB: (recomendado: 200) TrTab2.24=N\u00famero de n\u00facleos usados para transcoding (parece que tem %d): TrTab2.26=Manter faixas AC-3 TrTab2.27=Use LPCM para \u00e1udio TrTab2.28=Manter faixas DTS TrTab2.29=Bitrate de \u00e1udio AC-3 (em Kbits/s) (ex: 384, 576, 640): TrTab2.32=Defini\u00e7\u00f5es MPEG-2: TrTab2.50=N\u00famero de canais de \u00e1udio: TrTab2.51=Desactivar completamente as legendas TrTab2.52=Intervalo em minutos para a pasta Capitulos #Transcode# : TrTab2.53=Passagem de \u00e1udio codificada para AC-3 e o DTS TrTab2.55=2 canais (Stereo) TrTab2.56=6 canais (5.1) TrTab2.60=Grande qualidade TrTab2.61=Qualidade sem perdas TrTab2.62=Boa qualidade TrTab2.63=Boa qualidade (HD Wi-Fi) TrTab2.64=Qualidade m\u00e9dia (HD Wi-Fi) TrTab2.65=Baixa qualidade (CPU lento) TrTab2.67=Configura\u00e7\u00f5es de v\u00eddeo TrTab2.68=Defini\u00e7\u00f5es de \u00c1udio TrTab2.70=Habilitar a acelera\u00e7\u00e3o GPU TrTab2.71=Recomendado para redes com cabo TrTab2.72=Recomendado para redes sem fios TrTab2.73=<html><strong>Padr\u00e3o:</strong> 200 <br><strong>Notas:</strong> Usando uma configura\u00e7\u00e3o maior do que 200 pode causar problemas de saltos</html> TrTab2.74=<html><strong>Padr\u00e3o:</strong> Autom\u00e1tico (Com cabo ou sem fios, dependendo se o assistente de configura\u00e7\u00e3o foi executado) <br><strong>Notas:</strong> As configura\u00e7\u00f5es autom\u00e1ticas ir\u00e3o utilizar o m\u00e1ximo de qualidade para o seu sistema e s\u00e3o altamente recomendadas</html> TrTab2.75=<html><strong>Padr\u00e3o:</strong> Depende do idioma do programa. Geralmente "eng, fre, jpn, ger, und" <br><strong>Notas:</strong> voc\u00ea pode reorganizar a ordem dos idiomas ou adicionar qualquer novos c\u00f3digos de linguagem de 3-letras para esta lista <br>UMS ir\u00e1 carregar faixas de \u00e1udio nesta ordem</html> TrTab2.76=<html><strong>Padr\u00e3o:</strong> Depende do idioma do programa. Geralmente "eng, fre, jpn, ger, und" <br><strong>notas:</strong> Voc\u00ea pode reorganizar a ordem dos idiomas ou adicionar qualquer novo <a href="http://en.wikipedia.org/wiki/List_of_ISO_639-2_codes"> c\u00f3digos de idioma de 3-letras</a> para esta lista <br>UMS ir\u00e1 carregar faixas de legendas nesta ordem</html> TrTab2.77=<html><strong>Padr\u00e3o:</strong> Depende do idioma do programa. Geralmente "eng, fora; *, eng; *, und" <br><strong>Notas:</strong> uma explica\u00e7\u00e3o sobre o valor padr\u00e3o \u00e9: <ol><li>se o idioma de \u00e1udio \u00e9 Ingl\u00eas, legendas devem estar desligadas (sem legendas)</li> <li>se o idioma de \u00e1udio \u00e9 outro, carregar legendas em Ingl\u00eas</li> <li>se n\u00e3o houver legendas em Ingl\u00eas, carregar legendas indefinidas (legendas que n\u00e3o tiveram seu idioma especificado)</li></ol></html> TrTab2.78=<html><strong>Padr\u00e3o:</strong> Ativado <br><strong>Notas:</strong> se essa op\u00e7\u00e3o estiver ativada, legendas externas ser\u00e3o carregadas e priorizadas sobre legendas internas, mas ainda sujeito a suas prefer\u00eancias de prioridade do idioma</html> TrTab2.79=Qualidade de transcodifica\u00e7\u00e3o (H.264): TrTab2.80=Recomendado TrTab2.81=<html><strong>Padr\u00e3o:</strong> Autom\u00e1tico <br><strong>Notas:</strong> A configura\u00e7\u00e3o autom\u00e1tica ir\u00e1 servir a melhor qualidade para o seu sistema e \u00e9 altamente recomendada. <br> Voc\u00ea pode tamb\u00e9m manualmente especificar qualidade inserindo um valor de CRF.</html> TrTab2.82=<html><strong>Padr\u00e3o:</strong> Ativado <br><strong>Notas:</strong> Quando ativado, multiplexa as faixas de DVD v\u00eddeo em vez de transcodificacar.</html> TrTab2.83=<html><strong>Padr\u00e3o:</strong> Desativado <br><strong>Notas:</strong> Esta op\u00e7\u00e3o \u00e9 sem perdas, mas pode n\u00e3o ser a melhor escolha para conex\u00f5es sem fios por causa de sua alta taxa de bitrate.</html> TrTab2.84=<html><strong>Padr\u00e3o:</strong> Ativado <br><strong>Notas:</strong> Esta op\u00e7\u00e3o \u00e9 sem perdas e \u00e9 muito est\u00e1vel. No entanto se o \u00e1udio estiver fora de sincroniza\u00e7\u00e3o ou cortado, desabilitar pode ajudar.</html> TrTab2.85=<html><strong>Padr\u00e3o:</strong> Desativado <br><strong>Notas:</strong> Esta op\u00e7\u00e3o \u00e9 sem perdas mas, <strong>pode ser inst\u00e1vel</strong> em alguns dispositivos. <br> Para us\u00e1-la, o seu receptor deve suportar DTS e ser conectado via HDMI ou cabo \u00f3ptico.</html> TrTab2.86=<html><strong>Padr\u00e3o:</strong> Desativado <br><strong>Notas:</strong> Esta op\u00e7\u00e3o \u00e9 sem perdas.</html> TrTab2.87=For\u00e7ar legendas externas TrTab2.88=<html><strong>Padr\u00e3o:</strong> Ativado <br><strong>Notas:</strong> Se essa op\u00e7\u00e3o estiver ativada, legenda externas sempre ser\u00e3o exibidas caso elas existam. <br> Elas ser\u00e3o carregadas em ordem de prioridades do idioma, mas vamos ignorar a linguagem "desativada".</html> TrTab2.89=<html><strong>Padr\u00e3o:</strong> Ativado <br><strong>Notas:</strong> Se ativado, n\u00f3s n\u00e3o vamos modificar o estilo das legendas que tenham o seu pr\u00f3prio estilo (legendas ASS/SSA).</html> TrTab2.90=Profundidade legendas 3D TrTab2.92=Autom\u00e1tico (com fios) - recomendado para redes com cabo TrTab2.93=Autom\u00e1tico (sem fios) - recomendado para redes sem fios TrTab2.94=<html><strong>Padr\u00e3o:</strong> Auto detectar <br><strong>notas:</strong> voc\u00ea pode encontrar a lista de codifica\u00e7\u00f5es de caracteres suportados na <a href="http://userguide.icu-project.org/conversion/detection#TOC-Detected-Encodings"> p\u00e1gina ICU4J</a>. <br> <strong>AVISO:</strong> Se definir o c\u00f3digo de caracteres manualmente, legendas que usem codifica\u00e7\u00e3o diferente, podem n\u00e3o ser exibidas corretamente.</html> TrTab2.95=Codifica\u00e7\u00e3o de legendas "Non-unicode": TrTab2.96=<html><strong>Nota:</strong> isso substitui a configura\u00e7\u00e3o de renderer. Ele s\u00f3 deve ser usado para solucionar problemas quando voc\u00ea n\u00e3o \u00e9 capaz de editar a configura\u00e7\u00e3o de renderer.</html> TrTab2.97=<html>Para us\u00e1-la a fonte deve ser registada no sistema operativol. Para us\u00e1-las deve ser especificado o nome da fonte ou pelo ficheiro fonte. <br>No Win OS o ficheiro da fonte deve ser colocado na pasta "WindowsFonts" ou utilizadores Win 10 podem clicar com o bot\u00e3o direito do rato <br>no ficheiro de fonte e escolher "Instalar". Para outros sistemas operativos, o ficheiro de fonte deve ser tamb\u00e9m colocado na pasta fonte <br>ou usada uma t\u00e9cnica espec\u00edfica para registr\u00e1-lo no sistema operativo. <br> Se n\u00e3o forem devidamente especificadas ou n\u00e3o registradas no sistema operacional a fonte padr\u00e3o \u00e9 usada.</html> TracesTab.3=Limpar TracesTab.4=Arquivar ficheiros de depura\u00e7\u00e3o TracesTab.5=Abri log de depura\u00e7\u00e3o completo TracesTab.6=Erro TracesTab.7=Aviso TracesTab.8=Informa\u00e7\u00f5es TracesTab.9=Depura\u00e7\u00e3o de erros TracesTab.10=Rastreamento TracesTab.11=N\u00edvel de log TracesTab.12=Criar Logs de RASTREAMENTO TracesTab.13=<html>Para relatar mais quest\u00f5es \u00e9 melhor: <ul><li>reiniciar UMS no modo de log de rastreamento</li> <li>reproduzir o problema</li> <li>zipar logs usando o bot\u00e3o ' Empacotar ficheiros de depura\u00e7\u00e3o'</li></ul> Reiniciar UMS em modo de log de RASTREAMENTO?</html> TracesTab.14=N\u00edvel de log de inicializa\u00e7\u00e3o n\u00e3o foi RASTREADO TracesTab.15=Todos TracesTab.16=Desigado TracesTab.17=Linha de Buffer: TracesTab.18=Mostrar op\u00e7\u00f5es de logging TracesTab.19=Sens\u00edvel a Mai\u00fasculas e Min\u00fasculas TracesTab.20=Multilinha TracesTab.21='%s' n\u00e3o encontrado TracesTab.22=Erro de RegEx: %s TracesTab.23=Erro de pesquisa TracesTab.24=Filtro TracesTab.25=Registo com buffer: TracesTab.26=Op\u00e7\u00f5es de registo TracesTab.27=Registo para syslog: TracesTab.28=Syslog nome de host: TracesTab.29=Porta de Syslog: TracesTab.30=Syslog facility: TracesTab.31=Nome do host syslog n\u00e3o pode estar vazio! TracesTab.32="%s" n\u00e3o \u00e9 um nome de host ou endere\u00e7o IP v\u00e1lido! TracesTab.33=<html>Filtro de mensagens de log unicamente para a janela de log abaixo. Este filtro funciona ap\u00f3s o "filtro de raiz" especificado no "N\u00edvel de Log", que filtra todos os logs, incluindo logs de arquivo <br>.</html> TracesTab.34=Pesquise o log abaixo da posi\u00e7\u00e3o atual. Definir posi\u00e7\u00e3o clicando na janela de log. TracesTab.35=S\u00f3 procurar texto que corresponda a caso a frase busca. TracesTab.36=<html>Pesquisar usando <a href="https://en.wikipedia.org/wiki/Regular_expression"> express\u00f5es regulares</a>.</html> TracesTab.37=Habilite a pesquisa abranger v\u00e1rias linhas. TracesTab.38=O n\u00famero de linhas que a janela de log abaixo ir\u00e1 manter antes de eliminar o mais velho. TracesTab.39=Reinicie o servidor de m\u00eddia Universal no modo "Rastrear" criando registros detalhados por exemplo por relatar um problema. TracesTab.40=Empacotar de log e arquivos de configura\u00e7\u00e3o em um arquivo comprimido que pode ser facilmente carregado. TracesTab.41=Mostrar as op\u00e7\u00f5es configura\u00e7\u00f5es de registo. TracesTab.42=Defina o n\u00edvel de log de "raiz" que decide quais mensagens ser\u00e3o registradas para todos os destinos do log. TracesTab.43=<html>Activar o buffer/cache para arquivo de log. Em vez de escrever o log em disco para cada nova linha, o Universal Media Server escreve <br>pacotes de 8 KiB no disco. Isto ir\u00e1 reduzir o n\u00famero de grava\u00e7\u00f5es de disco, que pode estender a vida <br>de discos r\u00edgidos, drives de estado s\u00f3lido especialmente. Note que se o Universal Media Server terminar ou for encerrado externamente, <br>algumas linhas podem n\u00e3o ter sido escritas no log.</html> TracesTab.44=<html>Enviar o log para um <a href="https://en.wikipedia.org/wiki/Syslog"> servidor syslog</a>, em vez de para disco. Isto torna poss\u00edvel enviar todos os logs<br>para um computador diferente para reduzir o <a href="https://en.wikipedia.org/wiki/Input/output"> I/O</a> ou simplesmente para coleccionar logs num local dedicado.</html> TracesTab.45=<html>o computador host/nome ou endere\u00e7o IP para enviar as mensagens do syslog para. <br>Use <strong>localhost</strong> para enviar as mensagens do syslog para o computador local.</html> TracesTab.46=<html>Porta UDP para enviar mensagens syslog. O <strong>padr\u00e3o \u00e9 514</strong> e normalmente deve ser deixado por defeito.</html> TracesTab.47=<html><a href="https://en.wikipedia.org/wiki/Syslog#Facility"> instala\u00e7\u00f5es de Syslog</a> destina-se a identificar a fonte das mensagens de log. Infelizmente, <a href="https://tools.ietf.org/html/rfc3164"> o padr\u00e3o</a> foi definido <br>h\u00e1 muito tempo atr\u00e1s e a lista n\u00e3o \u00e9 extens\u00edvel. \u00c9 um pouco \u00fatil para filtragem de mensagens num est\u00e1gio posterior.</html> TranscodeVirtualFolder.0=#--TRANSCODIFICAR--# TreeNodeSettings.4=Este motor n\u00e3o est\u00e1 carregado! TsMuxeRVideo.2=For\u00e7ar FPS analizado pelo FFmpeg no ficheiro meta TsMuxeRVideo.19=Muxar todas a faixas de audio VirtualFolder.Watched=Visto VirtualFolder.1=Reproduzido Recentemente VirtualFolder.2=Novas m\u00eddias VirtualFolder.3=Listas de reprodu\u00e7\u00e3o salvas VirtualFolder.4=Emiss\u00e3o de TV VirtualFolder.5=Filmes VirtualFolder.6=Temporada VirtualFolder.7=Filmes 3D VirtualFolder.8=Desordenado VirtualFolder.9=Ainda n\u00e3o visto VlcTrans.3=Habilitar codecs experimentais Web.1=Reproduzirr em outro renderizador Web.2=Sem UPnP-control\u00e1veis renderizadores apropriados para receber a m\u00eddia est\u00e3o dispon\u00edveis. Atualize esta p\u00e1gina se um renderizador novo pode ter ligado recentemente. Web.3=N\u00e3o h\u00e1 outros renderizadores dispon\u00edveis Web.4=Remover da lista de reprodu\u00e7\u00e3o Web.5=Adicionar \u00e0 lista de reprodu\u00e7\u00e3o Web.6=Este item n\u00e3o \u00e9 utiliz\u00e1vel atrav\u00e9s do navegador, mas pode ser enviado para outros renderizadores. Web.7=(N\u00c3O UTILIZ\u00c1VEL NO NAVEGADOR) Web.8=Digite a sequ\u00eancia de pesquisa: Web.9=Digite o c\u00f3digo: Web.10=Voltar Wizard.IsStartupScan=Pretende que o UMS procure pastas partilhadas quando o programa inicia?\nIsto garante que a pasta Biblioteca de Media est\u00e1 atualizada.\nO programa pode ficar mais lento durante a procura. Wizard.2=Assistente de configura\u00e7\u00e3o: Pergunta Wizard.3=O UMS deve iniciar minimizado? Wizard.4=de Wizard.7=Qual das seguintes op\u00e7\u00f5es melhor descreve a sua rede? Wizard.8=Cabo (Gigabit) Wizard.9=Cabo (100 Megabit) Wizard.10=Sem fios Wizard.11=O UMS deve ocultar as op\u00e7\u00f5es avan\u00e7adas? Elas podem ser ativadas mais tarde Wizard.12=Por fim, escolha uma pasta para partilhar. Pode escolher posteriormente na aba Configura\u00e7\u00f5es de Navega\u00e7\u00e3o/Partilha.\n\nSe n\u00e3o escolher uma pasta, ser\u00e1 definido por defeito com base no seu sistema operativo.
{ "pile_set_name": "Github" }
# Define some default values that can be overridden by system properties hadoop.log.dir=. hadoop.log.file=hadoop.log # RootLogger - DailyRollingFileAppender log4j.rootLogger=INFO,DRFA # Logging Threshold log4j.threshhold=ALL #special logging requirements for some commandline tools log4j.logger.org.apache.nutch.crawl.Crawl=INFO,cmdstdout log4j.logger.org.apache.nutch.crawl.Injector=INFO,cmdstdout log4j.logger.org.apache.nutch.crawl.Generator=INFO,cmdstdout log4j.logger.org.apache.nutch.fetcher.Fetcher=INFO,cmdstdout log4j.logger.org.apache.nutch.parse.ParseSegment=INFO,cmdstdout log4j.logger.org.apache.nutch.crawl.CrawlDbReader=INFO,cmdstdout log4j.logger.org.apache.nutch.crawl.CrawlDbMerger=INFO,cmdstdout log4j.logger.org.apache.nutch.crawl.LinkDbReader=INFO,cmdstdout log4j.logger.org.apache.nutch.segment.SegmentReader=INFO,cmdstdout log4j.logger.org.apache.nutch.segment.SegmentMerger=INFO,cmdstdout log4j.logger.org.apache.nutch.crawl.CrawlDb=INFO,cmdstdout log4j.logger.org.apache.nutch.crawl.LinkDb=INFO,cmdstdout log4j.logger.org.apache.nutch.crawl.LinkDbMerger=INFO,cmdstdout log4j.logger.org.apache.nutch.indexer.Indexer=INFO,cmdstdout log4j.logger.org.apache.nutch.indexer.DeleteDuplicates=INFO,cmdstdout log4j.logger.org.apache.nutch.indexer.IndexMerger=INFO,cmdstdout #log4j.logger.org.apache.nutch=INFO #log4j.logger.org.apache.hadoop=WARN log4j.logger.org.apache.nutch=DEBUG log4j.logger.org.apache.hadoop=DEBUG # # Daily Rolling File Appender # log4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender log4j.appender.DRFA.File=${hadoop.log.dir}/${hadoop.log.file} # Rollver at midnight log4j.appender.DRFA.DatePattern=.yyyy-MM-dd # 30-day backup #log4j.appender.DRFA.MaxBackupIndex=30 log4j.appender.DRFA.layout=org.apache.log4j.PatternLayout # Pattern format: Date LogLevel LoggerName LogMessage log4j.appender.DRFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} - %m%n # Debugging Pattern format: Date LogLevel LoggerName (FileName:MethodName:LineNo) LogMessage #log4j.appender.DRFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n # # stdout # Add *stdout* to rootlogger above if you want to use this # log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n # # plain layout used for commandline tools to output to console # log4j.appender.cmdstdout=org.apache.log4j.ConsoleAppender log4j.appender.cmdstdout.layout=org.apache.log4j.PatternLayout log4j.appender.cmdstdout.layout.ConversionPattern=%m%n # # Rolling File Appender # #log4j.appender.RFA=org.apache.log4j.RollingFileAppender #log4j.appender.RFA.File=${hadoop.log.dir}/${hadoop.log.file} # Logfile size and and 30-day backups #log4j.appender.RFA.MaxFileSize=1MB #log4j.appender.RFA.MaxBackupIndex=30 #log4j.appender.RFA.layout=org.apache.log4j.PatternLayout #log4j.appender.RFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} - %m%n #log4j.appender.RFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "lib/commons.h" #include "util/StringUtil.h" #include "MCollectorOutputHandler.h" #include "lib/NativeObjectFactory.h" #include "lib/MapOutputCollector.h" #include "CombineHandler.h" using std::string; using std::vector; namespace NativeTask { const Command AbstractMapHandler::GET_OUTPUT_PATH(100, "GET_OUTPUT_PATH"); const Command AbstractMapHandler::GET_OUTPUT_INDEX_PATH(101, "GET_OUTPUT_INDEX_PATH"); const Command AbstractMapHandler::GET_SPILL_PATH(102, "GET_SPILL_PATH"); const Command AbstractMapHandler::GET_COMBINE_HANDLER(103, "GET_COMBINE_HANDLER"); } // namespace NativeTask
{ "pile_set_name": "Github" }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.apigateway.v20180808.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ModifyApiIncrementResponse extends AbstractModel{ /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public String getRequestId() { return this.RequestId; } /** * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
{ "pile_set_name": "Github" }
CMake - Cross Platform Makefile Generator Copyright 2000-2014 Kitware, Inc. Copyright 2000-2011 Insight Software Consortium Copyright 2014 Justin Jacobs <[email protected]> Copyright 2015 Cong Xu <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of Kitware, Inc., the Insight Software Consortium, nor the names of their contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ The above copyright and license notice applies to distributions of CMake in source and binary form. Some source files contain additional notices of original copyright by their contributors; see each source for details. Third-party software packages supplied with CMake under compatible licenses provide their own copyright notices documented in corresponding subdirectories. ------------------------------------------------------------------------------ CMake was initially developed by Kitware with the following sponsorship: * National Library of Medicine at the National Institutes of Health as part of the Insight Segmentation and Registration Toolkit (ITK). * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel Visualization Initiative. * National Alliance for Medical Image Computing (NAMIC) is funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. * Kitware, Inc.
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); namespace Documents\Functional; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** @ODM\Document(collection="embedded_test") */ class EmbeddedTestLevel0 { /** @ODM\Id */ public $id; /** @ODM\Field(type="string") */ public $name; /** @ODM\EmbedMany(targetDocument=EmbeddedTestLevel1::class) */ public $level1 = []; }
{ "pile_set_name": "Github" }
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 org.sakaibrary.xserver.session; public class MetasearchSession implements java.io.Serializable { private static final long serialVersionUID = 1L; private String guid; private String username; private String password; private boolean isLoggedIn; private String sessionId; private String baseUrl; private org.osid.shared.Id repositoryId; private String repositoryDisplayName; private org.osid.shared.Properties searchProperties; private java.util.Properties searchStatusProperties; private boolean singleSearchSource; private boolean gotMergeError; private String foundGroupNumber; private String mergedGroupNumber; private String recordsSetNumber; private Integer numRecordsFound; private Integer numRecordsFetched; private Integer numRecordsMerged; public MetasearchSession( String guid ) { this.guid = guid; } public String getGuid() { return guid; } public String getFoundGroupNumber() { return foundGroupNumber; } public void setFoundGroupNumber(String foundGroupNumber) { this.foundGroupNumber = foundGroupNumber; } public boolean isLoggedIn() { return isLoggedIn; } public void setLoggedIn(boolean isLoggedIn) { this.isLoggedIn = isLoggedIn; } public String getRecordsSetNumber() { return recordsSetNumber; } public void setRecordsSetNumber(String recordsSetNumber) { this.recordsSetNumber = recordsSetNumber; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Integer getNumRecordsFound() { return numRecordsFound; } public void setNumRecordsFound(Integer numRecordsFound) { this.numRecordsFound = numRecordsFound; } public Integer getNumRecordsFetched() { return numRecordsFetched; } public void setNumRecordsFetched(Integer numRecordsFetched) { this.numRecordsFetched = numRecordsFetched; } public String getMergedGroupNumber() { return mergedGroupNumber; } public void setMergedGroupNumber(String mergedGroupNumber) { this.mergedGroupNumber = mergedGroupNumber; } public org.osid.shared.Properties getSearchProperties() { return searchProperties; } public void setSearchProperties(org.osid.shared.Properties searchProperties) { this.searchProperties = searchProperties; } public org.osid.shared.Id getRepositoryId() { return repositoryId; } public void setRepositoryId(org.osid.shared.Id repositoryId) { this.repositoryId = repositoryId; } public String getRepositoryDisplayName() { return repositoryDisplayName; } public void setRepositoryDisplayName(String repositoryDisplayName) { this.repositoryDisplayName = repositoryDisplayName; } public Integer getNumRecordsMerged() { return numRecordsMerged; } public void setNumRecordsMerged(Integer numRecordsMerged) { this.numRecordsMerged = numRecordsMerged; } public boolean isSingleSearchSource() { return singleSearchSource; } public void setSingleSearchSource(boolean singleSearchSource) { this.singleSearchSource = singleSearchSource; } public boolean isGotMergeError() { return gotMergeError; } public void setGotMergeError(boolean gotMergeError) { this.gotMergeError = gotMergeError; } public java.util.Properties getSearchStatusProperties() { return searchStatusProperties; } public void setSearchStatusProperties( java.util.Properties searchStatusProperties) { this.searchStatusProperties = searchStatusProperties; } public String getBaseUrl() { return baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
{ "pile_set_name": "Github" }
<?php /** * Build Administration Menu. * * @package WordPress * @subpackage Administration */ if ( is_network_admin() ) { /** * Fires before the administration menu loads in the Network Admin. * * The hook fires before menus and sub-menus are removed based on user privileges. * * @private * @since 3.1.0 */ do_action( '_network_admin_menu' ); } elseif ( is_user_admin() ) { /** * Fires before the administration menu loads in the User Admin. * * The hook fires before menus and sub-menus are removed based on user privileges. * * @private * @since 3.1.0 */ do_action( '_user_admin_menu' ); } else { /** * Fires before the administration menu loads in the admin. * * The hook fires before menus and sub-menus are removed based on user privileges. * * @private * @since 2.2.0 */ do_action( '_admin_menu' ); } // Create list of page plugin hook names. foreach ($menu as $menu_page) { if ( false !== $pos = strpos($menu_page[2], '?') ) { // Handle post_type=post|page|foo pages. $hook_name = substr($menu_page[2], 0, $pos); $hook_args = substr($menu_page[2], $pos + 1); wp_parse_str($hook_args, $hook_args); // Set the hook name to be the post type. if ( isset($hook_args['post_type']) ) $hook_name = $hook_args['post_type']; else $hook_name = basename($hook_name, '.php'); unset($hook_args); } else { $hook_name = basename($menu_page[2], '.php'); } $hook_name = sanitize_title($hook_name); if ( isset($compat[$hook_name]) ) $hook_name = $compat[$hook_name]; elseif ( !$hook_name ) continue; $admin_page_hooks[$menu_page[2]] = $hook_name; } unset($menu_page, $compat); $_wp_submenu_nopriv = array(); $_wp_menu_nopriv = array(); // Loop over submenus and remove pages for which the user does not have privs. foreach ($submenu as $parent => $sub) { foreach ($sub as $index => $data) { if ( ! current_user_can($data[1]) ) { unset($submenu[$parent][$index]); $_wp_submenu_nopriv[$parent][$data[2]] = true; } } unset($index, $data); if ( empty($submenu[$parent]) ) unset($submenu[$parent]); } unset($sub, $parent); /* * Loop over the top-level menu. * Menus for which the original parent is not accessible due to lack of privileges * will have the next submenu in line be assigned as the new menu parent. */ foreach ( $menu as $id => $data ) { if ( empty($submenu[$data[2]]) ) continue; $subs = $submenu[$data[2]]; $first_sub = reset( $subs ); $old_parent = $data[2]; $new_parent = $first_sub[2]; /* * If the first submenu is not the same as the assigned parent, * make the first submenu the new parent. */ if ( $new_parent != $old_parent ) { $_wp_real_parent_file[$old_parent] = $new_parent; $menu[$id][2] = $new_parent; foreach ($submenu[$old_parent] as $index => $data) { $submenu[$new_parent][$index] = $submenu[$old_parent][$index]; unset($submenu[$old_parent][$index]); } unset($submenu[$old_parent], $index); if ( isset($_wp_submenu_nopriv[$old_parent]) ) $_wp_submenu_nopriv[$new_parent] = $_wp_submenu_nopriv[$old_parent]; } } unset($id, $data, $subs, $first_sub, $old_parent, $new_parent); if ( is_network_admin() ) { /** * Fires before the administration menu loads in the Network Admin. * * @since 3.1.0 * * @param string $context Empty context. */ do_action( 'network_admin_menu', '' ); } elseif ( is_user_admin() ) { /** * Fires before the administration menu loads in the User Admin. * * @since 3.1.0 * * @param string $context Empty context. */ do_action( 'user_admin_menu', '' ); } else { /** * Fires before the administration menu loads in the admin. * * @since 1.5.0 * * @param string $context Empty context. */ do_action( 'admin_menu', '' ); } /* * Remove menus that have no accessible submenus and require privileges * that the user does not have. Run re-parent loop again. */ foreach ( $menu as $id => $data ) { if ( ! current_user_can($data[1]) ) $_wp_menu_nopriv[$data[2]] = true; /* * If there is only one submenu and it is has same destination as the parent, * remove the submenu. */ if ( ! empty( $submenu[$data[2]] ) && 1 == count ( $submenu[$data[2]] ) ) { $subs = $submenu[$data[2]]; $first_sub = reset( $subs ); if ( $data[2] == $first_sub[2] ) unset( $submenu[$data[2]] ); } // If submenu is empty... if ( empty($submenu[$data[2]]) ) { // And user doesn't have privs, remove menu. if ( isset( $_wp_menu_nopriv[$data[2]] ) ) { unset($menu[$id]); } } } unset($id, $data, $subs, $first_sub); /** * * @param string $add * @param string $class * @return string */ function add_cssclass($add, $class) { $class = empty($class) ? $add : $class .= ' ' . $add; return $class; } /** * * @param array $menu * @return array */ function add_menu_classes($menu) { $first = $lastorder = false; $i = 0; $mc = count($menu); foreach ( $menu as $order => $top ) { $i++; if ( 0 == $order ) { // dashboard is always shown/single $menu[0][4] = add_cssclass('menu-top-first', $top[4]); $lastorder = 0; continue; } if ( 0 === strpos($top[2], 'separator') && false !== $lastorder ) { // if separator $first = true; $c = $menu[$lastorder][4]; $menu[$lastorder][4] = add_cssclass('menu-top-last', $c); continue; } if ( $first ) { $c = $menu[$order][4]; $menu[$order][4] = add_cssclass('menu-top-first', $c); $first = false; } if ( $mc == $i ) { // last item $c = $menu[$order][4]; $menu[$order][4] = add_cssclass('menu-top-last', $c); } $lastorder = $order; } /** * Filter administration menus array with classes added for top-level items. * * @since 2.7.0 * * @param array $menu Associative array of administration menu items. */ return apply_filters( 'add_menu_classes', $menu ); } uksort($menu, "strnatcasecmp"); // make it all pretty /** * Filter whether to enable custom ordering of the administration menu. * * See the {@see 'menu_order'} filter for reordering menu items. * * @since 2.8.0 * * @param bool $custom Whether custom ordering is enabled. Default false. */ if ( apply_filters( 'custom_menu_order', false ) ) { $menu_order = array(); foreach ( $menu as $menu_item ) { $menu_order[] = $menu_item[2]; } unset($menu_item); $default_menu_order = $menu_order; /** * Filter the order of administration menu items. * * A truthy value must first be passed to the {@see 'custom_menu_order'} filter * for this filter to work. Use the following to enable custom menu ordering: * * add_filter( 'custom_menu_order', '__return_true' ); * * @since 2.8.0 * * @param array $menu_order An ordered array of menu items. */ $menu_order = apply_filters( 'menu_order', $menu_order ); $menu_order = array_flip($menu_order); $default_menu_order = array_flip($default_menu_order); /** * * @global array $menu_order * @global array $default_menu_order * * @param array $a * @param array $b * @return int */ function sort_menu($a, $b) { global $menu_order, $default_menu_order; $a = $a[2]; $b = $b[2]; if ( isset($menu_order[$a]) && !isset($menu_order[$b]) ) { return -1; } elseif ( !isset($menu_order[$a]) && isset($menu_order[$b]) ) { return 1; } elseif ( isset($menu_order[$a]) && isset($menu_order[$b]) ) { if ( $menu_order[$a] == $menu_order[$b] ) return 0; return ($menu_order[$a] < $menu_order[$b]) ? -1 : 1; } else { return ($default_menu_order[$a] <= $default_menu_order[$b]) ? -1 : 1; } } usort($menu, 'sort_menu'); unset($menu_order, $default_menu_order); } // Prevent adjacent separators $prev_menu_was_separator = false; foreach ( $menu as $id => $data ) { if ( false === stristr( $data[4], 'wp-menu-separator' ) ) { // This item is not a separator, so falsey the toggler and do nothing $prev_menu_was_separator = false; } else { // The previous item was a separator, so unset this one if ( true === $prev_menu_was_separator ) { unset( $menu[ $id ] ); } // This item is a separator, so truthy the toggler and move on $prev_menu_was_separator = true; } } unset( $id, $data, $prev_menu_was_separator ); // Remove the last menu item if it is a separator. $last_menu_key = array_keys( $menu ); $last_menu_key = array_pop( $last_menu_key ); if ( !empty( $menu ) && 'wp-menu-separator' == $menu[ $last_menu_key ][ 4 ] ) unset( $menu[ $last_menu_key ] ); unset( $last_menu_key ); if ( !user_can_access_admin_page() ) { /** * Fires when access to an admin page is denied. * * @since 2.5.0 */ do_action( 'admin_page_access_denied' ); wp_die( __( 'You do not have sufficient permissions to access this page.' ), 403 ); } $menu = add_menu_classes($menu);
{ "pile_set_name": "Github" }
{ "name": "my-app", "version": "0.0.0", "description": "", "devDependencies": { "ember-cli": "~3.11.0-beta.1" } }
{ "pile_set_name": "Github" }
// // UsernameViewController.m // HutHelper // // Created by nine on 2016/11/20. // Copyright © 2016年 nine. All rights reserved. // #import "UsernameViewController.h" #import "JSONKit.h" #import "User.h" #import "MBProgressHUD+MJ.h" #import "APIRequest.h" @interface UsernameViewController () @property (weak, nonatomic) IBOutlet UITextField *Username; @end @implementation UsernameViewController - (void)viewDidLoad { [super viewDidLoad]; self.title=@"修改昵称"; [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}]; // Do any additional setup after loading the view. } - (IBAction)Add:(id)sender { [MBProgressHUD showMessage:@"修改中" toView:self.view]; NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults]; NSString *username_text=_Username.text; NSDictionary *dict = @{@"username":username_text}; [APIRequest POST:Config.getApiProfileUser parameters:dict success:^(id responseObject) { HideAllHUD NSLog(@"%@",Config.getApiProfileUser); NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSString *Msg=[responseDic objectForKey:@"msg"]; if ([Msg isEqualToString:@"ok"]) { [defaults setObject:username_text forKey:@"username"]; [MBProgressHUD showSuccess:@"修改成功" toView:self.view]; NSLog(@"%@",[Config getUserName]); } else if ([Msg isEqualToString:@"令牌错误"]){ [MBProgressHUD showError:@"登录过期,请重新登录" toView:self.view]; } else{ [MBProgressHUD showError:@"网络错误" toView:self.view]; } } failure:^(NSError *error) { HideAllHUD [MBProgressHUD showError:@"网络错误" toView:self.view]; }]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
{ "pile_set_name": "Github" }
using UnityEngine; using System.Collections; using UnityEngine.UI; namespace TMPro { public static class TMP_DefaultControls { public struct Resources { public Sprite standard; public Sprite background; public Sprite inputField; public Sprite knob; public Sprite checkmark; public Sprite dropdown; public Sprite mask; } private const float kWidth = 160f; private const float kThickHeight = 30f; private const float kThinHeight = 20f; private static Vector2 s_ThickElementSize = new Vector2(kWidth, kThickHeight); private static Vector2 s_ThinElementSize = new Vector2(kWidth, kThinHeight); //private static Vector2 s_ImageElementSize = new Vector2(100f, 100f); private static Color s_DefaultSelectableColor = new Color(1f, 1f, 1f, 1f); //private static Color s_PanelColor = new Color(1f, 1f, 1f, 0.392f); private static Color s_TextColor = new Color(50f / 255f, 50f / 255f, 50f / 255f, 1f); private static GameObject CreateUIElementRoot(string name, Vector2 size) { GameObject child = new GameObject(name); RectTransform rectTransform = child.AddComponent<RectTransform>(); rectTransform.sizeDelta = size; return child; } static GameObject CreateUIObject(string name, GameObject parent) { GameObject go = new GameObject(name); go.AddComponent<RectTransform>(); SetParentAndAlign(go, parent); return go; } private static void SetDefaultTextValues(TMP_Text lbl) { // Set text values we want across UI elements in default controls. // Don't set values which are the same as the default values for the Text component, // since there's no point in that, and it's good to keep them as consistent as possible. lbl.color = s_TextColor; lbl.fontSize = 14; } private static void SetDefaultColorTransitionValues(Selectable slider) { ColorBlock colors = slider.colors; colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f); colors.pressedColor = new Color(0.698f, 0.698f, 0.698f); colors.disabledColor = new Color(0.521f, 0.521f, 0.521f); } private static void SetParentAndAlign(GameObject child, GameObject parent) { if (parent == null) return; child.transform.SetParent(parent.transform, false); SetLayerRecursively(child, parent.layer); } private static void SetLayerRecursively(GameObject go, int layer) { go.layer = layer; Transform t = go.transform; for (int i = 0; i < t.childCount; i++) SetLayerRecursively(t.GetChild(i).gameObject, layer); } // Actual controls public static GameObject CreateScrollbar(Resources resources) { // Create GOs Hierarchy GameObject scrollbarRoot = CreateUIElementRoot("Scrollbar", s_ThinElementSize); GameObject sliderArea = CreateUIObject("Sliding Area", scrollbarRoot); GameObject handle = CreateUIObject("Handle", sliderArea); Image bgImage = scrollbarRoot.AddComponent<Image>(); bgImage.sprite = resources.background; bgImage.type = Image.Type.Sliced; bgImage.color = s_DefaultSelectableColor; Image handleImage = handle.AddComponent<Image>(); handleImage.sprite = resources.standard; handleImage.type = Image.Type.Sliced; handleImage.color = s_DefaultSelectableColor; RectTransform sliderAreaRect = sliderArea.GetComponent<RectTransform>(); sliderAreaRect.sizeDelta = new Vector2(-20, -20); sliderAreaRect.anchorMin = Vector2.zero; sliderAreaRect.anchorMax = Vector2.one; RectTransform handleRect = handle.GetComponent<RectTransform>(); handleRect.sizeDelta = new Vector2(20, 20); Scrollbar scrollbar = scrollbarRoot.AddComponent<Scrollbar>(); scrollbar.handleRect = handleRect; scrollbar.targetGraphic = handleImage; SetDefaultColorTransitionValues(scrollbar); return scrollbarRoot; } public static GameObject CreateButton(Resources resources) { GameObject buttonRoot = CreateUIElementRoot("Button", s_ThickElementSize); GameObject childText = new GameObject("Text (TMP)"); childText.AddComponent<RectTransform>(); SetParentAndAlign(childText, buttonRoot); Image image = buttonRoot.AddComponent<Image>(); image.sprite = resources.standard; image.type = Image.Type.Sliced; image.color = s_DefaultSelectableColor; Button bt = buttonRoot.AddComponent<Button>(); SetDefaultColorTransitionValues(bt); TextMeshProUGUI text = childText.AddComponent<TextMeshProUGUI>(); text.text = "Button"; text.alignment = TextAlignmentOptions.Center; SetDefaultTextValues(text); RectTransform textRectTransform = childText.GetComponent<RectTransform>(); textRectTransform.anchorMin = Vector2.zero; textRectTransform.anchorMax = Vector2.one; textRectTransform.sizeDelta = Vector2.zero; return buttonRoot; } public static GameObject CreateText(Resources resources) { GameObject go = CreateUIElementRoot("Text (TMP)", s_ThickElementSize); TextMeshProUGUI lbl = go.AddComponent<TextMeshProUGUI>(); lbl.text = "New Text"; SetDefaultTextValues(lbl); return go; } public static GameObject CreateInputField(Resources resources) { GameObject root = CreateUIElementRoot("InputField (TMP)", s_ThickElementSize); GameObject textArea = CreateUIObject("Text Area", root); GameObject childPlaceholder = CreateUIObject("Placeholder", textArea); GameObject childText = CreateUIObject("Text", textArea); Image image = root.AddComponent<Image>(); image.sprite = resources.inputField; image.type = Image.Type.Sliced; image.color = s_DefaultSelectableColor; TMP_InputField inputField = root.AddComponent<TMP_InputField>(); SetDefaultColorTransitionValues(inputField); // Use UI.Mask for Unity 5.0 - 5.1 and 2D RectMask for Unity 5.2 and up textArea.AddComponent<RectMask2D>(); RectTransform textAreaRectTransform = textArea.GetComponent<RectTransform>(); textAreaRectTransform.anchorMin = Vector2.zero; textAreaRectTransform.anchorMax = Vector2.one; textAreaRectTransform.sizeDelta = Vector2.zero; textAreaRectTransform.offsetMin = new Vector2(10, 6); textAreaRectTransform.offsetMax = new Vector2(-10, -7); TextMeshProUGUI text = childText.AddComponent<TextMeshProUGUI>(); text.text = ""; text.enableWordWrapping = false; text.extraPadding = true; text.richText = true; SetDefaultTextValues(text); TextMeshProUGUI placeholder = childPlaceholder.AddComponent<TextMeshProUGUI>(); placeholder.text = "Enter text..."; placeholder.fontSize = 14; placeholder.fontStyle = FontStyles.Italic; placeholder.enableWordWrapping = false; placeholder.extraPadding = true; // Make placeholder color half as opaque as normal text color. Color placeholderColor = text.color; placeholderColor.a *= 0.5f; placeholder.color = placeholderColor; RectTransform textRectTransform = childText.GetComponent<RectTransform>(); textRectTransform.anchorMin = Vector2.zero; textRectTransform.anchorMax = Vector2.one; textRectTransform.sizeDelta = Vector2.zero; textRectTransform.offsetMin = new Vector2(0, 0); textRectTransform.offsetMax = new Vector2(0, 0); RectTransform placeholderRectTransform = childPlaceholder.GetComponent<RectTransform>(); placeholderRectTransform.anchorMin = Vector2.zero; placeholderRectTransform.anchorMax = Vector2.one; placeholderRectTransform.sizeDelta = Vector2.zero; placeholderRectTransform.offsetMin = new Vector2(0, 0); placeholderRectTransform.offsetMax = new Vector2(0, 0); inputField.textViewport = textAreaRectTransform; inputField.textComponent = text; inputField.placeholder = placeholder; inputField.fontAsset = text.font; return root; } public static GameObject CreateDropdown(Resources resources) { GameObject root = CreateUIElementRoot("Dropdown", s_ThickElementSize); GameObject label = CreateUIObject("Label", root); GameObject arrow = CreateUIObject("Arrow", root); GameObject template = CreateUIObject("Template", root); GameObject viewport = CreateUIObject("Viewport", template); GameObject content = CreateUIObject("Content", viewport); GameObject item = CreateUIObject("Item", content); GameObject itemBackground = CreateUIObject("Item Background", item); GameObject itemCheckmark = CreateUIObject("Item Checkmark", item); GameObject itemLabel = CreateUIObject("Item Label", item); // Sub controls. GameObject scrollbar = CreateScrollbar(resources); scrollbar.name = "Scrollbar"; SetParentAndAlign(scrollbar, template); Scrollbar scrollbarScrollbar = scrollbar.GetComponent<Scrollbar>(); scrollbarScrollbar.SetDirection(Scrollbar.Direction.BottomToTop, true); RectTransform vScrollbarRT = scrollbar.GetComponent<RectTransform>(); vScrollbarRT.anchorMin = Vector2.right; vScrollbarRT.anchorMax = Vector2.one; vScrollbarRT.pivot = Vector2.one; vScrollbarRT.sizeDelta = new Vector2(vScrollbarRT.sizeDelta.x, 0); // Setup item UI components. TextMeshProUGUI itemLabelText = itemLabel.AddComponent<TextMeshProUGUI>(); SetDefaultTextValues(itemLabelText); itemLabelText.alignment = TextAlignmentOptions.Left; Image itemBackgroundImage = itemBackground.AddComponent<Image>(); itemBackgroundImage.color = new Color32(245, 245, 245, 255); Image itemCheckmarkImage = itemCheckmark.AddComponent<Image>(); itemCheckmarkImage.sprite = resources.checkmark; Toggle itemToggle = item.AddComponent<Toggle>(); itemToggle.targetGraphic = itemBackgroundImage; itemToggle.graphic = itemCheckmarkImage; itemToggle.isOn = true; // Setup template UI components. Image templateImage = template.AddComponent<Image>(); templateImage.sprite = resources.standard; templateImage.type = Image.Type.Sliced; ScrollRect templateScrollRect = template.AddComponent<ScrollRect>(); templateScrollRect.content = (RectTransform)content.transform; templateScrollRect.viewport = (RectTransform)viewport.transform; templateScrollRect.horizontal = false; templateScrollRect.movementType = ScrollRect.MovementType.Clamped; templateScrollRect.verticalScrollbar = scrollbarScrollbar; templateScrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport; templateScrollRect.verticalScrollbarSpacing = -3; Mask scrollRectMask = viewport.AddComponent<Mask>(); scrollRectMask.showMaskGraphic = false; Image viewportImage = viewport.AddComponent<Image>(); viewportImage.sprite = resources.mask; viewportImage.type = Image.Type.Sliced; // Setup dropdown UI components. TextMeshProUGUI labelText = label.AddComponent<TextMeshProUGUI>(); SetDefaultTextValues(labelText); labelText.alignment = TextAlignmentOptions.Left; Image arrowImage = arrow.AddComponent<Image>(); arrowImage.sprite = resources.dropdown; Image backgroundImage = root.AddComponent<Image>(); backgroundImage.sprite = resources.standard; backgroundImage.color = s_DefaultSelectableColor; backgroundImage.type = Image.Type.Sliced; TMP_Dropdown dropdown = root.AddComponent<TMP_Dropdown>(); dropdown.targetGraphic = backgroundImage; SetDefaultColorTransitionValues(dropdown); dropdown.template = template.GetComponent<RectTransform>(); dropdown.captionText = labelText; dropdown.itemText = itemLabelText; // Setting default Item list. itemLabelText.text = "Option A"; dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option A" }); dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option B" }); dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option C" }); dropdown.RefreshShownValue(); // Set up RectTransforms. RectTransform labelRT = label.GetComponent<RectTransform>(); labelRT.anchorMin = Vector2.zero; labelRT.anchorMax = Vector2.one; labelRT.offsetMin = new Vector2(10, 6); labelRT.offsetMax = new Vector2(-25, -7); RectTransform arrowRT = arrow.GetComponent<RectTransform>(); arrowRT.anchorMin = new Vector2(1, 0.5f); arrowRT.anchorMax = new Vector2(1, 0.5f); arrowRT.sizeDelta = new Vector2(20, 20); arrowRT.anchoredPosition = new Vector2(-15, 0); RectTransform templateRT = template.GetComponent<RectTransform>(); templateRT.anchorMin = new Vector2(0, 0); templateRT.anchorMax = new Vector2(1, 0); templateRT.pivot = new Vector2(0.5f, 1); templateRT.anchoredPosition = new Vector2(0, 2); templateRT.sizeDelta = new Vector2(0, 150); RectTransform viewportRT = viewport.GetComponent<RectTransform>(); viewportRT.anchorMin = new Vector2(0, 0); viewportRT.anchorMax = new Vector2(1, 1); viewportRT.sizeDelta = new Vector2(-18, 0); viewportRT.pivot = new Vector2(0, 1); RectTransform contentRT = content.GetComponent<RectTransform>(); contentRT.anchorMin = new Vector2(0f, 1); contentRT.anchorMax = new Vector2(1f, 1); contentRT.pivot = new Vector2(0.5f, 1); contentRT.anchoredPosition = new Vector2(0, 0); contentRT.sizeDelta = new Vector2(0, 28); RectTransform itemRT = item.GetComponent<RectTransform>(); itemRT.anchorMin = new Vector2(0, 0.5f); itemRT.anchorMax = new Vector2(1, 0.5f); itemRT.sizeDelta = new Vector2(0, 20); RectTransform itemBackgroundRT = itemBackground.GetComponent<RectTransform>(); itemBackgroundRT.anchorMin = Vector2.zero; itemBackgroundRT.anchorMax = Vector2.one; itemBackgroundRT.sizeDelta = Vector2.zero; RectTransform itemCheckmarkRT = itemCheckmark.GetComponent<RectTransform>(); itemCheckmarkRT.anchorMin = new Vector2(0, 0.5f); itemCheckmarkRT.anchorMax = new Vector2(0, 0.5f); itemCheckmarkRT.sizeDelta = new Vector2(20, 20); itemCheckmarkRT.anchoredPosition = new Vector2(10, 0); RectTransform itemLabelRT = itemLabel.GetComponent<RectTransform>(); itemLabelRT.anchorMin = Vector2.zero; itemLabelRT.anchorMax = Vector2.one; itemLabelRT.offsetMin = new Vector2(20, 1); itemLabelRT.offsetMax = new Vector2(-10, -2); template.SetActive(false); return root; } } }
{ "pile_set_name": "Github" }
'use strict'; var getPrototypeOf = Object.getPrototypeOf, prototype = Object.prototype , toString = prototype.toString , id = {}.toString(); module.exports = function (value) { var proto; if (!value || (typeof value !== 'object') || (toString.call(value) !== id)) { return false; } proto = getPrototypeOf(value); return (proto === prototype) || (getPrototypeOf(proto) === null); };
{ "pile_set_name": "Github" }
/* from asm/termbits.h */ #define TARGET_NCCS 19 struct target_termios { unsigned int c_iflag; /* input mode flags */ unsigned int c_oflag; /* output mode flags */ unsigned int c_cflag; /* control mode flags */ unsigned int c_lflag; /* local mode flags */ unsigned char c_line; /* line discipline */ unsigned char c_cc[TARGET_NCCS]; /* control characters */ }; /* c_cc characters */ #define TARGET_VINTR 0 #define TARGET_VQUIT 1 #define TARGET_VERASE 2 #define TARGET_VKILL 3 #define TARGET_VEOF 4 #define TARGET_VEOL 5 #define TARGET_VEOL2 6 #define TARGET_VSWTC 7 #define TARGET_VSTART 8 #define TARGET_VSTOP 9 #define TARGET_VSUSP 10 #define TARGET_VDSUSP 11 /* SunOS POSIX nicety I do believe... */ #define TARGET_VREPRINT 12 #define TARGET_VDISCARD 13 #define TARGET_VWERASE 14 #define TARGET_VLNEXT 15 /* Kernel keeps vmin/vtime separated, user apps assume vmin/vtime is * shared with eof/eol */ #define TARGET_VMIN TARGET_VEOF #define TARGET_VTIME TARGET_VEOL /* c_iflag bits */ #define TARGET_IGNBRK 0x00000001 #define TARGET_BRKINT 0x00000002 #define TARGET_IGNPAR 0x00000004 #define TARGET_PARMRK 0x00000008 #define TARGET_INPCK 0x00000010 #define TARGET_ISTRIP 0x00000020 #define TARGET_INLCR 0x00000040 #define TARGET_IGNCR 0x00000080 #define TARGET_ICRNL 0x00000100 #define TARGET_IUCLC 0x00000200 #define TARGET_IXON 0x00000400 #define TARGET_IXANY 0x00000800 #define TARGET_IXOFF 0x00001000 #define TARGET_IMAXBEL 0x00002000 #define TARGET_IUTF8 0x00004000 /* c_oflag bits */ #define TARGET_OPOST 0x00000001 #define TARGET_OLCUC 0x00000002 #define TARGET_ONLCR 0x00000004 #define TARGET_OCRNL 0x00000008 #define TARGET_ONOCR 0x00000010 #define TARGET_ONLRET 0x00000020 #define TARGET_OFILL 0x00000040 #define TARGET_OFDEL 0x00000080 #define TARGET_NLDLY 0x00000100 #define TARGET_NL0 0x00000000 #define TARGET_NL1 0x00000100 #define TARGET_CRDLY 0x00000600 #define TARGET_CR0 0x00000000 #define TARGET_CR1 0x00000200 #define TARGET_CR2 0x00000400 #define TARGET_CR3 0x00000600 #define TARGET_TABDLY 0x00001800 #define TARGET_TAB0 0x00000000 #define TARGET_TAB1 0x00000800 #define TARGET_TAB2 0x00001000 #define TARGET_TAB3 0x00001800 #define TARGET_XTABS 0x00001800 #define TARGET_BSDLY 0x00002000 #define TARGET_BS0 0x00000000 #define TARGET_BS1 0x00002000 #define TARGET_VTDLY 0x00004000 #define TARGET_VT0 0x00000000 #define TARGET_VT1 0x00004000 #define TARGET_FFDLY 0x00008000 #define TARGET_FF0 0x00000000 #define TARGET_FF1 0x00008000 #define TARGET_PAGEOUT 0x00010000 /* SUNOS specific */ #define TARGET_WRAP 0x00020000 /* SUNOS specific */ /* c_cflag bit meaning */ #define TARGET_CBAUD 0x0000100f #define TARGET_B0 0x00000000 /* hang up */ #define TARGET_B50 0x00000001 #define TARGET_B75 0x00000002 #define TARGET_B110 0x00000003 #define TARGET_B134 0x00000004 #define TARGET_B150 0x00000005 #define TARGET_B200 0x00000006 #define TARGET_B300 0x00000007 #define TARGET_B600 0x00000008 #define TARGET_B1200 0x00000009 #define TARGET_B1800 0x0000000a #define TARGET_B2400 0x0000000b #define TARGET_B4800 0x0000000c #define TARGET_B9600 0x0000000d #define TARGET_B19200 0x0000000e #define TARGET_B38400 0x0000000f #define TARGET_EXTA B19200 #define TARGET_EXTB B38400 #define TARGET_CSIZE 0x00000030 #define TARGET_CS5 0x00000000 #define TARGET_CS6 0x00000010 #define TARGET_CS7 0x00000020 #define TARGET_CS8 0x00000030 #define TARGET_CSTOPB 0x00000040 #define TARGET_CREAD 0x00000080 #define TARGET_PARENB 0x00000100 #define TARGET_PARODD 0x00000200 #define TARGET_HUPCL 0x00000400 #define TARGET_CLOCAL 0x00000800 #define TARGET_CBAUDEX 0x00001000 /* We'll never see these speeds with the Zilogs, but for completeness... */ #define TARGET_B57600 0x00001001 #define TARGET_B115200 0x00001002 #define TARGET_B230400 0x00001003 #define TARGET_B460800 0x00001004 /* This is what we can do with the Zilogs. */ #define TARGET_B76800 0x00001005 /* This is what we can do with the SAB82532. */ #define TARGET_B153600 0x00001006 #define TARGET_B307200 0x00001007 #define TARGET_B614400 0x00001008 #define TARGET_B921600 0x00001009 /* And these are the rest... */ #define TARGET_B500000 0x0000100a #define TARGET_B576000 0x0000100b #define TARGET_B1000000 0x0000100c #define TARGET_B1152000 0x0000100d #define TARGET_B1500000 0x0000100e #define TARGET_B2000000 0x0000100f /* These have totally bogus values and nobody uses them so far. Later on we'd have to use say 0x10000x and adjust CBAUD constant and drivers accordingly. #define B2500000 0x00001010 #define B3000000 0x00001011 #define B3500000 0x00001012 #define B4000000 0x00001013 */ #define TARGET_CIBAUD 0x100f0000 /* input baud rate (not used) */ #define TARGET_CMSPAR 0x40000000 /* mark or space (stick) parity */ #define TARGET_CRTSCTS 0x80000000 /* flow control */ /* c_lflag bits */ #define TARGET_ISIG 0x00000001 #define TARGET_ICANON 0x00000002 #define TARGET_XCASE 0x00000004 #define TARGET_ECHO 0x00000008 #define TARGET_ECHOE 0x00000010 #define TARGET_ECHOK 0x00000020 #define TARGET_ECHONL 0x00000040 #define TARGET_NOFLSH 0x00000080 #define TARGET_TOSTOP 0x00000100 #define TARGET_ECHOCTL 0x00000200 #define TARGET_ECHOPRT 0x00000400 #define TARGET_ECHOKE 0x00000800 #define TARGET_DEFECHO 0x00001000 /* SUNOS thing, what is it? */ #define TARGET_FLUSHO 0x00002000 #define TARGET_PENDIN 0x00004000 #define TARGET_IEXTEN 0x00008000 /* ioctls */ /* Big T */ #define TARGET_TCGETA TARGET_IOR('T', 1, struct target_termio) #define TARGET_TCSETA TARGET_IOW('T', 2, struct target_termio) #define TARGET_TCSETAW TARGET_IOW('T', 3, struct target_termio) #define TARGET_TCSETAF TARGET_IOW('T', 4, struct target_termio) #define TARGET_TCSBRK TARGET_IO('T', 5) #define TARGET_TCXONC TARGET_IO('T', 6) #define TARGET_TCFLSH TARGET_IO('T', 7) #define TARGET_TCGETS TARGET_IOR('T', 8, struct target_termios) #define TARGET_TCSETS TARGET_IOW('T', 9, struct target_termios) #define TARGET_TCSETSW TARGET_IOW('T', 10, struct target_termios) #define TARGET_TCSETSF TARGET_IOW('T', 11, struct target_termios) /* Note that all the ioctls that are not available in Linux have a * double underscore on the front to: a) avoid some programs to * thing we support some ioctls under Linux (autoconfiguration stuff) */ /* Little t */ #define TARGET_TIOCGETD TARGET_IOR('t', 0, int) #define TARGET_TIOCSETD TARGET_IOW('t', 1, int) //#define __TIOCHPCL _IO('t', 2) /* SunOS Specific */ //#define __TIOCMODG _IOR('t', 3, int) /* SunOS Specific */ //#define __TIOCMODS _IOW('t', 4, int) /* SunOS Specific */ //#define __TIOCGETP _IOR('t', 8, struct sgttyb) /* SunOS Specific */ //#define __TIOCSETP _IOW('t', 9, struct sgttyb) /* SunOS Specific */ //#define __TIOCSETN _IOW('t', 10, struct sgttyb) /* SunOS Specific */ #define TARGET_TIOCEXCL TARGET_IO('t', 13) #define TARGET_TIOCNXCL TARGET_IO('t', 14) //#define __TIOCFLUSH _IOW('t', 16, int) /* SunOS Specific */ //#define __TIOCSETC _IOW('t', 17, struct tchars) /* SunOS Specific */ //#define __TIOCGETC _IOR('t', 18, struct tchars) /* SunOS Specific */ //#define __TIOCTCNTL _IOW('t', 32, int) /* SunOS Specific */ //#define __TIOCSIGNAL _IOW('t', 33, int) /* SunOS Specific */ //#define __TIOCSETX _IOW('t', 34, int) /* SunOS Specific */ //#define __TIOCGETX _IOR('t', 35, int) /* SunOS Specific */ #define TARGET_TIOCCONS TARGET_IO('t', 36) //#define __TIOCSSIZE _IOW('t', 37, struct sunos_ttysize) /* SunOS Specific */ //#define __TIOCGSIZE _IOR('t', 38, struct sunos_ttysize) /* SunOS Specific */ #define TARGET_TIOCGSOFTCAR TARGET_IOR('t', 100, int) #define TARGET_TIOCSSOFTCAR TARGET_IOW('t', 101, int) //#define __TIOCUCNTL _IOW('t', 102, int) /* SunOS Specific */ #define TARGET_TIOCSWINSZ TARGET_IOW('t', 103, struct winsize) #define TARGET_TIOCGWINSZ TARGET_IOR('t', 104, struct winsize) //#define __TIOCREMOTE _IOW('t', 105, int) /* SunOS Specific */ #define TARGET_TIOCMGET TARGET_IOR('t', 106, int) #define TARGET_TIOCMBIC TARGET_IOW('t', 107, int) #define TARGET_TIOCMBIS TARGET_IOW('t', 108, int) #define TARGET_TIOCMSET TARGET_IOW('t', 109, int) #define TARGET_TIOCSTART TARGET_IO('t', 110) #define TARGET_TIOCSTOP TARGET_IO('t', 111) #define TARGET_TIOCPKT TARGET_IOW('t', 112, int) #define TARGET_TIOCNOTTY TARGET_IO('t', 113) #define TARGET_TIOCSTI TARGET_IOW('t', 114, char) #define TARGET_TIOCOUTQ TARGET_IOR('t', 115, int) //#define __TIOCGLTC _IOR('t', 116, struct ltchars) /* SunOS Specific */ //#define __TIOCSLTC _IOW('t', 117, struct ltchars) /* SunOS Specific */ /* 118 is the non-posix setpgrp tty ioctl */ /* 119 is the non-posix getpgrp tty ioctl */ //#define __TIOCCDTR TARGET_IO('t', 120) /* SunOS Specific */ //#define __TIOCSDTR TARGET_IO('t', 121) /* SunOS Specific */ #define TARGET_TIOCCBRK TARGET_IO('t', 122) #define TARGET_TIOCSBRK TARGET_IO('t', 123) //#define __TIOCLGET TARGET_IOW('t', 124, int) /* SunOS Specific */ //#define __TIOCLSET TARGET_IOW('t', 125, int) /* SunOS Specific */ //#define __TIOCLBIC TARGET_IOW('t', 126, int) /* SunOS Specific */ //#define __TIOCLBIS TARGET_IOW('t', 127, int) /* SunOS Specific */ //#define __TIOCISPACE TARGET_IOR('t', 128, int) /* SunOS Specific */ //#define __TIOCISIZE TARGET_IOR('t', 129, int) /* SunOS Specific */ #define TARGET_TIOCSPGRP TARGET_IOW('t', 130, int) #define TARGET_TIOCGPGRP TARGET_IOR('t', 131, int) #define TARGET_TIOCSCTTY TARGET_IO('t', 132) #define TARGET_TIOCGSID TARGET_IOR('t', 133, int) /* Get minor device of a pty master's FD -- Solaris equiv is ISPTM */ #define TARGET_TIOCGPTN TARGET_IOR('t', 134, unsigned int) /* Get Pty Number */ #define TARGET_TIOCSPTLCK TARGET_IOW('t', 135, int) /* Lock/unlock PTY */ #define TARGET_TIOCGPTPEER TARGET_IO('t', 137) /* Safely open the slave */ /* Little f */ #define TARGET_FIOCLEX TARGET_IO('f', 1) #define TARGET_FIONCLEX TARGET_IO('f', 2) #define TARGET_FIOASYNC TARGET_IOW('f', 125, int) #define TARGET_FIONBIO TARGET_IOW('f', 126, int) #define TARGET_FIONREAD TARGET_IOR('f', 127, int) #define TARGET_TIOCINQ TARGET_FIONREAD /* SCARY Rutgers local SunOS kernel hackery, perhaps I will support it * someday. This is completely bogus, I know... */ //#define __TCGETSTAT TARGET_IO('T', 200) /* Rutgers specific */ //#define __TCSETSTAT TARGET_IO('T', 201) /* Rutgers specific */ /* Linux specific, no SunOS equivalent. */ #define TARGET_TIOCLINUX 0x541C #define TARGET_TIOCGSERIAL 0x541E #define TARGET_TIOCSSERIAL 0x541F #define TARGET_TCSBRKP 0x5425 #define TARGET_TIOCTTYGSTRUCT 0x5426 #define TARGET_TIOCSERCONFIG 0x5453 #define TARGET_TIOCSERGWILD 0x5454 #define TARGET_TIOCSERSWILD 0x5455 #define TARGET_TIOCGLCKTRMIOS 0x5456 #define TARGET_TIOCSLCKTRMIOS 0x5457 #define TARGET_TIOCSERGSTRUCT 0x5458 /* For debugging only */ #define TARGET_TIOCSERGETLSR 0x5459 /* Get line status register */ #define TARGET_TIOCSERGETMULTI 0x545A /* Get multiport config */ #define TARGET_TIOCSERSETMULTI 0x545B /* Set multiport config */ #define TARGET_TIOCMIWAIT 0x545C /* Wait input */ #define TARGET_TIOCGICOUNT 0x545D /* Read serial port inline interrupt counts */
{ "pile_set_name": "Github" }
/* Copyright (C) 2009 Stig Brautaset. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import <Foundation/Foundation.h> extern NSString * SBJSONErrorDomain; enum { EUNSUPPORTED = 1, EPARSENUM, EPARSE, EFRAGMENT, ECTRL, EUNICODE, EDEPTH, EESCAPE, ETRAILCOMMA, ETRAILGARBAGE, EEOF, EINPUT }; /** @brief Common base class for parsing & writing. This class contains the common error-handling code and option between the parser/writer. */ @interface SBJsonBase : NSObject { NSMutableArray *errorTrace; @protected NSUInteger depth, maxDepth; } /** @brief The maximum recursing depth. Defaults to 512. If the input is nested deeper than this the input will be deemed to be malicious and the parser returns nil, signalling an error. ("Nested too deep".) You can turn off this security feature by setting the maxDepth value to 0. */ @property NSUInteger maxDepth; /** @brief Return an error trace, or nil if there was no errors. Note that this method returns the trace of the last method that failed. You need to check the return value of the call you're making to figure out if the call actually failed, before you know call this method. */ @property(copy,readonly) NSArray* errorTrace; /// @internal for use in subclasses to add errors to the stack trace - (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str; /// @internal for use in subclasess to clear the error before a new parsing attempt - (void)clearErrorTrace; @end
{ "pile_set_name": "Github" }
title: django.utils.timezone get_current_timezone Example Code category: page slug: django-utils-timezone-get-current-timezone-examples sortorder: 500011494 toc: False sidebartitle: django.utils.timezone get_current_timezone meta: Python example code for the get_current_timezone callable from the django.utils.timezone module of the Django project. get_current_timezone is a callable within the django.utils.timezone module of the Django project. ## Example 1 from django-filer [django-filer](https://github.com/divio/django-filer) ([project documentation](https://django-filer.readthedocs.io/en/latest/)) is a file management library for uploading and organizing files and images in Django's admin interface. The project's code is available under the [BSD 3-Clause "New" or "Revised" open source license](https://github.com/divio/django-filer/blob/develop/LICENSE.txt). [**django-filer / filer / models / imagemodels.py**](https://github.com/divio/django-filer/blob/develop/filer/models/imagemodels.py) ```python # imagemodels.py from __future__ import absolute_import import logging from datetime import datetime from django.conf import settings from django.db import models ~~from django.utils.timezone import get_current_timezone, make_aware, now from django.utils.translation import ugettext_lazy as _ from .abstract import BaseImage logger = logging.getLogger("filer") class Image(BaseImage): date_taken = models.DateTimeField(_('date taken'), null=True, blank=True, editable=False) author = models.CharField(_('author'), max_length=255, null=True, blank=True) must_always_publish_author_credit = models.BooleanField(_('must always publish author credit'), default=False) must_always_publish_copyright = models.BooleanField(_('must always publish copyright'), default=False) class Meta(BaseImage.Meta): swappable = 'FILER_IMAGE_MODEL' default_manager_name = 'objects' def save(self, *args, **kwargs): if self.date_taken is None: try: exif_date = self.exif.get('DateTimeOriginal', None) if exif_date is not None: d, t = exif_date.split(" ") year, month, day = d.split(':') hour, minute, second = t.split(':') if getattr(settings, "USE_TZ", False): ~~ tz = get_current_timezone() self.date_taken = make_aware(datetime( int(year), int(month), int(day), int(hour), int(minute), int(second)), tz) else: self.date_taken = datetime( int(year), int(month), int(day), int(hour), int(minute), int(second)) except Exception: pass if self.date_taken is None: self.date_taken = now() super(Image, self).save(*args, **kwargs) ## ... source file continues with no further get_current_timezone examples... ```
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" standalone="no" ?> <FinalDraft DocumentType="Script" Template="Yes" Version="2"> <Content> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No" Type="Scene Heading"> <SceneProperties Length="1/8" Page="1" Title=""> <SceneArcBeats/> </SceneProperties> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps">SONS OF ANARCHY</Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No" Type="Scene Heading"> <SceneProperties Length="1/8" Page="1" Title=""> <SceneArcBeats/> </SceneProperties> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps">"EPISODE TITLE"</Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No" Type="Scene Heading"> <SceneProperties Length="1/8" Page="1" Title=""> <SceneArcBeats/> </SceneProperties> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps">#EPISODE NUMBER</Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No" Type="Scene Heading"> <SceneProperties Length="1/8" Page="1" Title=""> <SceneArcBeats/> </SceneProperties> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps">PROLOGUE</Text> </Paragraph> <Paragraph Type="Action"> <Text>Enter some text here about something intriguing that is happening--</Text> </Paragraph> <Paragraph Type="Action"> <Text>SMASH UP ON:</Text> </Paragraph> <Paragraph Type="Scene Heading"> <SceneProperties Length="1 1/8" Page="1" Title=""> <SceneArcBeats> <CharacterArcBeat Name="GUARD"></CharacterArcBeat> <CharacterArcBeat Name="JAX"></CharacterArcBeat> </SceneArcBeats> </SceneProperties> <Text>INT. Stockton state prison - YARD - day</Text> </Paragraph> <Paragraph Type="Action"> <Text>TWO GLOVED HANDS wrap around a METAL BAR, then camera PULLS OUT to reveal a sweaty JAX, pulling himself up. A nearby GUARD crosses his arms, TAPPING his foot relentlessly.</Text> </Paragraph> <Paragraph Type="Character"> <Text>GUARD</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Note that prominent PROPS, CAMERA DIRECTIONS, ACTIONS, and other IMPORTANT THINGS are capitalized. </Text> </Paragraph> <Paragraph Type="Character"> <Text>JAX</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>I can see that. </Text> </Paragraph> <Paragraph Type="Character"> <Text>GUARD</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Did you know that “Sons of Anarchy” scripts have a prologue and four acts?</Text> </Paragraph> <Paragraph Type="Character"> <Text>JAX</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text AdornmentStyle="-1" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">Duh</Text> <Text>, I can read.</Text> </Paragraph> <Paragraph Type="Action"> <Text>Jax releases the CHIN-UP BAR and lands squarely on his feet. Camera PANS DOWN to reveal a homemade SHIV hiding in his pocket.</Text> </Paragraph> <Paragraph Type="Character"> <Text>GUARD</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Also it also says OPENING TITLE SEQUENCE at the end of the Prologue. </Text> </Paragraph> <Paragraph Type="Character"> <Text>JAX</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Blah. </Text> </Paragraph> <Paragraph Type="Character"> <Text>GUARD</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Blah?</Text> </Paragraph> <Paragraph Type="Character"> <Text>JAX</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>I said blah!</Text> </Paragraph> <Paragraph Type="Action"> <Text>Suddenly Jax pulls out the SHIV.</Text> </Paragraph> <Paragraph Type="Character"> <Text>GUARD</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Blah, blah!</Text> </Paragraph> <Paragraph Type="Character"> <Text>JAX</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text AdornmentStyle="-1" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">Blabbety</Text> <Text>, </Text> <Text AdornmentStyle="-1" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">blabbety</Text> <Text>, blah! Blah blah </Text> <Text AdornmentStyle="-1" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">blah</Text> <Text> </Text> <Text AdornmentStyle="-1" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">blah</Text> <Text> </Text> <Text AdornmentStyle="-1" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">blah</Text> <Text>!</Text> </Paragraph> <Paragraph Type="Action"> <Text>The guard MOTIONS for backup--</Text> </Paragraph> <Paragraph Type="Character"> <Text>GUARD</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>BLAH!</Text> </Paragraph> <Paragraph Type="Action"> <Text>Jax runs straight at the guard--</Text> </Paragraph> <Paragraph Type="Transition"> <Text>SMASH TO:</Text> </Paragraph> <Paragraph Type="End Of Act"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="End Of Act"> <Text>OPENING TITLE SEQUENCE</Text> </Paragraph> <Paragraph Type="New Act"> <Text>Act one</Text> </Paragraph> <Paragraph Type="Scene Heading"> <SceneProperties Length="1/8" Page="3" Title=""> <SceneArcBeats/> </SceneProperties> <Text>SMASH UP ON:</Text> </Paragraph> <Paragraph Type="Scene Heading"> <SceneProperties Length="5/8" Page="3" Title=""> <SceneArcBeats> <CharacterArcBeat Name="GEMMA"></CharacterArcBeat> <CharacterArcBeat Name="TARA"></CharacterArcBeat> </SceneArcBeats> </SceneProperties> <Text>Int. jax’s house - day</Text> </Paragraph> <Paragraph Type="Action"> <Text>GEMMA says something interesting and DOES SOMETHING here. TARA walks in. </Text> </Paragraph> <Paragraph Type="Character"> <Text>GEMMA</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Why do they call the teaser a “prologue”?</Text> </Paragraph> <Paragraph Type="Character"> <Text>TARA</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Because it sounds way cooler to call it a Prologue. </Text> </Paragraph> <Paragraph Type="Character"> <Text>GEMMA</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Yeah. </Text> </Paragraph> <Paragraph Type="Character"> <Text>TARa </Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Blah, blah, blah.</Text> </Paragraph> <Paragraph Type="Character"> <Text>GEMMA</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Blah!</Text> </Paragraph> <Paragraph Type="Character"> <Text>TARA</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Blah, blah, blah, blah, blah, blah, Jax. </Text> </Paragraph> <Paragraph Type="Transition"> <Text>SMASH TO BLACK. </Text> </Paragraph> <Paragraph Type="End Of Act"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="End Of Act"> <Text>End of act onE</Text> </Paragraph> <Paragraph Type="New Act"> <Text>Act two</Text> </Paragraph> <Paragraph Type="Scene Heading"> <SceneProperties Length="4/8" Page="4" Title=""> <SceneArcBeats> <CharacterArcBeat Name="CLAY"></CharacterArcBeat> <CharacterArcBeat Name="SHERIFF"></CharacterArcBeat> </SceneArcBeats> </SceneProperties> <Text>Ext. Street - charming - day</Text> </Paragraph> <Paragraph Type="Action"> <Text>Write some INTERESTING action here, preferably with some SHERIFFS out on the prowl. </Text> </Paragraph> <Paragraph Type="Action"> <Text>A Sheriff pulls CLAY over. </Text> </Paragraph> <Paragraph Type="Character"> <Text>SHERIFF</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Notice it says SMASH TO BLACK instead of CUT TO BLACK or FADE TO BLACK. </Text> </Paragraph> <Paragraph Type="Character"> <Text>CLAY</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Blah. </Text> </Paragraph> <Paragraph Type="Character"> <Text>SHERIFF</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Blah, blah, blah?</Text> </Paragraph> <Paragraph Type="Character"> <Text>CLAY</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>I said blah. </Text> </Paragraph> <Paragraph Type="Action"> <Text>Clay gets arrested.</Text> </Paragraph> <Paragraph Type="Transition"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">SMASH TO BLACK.</Text> </Paragraph> <Paragraph Type="End Of Act"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="End Of Act"> <Text>End of act two</Text> </Paragraph> <Paragraph Type="New Act"> <Text>Act three</Text> </Paragraph> <Paragraph Type="Scene Heading"> <SceneProperties Length="3/8" Page="5" Title=""> <SceneArcBeats> <CharacterArcBeat Name="BOBBY"></CharacterArcBeat> <CharacterArcBeat Name="CLAY"></CharacterArcBeat> <CharacterArcBeat Name="GEMMA"></CharacterArcBeat> <CharacterArcBeat Name="JAX"></CharacterArcBeat> </SceneArcBeats> </SceneProperties> <Text>Ext. Samcro compound - back lot - NIGHT</Text> </Paragraph> <Paragraph Type="Action"> <Text>The gang’s all here. Something CRAZY happens. </Text> </Paragraph> <Paragraph Type="Character"> <Text>Gemma</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Dialogue goes here. </Text> </Paragraph> <Paragraph Type="Character"> <Text>Clay</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>And here. </Text> </Paragraph> <Paragraph Type="Character"> <Text>Jax</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>And here. </Text> </Paragraph> <Paragraph Type="Character"> <Text>BOBBY</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Here too. </Text> </Paragraph> <Paragraph Type="End Of Act"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="End Of Act"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="End Of Act"> <Text>End of act three</Text> </Paragraph> <Paragraph Type="New Act"> <Text>Act four</Text> </Paragraph> <Paragraph Type="Scene Heading"> <SceneProperties Length="4/8" Page="6" Title=""> <SceneArcBeats> <CharacterArcBeat Name=""></CharacterArcBeat> <CharacterArcBeat Name="GEMMA"></CharacterArcBeat> <CharacterArcBeat Name="JAX"></CharacterArcBeat> </SceneArcBeats> </SceneProperties> <Text>Int. Jax’s house - day</Text> </Paragraph> <Paragraph Type="Action"> <Text>JAX and GEMMA argue. </Text> </Paragraph> <Paragraph Type="Character"> <Text>Jax</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>Dialogue goes here. </Text> </Paragraph> <Paragraph Type="Character"> <Text>Gemma</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>No, it goes here. </Text> </Paragraph> <Paragraph Type="Character"> <Text>JAX</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>I’m pretty sure it goes here. </Text> </Paragraph> <Paragraph Type="Character"> <Text>Gemma</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>You know what I think’s coming up?</Text> </Paragraph> <Paragraph Type="Character"> <Text>JAX</Text> </Paragraph> <Paragraph Type="Dialogue"> <Text>What?</Text> </Paragraph> <Paragraph Type="Action"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="Transition"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">SMASH TO BLACK.</Text> </Paragraph> <Paragraph Type="End Of Act"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="End Of Act"> <Text>END OF SHOW</Text> </Paragraph> <Paragraph Type="Character"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="Action"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="End Of Act"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> <Paragraph Type="Action"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"></Text> </Paragraph> </Content> <Watermarking Text=""/> <HeaderAndFooter FooterFirstPage="Yes" FooterVisible="No" HeaderFirstPage="No" HeaderVisible="Yes" StartingPage="1"> <Header> <Paragraph Alignment="Right" FirstIndent="0.00" Leading="Regular" LeftIndent="1.25" RightIndent="-0.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""> Ep. # </Text> <DynamicLabel Type="Last Revised"/> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""> </Text> <DynamicLabel Type="Page #"/> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">.</Text> <Tabstops> <Tabstop Position="7.25" Type="Right"/> <Tabstop Position="2.00" Type="Decimal"/> <Tabstop Position="4.00" Type="Center"/> </Tabstops> </Paragraph> </Header> <Footer> <Paragraph Alignment="Right" FirstIndent="0.00" Leading="Regular" LeftIndent="1.25" RightIndent="-1.25" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""> </Text> </Paragraph> </Footer> </HeaderAndFooter> <SpellCheckIgnoreLists> <IgnoredRanges/> <IgnoredWords/> </SpellCheckIgnoreLists> <PageLayout BackgroundColor="#FFFFFFFFFFFF" BottomMargin="72" BreakDialogueAndActionAtSentences="Yes" DocumentLeading="Normal" FooterMargin="36" ForegroundColor="#000000000000" HeaderMargin="36" InvisiblesColor="#A0A0A0A0A0A0" TopMargin="72" UsesSmartQuotes="Yes"> <PageSize Height="11.00" Width="8.50"/> <AutoCastList AddParentheses="Yes" AutomaticallyGenerate="Yes" CastListElement="Cast List"/> </PageLayout> <WindowState Height="635" Left="2" Mode="Maximized" Top="2" Width="649"/> <TextState Scaling="100" Selection="0,0" ShowInvisibles="No"/> <ElementSettings Type="General"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""/> <ParagraphSpec Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="General" ReturnKey="General" Shortcut="0"/> </ElementSettings> <ElementSettings Type="Scene Heading"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="AllCaps"/> <ParagraphSpec Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="22" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Scene Heading" ReturnKey="Action" Shortcut="1"/> </ElementSettings> <ElementSettings Type="Action"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""/> <ParagraphSpec Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="11" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Action" ReturnKey="Action" Shortcut="2"/> </ElementSettings> <ElementSettings Type="Character"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="AllCaps"/> <ParagraphSpec Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="4.00" RightIndent="7.25" SpaceBefore="11" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Character" ReturnKey="Dialogue" Shortcut="3"/> </ElementSettings> <ElementSettings Type="Parenthetical"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""/> <ParagraphSpec Alignment="Left" FirstIndent="-0.10" Leading="Regular" LeftIndent="3.00" RightIndent="5.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Parenthetical" ReturnKey="Dialogue" Shortcut="4"/> </ElementSettings> <ElementSettings Type="Dialogue"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""/> <ParagraphSpec Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="2.60" RightIndent="6.38" SpaceBefore="0" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Dialogue" ReturnKey="Action" Shortcut="5"/> </ElementSettings> <ElementSettings Type="Transition"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="AllCaps"/> <ParagraphSpec Alignment="Right" FirstIndent="0.00" Leading="Regular" LeftIndent="5.50" RightIndent="7.10" SpaceBefore="11" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Transition" ReturnKey="Scene Heading" Shortcut="6"/> </ElementSettings> <ElementSettings Type="Shot"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="AllCaps"/> <ParagraphSpec Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="22" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Scene Heading" ReturnKey="Action" Shortcut="7"/> </ElementSettings> <ElementSettings Type="Cast List"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="AllCaps"/> <ParagraphSpec Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Action" ReturnKey="Action" Shortcut="8"/> </ElementSettings> <ElementSettings Type="New Act"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"/> <ParagraphSpec Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="Yes"/> <Behavior PaginateAs="General" ReturnKey="Scene Heading" Shortcut=""/> </ElementSettings> <ElementSettings Type="End Of Act"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps"/> <ParagraphSpec Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="General" ReturnKey="New Act" Shortcut="9"/> </ElementSettings> <ElementSettings Type="Act Break"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""/> <ParagraphSpec Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"/> <Behavior PaginateAs="Action" ReturnKey="Action" Shortcut=":"/> </ElementSettings> <TitlePage> <HeaderAndFooter FooterFirstPage="Yes" FooterVisible="No" HeaderFirstPage="No" HeaderVisible="Yes" StartingPage="1"> <Header> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.25" RightIndent="-0.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""> </Text> <DynamicLabel Type="Page #"/> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">.</Text> <Tabstops> <Tabstop Position="7.50" Type="Right"/> </Tabstops> </Paragraph> </Header> <Footer> <Paragraph Alignment="Right" FirstIndent="0.00" Leading="Regular" LeftIndent="1.25" RightIndent="-1.25" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""> </Text> </Paragraph> </Footer> </HeaderAndFooter> <Content> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="Underline+AllCaps">Sons of anarchy</Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">"EPISODE TITLE"</Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">Written by</Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">(Name of Writer)</Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Center" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="0" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.50" RightIndent="7.50" SpaceBefore="12" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="12" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">Address</Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="12" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style="">Phone Number</Text> </Paragraph> <Paragraph Alignment="Left" FirstIndent="0.00" Leading="Regular" LeftIndent="1.00" RightIndent="7.50" SpaceBefore="12" Spacing="1" StartsNewPage="No"> <Text AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""></Text> <Tabstops> <Tabstop Position="5.25" Type="Left"/> <Tabstop Position="1.25" Type="Left"/> <Tabstop Position="5.50" Type="Left"/> </Tabstops> </Paragraph> </Content> <TextState Scaling="100" Selection="7,7" ShowInvisibles="No"/> </TitlePage> <UnanchoredScriptNotes/> <SmartType> <Characters> <Character>GUARD</Character> <Character>JAX</Character> <Character>GEMMA</Character> <Character>TARA</Character> <Character>SHERIFF</Character> <Character>CLAY</Character> <Character>BOBBY</Character> </Characters> <Extensions> <Extension>(V.O.)</Extension> <Extension>(O.S.)</Extension> <Extension>(O.C.)</Extension> <Extension>(SUBTITLE)</Extension> </Extensions> <SceneIntros Separator=". "> <SceneIntro>INT</SceneIntro> <SceneIntro>EXT</SceneIntro> <SceneIntro>I/E</SceneIntro> </SceneIntros> <Locations> <Location>STOCKTON STATE PRISON - CELL</Location> <Location>JAX'S HOUSE - THOMAS' NURSERY</Location> <Location>STREET - CHARMING</Location> <Location>SAMCRO COMPOUND</Location> <Location>SAMCRO COMPOUND - BACK LOT</Location> <Location>JAX'S HOUSE</Location> </Locations> <TimesOfDay Separator=" - "> <TimeOfDay>DAY</TimeOfDay> <TimeOfDay>NIGHT</TimeOfDay> <TimeOfDay>AFTERNOON</TimeOfDay> <TimeOfDay>MORNING</TimeOfDay> <TimeOfDay>EVENING</TimeOfDay> <TimeOfDay>LATER</TimeOfDay> <TimeOfDay>MOMENTS LATER</TimeOfDay> <TimeOfDay>CONTINUOUS</TimeOfDay> <TimeOfDay>THE NEXT DAY</TimeOfDay> </TimesOfDay> <Transitions> <Transition>CUT TO:</Transition> <Transition>FADE IN:</Transition> <Transition>FADE OUT.</Transition> <Transition>FADE TO:</Transition> <Transition>DISSOLVE TO:</Transition> <Transition>BACK TO:</Transition> <Transition>MATCH CUT TO:</Transition> <Transition>JUMP CUT TO:</Transition> <Transition>FADE TO BLACK.</Transition> <Transition>SMASH TO:</Transition> <Transition>SMASH TO BLACK.</Transition> </Transitions> </SmartType> <MoresAndContinueds> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""/> <DialogueBreaks AutomaticCharacterContinueds="Yes" BottomOfPage="Yes" DialogueBottom="(MORE)" DialogueTop="(CONT'D)" TopOfNext="Yes"/> <SceneBreaks ContinuedNumber="Yes" SceneBottom="(CONTINUED)" SceneBottomOfPage="Yes" SceneTop="CONTINUED:" SceneTopOfNext="Yes"/> </MoresAndContinueds> <LockedPages/> <Revisions ActiveSet="1" Location="7.75" RevisionMode="No" RevisionsShown="Active" ShowAllMarks="No" ShowAllSets="No" ShowPageColor="No"> <Revision Color="#000000000000" FullRevision="No" ID="1" Mark="*" Name="Blue (mm/dd/yyyy)" PageColor="#C6C6EDEDFEFE" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="2" Mark="*" Name="Pink (mm/dd/yyyy)" PageColor="#FDFDCCCCD4D4" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="3" Mark="*" Name="Yellow (mm/dd/yyyy) " PageColor="#FDFDFFFFABAB" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="4" Mark="*" Name="Green (mm/dd/yyyy)" PageColor="#D1D1FEFED0D0" Style=""/> <Revision Color="#000000000101" FullRevision="No" ID="5" Mark="*" Name="Goldenrod (mm/dd/yyyy)" PageColor="#FAFACDCD3939" Style=""/> <Revision Color="#000000000101" FullRevision="No" ID="6" Mark="*" Name="Buff (mm/dd/yyyy) " PageColor="#FCFCEDED9D9D" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="7" Mark="*" Name="Salmon (mm/dd/yyyy)" PageColor="#F8F8AEAE8E8E" Style=""/> <Revision Color="#000000000101" FullRevision="No" ID="8" Mark="*" Name="Cherry (mm/dd/yyyy)" PageColor="#FBFBA4A4B4B4" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="9" Mark="*" Name="Tan (mm/dd/yyyy) " PageColor="#FDFDF1F1C7C7" Style=""/> <Revision Color="#000000000303" FullRevision="No" ID="10" Mark="*" Name="2nd White (mm/dd/yyyy) " PageColor="#FFFFFFFFFFFF" Style=""/> <Revision Color="#000000000303" FullRevision="No" ID="11" Mark="*" Name="2nd Blue (mm/dd/yyyy) " PageColor="#C6C6EDEDFEFE" Style=""/> <Revision Color="#000000000101" FullRevision="No" ID="12" Mark="*" Name="2nd Pink (mm/dd/yyyy)" PageColor="#FDFDCCCCD4D4" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="13" Mark="*" Name="2nd Yellow (mm/dd/yyyy)" PageColor="#FDFDFFFFABAB" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="14" Mark="*" Name="2nd Green (mm/dd/yyyy)" PageColor="#D1D1FEFED0D0" Style=""/> <Revision Color="#000000000101" FullRevision="No" ID="15" Mark="*" Name="2nd Goldenrod (mm/dd/yyyy) " PageColor="#FAFACDCD3939" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="16" Mark="*" Name="2nd Buff (mm/dd/yyyy) " PageColor="#FCFCEDED9D9D" Style=""/> <Revision Color="#000000000202" FullRevision="No" ID="17" Mark="*" Name="2nd Salmon (mm/dd/yyyy)" PageColor="#F8F8AEAE8E8E" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="18" Mark="*" Name="2nd Cherry (mm/dd/yyyy)" PageColor="#FBFBA4A4B4B4" Style=""/> <Revision Color="#000000000000" FullRevision="No" ID="19" Mark="*" Name="2nd Tan (mm/dd/yyyy)" PageColor="#FDFDF1F1C7C7" Style=""/> </Revisions> <SplitState ActivePanel="1" SplitMode="None" SplitterPosition="1013"> <ScriptPanel DisplayMode="Page"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Verdana" RevisionID="0" Size="9" Style=""/> </ScriptPanel> </SplitState> <Macros> <Macro Element="Scene Heading" Name="INT" Shortcut="Ctrl+Alt+1" Text="INT. " Transition="None"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Scene Heading" Name="EXT" Shortcut="Ctrl+Alt+2" Text="EXT. " Transition="None"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Scene Heading" Name="I/E" Shortcut="Ctrl+Alt+3" Text="I/E " Transition="None"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Scene Heading" Name="DAY" Shortcut="Ctrl+Alt+4" Text=" - DAY" Transition="Action"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Scene Heading" Name="NIGHT" Shortcut="Ctrl+Alt+5" Text=" - NIGHT" Transition="Action"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Scene Heading" Name="SUNRISE" Shortcut="Ctrl+Alt+6" Text=" - SUNRISE" Transition="Action"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Scene Heading" Name="MAGIC" Shortcut="Ctrl+Alt+7" Text=" - MAGIC" Transition="Action"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Parenthetical" Name="CONT" Shortcut="Ctrl+Alt+8" Text="continuing" Transition="Dialogue"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Parenthetical" Name="INTER" Shortcut="Ctrl+Alt+9" Text="interrupting" Transition="Dialogue"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="None" Name="" Shortcut="E" Text="" Transition="None"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Transition" Name="CUTTO" Shortcut="Ctrl+Shift+Alt+1" Text="CUT TO:" Transition="Scene Heading"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Action" Name="FADEIN" Shortcut="Ctrl+Shift+Alt+2" Text="FADE IN:" Transition="Scene Heading"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Transition" Name="FADEOUT" Shortcut="Ctrl+Shift+Alt+3" Text="FADE OUT." Transition="Scene Heading"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Transition" Name="FADETO" Shortcut="Ctrl+Shift+Alt+4" Text="FADE TO:" Transition="Scene Heading"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Transition" Name="DISSLV" Shortcut="Ctrl+Shift+Alt+5" Text="DISSOLVE TO:" Transition="Scene Heading"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Transition" Name="BACKTO" Shortcut="Ctrl+Shift+Alt+6" Text="BACK TO:" Transition="Scene Heading"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Transition" Name="MATCHCUT" Shortcut="Ctrl+Shift+Alt+7" Text="MATCH CUT TO:" Transition="Scene Heading"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Transition" Name="JUMPCUT" Shortcut="Ctrl+Shift+Alt+8" Text="JUMP CUT TO:" Transition="Scene Heading"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="Transition" Name="FBLACK" Shortcut="Ctrl+Shift+Alt+9" Text="FADE TO BLACK." Transition="None"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="None" Name="" Shortcut="E" Text="" Transition="None"> <Alias Confirm="No" MatchCase="No" SmartReplace="Yes" Text="" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="Parenthetical"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="New Act"/> <ActivateIn Element="End Of Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="None" Name="Start Teaser" Shortcut="E" Text="TEASER" Transition="Scene Heading"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="st1" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="New Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="End Of Act" Name="End Teaser" Shortcut="E" Text="END OF TEASER" Transition="New Act"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="et1" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="End Of Act"/> </Alias> </Macro> <Macro Element="New Act" Name="Start Act 1" Shortcut="E" Text="ACT ONE" Transition="Scene Heading"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="sa1" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="New Act"/> <ActivateIn Element="Teaser/Act One"/> <ActivateIn Element="Show/Ep. Title"/> </Alias> </Macro> <Macro Element="End Of Act" Name="End Act 1" Shortcut="E" Text="END OF ACT ONE" Transition="New Act"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="ea1" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="End Of Act"/> </Alias> </Macro> <Macro Element="New Act" Name="Start Act 2" Shortcut="E" Text="ACT TWO" Transition="Scene Heading"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="sa2" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="New Act"/> </Alias> </Macro> <Macro Element="End Of Act" Name="End Act 2" Shortcut="E" Text="END OF ACT TWO" Transition="New Act"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="ea2" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="End Of Act"/> </Alias> </Macro> <Macro Element="New Act" Name="Start Act 3" Shortcut="E" Text="ACT THREE" Transition="Scene Heading"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="sa3" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="New Act"/> </Alias> </Macro> <Macro Element="End Of Act" Name="End Act 3" Shortcut="E" Text="END OF ACT THREE" Transition="New Act"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="ea3" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="End Of Act"/> </Alias> </Macro> <Macro Element="New Act" Name="Start Act 4" Shortcut="E" Text="ACT FOUR" Transition="Scene Heading"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="sa4" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Character"/> <ActivateIn Element="New Act"/> </Alias> </Macro> <Macro Element="End Of Act" Name="End Act 4" Shortcut="E" Text="END OF ACT FOUR" Transition="None"> <Alias Confirm="Yes" MatchCase="No" SmartReplace="Yes" Text="ea4" WordOnly="No"> <ActivateIn Element="General"/> <ActivateIn Element="Scene Heading"/> <ActivateIn Element="Action"/> <ActivateIn Element="Dialogue"/> <ActivateIn Element="Transition"/> <ActivateIn Element="Shot"/> <ActivateIn Element="End Of Act"/> </Alias> </Macro> </Macros> <Actors> <Actor MacVoice="" Name="Man 1" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Man 2" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Woman 1" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Woman 2" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Boy 1" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Boy 2" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Girl 1" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Girl 2" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Old Man" Pitch="Normal" Speed="Medium" WinVoice=""/> <Actor MacVoice="" Name="Old Woman" Pitch="Normal" Speed="Medium" WinVoice=""/> </Actors> <Cast> <Narrator Actor="Man 1"> <Element Type="Character"/> <Element Type="Dialogue"/> </Narrator> <Member Actor="Man 1" Character="GUARD"/> <Member Actor="Man 1" Character="JAX"/> <Member Actor="Man 1" Character="GEMMA"/> <Member Actor="Man 1" Character="TARA"/> <Member Actor="Man 1" Character="SHERIFF"/> <Member Actor="Man 1" Character="CLAY"/> <Member Actor="Man 1" Character="BOBBY"/> </Cast> <SceneNumberOptions LeftLocation="0.75" RightLocation="7.38" ShowNumbersOnLeft="Yes" ShowNumbersOnRight="Yes"> <FontSpec AdornmentStyle="0" Background="#FFFFFFFFFFFF" Color="#000000000000" Font="Courier Final Draft" RevisionID="0" Size="12" Style=""/> </SceneNumberOptions> <CastList SortOption="Alphabetical"> <CustomOrder/> </CastList> <CharacterHighlighting> <Character Color="#FFFFFFFFFFFF" Name="GUARD" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="JAX" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GEMMA" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="TARA" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="G" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GA" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GAM" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GAMM" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GE" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GEM" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GEMM" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="T" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="TA" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="TAR" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="S" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="SH" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="SHE" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="SHER" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="SHERI" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="SHERIF" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="SHERIFF" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="C" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="CL" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="CLA" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="CLAY" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GUAR" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GUA" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GU" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="J" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="JA" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="B" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="BO" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="BOB" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="BOBB" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="BOBBY" Visible="No"/> <Character Color="#FFFFFFFFFFFF" Name="GAMME" Visible="No"/> </CharacterHighlighting> <CharacterNavigatorPreferences IsSortAscending="Yes" SortColumn=""/> </FinalDraft>
{ "pile_set_name": "Github" }
config NET_DSA tristate "Distributed Switch Architecture support" default n depends on EXPERIMENTAL && NETDEVICES && !S390 select PHYLIB ---help--- This allows you to use hardware switch chips that use the Distributed Switch Architecture. if NET_DSA # tagging formats config NET_DSA_TAG_DSA bool default n config NET_DSA_TAG_EDSA bool default n config NET_DSA_TAG_TRAILER bool default n endif
{ "pile_set_name": "Github" }
/*! * Copyright (c) 2018 by Contributors * \file attrs.cc */ #include <tvm/attrs.h> namespace tvm { void DictAttrsNode::VisitAttrs(AttrVisitor* v) { v->Visit("__dict__", &dict); } void DictAttrsNode::InitByPackedArgs( const runtime::TVMArgs& args, bool allow_unknown) { for (int i = 0; i < args.size(); i += 2) { std::string key = args[i]; runtime::TVMArgValue val = args[i + 1]; if (val.type_code() == kNodeHandle) { dict.Set(key, val.operator NodeRef()); } else if (val.type_code() == kStr) { dict.Set(key, Expr(val.operator std::string())); } else { dict.Set(key, val.operator Expr()); } } } Array<AttrFieldInfo> DictAttrsNode::ListFieldInfo() const { return {}; } Attrs DictAttrsNode::make(Map<std::string, NodeRef> dict) { NodePtr<DictAttrsNode> n = make_node<DictAttrsNode>(); n->dict = std::move(dict); return Attrs(n); } TVM_STATIC_IR_FUNCTOR(IRPrinter, vtable) .set_dispatch<DictAttrsNode>([](const DictAttrsNode *op, IRPrinter *p) { p->stream << op->dict; }); TVM_REGISTER_NODE_TYPE(DictAttrsNode); TVM_REGISTER_NODE_TYPE(AttrFieldInfoNode); } // namespace tvm
{ "pile_set_name": "Github" }
config EXYNOS_THERMAL tristate "Exynos thermal management unit driver" depends on THERMAL_OF depends on HAS_IOMEM help If you say yes here you get support for the TMU (Thermal Management Unit) driver for SAMSUNG EXYNOS series of SoCs. This driver initialises the TMU, reports temperature and handles cooling action if defined. This driver uses the Exynos core thermal APIs and TMU configuration data from the supported SoCs.
{ "pile_set_name": "Github" }
class ProductsController < ApplicationController def index @products = Product.all end def show @product = Product.find(params[:id]) end end
{ "pile_set_name": "Github" }
# # This Dockerfile builds a recent curl with HTTP/2 client support, using # a recent nghttp2 build. # # See the Makefile for how to tag it. If Docker and that image is found, the # Go tests use this curl binary for integration tests. # FROM ubuntu:trusty RUN apt-get update && \ apt-get upgrade -y && \ apt-get install -y git-core build-essential wget RUN apt-get install -y --no-install-recommends \ autotools-dev libtool pkg-config zlib1g-dev \ libcunit1-dev libssl-dev libxml2-dev libevent-dev \ automake autoconf # The list of packages nghttp2 recommends for h2load: RUN apt-get install -y --no-install-recommends make binutils \ autoconf automake autotools-dev \ libtool pkg-config zlib1g-dev libcunit1-dev libssl-dev libxml2-dev \ libev-dev libevent-dev libjansson-dev libjemalloc-dev \ cython python3.4-dev python-setuptools # Note: setting NGHTTP2_VER before the git clone, so an old git clone isn't cached: ENV NGHTTP2_VER 895da9a RUN cd /root && git clone https://github.com/tatsuhiro-t/nghttp2.git WORKDIR /root/nghttp2 RUN git reset --hard $NGHTTP2_VER RUN autoreconf -i RUN automake RUN autoconf RUN ./configure RUN make RUN make install WORKDIR /root RUN wget http://curl.haxx.se/download/curl-7.45.0.tar.gz RUN tar -zxvf curl-7.45.0.tar.gz WORKDIR /root/curl-7.45.0 RUN ./configure --with-ssl --with-nghttp2=/usr/local RUN make RUN make install RUN ldconfig CMD ["-h"] ENTRYPOINT ["/usr/local/bin/curl"]
{ "pile_set_name": "Github" }
\version "2.19.21" \header { texidoc = "Tuplets may contain rests. " } \context Voice \relative { \time 2/4 \tuplet 3/2 { r c, c''' } \tuplet 3/2 { r c c } \tuplet 3/2 { r c r } \tuplet 3/2 { r r r } \tuplet 3/2 { r c e } \tuplet 3/2 { c r e } \tuplet 3/2 { r c g } \tuplet 3/2 { c r g } }
{ "pile_set_name": "Github" }
<?php namespace Gerardojbaez\Laraplans\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Gerardojbaez\Laraplans\Contracts\PlanSubscriptionUsageInterface; class PlanSubscriptionUsage extends Model implements PlanSubscriptionUsageInterface { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'subscription_id', 'code', 'valid_until', 'used' ]; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'created_at', 'updated_at', 'valid_until', ]; /** * Get feature. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function feature() { return $this->belongsTo(config('laraplans.models.plan_feature')); } /** * Get subscription. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function subscription() { return $this->belongsTo(config('laraplans.models.plan_subscription')); } /** * Scope by feature code. * * @param \Illuminate\Database\Eloquent\Builder * @return \Illuminate\Database\Eloquent\Builder */ public function scopeByFeatureCode($query, $feature_code) { return $query->whereCode($feature_code); } /** * Check whether usage has been expired or not. * * @return bool */ public function isExpired() { if (is_null($this->valid_until)) { return false; } return Carbon::now()->gte($this->valid_until); } }
{ "pile_set_name": "Github" }
// Package printf implements a parser for fmt.Printf-style format // strings. // // It parses verbs according to the following syntax: // Numeric -> '0'-'9' // Letter -> 'a'-'z' | 'A'-'Z' // Index -> '[' Numeric+ ']' // Star -> '*' // Star -> Index '*' // // Precision -> Numeric+ | Star // Width -> Numeric+ | Star // // WidthAndPrecision -> Width '.' Precision // WidthAndPrecision -> Width '.' // WidthAndPrecision -> Width // WidthAndPrecision -> '.' Precision // WidthAndPrecision -> '.' // // Flag -> '+' | '-' | '#' | ' ' | '0' // Verb -> Letter | '%' // // Input -> '%' [ Flag+ ] [ WidthAndPrecision ] [ Index ] Verb package printf import ( "errors" "regexp" "strconv" "strings" ) // ErrInvalid is returned for invalid format strings or verbs. var ErrInvalid = errors.New("invalid format string") type Verb struct { Letter rune Flags string Width Argument Precision Argument // Which value in the argument list the verb uses. // -1 denotes the next argument, // values > 0 denote explicit arguments. // The value 0 denotes that no argument is consumed. This is the case for %%. Value int Raw string } // Argument is an implicit or explicit width or precision. type Argument interface { isArgument() } // The Default value, when no width or precision is provided. type Default struct{} // Zero is the implicit zero value. // This value may only appear for precisions in format strings like %6.f type Zero struct{} // Star is a * value, which may either refer to the next argument (Index == -1) or an explicit argument. type Star struct{ Index int } // A Literal value, such as 6 in %6d. type Literal int func (Default) isArgument() {} func (Zero) isArgument() {} func (Star) isArgument() {} func (Literal) isArgument() {} // Parse parses f and returns a list of actions. // An action may either be a literal string, or a Verb. func Parse(f string) ([]interface{}, error) { var out []interface{} for len(f) > 0 { if f[0] == '%' { v, n, err := ParseVerb(f) if err != nil { return nil, err } f = f[n:] out = append(out, v) } else { n := strings.IndexByte(f, '%') if n > -1 { out = append(out, f[:n]) f = f[n:] } else { out = append(out, f) f = "" } } } return out, nil } func atoi(s string) int { n, _ := strconv.Atoi(s) return n } // ParseVerb parses the verb at the beginning of f. // It returns the verb, how much of the input was consumed, and an error, if any. func ParseVerb(f string) (Verb, int, error) { if len(f) < 2 { return Verb{}, 0, ErrInvalid } const ( flags = 1 width = 2 widthStar = 3 widthIndex = 5 dot = 6 prec = 7 precStar = 8 precIndex = 10 verbIndex = 11 verb = 12 ) m := re.FindStringSubmatch(f) if m == nil { return Verb{}, 0, ErrInvalid } v := Verb{ Letter: []rune(m[verb])[0], Flags: m[flags], Raw: m[0], } if m[width] != "" { // Literal width v.Width = Literal(atoi(m[width])) } else if m[widthStar] != "" { // Star width if m[widthIndex] != "" { v.Width = Star{atoi(m[widthIndex])} } else { v.Width = Star{-1} } } else { // Default width v.Width = Default{} } if m[dot] == "" { // default precision v.Precision = Default{} } else { if m[prec] != "" { // Literal precision v.Precision = Literal(atoi(m[prec])) } else if m[precStar] != "" { // Star precision if m[precIndex] != "" { v.Precision = Star{atoi(m[precIndex])} } else { v.Precision = Star{-1} } } else { // Zero precision v.Precision = Zero{} } } if m[verb] == "%" { v.Value = 0 } else if m[verbIndex] != "" { v.Value = atoi(m[verbIndex]) } else { v.Value = -1 } return v, len(m[0]), nil } const ( flags = `([+#0 -]*)` verb = `([a-zA-Z%])` index = `(?:\[([0-9]+)\])` star = `((` + index + `)?\*)` width1 = `([0-9]+)` width2 = star width = `(?:` + width1 + `|` + width2 + `)` precision = width widthAndPrecision = `(?:(?:` + width + `)?(?:(\.)(?:` + precision + `)?)?)` ) var re = regexp.MustCompile(`^%` + flags + widthAndPrecision + `?` + index + `?` + verb)
{ "pile_set_name": "Github" }
'use strict'; /*! * Module dependencies. */ const MongooseError = require('./error'); const $exists = require('./schema/operators/exists'); const $type = require('./schema/operators/type'); const get = require('lodash.get'); const immediate = require('./helpers/immediate'); const utils = require('./utils'); const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol; const CastError = MongooseError.CastError; const ValidatorError = MongooseError.ValidatorError; /** * SchemaType constructor. Do **not** instantiate `SchemaType` directly. * Mongoose converts your schema paths into SchemaTypes automatically. * * ####Example: * * const schema = new Schema({ name: String }); * schema.path('name') instanceof SchemaType; // true * * @param {String} path * @param {Object} [options] * @param {String} [instance] * @api public */ function SchemaType(path, options, instance) { this.path = path; this.instance = instance; this.validators = []; this.setters = []; this.getters = []; this.options = options; this._index = null; this.selected; for (const prop in options) { if (this[prop] && typeof this[prop] === 'function') { // { unique: true, index: true } if (prop === 'index' && this._index) { continue; } const val = options[prop]; // Special case so we don't screw up array defaults, see gh-5780 if (prop === 'default') { this.default(val); continue; } const opts = Array.isArray(val) ? val : [val]; this[prop].apply(this, opts); } } Object.defineProperty(this, '$$context', { enumerable: false, configurable: false, writable: true, value: null }); } /** * Sets a default value for this SchemaType. * * ####Example: * * var schema = new Schema({ n: { type: Number, default: 10 }) * var M = db.model('M', schema) * var m = new M; * console.log(m.n) // 10 * * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. * * ####Example: * * // values are cast: * var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) * var M = db.model('M', schema) * var m = new M; * console.log(m.aNumber) // 4.815162342 * * // default unique objects for Mixed types: * var schema = new Schema({ mixed: Schema.Types.Mixed }); * schema.path('mixed').default(function () { * return {}; * }); * * // if we don't use a function to return object literals for Mixed defaults, * // each document will receive a reference to the same object literal creating * // a "shared" object instance: * var schema = new Schema({ mixed: Schema.Types.Mixed }); * schema.path('mixed').default({}); * var M = db.model('M', schema); * var m1 = new M; * m1.mixed.added = 1; * console.log(m1.mixed); // { added: 1 } * var m2 = new M; * console.log(m2.mixed); // { added: 1 } * * @param {Function|any} val the default value * @return {defaultValue} * @api public */ SchemaType.prototype.default = function(val) { if (arguments.length === 1) { if (val === void 0) { this.defaultValue = void 0; return void 0; } this.defaultValue = val; return this.defaultValue; } else if (arguments.length > 1) { this.defaultValue = utils.args(arguments); } return this.defaultValue; }; /** * Declares the index options for this schematype. * * ####Example: * * var s = new Schema({ name: { type: String, index: true }) * var s = new Schema({ loc: { type: [Number], index: 'hashed' }) * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) * Schema.path('my.path').index(true); * Schema.path('my.date').index({ expires: 60 }); * Schema.path('my.path').index({ unique: true, sparse: true }); * * ####NOTE: * * _Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background) * by default. If `background` is set to `false`, MongoDB will not execute any * read/write operations you send until the index build. * Specify `background: false` to override Mongoose's default._ * * @param {Object|Boolean|String} options * @return {SchemaType} this * @api public */ SchemaType.prototype.index = function(options) { this._index = options; utils.expires(this._index); return this; }; /** * Declares an unique index. * * ####Example: * * var s = new Schema({ name: { type: String, unique: true }}); * Schema.path('name').index({ unique: true }); * * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ * * @param {Boolean} bool * @return {SchemaType} this * @api public */ SchemaType.prototype.unique = function(bool) { if (this._index === false) { if (!bool) { return; } throw new Error('Path "' + this.path + '" may not have `index` set to ' + 'false and `unique` set to true'); } if (this._index == null || this._index === true) { this._index = {}; } else if (typeof this._index === 'string') { this._index = {type: this._index}; } this._index.unique = bool; return this; }; /** * Declares a full text index. * * ###Example: * * var s = new Schema({name : {type: String, text : true }) * Schema.path('name').index({text : true}); * @param {Boolean} bool * @return {SchemaType} this * @api public */ SchemaType.prototype.text = function(bool) { if (this._index === null || this._index === undefined || typeof this._index === 'boolean') { this._index = {}; } else if (typeof this._index === 'string') { this._index = {type: this._index}; } this._index.text = bool; return this; }; /** * Declares a sparse index. * * ####Example: * * var s = new Schema({ name: { type: String, sparse: true }) * Schema.path('name').index({ sparse: true }); * * @param {Boolean} bool * @return {SchemaType} this * @api public */ SchemaType.prototype.sparse = function(bool) { if (this._index === null || this._index === undefined || typeof this._index === 'boolean') { this._index = {}; } else if (typeof this._index === 'string') { this._index = {type: this._index}; } this._index.sparse = bool; return this; }; /** * Adds a setter to this schematype. * * ####Example: * * function capitalize (val) { * if (typeof val !== 'string') val = ''; * return val.charAt(0).toUpperCase() + val.substring(1); * } * * // defining within the schema * var s = new Schema({ name: { type: String, set: capitalize }}); * * // or with the SchemaType * var s = new Schema({ name: String }) * s.path('name').set(capitalize); * * Setters allow you to transform the data before it gets to the raw mongodb * document or query. * * Suppose you are implementing user registration for a website. Users provide * an email and password, which gets saved to mongodb. The email is a string * that you will want to normalize to lower case, in order to avoid one email * having more than one account -- e.g., otherwise, [email protected] can be registered for 2 accounts via [email protected] and [email protected]. * * You can set up email lower case normalization easily via a Mongoose setter. * * function toLower(v) { * return v.toLowerCase(); * } * * var UserSchema = new Schema({ * email: { type: String, set: toLower } * }); * * var User = db.model('User', UserSchema); * * var user = new User({email: '[email protected]'}); * console.log(user.email); // '[email protected]' * * // or * var user = new User(); * user.email = '[email protected]'; * console.log(user.email); // '[email protected]' * User.updateOne({ _id: _id }, { $set: { email: '[email protected]' } }); // update to '[email protected]' * * As you can see above, setters allow you to transform the data before it * stored in MongoDB, or before executing a query. * * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ * * new Schema({ email: { type: String, lowercase: true }}) * * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. * * function inspector (val, schematype) { * if (schematype.options.required) { * return schematype.path + ' is required'; * } else { * return val; * } * } * * var VirusSchema = new Schema({ * name: { type: String, required: true, set: inspector }, * taxonomy: { type: String, set: inspector } * }) * * var Virus = db.model('Virus', VirusSchema); * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); * * console.log(v.name); // name is required * console.log(v.taxonomy); // Parvovirinae * * You can also use setters to modify other properties on the document. If * you're setting a property `name` on a document, the setter will run with * `this` as the document. Be careful, in mongoose 5 setters will also run * when querying by `name` with `this` as the query. * * ```javascript * const nameSchema = new Schema({ name: String, keywords: [String] }); * nameSchema.path('name').set(function(v) { * // Need to check if `this` is a document, because in mongoose 5 * // setters will also run on queries, in which case `this` will be a * // mongoose query object. * if (this instanceof Document && v != null) { * this.keywords = v.split(' '); * } * return v; * }); * ``` * * @param {Function} fn * @return {SchemaType} this * @api public */ SchemaType.prototype.set = function(fn) { if (typeof fn !== 'function') { throw new TypeError('A setter must be a function.'); } this.setters.push(fn); return this; }; /** * Adds a getter to this schematype. * * ####Example: * * function dob (val) { * if (!val) return val; * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); * } * * // defining within the schema * var s = new Schema({ born: { type: Date, get: dob }) * * // or by retreiving its SchemaType * var s = new Schema({ born: Date }) * s.path('born').get(dob) * * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. * * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: * * function obfuscate (cc) { * return '****-****-****-' + cc.slice(cc.length-4, cc.length); * } * * var AccountSchema = new Schema({ * creditCardNumber: { type: String, get: obfuscate } * }); * * var Account = db.model('Account', AccountSchema); * * Account.findById(id, function (err, found) { * console.log(found.creditCardNumber); // '****-****-****-1234' * }); * * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. * * function inspector (val, schematype) { * if (schematype.options.required) { * return schematype.path + ' is required'; * } else { * return schematype.path + ' is not'; * } * } * * var VirusSchema = new Schema({ * name: { type: String, required: true, get: inspector }, * taxonomy: { type: String, get: inspector } * }) * * var Virus = db.model('Virus', VirusSchema); * * Virus.findById(id, function (err, virus) { * console.log(virus.name); // name is required * console.log(virus.taxonomy); // taxonomy is not * }) * * @param {Function} fn * @return {SchemaType} this * @api public */ SchemaType.prototype.get = function(fn) { if (typeof fn !== 'function') { throw new TypeError('A getter must be a function.'); } this.getters.push(fn); return this; }; /** * Adds validator(s) for this document path. * * Validators always receive the value to validate as their first argument and * must return `Boolean`. Returning `false` or throwing an error means * validation failed. * * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. * * ####Examples: * * // make sure every value is equal to "something" * function validator (val) { * return val == 'something'; * } * new Schema({ name: { type: String, validate: validator }}); * * // with a custom error message * * var custom = [validator, 'Uh oh, {PATH} does not equal "something".'] * new Schema({ name: { type: String, validate: custom }}); * * // adding many validators at a time * * var many = [ * { validator: validator, msg: 'uh oh' } * , { validator: anotherValidator, msg: 'failed' } * ] * new Schema({ name: { type: String, validate: many }}); * * // or utilizing SchemaType methods directly: * * var schema = new Schema({ name: 'string' }); * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); * * ####Error message templates: * * From the examples above, you may have noticed that error messages support * basic templating. There are a few other template keywords besides `{PATH}` * and `{VALUE}` too. To find out more, details are available * [here](#error_messages_MongooseError.messages). * * If Mongoose's built-in error message templating isn't enough, Mongoose * supports setting the `message` property to a function. * * schema.path('name').validate({ * validator: function() { return v.length > 5; }, * // `errors['name']` will be "name must have length 5, got 'foo'" * message: function(props) { * return `${props.path} must have length 5, got '${props.value}'`; * } * }); * * To bypass Mongoose's error messages and just copy the error message that * the validator throws, do this: * * schema.path('name').validate({ * validator: function() { throw new Error('Oops!'); }, * // `errors['name']` will be "Oops!" * message: function(props) { return props.reason.message; } * }); * * ####Asynchronous validation: * * Mongoose supports validators that return a promise. A validator that returns * a promise is called an _async validator_. Async validators run in * parallel, and `validate()` will wait until all async validators have settled. * * schema.path('name').validate({ * validator: function (value) { * return new Promise(function (resolve, reject) { * resolve(false); // validation failed * }); * } * }); * * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. * * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). * * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. * * var conn = mongoose.createConnection(..); * conn.on('error', handleError); * * var Product = conn.model('Product', yourSchema); * var dvd = new Product(..); * dvd.save(); // emits error on the `conn` above * * If you want to handle these errors at the Model level, add an `error` * listener to your Model as shown below. * * // registering an error listener on the Model lets us handle errors more locally * Product.on('error', handleError); * * @param {RegExp|Function|Object} obj validator function, or hash describing options * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns falsy (except `undefined`) or throws an error, validation fails. * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators. * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string * @param {String} [type] optional validator type * @return {SchemaType} this * @api public */ SchemaType.prototype.validate = function(obj, message, type) { if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { let properties; if (message instanceof Object && !type) { properties = utils.clone(message); if (!properties.message) { properties.message = properties.msg; } properties.validator = obj; properties.type = properties.type || 'user defined'; } else { if (!message) { message = MongooseError.messages.general.default; } if (!type) { type = 'user defined'; } properties = {message: message, type: type, validator: obj}; } this.validators.push(properties); return this; } let i; let length; let arg; for (i = 0, length = arguments.length; i < length; i++) { arg = arguments[i]; if (!(arg && utils.getFunctionName(arg.constructor) === 'Object')) { const msg = 'Invalid validator. Received (' + typeof arg + ') ' + arg + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; throw new Error(msg); } this.validate(arg.validator, arg); } return this; }; /** * Adds a required validator to this SchemaType. The validator gets added * to the front of this SchemaType's validators array using `unshift()`. * * ####Example: * * var s = new Schema({ born: { type: Date, required: true }) * * // or with custom error message * * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) * * // or with a function * * var s = new Schema({ * userId: ObjectId, * username: { * type: String, * required: function() { return this.userId != null; } * } * }) * * // or with a function and a custom message * var s = new Schema({ * userId: ObjectId, * username: { * type: String, * required: [ * function() { return this.userId != null; }, * 'username is required if id is specified' * ] * } * }) * * // or through the path API * * Schema.path('name').required(true); * * // with custom error messaging * * Schema.path('name').required(true, 'grrr :( '); * * // or make a path conditionally required based on a function * var isOver18 = function() { return this.age >= 18; }; * Schema.path('voterRegistrationId').required(isOver18); * * The required validator uses the SchemaType's `checkRequired` function to * determine whether a given value satisfies the required validator. By default, * a value satisfies the required validator if `val != null` (that is, if * the value is not null nor undefined). However, most built-in mongoose schema * types override the default `checkRequired` function: * * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties. * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired * @api public */ SchemaType.prototype.required = function(required, message) { let customOptions = {}; if (typeof required === 'object') { customOptions = required; message = customOptions.message || message; required = required.isRequired; } if (required === false) { this.validators = this.validators.filter(function(v) { return v.validator !== this.requiredValidator; }, this); this.isRequired = false; delete this.originalRequiredValue; return this; } const _this = this; this.isRequired = true; this.requiredValidator = function(v) { const cachedRequired = get(this, '$__.cachedRequired'); // no validation when this path wasn't selected in the query. if (cachedRequired != null && !this.isSelected(_this.path) && !this.isModified(_this.path)) { return true; } // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we // don't call required functions multiple times in one validate call // See gh-6801 if (cachedRequired != null && _this.path in cachedRequired) { const res = cachedRequired[_this.path] ? _this.checkRequired(v, this) : true; delete cachedRequired[_this.path]; return res; } else if (typeof required === 'function') { return required.apply(this) ? _this.checkRequired(v, this) : true; } return _this.checkRequired(v, this); }; this.originalRequiredValue = required; if (typeof required === 'string') { message = required; required = undefined; } const msg = message || MongooseError.messages.general.required; this.validators.unshift(Object.assign({}, customOptions, { validator: this.requiredValidator, message: msg, type: 'required' })); return this; }; /** * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html) * looks at to determine the foreign collection it should query. * * ####Example: * const userSchema = new Schema({ name: String }); * const User = mongoose.model('User', userSchema); * * const postSchema = new Schema({ user: mongoose.ObjectId }); * postSchema.path('user').ref('User'); // By model name * postSchema.path('user').ref(User); // Can pass the model as well * * // Or you can just declare the `ref` inline in your schema * const postSchema2 = new Schema({ * user: { type: mongoose.ObjectId, ref: User } * }); * * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model. * @return {SchemaType} this * @api public */ SchemaType.prototype.ref = function(ref) { this.options.ref = ref; return this; }; /** * Gets the default value * * @param {Object} scope the scope which callback are executed * @param {Boolean} init * @api private */ SchemaType.prototype.getDefault = function(scope, init) { let ret = typeof this.defaultValue === 'function' ? this.defaultValue.call(scope) : this.defaultValue; if (ret !== null && ret !== undefined) { if (typeof ret === 'object' && (!this.options || !this.options.shared)) { ret = utils.clone(ret); } const casted = this.cast(ret, scope, init); if (casted && casted.$isSingleNested) { casted.$parent = scope; } return casted; } return ret; }; /*! * Applies setters without casting * * @api private */ SchemaType.prototype._applySetters = function(value, scope, init, priorVal) { let v = value; const setters = this.setters; let len = setters.length; const caster = this.caster; while (len--) { v = setters[len].call(scope, v, this); } if (Array.isArray(v) && caster && caster.setters) { const newVal = []; for (let i = 0; i < v.length; i++) { newVal.push(caster.applySetters(v[i], scope, init, priorVal)); } v = newVal; } return v; }; /** * Applies setters * * @param {Object} value * @param {Object} scope * @param {Boolean} init * @api private */ SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { let v = this._applySetters(value, scope, init, priorVal, options); if (v == null) { return v; } // do not cast until all setters are applied #665 v = this.cast(v, scope, init, priorVal, options); return v; }; /** * Applies getters to a value * * @param {Object} value * @param {Object} scope * @api private */ SchemaType.prototype.applyGetters = function(value, scope) { let v = value; const getters = this.getters; const len = getters.length; if (len === 0) { return v; } for (let i = 0; i < len; ++i) { v = getters[i].call(scope, v, this); } return v; }; /** * Sets default `select()` behavior for this path. * * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. * * ####Example: * * T = db.model('T', new Schema({ x: { type: String, select: true }})); * T.find(..); // field x will always be selected .. * // .. unless overridden; * T.find().select('-x').exec(callback); * * @param {Boolean} val * @return {SchemaType} this * @api public */ SchemaType.prototype.select = function select(val) { this.selected = !!val; return this; }; /** * Performs a validation of `value` using the validators declared for this SchemaType. * * @param {any} value * @param {Function} callback * @param {Object} scope * @api private */ SchemaType.prototype.doValidate = function(value, fn, scope) { let err = false; const path = this.path; let count = this.validators.length; if (!count) { return fn(null); } const validate = function(ok, validatorProperties) { if (err) { return; } if (ok === undefined || ok) { if (--count <= 0) { immediate(function() { fn(null); }); } } else { const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; immediate(function() { fn(err); }); } }; const _this = this; this.validators.forEach(function(v) { if (err) { return; } const validator = v.validator; let ok; const validatorProperties = utils.clone(v); validatorProperties.path = path; validatorProperties.value = value; if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); } else if (typeof validator === 'function') { if (value === undefined && validator !== _this.requiredValidator) { validate(true, validatorProperties); return; } if (validatorProperties.isAsync) { asyncValidate(validator, scope, value, validatorProperties, validate); } else { try { if (validatorProperties.propsParameter) { ok = validator.call(scope, value, validatorProperties); } else { ok = validator.call(scope, value); } } catch (error) { ok = false; validatorProperties.reason = error; if (error.message) { validatorProperties.message = error.message; } } if (ok != null && typeof ok.then === 'function') { ok.then( function(ok) { validate(ok, validatorProperties); }, function(error) { validatorProperties.reason = error; ok = false; validate(ok, validatorProperties); }); } else { validate(ok, validatorProperties); } } } }); }; /*! * Handle async validators */ function asyncValidate(validator, scope, value, props, cb) { let called = false; const returnVal = validator.call(scope, value, function(ok, customMsg) { if (called) { return; } called = true; if (customMsg) { props.message = customMsg; } cb(ok, props); }); if (typeof returnVal === 'boolean') { called = true; cb(returnVal, props); } else if (returnVal && typeof returnVal.then === 'function') { // Promise returnVal.then( function(ok) { if (called) { return; } called = true; cb(ok, props); }, function(error) { if (called) { return; } called = true; props.reason = error; cb(false, props); }); } } /** * Performs a validation of `value` using the validators declared for this SchemaType. * * ####Note: * * This method ignores the asynchronous validators. * * @param {any} value * @param {Object} scope * @return {MongooseError|undefined} * @api private */ SchemaType.prototype.doValidateSync = function(value, scope) { let err = null; const path = this.path; const count = this.validators.length; if (!count) { return null; } const validate = function(ok, validatorProperties) { if (err) { return; } if (ok !== undefined && !ok) { const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; } }; let validators = this.validators; if (value === void 0) { if (this.validators.length > 0 && this.validators[0].type === 'required') { validators = [this.validators[0]]; } else { return null; } } validators.forEach(function(v) { if (err) { return; } const validator = v.validator; const validatorProperties = utils.clone(v); validatorProperties.path = path; validatorProperties.value = value; let ok; // Skip any explicit async validators. Validators that return a promise // will still run, but won't trigger any errors. if (validator.isAsync) { return; } if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); } else if (typeof validator === 'function') { try { if (validatorProperties.propsParameter) { ok = validator.call(scope, value, validatorProperties); } else { ok = validator.call(scope, value); } } catch (error) { ok = false; validatorProperties.reason = error; } // Skip any validators that return a promise, we can't handle those // synchronously if (ok != null && typeof ok.then === 'function') { return; } validate(ok, validatorProperties); } }); return err; }; /** * Determines if value is a valid Reference. * * @param {SchemaType} self * @param {Object} value * @param {Document} doc * @param {Boolean} init * @return {Boolean} * @api private */ SchemaType._isRef = function(self, value, doc, init) { // fast path let ref = init && self.options && (self.options.ref || self.options.refPath); if (!ref && doc && doc.$__ != null) { // checks for // - this populated with adhoc model and no ref was set in schema OR // - setting / pushing values after population const path = doc.$__fullPath(self.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; ref = owner.populated(path); } if (ref) { if (value == null) { return true; } if (!Buffer.isBuffer(value) && // buffers are objects too value._bsontype !== 'Binary' // raw binary value from the db && utils.isObject(value) // might have deselected _id in population query ) { return true; } } return false; }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } /*! * ignore */ function handleArray(val) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { return _this.castForQuery(m); }); } /*! * Just like handleArray, except also allows `[]` because surprisingly * `$in: [1, []]` works fine */ function handle$in(val) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { if (Array.isArray(m) && m.length === 0) { return m; } return _this.castForQuery(m); }); } /*! * ignore */ SchemaType.prototype.$conditionalHandlers = { $all: handleArray, $eq: handleSingle, $in: handle$in, $ne: handleSingle, $nin: handleArray, $exists: $exists, $type: $type }; /*! * Wraps `castForQuery` to handle context */ SchemaType.prototype.castForQueryWrapper = function(params) { this.$$context = params.context; if ('$conditional' in params) { return this.castForQuery(params.$conditional, params.val); } if (params.$skipQueryCastForUpdate) { return this._castForQuery(params.val); } return this.castForQuery(params.val); }; /** * Cast the given value with the given optional query operator. * * @param {String} [$conditional] query operator, like `$eq` or `$in` * @param {any} val * @api private */ SchemaType.prototype.castForQuery = function($conditional, val) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional); } return handler.call(this, val); } val = $conditional; return this._castForQuery(val); }; /*! * Internal switch for runSetters * * @api private */ SchemaType.prototype._castForQuery = function(val) { return this.applySetters(val, this.$$context); }; /** * Default check for if this path satisfies the `required` validator. * * @param {any} val * @api private */ SchemaType.prototype.checkRequired = function(val) { return val != null; }; /*! * Module exports. */ module.exports = exports = SchemaType; exports.CastError = CastError; exports.ValidatorError = ValidatorError;
{ "pile_set_name": "Github" }
// // This file is auto-generated. Please don't modify it! // package org.opencv.plot; import org.opencv.core.Algorithm; import org.opencv.core.Mat; import org.opencv.core.Scalar; import org.opencv.plot.Plot2d; // C++: class Plot2d //javadoc: Plot2d public class Plot2d extends Algorithm { protected Plot2d(long addr) { super(addr); } // internal usage only public static Plot2d __fromPtr__(long addr) { return new Plot2d(addr); } // // C++: static Ptr_Plot2d create(Mat data) // //javadoc: Plot2d::create(data) public static Plot2d create(Mat data) { Plot2d retVal = Plot2d.__fromPtr__(create_0(data.nativeObj)); return retVal; } // // C++: static Ptr_Plot2d create(Mat dataX, Mat dataY) // //javadoc: Plot2d::create(dataX, dataY) public static Plot2d create(Mat dataX, Mat dataY) { Plot2d retVal = Plot2d.__fromPtr__(create_1(dataX.nativeObj, dataY.nativeObj)); return retVal; } // // C++: void render(Mat& _plotResult) // //javadoc: Plot2d::render(_plotResult) public void render(Mat _plotResult) { render_0(nativeObj, _plotResult.nativeObj); return; } // // C++: void setGridLinesNumber(int gridLinesNumber) // //javadoc: Plot2d::setGridLinesNumber(gridLinesNumber) public void setGridLinesNumber(int gridLinesNumber) { setGridLinesNumber_0(nativeObj, gridLinesNumber); return; } // // C++: void setInvertOrientation(bool _invertOrientation) // //javadoc: Plot2d::setInvertOrientation(_invertOrientation) public void setInvertOrientation(boolean _invertOrientation) { setInvertOrientation_0(nativeObj, _invertOrientation); return; } // // C++: void setMaxX(double _plotMaxX) // //javadoc: Plot2d::setMaxX(_plotMaxX) public void setMaxX(double _plotMaxX) { setMaxX_0(nativeObj, _plotMaxX); return; } // // C++: void setMaxY(double _plotMaxY) // //javadoc: Plot2d::setMaxY(_plotMaxY) public void setMaxY(double _plotMaxY) { setMaxY_0(nativeObj, _plotMaxY); return; } // // C++: void setMinX(double _plotMinX) // //javadoc: Plot2d::setMinX(_plotMinX) public void setMinX(double _plotMinX) { setMinX_0(nativeObj, _plotMinX); return; } // // C++: void setMinY(double _plotMinY) // //javadoc: Plot2d::setMinY(_plotMinY) public void setMinY(double _plotMinY) { setMinY_0(nativeObj, _plotMinY); return; } // // C++: void setNeedPlotLine(bool _needPlotLine) // //javadoc: Plot2d::setNeedPlotLine(_needPlotLine) public void setNeedPlotLine(boolean _needPlotLine) { setNeedPlotLine_0(nativeObj, _needPlotLine); return; } // // C++: void setPlotAxisColor(Scalar _plotAxisColor) // //javadoc: Plot2d::setPlotAxisColor(_plotAxisColor) public void setPlotAxisColor(Scalar _plotAxisColor) { setPlotAxisColor_0(nativeObj, _plotAxisColor.val[0], _plotAxisColor.val[1], _plotAxisColor.val[2], _plotAxisColor.val[3]); return; } // // C++: void setPlotBackgroundColor(Scalar _plotBackgroundColor) // //javadoc: Plot2d::setPlotBackgroundColor(_plotBackgroundColor) public void setPlotBackgroundColor(Scalar _plotBackgroundColor) { setPlotBackgroundColor_0(nativeObj, _plotBackgroundColor.val[0], _plotBackgroundColor.val[1], _plotBackgroundColor.val[2], _plotBackgroundColor.val[3]); return; } // // C++: void setPlotGridColor(Scalar _plotGridColor) // //javadoc: Plot2d::setPlotGridColor(_plotGridColor) public void setPlotGridColor(Scalar _plotGridColor) { setPlotGridColor_0(nativeObj, _plotGridColor.val[0], _plotGridColor.val[1], _plotGridColor.val[2], _plotGridColor.val[3]); return; } // // C++: void setPlotLineColor(Scalar _plotLineColor) // //javadoc: Plot2d::setPlotLineColor(_plotLineColor) public void setPlotLineColor(Scalar _plotLineColor) { setPlotLineColor_0(nativeObj, _plotLineColor.val[0], _plotLineColor.val[1], _plotLineColor.val[2], _plotLineColor.val[3]); return; } // // C++: void setPlotLineWidth(int _plotLineWidth) // //javadoc: Plot2d::setPlotLineWidth(_plotLineWidth) public void setPlotLineWidth(int _plotLineWidth) { setPlotLineWidth_0(nativeObj, _plotLineWidth); return; } // // C++: void setPlotSize(int _plotSizeWidth, int _plotSizeHeight) // //javadoc: Plot2d::setPlotSize(_plotSizeWidth, _plotSizeHeight) public void setPlotSize(int _plotSizeWidth, int _plotSizeHeight) { setPlotSize_0(nativeObj, _plotSizeWidth, _plotSizeHeight); return; } // // C++: void setPlotTextColor(Scalar _plotTextColor) // //javadoc: Plot2d::setPlotTextColor(_plotTextColor) public void setPlotTextColor(Scalar _plotTextColor) { setPlotTextColor_0(nativeObj, _plotTextColor.val[0], _plotTextColor.val[1], _plotTextColor.val[2], _plotTextColor.val[3]); return; } // // C++: void setPointIdxToPrint(int pointIdx) // //javadoc: Plot2d::setPointIdxToPrint(pointIdx) public void setPointIdxToPrint(int pointIdx) { setPointIdxToPrint_0(nativeObj, pointIdx); return; } // // C++: void setShowGrid(bool needShowGrid) // //javadoc: Plot2d::setShowGrid(needShowGrid) public void setShowGrid(boolean needShowGrid) { setShowGrid_0(nativeObj, needShowGrid); return; } // // C++: void setShowText(bool needShowText) // //javadoc: Plot2d::setShowText(needShowText) public void setShowText(boolean needShowText) { setShowText_0(nativeObj, needShowText); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: static Ptr_Plot2d create(Mat data) private static native long create_0(long data_nativeObj); // C++: static Ptr_Plot2d create(Mat dataX, Mat dataY) private static native long create_1(long dataX_nativeObj, long dataY_nativeObj); // C++: void render(Mat& _plotResult) private static native void render_0(long nativeObj, long _plotResult_nativeObj); // C++: void setGridLinesNumber(int gridLinesNumber) private static native void setGridLinesNumber_0(long nativeObj, int gridLinesNumber); // C++: void setInvertOrientation(bool _invertOrientation) private static native void setInvertOrientation_0(long nativeObj, boolean _invertOrientation); // C++: void setMaxX(double _plotMaxX) private static native void setMaxX_0(long nativeObj, double _plotMaxX); // C++: void setMaxY(double _plotMaxY) private static native void setMaxY_0(long nativeObj, double _plotMaxY); // C++: void setMinX(double _plotMinX) private static native void setMinX_0(long nativeObj, double _plotMinX); // C++: void setMinY(double _plotMinY) private static native void setMinY_0(long nativeObj, double _plotMinY); // C++: void setNeedPlotLine(bool _needPlotLine) private static native void setNeedPlotLine_0(long nativeObj, boolean _needPlotLine); // C++: void setPlotAxisColor(Scalar _plotAxisColor) private static native void setPlotAxisColor_0(long nativeObj, double _plotAxisColor_val0, double _plotAxisColor_val1, double _plotAxisColor_val2, double _plotAxisColor_val3); // C++: void setPlotBackgroundColor(Scalar _plotBackgroundColor) private static native void setPlotBackgroundColor_0(long nativeObj, double _plotBackgroundColor_val0, double _plotBackgroundColor_val1, double _plotBackgroundColor_val2, double _plotBackgroundColor_val3); // C++: void setPlotGridColor(Scalar _plotGridColor) private static native void setPlotGridColor_0(long nativeObj, double _plotGridColor_val0, double _plotGridColor_val1, double _plotGridColor_val2, double _plotGridColor_val3); // C++: void setPlotLineColor(Scalar _plotLineColor) private static native void setPlotLineColor_0(long nativeObj, double _plotLineColor_val0, double _plotLineColor_val1, double _plotLineColor_val2, double _plotLineColor_val3); // C++: void setPlotLineWidth(int _plotLineWidth) private static native void setPlotLineWidth_0(long nativeObj, int _plotLineWidth); // C++: void setPlotSize(int _plotSizeWidth, int _plotSizeHeight) private static native void setPlotSize_0(long nativeObj, int _plotSizeWidth, int _plotSizeHeight); // C++: void setPlotTextColor(Scalar _plotTextColor) private static native void setPlotTextColor_0(long nativeObj, double _plotTextColor_val0, double _plotTextColor_val1, double _plotTextColor_val2, double _plotTextColor_val3); // C++: void setPointIdxToPrint(int pointIdx) private static native void setPointIdxToPrint_0(long nativeObj, int pointIdx); // C++: void setShowGrid(bool needShowGrid) private static native void setShowGrid_0(long nativeObj, boolean needShowGrid); // C++: void setShowText(bool needShowText) private static native void setShowText_0(long nativeObj, boolean needShowText); // native support for java finalize() private static native void delete(long nativeObj); }
{ "pile_set_name": "Github" }
/* See LICENSE file in root folder */ #ifndef ___C3D_GlslMaterials_H___ #define ___C3D_GlslMaterials_H___ #include "SdwModule.hpp" #include <ShaderWriter/MatTypes/Mat4.hpp> #include <ShaderWriter/CompositeTypes/StructInstance.hpp> namespace castor3d { namespace shader { castor::String const PassBufferName = cuT( "Materials" ); struct BaseMaterial : public sdw::StructInstance { friend class Materials; virtual ~BaseMaterial() = default; C3D_API virtual sdw::Vec3 m_diffuse()const = 0; protected: C3D_API BaseMaterial( ast::Shader * shader , ast::expr::ExprPtr expr ); protected: using sdw::StructInstance::getMember; using sdw::StructInstance::getMemberArray; protected: sdw::Vec4 m_common; sdw::Vec4 m_reflRefr; sdw::Vec4 m_sssInfo; public: sdw::Float m_opacity; sdw::Float m_emissive; sdw::Float m_alphaRef; sdw::Float m_gamma; sdw::Float m_refractionRatio; sdw::Int m_hasRefraction; sdw::Int m_hasReflection; sdw::Float m_bwAccumulationOperator; sdw::Int m_subsurfaceScatteringEnabled; sdw::Float m_gaussianWidth; sdw::Float m_subsurfaceScatteringStrength; sdw::Int m_transmittanceProfileSize; sdw::Array< sdw::Vec4 > m_transmittanceProfile; }; CU_DeclareSmartPtr( BaseMaterial ); struct LegacyMaterial : public BaseMaterial { friend class LegacyMaterials; C3D_API LegacyMaterial( ast::Shader * shader , ast::expr::ExprPtr expr ); C3D_API static ast::type::StructPtr makeType( ast::type::TypesCache & cache ); C3D_API static std::unique_ptr< sdw::Struct > declare( sdw::ShaderWriter & writer ); C3D_API sdw::Vec3 m_diffuse()const override; private: sdw::Vec4 m_diffAmb; sdw::Vec4 m_specShin; public: sdw::Float m_ambient; sdw::Vec3 m_specular; sdw::Float m_shininess; }; struct MetallicRoughnessMaterial : public BaseMaterial { friend class PbrMRMaterials; C3D_API MetallicRoughnessMaterial( ast::Shader * shader , ast::expr::ExprPtr expr ); C3D_API static ast::type::StructPtr makeType( ast::type::TypesCache & cache ); C3D_API static std::unique_ptr< sdw::Struct > declare( sdw::ShaderWriter & writer ); C3D_API sdw::Vec3 m_diffuse()const override; protected: sdw::Vec4 m_albRough; sdw::Vec4 m_metDiv; public: sdw::Vec3 m_albedo; sdw::Float m_roughness; sdw::Float m_metallic; }; struct SpecularGlossinessMaterial : public BaseMaterial { friend class PbrSGMaterials; C3D_API SpecularGlossinessMaterial( ast::Shader * shader , ast::expr::ExprPtr expr ); C3D_API static ast::type::StructPtr makeType( ast::type::TypesCache & cache ); C3D_API static std::unique_ptr< sdw::Struct > declare( sdw::ShaderWriter & writer ); C3D_API sdw::Vec3 m_diffuse()const override; protected: sdw::Vec4 m_diffDiv; sdw::Vec4 m_specGloss; public: sdw::Vec3 m_specular; sdw::Float m_glossiness; }; class Materials { protected: C3D_API explicit Materials( sdw::ShaderWriter & writer ); public: virtual ~Materials() = default; C3D_API virtual void declare( bool hasSsbo ) = 0; C3D_API virtual BaseMaterialUPtr getBaseMaterial( sdw::UInt const & index )const = 0; protected: sdw::ShaderWriter & m_writer; std::unique_ptr< sdw::Struct > m_type; }; class LegacyMaterials : public Materials { public: C3D_API explicit LegacyMaterials( sdw::ShaderWriter & writer ); C3D_API void declare( bool hasSsbo )override; C3D_API LegacyMaterial getMaterial( sdw::UInt const & index )const; C3D_API BaseMaterialUPtr getBaseMaterial( sdw::UInt const & index )const override; private: std::unique_ptr< sdw::ArraySsboT< LegacyMaterial > > m_ssbo; sdw::Function< LegacyMaterial, sdw::InUInt > m_getMaterial; }; class PbrMRMaterials : public Materials { public: C3D_API explicit PbrMRMaterials( sdw::ShaderWriter & writer ); C3D_API void declare( bool hasSsbo )override; C3D_API MetallicRoughnessMaterial getMaterial( sdw::UInt const & index )const; C3D_API BaseMaterialUPtr getBaseMaterial( sdw::UInt const & index )const override; private: std::unique_ptr< sdw::ArraySsboT< MetallicRoughnessMaterial > > m_ssbo; sdw::Function< MetallicRoughnessMaterial, sdw::InUInt > m_getMaterial; }; class PbrSGMaterials : public Materials { public: C3D_API explicit PbrSGMaterials( sdw::ShaderWriter & writer ); C3D_API void declare( bool hasSsbo )override; C3D_API SpecularGlossinessMaterial getMaterial( sdw::UInt const & index )const; C3D_API BaseMaterialUPtr getBaseMaterial( sdw::UInt const & index )const override; private: std::unique_ptr< sdw::ArraySsboT< SpecularGlossinessMaterial > > m_ssbo; sdw::Function< SpecularGlossinessMaterial, sdw::InUInt > m_getMaterial; }; } } #endif
{ "pile_set_name": "Github" }
/* * Copyright 2019-2020 David Karnok * * 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 hu.akarnokd.kotlin.flow.impl import hu.akarnokd.kotlin.flow.ParallelFlow import kotlinx.coroutines.flow.FlowCollector /** * Reduces the source items into a single value on each rail * and emits those. */ internal class FlowParallelReduce<T, R>( private val source: ParallelFlow<T>, private val seed: suspend () -> R, private val combine: suspend (R, T) -> R ) : ParallelFlow<R> { override val parallelism: Int get() = source.parallelism override suspend fun collect(vararg collectors: FlowCollector<R>) { val n = parallelism val rails = Array(n) { ReducerCollector(combine) } // Array constructor doesn't support suspendable initializer? for (i in 0 until n) { rails[i].accumulator = seed() } source.collect(*rails) for (i in 0 until n) { collectors[i].emit(rails[i].accumulator) } } class ReducerCollector<T, R>(private val combine: suspend (R, T) -> R) : FlowCollector<T> { @Suppress("UNCHECKED_CAST") var accumulator : R = null as R override suspend fun emit(value: T) { accumulator = combine(accumulator, value) } } }
{ "pile_set_name": "Github" }
// // NSURL+Argo.swift // Yomu // // Created by Sendy Halim on 6/10/16. // Copyright © 2016 Sendy Halim. All rights reserved. // import Argo import Swiftz extension URL: Argo.Decodable { public static func decode(_ json: JSON) -> Decoded<URL> { switch json { case JSON.string(let url): return URL(string: url).map(pure) ?? .typeMismatch( expected: "A String that is convertible to NSURL", actual: url ) default: return .typeMismatch(expected: "String", actual: json) } } }
{ "pile_set_name": "Github" }
# [AwGo](https://github.com/deanishe/awgo) An awesome library to make Alfred Workflows made by [Deanishe](https://github.com/deanishe). ## Notes - Using macOS console app is a lot nicer than using Alfred debugger. You can access it by running `workflow:log` in a script filter. Where `workflow:` is a magic argument with a bunch of other dev related things you can run. - You need to add unique UID to have Alfred learn from your usage.
{ "pile_set_name": "Github" }
/* * BatteryHelper.cpp * Copyright (C) 2016-2020 Linar Yusupov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #if defined(ARDUINO) #include <Arduino.h> #endif #include "SoCHelper.h" #include "BatteryHelper.h" unsigned long Battery_TimeMarker = 0; static int Battery_cutoff_count = 0; void Battery_setup() { SoC->Battery_setup(); Battery_TimeMarker = millis(); } float Battery_voltage() { return SoC->Battery_voltage(); } /* low battery voltage threshold */ float Battery_threshold() { return hw_info.model == SOFTRF_MODEL_PRIME_MK2 || (hw_info.model == SOFTRF_MODEL_STANDALONE && hw_info.revision == 16) || /* TTGO T3 V2.1.6 */ hw_info.model == SOFTRF_MODEL_DONGLE || hw_info.model == SOFTRF_MODEL_MINI ? BATTERY_THRESHOLD_LIPO : hw_info.model == SOFTRF_MODEL_UNI ? BATTERY_THRESHOLD_NIZNX2 : BATTERY_THRESHOLD_NIMHX2; } /* Battery is empty */ float Battery_cutoff() { return hw_info.model == SOFTRF_MODEL_PRIME_MK2 || (hw_info.model == SOFTRF_MODEL_STANDALONE && hw_info.revision == 16) || /* TTGO T3 V2.1.6 */ hw_info.model == SOFTRF_MODEL_DONGLE || hw_info.model == SOFTRF_MODEL_MINI ? BATTERY_CUTOFF_LIPO : hw_info.model == SOFTRF_MODEL_UNI ? BATTERY_CUTOFF_NIZNX2 : BATTERY_CUTOFF_NIMHX2; } void Battery_loop() { if (hw_info.model == SOFTRF_MODEL_PRIME_MK2 || (hw_info.model == SOFTRF_MODEL_STANDALONE && hw_info.revision == 16) || /* TTGO T3 V2.1.6 */ hw_info.model == SOFTRF_MODEL_DONGLE || hw_info.model == SOFTRF_MODEL_MINI || hw_info.model == SOFTRF_MODEL_UNI ) { if (isTimeToBattery()) { float voltage = Battery_voltage(); if (voltage > 1.8 && voltage < Battery_cutoff()) { if (Battery_cutoff_count > 2) { shutdown("LOW BAT"); } else { Battery_cutoff_count++; } } else { Battery_cutoff_count = 0; } Battery_TimeMarker = millis(); } } }
{ "pile_set_name": "Github" }
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** \file * \ingroup freestyle */ #include "BPy_GetProjectedZF1D.h" #include "../../../view_map/Functions1D.h" #include "../../BPy_Convert.h" #include "../../BPy_IntegrationType.h" #ifdef __cplusplus extern "C" { #endif /////////////////////////////////////////////////////////////////////////////////////////// //------------------------INSTANCE METHODS ---------------------------------- static char GetProjectedZF1D___doc__[] = "Class hierarchy: :class:`freestyle.types.UnaryFunction1D` > " ":class:`freestyle.types.UnaryFunction1DDouble` > :class:`GetProjectedZF1D`\n" "\n" ".. method:: __init__(integration_type=IntegrationType.MEAN)\n" "\n" " Builds a GetProjectedZF1D object.\n" "\n" " :arg integration_type: The integration method used to compute a single value\n" " from a set of values. \n" " :type integration_type: :class:`freestyle.types.IntegrationType`\n" "\n" ".. method:: __call__(inter)\n" "\n" " Returns the projected Z 3D coordinate of an Interface1D.\n" "\n" " :arg inter: An Interface1D object.\n" " :type inter: :class:`freestyle.types.Interface1D`\n" " :return: The projected Z 3D coordinate of an Interface1D.\n" " :rtype: float\n"; static int GetProjectedZF1D___init__(BPy_GetProjectedZF1D *self, PyObject *args, PyObject *kwds) { static const char *kwlist[] = {"integration_type", NULL}; PyObject *obj = 0; if (!PyArg_ParseTupleAndKeywords( args, kwds, "|O!", (char **)kwlist, &IntegrationType_Type, &obj)) { return -1; } IntegrationType t = (obj) ? IntegrationType_from_BPy_IntegrationType(obj) : MEAN; self->py_uf1D_double.uf1D_double = new Functions1D::GetProjectedZF1D(t); return 0; } /*-----------------------BPy_GetProjectedZF1D type definition ------------------------------*/ PyTypeObject GetProjectedZF1D_Type = { PyVarObject_HEAD_INIT(NULL, 0) "GetProjectedZF1D", /* tp_name */ sizeof(BPy_GetProjectedZF1D), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ GetProjectedZF1D___doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &UnaryFunction1DDouble_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)GetProjectedZF1D___init__, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /////////////////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus } #endif
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 145914066afeadc48815a73e4b263190 timeCreated: 18446744011573954816 NativeFormatImporter: mainObjectFileID: 0 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package scanner provides a scanner and tokenizer for UTF-8-encoded text. // It takes an io.Reader providing the source, which then can be tokenized // through repeated calls to the Scan function. For compatibility with // existing tools, the NUL character is not allowed. If the first character // in the source is a UTF-8 encoded byte order mark (BOM), it is discarded. // // By default, a Scanner skips white space and Go comments and recognizes all // literals as defined by the Go language specification. It may be // customized to recognize only a subset of those literals and to recognize // different identifier and white space characters. // // Basic usage pattern: // // var s scanner.Scanner // s.Init(src) // tok := s.Scan() // for tok != scanner.EOF { // // do something with tok // tok = s.Scan() // } // package scanner import ( "bytes" "fmt" "io" "os" "unicode" "unicode/utf8" ) // A source position is represented by a Position value. // A position is valid if Line > 0. type Position struct { Filename string // filename, if any Offset int // byte offset, starting at 0 Line int // line number, starting at 1 Column int // column number, starting at 1 (character count per line) } // IsValid returns true if the position is valid. func (pos *Position) IsValid() bool { return pos.Line > 0 } func (pos Position) String() string { s := pos.Filename if pos.IsValid() { if s != "" { s += ":" } s += fmt.Sprintf("%d:%d", pos.Line, pos.Column) } if s == "" { s = "???" } return s } // Predefined mode bits to control recognition of tokens. For instance, // to configure a Scanner such that it only recognizes (Go) identifiers, // integers, and skips comments, set the Scanner's Mode field to: // // ScanIdents | ScanInts | SkipComments // // With the exceptions of comments, which are skipped if SkipComments is // set, unrecognized tokens are not ignored. Instead, the scanner simply // returns the respective individual characters (or possibly sub-tokens). // For instance, if the mode is ScanIdents (not ScanStrings), the string // "foo" is scanned as the token sequence '"' Ident '"'. // const ( ScanIdents = 1 << -Ident ScanInts = 1 << -Int ScanFloats = 1 << -Float // includes Ints ScanChars = 1 << -Char ScanStrings = 1 << -String ScanRawStrings = 1 << -RawString ScanComments = 1 << -Comment SkipComments = 1 << -skipComment // if set with ScanComments, comments become white space GoTokens = ScanIdents | ScanFloats | ScanChars | ScanStrings | ScanRawStrings | ScanComments | SkipComments ) // The result of Scan is one of the following tokens or a Unicode character. const ( EOF = -(iota + 1) Ident Int Float Char String RawString Comment skipComment ) var tokenString = map[rune]string{ EOF: "EOF", Ident: "Ident", Int: "Int", Float: "Float", Char: "Char", String: "String", RawString: "RawString", Comment: "Comment", } // TokenString returns a printable string for a token or Unicode character. func TokenString(tok rune) string { if s, found := tokenString[tok]; found { return s } return fmt.Sprintf("%q", string(tok)) } // GoWhitespace is the default value for the Scanner's Whitespace field. // Its value selects Go's white space characters. const GoWhitespace = 1<<'\t' | 1<<'\n' | 1<<'\r' | 1<<' ' const bufLen = 1024 // at least utf8.UTFMax // A Scanner implements reading of Unicode characters and tokens from an io.Reader. type Scanner struct { // Input src io.Reader // Source buffer srcBuf [bufLen + 1]byte // +1 for sentinel for common case of s.next() srcPos int // reading position (srcBuf index) srcEnd int // source end (srcBuf index) // Source position srcBufOffset int // byte offset of srcBuf[0] in source line int // line count column int // character count lastLineLen int // length of last line in characters (for correct column reporting) lastCharLen int // length of last character in bytes // Token text buffer // Typically, token text is stored completely in srcBuf, but in general // the token text's head may be buffered in tokBuf while the token text's // tail is stored in srcBuf. tokBuf bytes.Buffer // token text head that is not in srcBuf anymore tokPos int // token text tail position (srcBuf index); valid if >= 0 tokEnd int // token text tail end (srcBuf index) // One character look-ahead ch rune // character before current srcPos // Error is called for each error encountered. If no Error // function is set, the error is reported to os.Stderr. Error func(s *Scanner, msg string) // ErrorCount is incremented by one for each error encountered. ErrorCount int // The Mode field controls which tokens are recognized. For instance, // to recognize Ints, set the ScanInts bit in Mode. The field may be // changed at any time. Mode uint // The Whitespace field controls which characters are recognized // as white space. To recognize a character ch <= ' ' as white space, // set the ch'th bit in Whitespace (the Scanner's behavior is undefined // for values ch > ' '). The field may be changed at any time. Whitespace uint64 // IsIdentRune is a predicate controlling the characters accepted // as the ith rune in an identifier. The set of valid characters // must not intersect with the set of white space characters. // If no IsIdentRune function is set, regular Go identifiers are // accepted instead. The field may be changed at any time. IsIdentRune func(ch rune, i int) bool // Start position of most recently scanned token; set by Scan. // Calling Init or Next invalidates the position (Line == 0). // The Filename field is always left untouched by the Scanner. // If an error is reported (via Error) and Position is invalid, // the scanner is not inside a token. Call Pos to obtain an error // position in that case. Position } // Init initializes a Scanner with a new source and returns s. // Error is set to nil, ErrorCount is set to 0, Mode is set to GoTokens, // and Whitespace is set to GoWhitespace. func (s *Scanner) Init(src io.Reader) *Scanner { s.src = src // initialize source buffer // (the first call to next() will fill it by calling src.Read) s.srcBuf[0] = utf8.RuneSelf // sentinel s.srcPos = 0 s.srcEnd = 0 // initialize source position s.srcBufOffset = 0 s.line = 1 s.column = 0 s.lastLineLen = 0 s.lastCharLen = 0 // initialize token text buffer // (required for first call to next()). s.tokPos = -1 // initialize one character look-ahead s.ch = -1 // no char read yet // initialize public fields s.Error = nil s.ErrorCount = 0 s.Mode = GoTokens s.Whitespace = GoWhitespace s.Line = 0 // invalidate token position return s } // next reads and returns the next Unicode character. It is designed such // that only a minimal amount of work needs to be done in the common ASCII // case (one test to check for both ASCII and end-of-buffer, and one test // to check for newlines). func (s *Scanner) next() rune { ch, width := rune(s.srcBuf[s.srcPos]), 1 if ch >= utf8.RuneSelf { // uncommon case: not ASCII or not enough bytes for s.srcPos+utf8.UTFMax > s.srcEnd && !utf8.FullRune(s.srcBuf[s.srcPos:s.srcEnd]) { // not enough bytes: read some more, but first // save away token text if any if s.tokPos >= 0 { s.tokBuf.Write(s.srcBuf[s.tokPos:s.srcPos]) s.tokPos = 0 // s.tokEnd is set by Scan() } // move unread bytes to beginning of buffer copy(s.srcBuf[0:], s.srcBuf[s.srcPos:s.srcEnd]) s.srcBufOffset += s.srcPos // read more bytes // (an io.Reader must return io.EOF when it reaches // the end of what it is reading - simply returning // n == 0 will make this loop retry forever; but the // error is in the reader implementation in that case) i := s.srcEnd - s.srcPos n, err := s.src.Read(s.srcBuf[i:bufLen]) s.srcPos = 0 s.srcEnd = i + n s.srcBuf[s.srcEnd] = utf8.RuneSelf // sentinel if err != nil { if err != io.EOF { s.error(err.Error()) } if s.srcEnd == 0 { if s.lastCharLen > 0 { // previous character was not EOF s.column++ } s.lastCharLen = 0 return EOF } // If err == EOF, we won't be getting more // bytes; break to avoid infinite loop. If // err is something else, we don't know if // we can get more bytes; thus also break. break } } // at least one byte ch = rune(s.srcBuf[s.srcPos]) if ch >= utf8.RuneSelf { // uncommon case: not ASCII ch, width = utf8.DecodeRune(s.srcBuf[s.srcPos:s.srcEnd]) if ch == utf8.RuneError && width == 1 { // advance for correct error position s.srcPos += width s.lastCharLen = width s.column++ s.error("illegal UTF-8 encoding") return ch } } } // advance s.srcPos += width s.lastCharLen = width s.column++ // special situations switch ch { case 0: // for compatibility with other tools s.error("illegal character NUL") case '\n': s.line++ s.lastLineLen = s.column s.column = 0 } return ch } // Next reads and returns the next Unicode character. // It returns EOF at the end of the source. It reports // a read error by calling s.Error, if not nil; otherwise // it prints an error message to os.Stderr. Next does not // update the Scanner's Position field; use Pos() to // get the current position. func (s *Scanner) Next() rune { s.tokPos = -1 // don't collect token text s.Line = 0 // invalidate token position ch := s.Peek() s.ch = s.next() return ch } // Peek returns the next Unicode character in the source without advancing // the scanner. It returns EOF if the scanner's position is at the last // character of the source. func (s *Scanner) Peek() rune { if s.ch < 0 { // this code is only run for the very first character s.ch = s.next() if s.ch == '\uFEFF' { s.ch = s.next() // ignore BOM } } return s.ch } func (s *Scanner) error(msg string) { s.ErrorCount++ if s.Error != nil { s.Error(s, msg) return } pos := s.Position if !pos.IsValid() { pos = s.Pos() } fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg) } func (s *Scanner) isIdentRune(ch rune, i int) bool { if s.IsIdentRune != nil { return s.IsIdentRune(ch, i) } return ch == '_' || unicode.IsLetter(ch) || unicode.IsDigit(ch) && i > 0 } func (s *Scanner) scanIdentifier() rune { // we know the zero'th rune is OK; start scanning at the next one ch := s.next() for i := 1; s.isIdentRune(ch, i); i++ { ch = s.next() } return ch } func digitVal(ch rune) int { switch { case '0' <= ch && ch <= '9': return int(ch - '0') case 'a' <= ch && ch <= 'f': return int(ch - 'a' + 10) case 'A' <= ch && ch <= 'F': return int(ch - 'A' + 10) } return 16 // larger than any legal digit val } func isDecimal(ch rune) bool { return '0' <= ch && ch <= '9' } func (s *Scanner) scanMantissa(ch rune) rune { for isDecimal(ch) { ch = s.next() } return ch } func (s *Scanner) scanFraction(ch rune) rune { if ch == '.' { ch = s.scanMantissa(s.next()) } return ch } func (s *Scanner) scanExponent(ch rune) rune { if ch == 'e' || ch == 'E' { ch = s.next() if ch == '-' || ch == '+' { ch = s.next() } ch = s.scanMantissa(ch) } return ch } func (s *Scanner) scanNumber(ch rune) (rune, rune) { // isDecimal(ch) if ch == '0' { // int or float ch = s.next() if ch == 'x' || ch == 'X' { // hexadecimal int ch = s.next() hasMantissa := false for digitVal(ch) < 16 { ch = s.next() hasMantissa = true } if !hasMantissa { s.error("illegal hexadecimal number") } } else { // octal int or float has8or9 := false for isDecimal(ch) { if ch > '7' { has8or9 = true } ch = s.next() } if s.Mode&ScanFloats != 0 && (ch == '.' || ch == 'e' || ch == 'E') { // float ch = s.scanFraction(ch) ch = s.scanExponent(ch) return Float, ch } // octal int if has8or9 { s.error("illegal octal number") } } return Int, ch } // decimal int or float ch = s.scanMantissa(ch) if s.Mode&ScanFloats != 0 && (ch == '.' || ch == 'e' || ch == 'E') { // float ch = s.scanFraction(ch) ch = s.scanExponent(ch) return Float, ch } return Int, ch } func (s *Scanner) scanDigits(ch rune, base, n int) rune { for n > 0 && digitVal(ch) < base { ch = s.next() n-- } if n > 0 { s.error("illegal char escape") } return ch } func (s *Scanner) scanEscape(quote rune) rune { ch := s.next() // read character after '/' switch ch { case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', quote: // nothing to do ch = s.next() case '0', '1', '2', '3', '4', '5', '6', '7': ch = s.scanDigits(ch, 8, 3) case 'x': ch = s.scanDigits(s.next(), 16, 2) case 'u': ch = s.scanDigits(s.next(), 16, 4) case 'U': ch = s.scanDigits(s.next(), 16, 8) default: s.error("illegal char escape") } return ch } func (s *Scanner) scanString(quote rune) (n int) { ch := s.next() // read character after quote for ch != quote { if ch == '\n' || ch < 0 { s.error("literal not terminated") return } if ch == '\\' { ch = s.scanEscape(quote) } else { ch = s.next() } n++ } return } func (s *Scanner) scanRawString() { ch := s.next() // read character after '`' for ch != '`' { if ch < 0 { s.error("literal not terminated") return } ch = s.next() } } func (s *Scanner) scanChar() { if s.scanString('\'') != 1 { s.error("illegal char literal") } } func (s *Scanner) scanComment(ch rune) rune { // ch == '/' || ch == '*' if ch == '/' { // line comment ch = s.next() // read character after "//" for ch != '\n' && ch >= 0 { ch = s.next() } return ch } // general comment ch = s.next() // read character after "/*" for { if ch < 0 { s.error("comment not terminated") break } ch0 := ch ch = s.next() if ch0 == '*' && ch == '/' { ch = s.next() break } } return ch } // Scan reads the next token or Unicode character from source and returns it. // It only recognizes tokens t for which the respective Mode bit (1<<-t) is set. // It returns EOF at the end of the source. It reports scanner errors (read and // token errors) by calling s.Error, if not nil; otherwise it prints an error // message to os.Stderr. func (s *Scanner) Scan() rune { ch := s.Peek() // reset token text position s.tokPos = -1 s.Line = 0 redo: // skip white space for s.Whitespace&(1<<uint(ch)) != 0 { ch = s.next() } // start collecting token text s.tokBuf.Reset() s.tokPos = s.srcPos - s.lastCharLen // set token position // (this is a slightly optimized version of the code in Pos()) s.Offset = s.srcBufOffset + s.tokPos if s.column > 0 { // common case: last character was not a '\n' s.Line = s.line s.Column = s.column } else { // last character was a '\n' // (we cannot be at the beginning of the source // since we have called next() at least once) s.Line = s.line - 1 s.Column = s.lastLineLen } // determine token value tok := ch switch { case s.isIdentRune(ch, 0): if s.Mode&ScanIdents != 0 { tok = Ident ch = s.scanIdentifier() } else { ch = s.next() } case isDecimal(ch): if s.Mode&(ScanInts|ScanFloats) != 0 { tok, ch = s.scanNumber(ch) } else { ch = s.next() } default: switch ch { case '"': if s.Mode&ScanStrings != 0 { s.scanString('"') tok = String } ch = s.next() case '\'': if s.Mode&ScanChars != 0 { s.scanChar() tok = Char } ch = s.next() case '.': ch = s.next() if isDecimal(ch) && s.Mode&ScanFloats != 0 { tok = Float ch = s.scanMantissa(ch) ch = s.scanExponent(ch) } case '/': ch = s.next() if (ch == '/' || ch == '*') && s.Mode&ScanComments != 0 { if s.Mode&SkipComments != 0 { s.tokPos = -1 // don't collect token text ch = s.scanComment(ch) goto redo } ch = s.scanComment(ch) tok = Comment } case '`': if s.Mode&ScanRawStrings != 0 { s.scanRawString() tok = String } ch = s.next() default: ch = s.next() } } // end of token text s.tokEnd = s.srcPos - s.lastCharLen s.ch = ch return tok } // Pos returns the position of the character immediately after // the character or token returned by the last call to Next or Scan. func (s *Scanner) Pos() (pos Position) { pos.Filename = s.Filename pos.Offset = s.srcBufOffset + s.srcPos - s.lastCharLen switch { case s.column > 0: // common case: last character was not a '\n' pos.Line = s.line pos.Column = s.column case s.lastLineLen > 0: // last character was a '\n' pos.Line = s.line - 1 pos.Column = s.lastLineLen default: // at the beginning of the source pos.Line = 1 pos.Column = 1 } return } // TokenText returns the string corresponding to the most recently scanned token. // Valid after calling Scan(). func (s *Scanner) TokenText() string { if s.tokPos < 0 { // no token text return "" } if s.tokEnd < 0 { // if EOF was reached, s.tokEnd is set to -1 (s.srcPos == 0) s.tokEnd = s.tokPos } if s.tokBuf.Len() == 0 { // common case: the entire token text is still in srcBuf return string(s.srcBuf[s.tokPos:s.tokEnd]) } // part of the token text was saved in tokBuf: save the rest in // tokBuf as well and return its content s.tokBuf.Write(s.srcBuf[s.tokPos:s.tokEnd]) s.tokPos = s.tokEnd // ensure idempotency of TokenText() call return s.tokBuf.String() }
{ "pile_set_name": "Github" }
using System.Threading.Tasks; using OrchardCore.ContentFields.Fields; using OrchardCore.Indexing; using OrchardCore.Modules; namespace OrchardCore.ContentFields.Indexing { [RequireFeatures("OrchardCore.ContentLocalization")] public class LocalizationSetContentPickerFieldIndexHandler : ContentFieldIndexHandler<LocalizationSetContentPickerField> { public override Task BuildIndexAsync(LocalizationSetContentPickerField field, BuildFieldIndexContext context) { var options = DocumentIndexOptions.Store; foreach (var localizationSet in field.LocalizationSets) { foreach (var key in context.Keys) { context.DocumentIndex.Set(key, localizationSet, options); } } return Task.CompletedTask; } } }
{ "pile_set_name": "Github" }
- [Introduction](/) - [Getting Started](/getting-started/) - [Next.js](/getting-started/next) - [Gatsby](/getting-started/gatsby) - [Create React App](/getting-started/create-react-app) - [React Static](/getting-started/react-static) - [Webpack](/getting-started/webpack) - [Parcel](/getting-started/parcel) - [Zero](/getting-started/zero) - [Table of components](/table-of-components) - [Playground <sup style={{ color: '#444', textTransform: 'uppercase' }}>_alpha_</sup>](/playground) - [Guides](/guides/) - [Syntax highlighting](/guides/syntax-highlighting) - [Live code editor](/guides/live-code) - [Math blocks](/guides/math-blocks) - [Table of contents](/guides/table-of-contents) - [Writing a plugin](/guides/writing-a-plugin) - [Custom loader](/guides/custom-loader) - [Wrapper customization](/guides/wrapper-customization) - [Render MDX to the terminal](/guides/terminal) - [Vue <sup style={{ color: '#444', textTransform: 'uppercase' }}>_alpha_</sup>](/guides/vue) - [Advanced](/advanced/) - [API](/advanced/api) - [Runtime](/advanced/runtime) - [AST](/advanced/ast) - [Components](/advanced/components) - [Plugins](/advanced/plugins) - [Transform Content](/advanced/transform-content) - [TypeScript](/advanced/typescript) - [Support](/support) - [Contributing](/contributing) - [Projects](/projects) - [Editors](/editors) - [Blog](/blog/) - [About](/about) - [Migrating from v0 to v1](/migrating/v1) - [V0](https://v0.mdxjs.com)
{ "pile_set_name": "Github" }
TEMPLATE = subdirs SUBDIRS = analogclock \ calculator \ calendarwidget \ charactermap \ codeeditor \ digitalclock \ groupbox \ icons \ imageviewer \ lineedits \ movie \ scribble \ shapedclock \ sliders \ spinboxes \ stylesheet \ tablet \ tetrix \ tooltips \ validators \ wiggly \ windowflags symbian: SUBDIRS = \ analogclock \ calculator \ calendarwidget \ lineedits \ shapedclock \ tetrix \ wiggly \ softkeys contains(styles, motif): SUBDIRS += styles # install target.path = $$[QT_INSTALL_EXAMPLES]/widgets sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS widgets.pro README sources.path = $$[QT_INSTALL_EXAMPLES]/widgets INSTALLS += target sources symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ This file is part of Popcorn Time. ~ ~ Popcorn Time is free software: you can redistribute it and/or modify ~ it under the terms of the GNU General Public License as published by ~ the Free Software Foundation, either version 3 of the License, or ~ (at your option) any later version. ~ ~ Popcorn Time is distributed in the hope that it will be useful, ~ but WITHOUT ANY WARRANTY; without even the implied warranty of ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ~ GNU General Public License for more details. ~ ~ You should have received a copy of the GNU General Public License ~ along with Popcorn Time. If not, see <http://www.gnu.org/licenses/>. --> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@android:id/background" android:drawable="@drawable/scrubber_track_holo_dark" /> <item android:id="@android:id/secondaryProgress"> <scale android:scaleWidth="100%" android:drawable="@drawable/scrubber_secondary_holo" /> </item> <item android:id="@android:id/progress"> <scale android:scaleWidth="100%" android:drawable="@drawable/scrubber_primary_holo" /> </item> </layer-list>
{ "pile_set_name": "Github" }
from arelle.ModelValue import qname from arelle.XmlValidate import VALID import time from collections import defaultdict caNamespace2011 = "http://xbrl.us/corporateActions/2011-05-31" caNamespace2012 = "http://xbrl.us/corporateActions/2012-03-31" eventTypeMap = { "CashDividendMember": {"Cash Dividend", "Sale Of Rights"}, "StockDividendMember": {"Stock Dividend"}, "SpecialDividendMember": {"Special Dividend"}, "CashDividendWithCurrencyOptionMember": {"Cash Dividend with Currency Option"}, "DividendwithOptionMember": {"Dividend with Option"}, "CancelMember": {"Sale Of Rights", "Annual General Meeting", "Assimilation", "Attachment", "Automatic Dividend Reinvestment", "Bankruptcy Note", "Bankruptcy Vote", "Bankruptcy", "Bearer to Registered Form", "Bid Tender / Sealed Tender", "Bonus Issue", "Bonus Rights Issue", "Buy Up", "Capital Distribution", "Capital Gains Distribution", "Capitalisation", "Cash and Securities Merger", "Cash Dividend with Currency Option", "Cash Dividend", "Cash in Lieu", "Cash Merger", "Change in Board Lot", "Change in Domicile", "Change in Name", "Change in Place of Incorporation", "Change in Place of Listing", "Change In Security Term", "Change Resulting in Decrease of Par Value", "Change Resulting in Increase of Par Value", "Class Action", "Consent for Plan of Reorganization", "Consent Tender", "Consent with No Payout", "Consent with Payout", "Convert And Tender", "Convertible Security Issue", "Coupon Distribution", "Credit Event", "Decimalisation", "Default", "Dematerialised to Physical Form", "Dissent", "Distribution on Recapitalization", "Distribution", "Dividend Reinvestment", "Dividend with Option", "Drawing", "Dutch Auction Tender", "Dutch Auction", "Exchange Offer with Consent Fee", "Exchange Offer", "Exchange on 144a Type Securities", "Exchange on Reg S Type Securities", "Exercise", "Extraordinary General Meeting", "Final Paydown", "Full Call on Convertible Security", "Full Call", "Full Pre-refunding", "General Information", "Global Permanent to Physical Form", "Global Temporary to Global Permanent Form", "Global Temporary to Physical Form", "Holdings Disclosure", "Interest", "Issue Fraction", "Liquidation", "Mandatory (Put) Tender", "Mandatory (Put) With Option to Retain", "Mandatory Exchange", "Mandatory Redemption of Shares", "Mandatory Tender", "Maturity Extension", "Maturity", "Meeting", "Merger", "Mini Tender", "Mortgage Backed", "Non US TEFRAD Certification", "Odd Lot Offer", "Offer To Purchase", "Ordinary Meeting", "Par Value Change", "Partial Call on Convertible Security", "Partial Call With Reduction in Nominal Value", "Partial Call", "Partial Defeasance", "Partial Mandatory (Put) Tender", "Partial Mandatory Tender", "Partial Prerefunding", "Pay in Kind", "Physical to Dematerialised Form", "Physical to Dematerialized Form", "Principal", "Put", "Redemption", "Redenomination", "Registered to Bearer Form", "Remarketing Agreement", "Remarketing", "Reorganization", "Return of Capital", "Reverse Stock Split", "Rights Issue", "Rights Subscription", "Round Down", "Round to Nearest", "Round Up", "Sale of Assets", "Securities Merger", "Security Delisted", "Security Separation", "Security to Certificate ", "Self Tender", "Share Exchange", "Share Premium Dividend", "Special Dividend Reinvestment", "Special Dividend", "Special Meeting", "Special Memorial Dividend", "Spinoff", "Standard Exchange", "Stock Dividend", "Stock Split with Mandatory Redemption of Shares", "Stock Split", "Subscription Offer Open Offer", "Subscription Offer Share Purchase Plan", "Subscription Offer", "Survivor Option", "Temporary Rate/Price Change", "Tender With Rights", "Termination", "Trading Status Active", "Transfer", "Unknown", "Warrants Issue"} } def checkCorporateActions(val, *args, **kwargs): modelXbrl = val.modelXbrl if caNamespace2011 in modelXbrl.namespaceDocs: caNamespace = caNamespace2011 elif caNamespace2012 in modelXbrl.namespaceDocs: caNamespace = caNamespace2012 else: return # no corporate actions taxonomy #Axes qnEventOptionsSequenceTypedAxis = qname(caNamespace, "ca:EventOptionsSequenceTypedAxis") qnEventTypeAxis = qname(caNamespace, "ca:EventTypeAxis") qnIssueTypeAxis = qname(caNamespace, "ca:IssueTypeAxis") qnMandatoryVoluntaryAxis = qname(caNamespace, "ca:MandatoryVoluntaryAxis") qnMarketTypeAxis = qname(caNamespace, "ca:MarketTypeAxis") qnPayoutSecurityIdentifierSchemeAxis = qname(caNamespace, "ca:PayoutSecurityIdentifierSchemeAxis") qnPayoutSequenceTypedAxis = qname(caNamespace, "ca:PayoutSequenceTypedAxis") qnStatusAxis = qname(caNamespace, "ca:StatusAxis") qnUnderlyingInstrumentIdentifierSchemeAxis = qname(caNamespace, "ca:UnderlyingInstrumentIdentifierSchemeAxis") qnUnderlyingSecuritiesImpactedTypedAxis = qname(caNamespace, "ca:UnderlyingSecuritiesImpactedTypedAxis") #Members qnCancelMember = qname(caNamespace, "ca:CancelMember") qnCashDividendMember = qname(caNamespace, "ca:CashDividendMember") qnEquityMember = qname(caNamespace, "ca:EquityMember") qnMandatoryMember = qname(caNamespace, "ca:MandatoryMember") qnPreliminaryMember = qname(caNamespace, "ca:PreliminaryMember") qnStockDividendMember = qname(caNamespace, "ca:StockDividendMember") qnUnconfirmedMember = qname(caNamespace, "ca:UnconfirmedMember") qnUnitedStatesMember = qname(caNamespace, "ca:UnitedStatesMember") startedAt = time.time() caFacts = defaultdict(list) hasUsEquityCashDiv = False hasUsEquityStockDiv = False hasCancel = False for f in modelXbrl.facts: if f.qname.namespaceURI == caNamespace: context = f.context if context is not None and getattr(f, "xValid", 0) == 4: caFacts[f.qname.localName].append(f) qnEventTypeMember = context.dimMemberQname(qnEventTypeAxis) qnIssueTypeMember = context.dimMemberQname(qnIssueTypeAxis) qnMandatoryVoluntaryMember = context.dimMemberQname(qnMandatoryVoluntaryAxis) qnMarketTypeMember = context.dimMemberQname(qnMarketTypeAxis) if (not hasUsEquityCashDiv and qnEventTypeMember == qnCashDividendMember and qnIssueTypeMember == qnEquityMember and qnMandatoryVoluntaryMember == qnMandatoryMember and qnMarketTypeMember == qnUnitedStatesMember): hasUsEquityCashDiv = True if (not hasUsEquityStockDiv and qnEventTypeMember == qnStockDividendMember and qnIssueTypeMember == qnEquityMember and qnMandatoryVoluntaryMember == qnMandatoryMember and qnMarketTypeMember == qnUnitedStatesMember): hasUsEquityStockDiv = True if (not hasCancel and qnEventTypeMember == qnCancelMember and qnIssueTypeMember == qnCancelMember and qnMandatoryVoluntaryMember == qnCancelMember and qnMarketTypeMember == qnCancelMember): hasCancel = True hasEventComplete = False eventCompleteContextHash = None for f in caFacts["EventCompleteness"]: if f.xValue == "Complete": eventCompleteContextHash = f.context.contextDimAwareHash hasEventComplete = True break if hasEventComplete: facts = [f for f in modelXbrl.facts if f.context is not None and f.context.dimMemberQname(qnStatusAxis) == qnPreliminaryMember] if facts: modelXbrl.error("US-CA.PreliminaryAndComplete.100", _("Facts have a preliminary status, but the event is indicated to be complete: %(facts)s"), modelObject=facts, facts=", ".join(f.localName for f in facts)) facts = [f for f in modelXbrl.facts if f.context is not None and f.context.dimMemberQname(qnStatusAxis) == qnUnconfirmedMember] if facts: modelXbrl.error("US-CA.UnconfirmedAndComplete.101", _("Facts have an unconfirmed status, but the event is indicated to be complete: %(facts)s"), modelObject=facts, facts=", ".join(f.localName for f in facts)) for i, localName in ((1, "AnnouncementDate"), (2, "EventCompleteness"), (3, "UniqueUniversalEventIdentifier"), (4, "AnnouncementIdentifier"), (5, "AnnouncementType"), (6, "EventType"), # 7, 8 below under hasUsEquityCashDiv (9, "MandatoryVoluntaryChoiceIndicator")): if localName not in caFacts: modelXbrl.error("US-CA.Exists.{0}".format(i), _("A %(fact)s must exist in the document."), modelObject=modelXbrl, fact=localName) if hasEventComplete: if not caFacts["EventConfirmationStatus"]: modelXbrl.error("US-CA.Exists.10", _("An EventConfirmationStatus must exist in the document if the document is Complete."), modelObject=modelXbrl, fact="EventConfirmationStatus") if hasUsEquityCashDiv: for i, localName in ((12, "CountryOfIssuer"), (14, "PaymentDate")): if not any(f.context.contextDimAwareHash == eventCompleteContextHash for f in caFacts[localName]): modelXbrl.error("US-CA.Exists.{0}".format(i), _("A %(fact)s must exist in the document if the document is Complete."), modelObject=modelXbrl, fact=localName) if not any(f.context.hasDimension(qnEventOptionsSequenceTypedAxis) for f in caFacts["OptionType"]): modelXbrl.error("US-CA.Exists.15", _("A OptionType must exist in the document for the security impacted by the corporate action."), modelObject=modelXbrl, fact="InstrumentIdentifier") dupFacts = defaultdict(list) for localName, facts in caFacts.items(): for f in facts: dupFacts[f.context.contextDimAwareHash].append(f) for dups in dupFacts.values(): if len(dups) > 1: modelXbrl.error("US-CA.DuplicateValue.11", _("Fact %(fact)s exists %(count)s times in the document."), modelObject=dups, fact=localName, count=len(dups)) dupFacts.clear() del dupFacts if hasUsEquityCashDiv: if not any(f.context.hasDimension(qnUnderlyingSecuritiesImpactedTypedAxis) and f.context.hasDimension(qnUnderlyingInstrumentIdentifierSchemeAxis) for f in caFacts["InstrumentIdentifier"]): modelXbrl.error("US-CA.Exists.7", _("A InstrumentIdentifier must exist in the document for the security impacted by the corporate action."), modelObject=modelXbrl, fact="InstrumentIdentifier") if "RecordDate" not in caFacts: modelXbrl.error("US-CA.Exists.8", _("A RecordDate must exist in the document."), modelObject=modelXbrl) countOptions = len(caFacts["OptionType"]) if not countOptions: modelXbrl.error("US-CA.atLeastOneOptionIsRequired.16", _("At least one %(fact)s must be defined for a mandatory cash dividend."), modelObject=modelXbrl, fact="OptionType") countWithholdingRates = len(caFacts["WithholdingTaxPercentage"]) if (countOptions != len(caFacts["TaxRateDescription"]) and countOptions > 1 and countWithholdingRates != countOptions): modelXbrl.error("US-CA.noMoreThanOnOption.16a", _("More than one option has been defined for a cash dividend only one Option can be defined for a mandatory cash dividend unless there is multiple tax rates defined. In the file there are %(countOfWithholdingRates)s unique withholding rates defined but %(countOfOptions)s options defined."), modelObject=modelXbrl, fact="OptionType", countOfWithholdingRates=countWithholdingRates, countOfOptions=countOptions) for f in caFacts["OptionType"]: if f.xValue != "Cash": modelXbrl.error("US-CA.onlyOneOptionAllowed.26", _("The Option Type for a mandatory cash dividend, %(value)s must be defined as \"Cash\"."), modelObject=f, fact="OptionType", value=f.value) for f in caFacts["PayoutType"]: if f.xValue != "Dividend": modelXbrl.error("US-CA.paymentOptions.17", _("The Payout Type for a cash dividend, %(value)s must be defined as \"Dividend\"."), modelObject=f, fact="PayoutType", value=f.value) for f1 in caFacts["PayoutAmount"]: for f2 in caFacts["PayoutAmountNetOfTax"]: if f1.xValue < f2.xValue: modelXbrl.error("US-CA.gte.18", _("The PayoutType %(value1)s must be greater than PayoutAmountNetOfTax %(value2)s."), modelObject=(f1,f2), fact="PayoutAmount", value1=f1.value, value2=f2.value) for i, localName in ((19, "PayoutAmount"), (21, "PayoutAmountNetOfTax")): for f in caFacts[localName]: if f.xValue < 0: modelXbrl.error("US-CA.nonNeg.{0}".format(i), _("The %(fact)s, %(value)s must be positive."), modelObject=f, fact=localName, value=f.value) for i, localName1, localName2 in ((22, "PaymentDate", "RecordDate"), (23, "OrdPaymentDate", "OrdRecordDate"), (103, "PaymentDate", "OrdPaymentDate"), (104, "AnnouncementDate", "OrdinaryAnnouncementDate"), (105, "BooksClosedEndDate", "BooksClosedStartDate")): for f1 in caFacts[localName1]: for f2 in caFacts[localName2]: if (f1.context.contextDimAwareHash == f2.context.contextDimAwareHash and f1.xValue < f2.xValue): modelXbrl.error("US-CA.date.{0}".format(i), _("The %(fact1)s %(value1)s must be later than the %(fact2)s %(value2)s."), modelObject=(f1,f2), fact1=localName1, fact2=localName2, value1=f1.value, value2=f2.value) if hasUsEquityCashDiv: for f in caFacts["EventType"]: eventTypeMember = f.context.dimMemberQname(qnEventTypeAxis) if eventTypeMember: if f.xValue not in eventTypeMap[eventTypeMember.localName]: modelXbrl.error("US-CA.eventTypeMatch.20", _("The %(fact)s, %(value)s must be defined as \"Cash Dividend\" or \"Sale Of Rights\"."), modelObject=f, fact="EventType", value=f.value) paymentDateFacts = caFacts["PaymentDate"] for fEvent in paymentDateFacts: if (qnEventOptionsSequenceTypedAxis not in fEvent.context.qnameDims and qnPayoutSequenceTypedAxis not in fEvent.context.qnameDims): for fDetail in paymentDateFacts: if (f.context.hasDimension(qnEventOptionsSequenceTypedAxis) and f.context.hasDimension(qnPayoutSequenceTypedAxis) and fEvent.xValue != fDetail.xValue): modelXbrl.error("US-CA.us-equity-cashDiv-mand.dupValues.24", _("The PaymentDate %(detailValue)s at the detail level must equal the PaymentDate %(eventValue)s at the event level."), modelObject=(fDetail,fEvent), fact="PaymentDate", detailValue=fDetail.value, eventValue=fEvent.value) for i, f1 in enumerate(paymentDateFacts): if (not f.context.hasDimension(qnEventOptionsSequenceTypedAxis) and not f.context.hasDimension(qnPayoutSequenceTypedAxis)): for f2 in paymentDateFacts[i+1:]: if (f.context.hasDimension(qnEventOptionsSequenceTypedAxis) and f.context.hasDimension(qnPayoutSequenceTypedAxis) and f1.xValue != f2.xValue): modelXbrl.error("US-CA.us-equity-cashDiv-mand.multPayouts.25", _("The PaymentDate %(detailValue)s at the detail level must equal the PaymentDate %(eventValue)s at the detail level."), modelObject=(f1, f2), fact="PaymentDate", detailValue=f1.value, eventValue=f2.value) if (hasEventComplete and len(caFacts["OptionType"]) > len(caFacts["PayoutType"])): modelXbrl.error("US-CA.us-equity-cashDiv-mand.missingPayouts.25a", _("The number of payouts associated with a cash dividend must match the number of options on a complete corporate action event. Each option must have at least one payout associated with it."), modelObject=(caFacts["OptionType"] + caFacts["PayoutType"])) if len(caFacts["OptionType"]) > 1: fmax = None maxValue = max((f.xValue for f in caFacts["WithholdingTaxPercentage"])) f1 = None for f in caFacts["WithholdingTaxPercentage"]: if fmax is None or f.xValue > fmax.xValue: fmax = f if (f.context.hasDimension(qnEventOptionsSequenceTypedAxis) and f.context.dimValue(qnEventOptionsSequenceTypedAxis).typedMember.xValue == 1): f1 = f if f1 is not None and fmax.xValue != f1.xValue: modelXbrl.error("US-CA.noMoreThanOnOption.16b", _("In those cases where multiple tax rates are defined the highest rate typically represents the payout rate associated with the " "corporate action to the clearing and settlement organization. The first option should represent the distribution made for settlement. " "In this case the withholding tax rate for option 1 is %(seq1Value)s. This is not the maximium withholding rate assoicated with the " "action which is %(maxValue)s. Make the payout with the highest withholding rate the first option."), modelObject=(fmax,f1),maxValue=fmax.value, seq1Value=f1.value) for fPayoutAmt in caFacts["PayoutAmount"]: for fPayoutAmtNetOfTax in caFacts["PayoutAmountNetOfTax"]: if fPayoutAmt.context.contextDimAwareHash == fPayoutAmtNetOfTax.context.contextDimAwareHash: for fTax in caFacts["TaxAmountWithheldFromPayout"]: if (fPayoutAmt.context.contextDimAwareHash == fTax.context.contextDimAwareHash and fPayoutAmt.xValue < fPayoutAmtNetOfTax.xValue + fTax.xValue): modelXbrl.error("US-CA.ne.26c", _("The PayoutAmount of %(payoutAmt)s must always be greater than or equal to the sum of PayoutAmountNetOfTax with a value of " "%(payoutNetOfTax)s and TaxAmountWithheldFromPayout with a value of %(taxAmt)s."), modelObject=(fPayoutAmt, fPayoutAmtNetOfTax, fTax), payoutAmt=fPayoutAmt.xValue, payoutNetOfTax=fPayoutAmtNetOfTax.xValue, taxAmt=fTax.xValue) # stock dividend if hasUsEquityStockDiv: if len(caFacts["OptionType"]) != 1: modelXbrl.error("US-CA.stockDiv.onlyOneOptionAllowed.41", _("Only one Option Type can be defined for a mandatory stock dividend."), modelObject=caFacts["OptionType"],) if (len(caFacts["OptionType"]) != len(caFacts["TaxRateDescription"]) and len(caFacts["OptionType"]) > 1 and len(set(f.xValue for f in caFacts["WithholdingTaxPercentage"])) != len(caFacts["OptionType"])): modelXbrl.error("US-CA.noMoreThanOnOption.41a", _("More than one option has been defined for a stock dividend. Only one Option can be defined for a mandatory stock dividend unless there is multiple tax rates defined.\n(id:41a)\n$"), modelObject=caFacts["OptionType"]) if hasEventComplete and not caFacts["CountryOfIssuer"]: modelXbrl.error("US-CA.completedExists.50", _("The Country Of Issuer must be populated in the document for a stock Dividend if the document is complete."), modelObject=val.modeXbrl, fact="CountryOfIssuer") if (hasEventComplete and not any(f.context.hasDimension(qnEventOptionsSequenceTypedAxis) for f in caFacts["OptionType"])): modelXbrl.error("US-CA.completedExists.48", _("The Option Type must be populated in the document if the document is complete."), modelObject=val.modeXbrl, fact="OptionType") if not any(f.context.hasDimension(qnUnderlyingSecuritiesImpactedTypedAxis) and f.context.hasDimension(qnUnderlyingInstrumentIdentifierSchemeAxis) for f in caFacts["InstrumentIdentifier"]): modelXbrl.error("US-CA.exists.40", _("An InstrumentIdentifier fact must exist in the document for the security impacted by the corporate action."), modelObject=val.modeXbrl, fact="InstrumentIdentifier") if not caFacts["RecordDate"]: modelXbrl.error("US-CA.exists.42", _("A RecordDate fact must exist in the document."), modelObject=val.modeXbrl, fact="RecordDate") if hasEventComplete and not caFacts["PaymentDate"]: modelXbrl.error("US-CA.completedExists.43", _("The PaymentDate must be populated in the document if the document is complete."), modelObject=val.modeXbrl, fact="PaymentDate") for f in caFacts["PayoutType"]: if f.xValue != "Dividend": modelXbrl.error("US-CA.stockDiv.paymentOptions.44", _("The Payout Type for a cash dividend must be defined as a \"Dividend\"."), modelObject=f, fact="PayoutType") for f in caFacts["OptionType"]: if f.xValue != "Securities": modelXbrl.error("US-CA.stockDiv.optionType.45", _("The Option Type for a cash dividend must be defined as a \"Securities\"."), modelObject=f, fact="OptionType") for f in caFacts["EventType"]: eventTypeMember = f.context.dimMemberQname(qnEventTypeAxis) if eventTypeMember: if f.xValue not in eventTypeMap[eventTypeMember.localName]: modelXbrl.error("US-CA.stockDiv-mand.eventTypeMatch.46", _("The %(fact)s, %(value)s must be defined as \"Stock Dividend\"."), modelObject=f, fact="EventType", value=f.value) paymentDateFacts = caFacts["PaymentDate"] for i, f1 in enumerate(paymentDateFacts): if (not f.context.hasDimension(qnEventOptionsSequenceTypedAxis) and not f.context.hasDimension(qnPayoutSequenceTypedAxis)): for f2 in paymentDateFacts[i+1:]: if (f.context.hasDimension(qnEventOptionsSequenceTypedAxis) and f.context.hasDimension(qnPayoutSequenceTypedAxis) and f1.xValue != f2.xValue): modelXbrl.error("US-CA.stockDiv-mand.dupValues.47", _("The PaymentDate %(detailValue)s at the detail level must equal the PaymentDate %(eventValue)s at the detail level."), modelObject=(f1, f2), fact="PaymentDate", detailValue=f1.value, eventValue=f2.value) if (hasEventComplete and not any(f.context.hasDimension(qnPayoutSequenceTypedAxis) and f.context.hasDimension(qnPayoutSecurityIdentifierSchemeAxis) for f in caFacts["InstrumentIdentifier"])): modelXbrl.error("US-CA.completedExists.49", _("An InstrumentIdentifier fact must exist in the document for the security paid out as part of the corporate action if the event is complete"), modelObject=modelXbrl, fact="InstrumentIdentifier") if (hasEventComplete and len(caFacts["OptionType"]) > len(caFacts["PayoutType"])): modelXbrl.error("US-CA.stockDiv-mand.missingPayouts.49a", _("The number of payouts associated with a stock dividend must match the number of options on a complete corporate action event. Each option must have at least one payout associated with it."), modelObject=(caFacts["OptionType"] + caFacts["PayoutType"])) if (hasEventComplete and not any(f.context.hasDimension(qnPayoutSequenceTypedAxis) for f in caFacts["DisbursedQuantity"])): modelXbrl.error("US-CA.stockDiv-mand.missingPayouts.49b", _("An DisbursedQuantity fact must exist in the document for the security paid out as part of the corporate action if the event is complete."), modelObject=modelXbrl, fact="DisbursedQuantity") if (hasEventComplete and not any(f.context.hasDimension(qnPayoutSequenceTypedAxis) for f in caFacts["BaseQuantity"])): modelXbrl.error("US-CA.stockDiv-mand.missingPayouts.49c", _("An BaseQuantity fact must exist in the document for the security paid out as part of the corporate action if the event is complete."), modelObject=modelXbrl, fact="BaseQuantity") if hasCancel: if not hasEventComplete: modelXbrl.error("US-CA.cancelComplete.30", _("The Details Completness Status (EventCompletenes) must have a value of Complete for a cancel event."), modelObject=modelXbrl, fact="EventCompleteness") if not caFacts["EventCompleteness"]: modelXbrl.error("US-CA.exists.31", _("The Details Completness Status must must be tagged in the cancel document with a value of Complete."), modelObject=modelXbrl, fact="EventCompleteness") if not (caFacts["EventConfirmationStatus"] and all(f.xValue == "Confirmed" for f in caFacts["EventConfirmationStatus"])): modelXbrl.error("US-CA.cancelComplete.32", _("The Event Confirmation Status must be tagged with a value of Confirmed for a cancel event."), modelObject=modelXbrl, fact="EventConfirmationStatus") facts = [f for f in modelXbrl.facts if f.context is not None and f.context.dimValue(qnStatusAxis) == qnUnconfirmedMember] if facts: modelXbrl.error("US-CA.cancel.invalid_member.33", _("Facts have been reported with the UnconfirmedMember on the StatusAxis for a cancel event: %(facts)s."), modelObject=facts, facts=", ".join(f.localName for f in facts)) facts = [f for f in modelXbrl.facts if f.context is not None and f.context.dimValue(qnStatusAxis) == qnPreliminaryMember and f.context.dimValue(qnEventTypeAxis) == qnCancelMember] if facts: modelXbrl.error("US-CA.cancel.invalid_member.34", _("Facts have been reported with the PreliminaryMember on the StatusAxis for a cancel event: %(facts)s. " "A cancel event must use the ConfirmedMember on the StatusAxis."), modelObject=facts, facts=", ".join(f.localName for f in facts)) facts = [f for f in modelXbrl.facts if f.context is not None and f.context.dimValue(qnStatusAxis) == qnUnconfirmedMember and f.context.dimValue(qnEventTypeAxis) == qnCancelMember] if facts: modelXbrl.error("US-CA.cancel.invalid_member.36", _("Facts have been reported with the UnconfirmedMember on the StatusAxis for a cancel event: %(facts)s. " "A cancel event must use the ConfirmedMember on the StatusAxis."), modelObject=facts, facts=", ".join(f.localName for f in facts)) for f in caFacts["EventType"]: eventTypeMember = f.context.dimMemberQname(qnEventTypeAxis) if eventTypeMember: if f.xValue not in eventTypeMap[eventTypeMember.localName]: modelXbrl.error("US-CA.cancel.eventTypeMatch.37", _("The %(fact)s, %(value)s must be defined as \"Stock Dividend\"."), modelObject=f, fact="EventType", value=f.value) if 'facts' in locals(): del facts del caFacts # dereference explicitly modelXbrl.profileStat(_("validate US Corporate Actions"), time.time() - startedAt) __pluginInfo__ = { # Do not use _( ) in pluginInfo itself (it is applied later, after loading 'name': 'Validate XBRL-US Corporate Actions', 'version': '0.9', 'description': '''XBRL-US Corporate Actions Validation.''', 'license': 'Apache-2', 'author': 'Ewe S. Gap', 'copyright': '(c) Copyright 2012 Mark V Systems Limited, All rights reserved.', # classes of mount points (required) 'Validate.XBRL.Finally': checkCorporateActions }
{ "pile_set_name": "Github" }
#ifndef __PLAYER_MENU_SERVICE_PROTOCOL_H #define __PLAYER_MENU_SERVICE_PROTOCOL_H #include <string> #include "cocos2d.h" #include "PlayerMacros.h" #include "PlayerServiceProtocol.h" PLAYER_NS_BEGIN #define kPlayerSuperModifyKey "super" #define kPlayerShiftModifyKey "shift" #define kPlayerCtrlModifyKey "ctrl" #define kPlayerAltModifyKey "alt" class PlayerMenuItem : public cocos2d::Ref { public: virtual ~PlayerMenuItem(); std::string getMenuId() const; std::string getTitle() const; int getOrder() const; bool isGroup() const; bool isEnabled() const; bool isChecked() const; std::string getShortcut() const; virtual void setTitle(const std::string &title) = 0; virtual void setEnabled(bool enabled) = 0; virtual void setChecked(bool checked) = 0; virtual void setShortcut(const std::string &shortcut) = 0; protected: PlayerMenuItem(); std::string _menuId; std::string _title; int _order; bool _isGroup; bool _isEnabled; bool _isChecked; // ignored when isGroup = true std::string _shortcut; // ignored when isGroup = true }; class PlayerMenuServiceProtocol : public PlayerServiceProtocol { public: static const int MAX_ORDER = 9999; virtual PlayerMenuItem *addItem(const std::string &menuId, const std::string &title, const std::string &parentId, int order = MAX_ORDER) = 0; virtual PlayerMenuItem *addItem(const std::string &menuId, const std::string &title) = 0; virtual PlayerMenuItem *getItem(const std::string &menuId) = 0; virtual bool removeItem(const std::string &menuId) = 0; virtual void setMenuBarEnabled(bool enabled) = 0; }; PLAYER_NS_END #endif // __PLAYER_MENU_SERVICE_PROTOCOL_H
{ "pile_set_name": "Github" }
// Copyright (c) 2012-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <clientversion.h> #include <tinyformat.h> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-qt, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("LBRY"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include <obj/build.h> #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID "$Format:%H$" #define GIT_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
{ "pile_set_name": "Github" }
80a66dfdc56067c1a93c541d3bc687c78dc1ba6e
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CSS Reftest Reference</title> <link rel="author" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/" /> <style type="text/css"><![CDATA[ div { border: black solid medium; height: 288px; width: 288px; } img { display: block; height: 100px; margin-bottom: 10px; width: 200px; } img + img {height: 96px;} ]]></style> </head> <body> <p>Test passes if the blue and orange rectangles have the same width and the blue rectangle is in the upper-left corner of an hollow black square.</p> <div><img src="support/blue15x15.png" alt="Image download support must be enabled" /><img src="support/swatch-orange.png" alt="Image download support must be enabled" /></div> </body> </html>
{ "pile_set_name": "Github" }
#!/usr/bin/env python # # Copyright (C) 2015 Igalia S.L. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public License # along with this library; see the file COPYING.LIB. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301, USA. import os, sys from webkitpy.common.host import Host PLATFORM_GENERATED_HEADERS = ("HTTPHeaderNames.h") def get_platform_headers(platform_dir): platform_headers = ["config.h"] for root, dirs, files in os.walk(platform_dir): for file_name in files: if file_name.endswith(".h"): platform_headers.append(file_name) return platform_headers def check_source_file(source_file, checkout_root, platform_headers): failures_found = 0 line_count = 0 f = open(source_file, 'r') for line in f.readlines(): line_count += 1 if line[0] != '#': continue tokens = line.split(' ') if tokens[0] not in ('#include', '#import'): continue header = tokens[1] if header[0] != '"': continue header = header[1:header.rfind('"')] if not header.endswith('.h'): continue if header not in platform_headers and header not in PLATFORM_GENERATED_HEADERS: print "ERROR: %s:%d %s" % (source_file[len(checkout_root) + 1:], line_count, line.strip('\n')) failures_found += 1 f.close() return failures_found host = Host() host.initialize_scm() checkout_root = host.scm().checkout_root platform_dir = os.path.join(checkout_root, "Source", "WebCore", "platform") platform_headers = get_platform_headers(platform_dir) layering_violations_count = 0 for root, dirs, files in os.walk(platform_dir): for file_name in files: if os.path.splitext(file_name)[1] in ('.cpp', '.mm'): layering_violations_count += check_source_file(os.path.join(root, file_name), checkout_root, platform_headers) if layering_violations_count: print "Total: %d layering violations found in %s" % (layering_violations_count, platform_dir[len(checkout_root) + 1:]) sys.exit(1) sys.exit(0)
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// /// A `StreamClosedEvent` is fired whenever a stream is closed. /// /// This event is fired whether the stream is closed normally, or via RST_STREAM, /// or via GOAWAY. Normal closure is indicated by having `reason` be `nil`. In the /// case of closure by GOAWAY the `reason` is always `.refusedStream`, indicating that /// the remote peer has not processed this stream. In the case of RST_STREAM, /// the `reason` contains the error code sent by the peer in the RST_STREAM frame. public struct StreamClosedEvent { /// The stream ID of the stream that is closed. public let streamID: HTTP2StreamID /// The reason for the stream closure. `nil` if the stream was closed without /// error. Otherwise, the error code indicating why the stream was closed. public let reason: HTTP2ErrorCode? public init(streamID: HTTP2StreamID, reason: HTTP2ErrorCode?) { self.streamID = streamID self.reason = reason } } extension StreamClosedEvent: Hashable { } /// A `NIOHTTP2WindowUpdatedEvent` is fired whenever a flow control window is changed. /// This includes changes on the connection flow control window, which is signalled by /// this event having `streamID` set to `.rootStream`. public struct NIOHTTP2WindowUpdatedEvent { /// The stream ID of the window that has been changed. May be .rootStream, in which /// case the connection window has changed. public let streamID: HTTP2StreamID /// The new inbound window size for this stream, if any. May be nil if this stream is half-closed. public var inboundWindowSize: Int? { get { return self._inboundWindowSize.map { Int($0) } } set { self._inboundWindowSize = newValue.map { Int32($0) } } } /// The new outbound window size for this stream, if any. May be nil if this stream is half-closed. public var outboundWindowSize: Int? { get { return self._outboundWindowSize.map { Int($0) } } set { self._outboundWindowSize = newValue.map { Int32($0) } } } private var _inboundWindowSize: Int32? private var _outboundWindowSize: Int32? public init(streamID: HTTP2StreamID, inboundWindowSize: Int?, outboundWindowSize: Int?) { // We use Int here instead of Int32. Nonetheless, the value must fit in the Int32 range. precondition(inboundWindowSize == nil || inboundWindowSize! <= Int(HTTP2FlowControlWindow.maxSize)) precondition(outboundWindowSize == nil || outboundWindowSize! <= Int(HTTP2FlowControlWindow.maxSize)) precondition(inboundWindowSize == nil || inboundWindowSize! >= Int(Int32.min)) precondition(outboundWindowSize == nil || outboundWindowSize! >= Int(Int32.min)) self.streamID = streamID self._inboundWindowSize = inboundWindowSize.map { Int32($0) } self._outboundWindowSize = outboundWindowSize.map { Int32($0) } } } extension NIOHTTP2WindowUpdatedEvent: Hashable { } /// A `NIOHTTP2StreamCreatedEvent` is fired whenever a HTTP/2 stream is created. public struct NIOHTTP2StreamCreatedEvent { public let streamID: HTTP2StreamID /// The initial local stream window size. May be nil if this stream may never have data sent on it. public let localInitialWindowSize: UInt32? /// The initial remote stream window size. May be nil if this stream may never have data received on it. public let remoteInitialWidowSize: UInt32? public init(streamID: HTTP2StreamID, localInitialWindowSize: UInt32?, remoteInitialWindowSize: UInt32?) { self.streamID = streamID self.localInitialWindowSize = localInitialWindowSize self.remoteInitialWidowSize = remoteInitialWindowSize } } extension NIOHTTP2StreamCreatedEvent: Hashable { } /// A `NIOHTTP2BulkStreamWindowChangeEvent` is fired whenever all of the remote flow control windows for a given stream have been changed. /// /// This occurs when an ACK to a SETTINGS frame is received that changes the value of SETTINGS_INITIAL_WINDOW_SIZE. This is only fired /// when the local peer has changed its settings. public struct NIOHTTP2BulkStreamWindowChangeEvent { /// The change in the remote stream window sizes. public let delta: Int public init(delta: Int) { self.delta = delta } } extension NIOHTTP2BulkStreamWindowChangeEvent: Hashable { }
{ "pile_set_name": "Github" }
/* * #%L * ACS AEM Commons Bundle * %% * Copyright (C) 2013 Adobe * %% * 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. * #L% */ package com.adobe.acs.commons.forms; import org.osgi.annotation.versioning.ProviderType; import org.apache.sling.api.resource.ValueMap; import java.util.Map; @ProviderType public interface Form { /** * Get the Form's name * <p> * This should uniquely identify a Form on a Page * * @return */ String getName(); /** * Sets the Form name * <p> * Typically this setter is not used and Form names are set in constructor. * <p> * This can be helpful for changing the flow or using Form X to populate Form Y * * @param name */ void setName(String name); /** * Get the Form's resource path * * @return */ String getResourcePath(); /** * Sets the Form's resource path * * @param resourcePath */ void setResourcePath(String resourcePath); /** * Gets a Map of the Form data * * @return */ Map<String, String> getData(); /** * Gets a Map of the error data * * @return */ Map<String, String> getErrors(); /** * Determines if a Form data key exists and has non-blank data * * @param key * @return */ boolean has(String key); /** * Gets the data associated with a Form data key * * @param key * @return */ String get(String key); /** * Sets Form data * * @param key * @param value */ void set(String key, String value); /** * Determines if any Form Data exists; atleast 1 key w non-blank data must exist in the data map. * * @return */ boolean hasData(); /** * Determines if an error exists * * @param key * @return */ boolean hasError(String key); /** * Gets the error message * * @param key * @return */ String getError(String key); /** * Sets an error * <p> * This is used if no corresponding error message/data is required to be associated; and the only information required is that an error occurred against key X. * * @param key */ void setError(String key); /** * Sets an error for key with corresponding error message/data * * @param key * @param value */ void setError(String key, String value); /** * Checks if has data * * @return */ boolean hasErrors(); /** * Get data as ValueMap * * @return */ ValueMap getValueMap(); /** * Get Errors as ValueMap * * @return */ ValueMap getErrorsValueMap(); }
{ "pile_set_name": "Github" }
/* $Date: 2005/03/07 23:59:05 $ $RCSfile: tp.h,v $ $Revision: 1.20 $ */ #ifndef CHELSIO_TP_H #define CHELSIO_TP_H #include "common.h" #define TP_MAX_RX_COALESCING_SIZE 16224U struct tp_mib_statistics { /* IP */ u32 ipInReceive_hi; u32 ipInReceive_lo; u32 ipInHdrErrors_hi; u32 ipInHdrErrors_lo; u32 ipInAddrErrors_hi; u32 ipInAddrErrors_lo; u32 ipInUnknownProtos_hi; u32 ipInUnknownProtos_lo; u32 ipInDiscards_hi; u32 ipInDiscards_lo; u32 ipInDelivers_hi; u32 ipInDelivers_lo; u32 ipOutRequests_hi; u32 ipOutRequests_lo; u32 ipOutDiscards_hi; u32 ipOutDiscards_lo; u32 ipOutNoRoutes_hi; u32 ipOutNoRoutes_lo; u32 ipReasmTimeout; u32 ipReasmReqds; u32 ipReasmOKs; u32 ipReasmFails; u32 reserved[8]; /* TCP */ u32 tcpActiveOpens; u32 tcpPassiveOpens; u32 tcpAttemptFails; u32 tcpEstabResets; u32 tcpOutRsts; u32 tcpCurrEstab; u32 tcpInSegs_hi; u32 tcpInSegs_lo; u32 tcpOutSegs_hi; u32 tcpOutSegs_lo; u32 tcpRetransSeg_hi; u32 tcpRetransSeg_lo; u32 tcpInErrs_hi; u32 tcpInErrs_lo; u32 tcpRtoMin; u32 tcpRtoMax; }; struct petp; struct tp_params; struct petp *t1_tp_create(adapter_t *adapter, struct tp_params *p); void t1_tp_destroy(struct petp *tp); void t1_tp_intr_disable(struct petp *tp); void t1_tp_intr_enable(struct petp *tp); void t1_tp_intr_clear(struct petp *tp); int t1_tp_intr_handler(struct petp *tp); void t1_tp_get_mib_statistics(adapter_t *adap, struct tp_mib_statistics *tps); void t1_tp_set_udp_checksum_offload(struct petp *tp, int enable); void t1_tp_set_tcp_checksum_offload(struct petp *tp, int enable); void t1_tp_set_ip_checksum_offload(struct petp *tp, int enable); int t1_tp_set_coalescing_size(struct petp *tp, unsigned int size); int t1_tp_reset(struct petp *tp, struct tp_params *p, unsigned int tp_clk); #endif
{ "pile_set_name": "Github" }
start_server {tags {"protocol"}} { test "Handle an empty query" { reconnect r write "\r\n" r flush assert_equal "PONG" [r ping] } test "Negative multibulk length" { reconnect r write "*-10\r\n" r flush assert_equal PONG [r ping] } test "Out of range multibulk length" { reconnect r write "*20000000\r\n" r flush assert_error "*invalid multibulk length*" {r read} } test "Wrong multibulk payload header" { reconnect r write "*3\r\n\$3\r\nSET\r\n\$1\r\nx\r\nfooz\r\n" r flush assert_error "*expected '$', got 'f'*" {r read} } test "Negative multibulk payload length" { reconnect r write "*3\r\n\$3\r\nSET\r\n\$1\r\nx\r\n\$-10\r\n" r flush assert_error "*invalid bulk length*" {r read} } test "Out of range multibulk payload length" { reconnect r write "*3\r\n\$3\r\nSET\r\n\$1\r\nx\r\n\$2000000000\r\n" r flush assert_error "*invalid bulk length*" {r read} } test "Non-number multibulk payload length" { reconnect r write "*3\r\n\$3\r\nSET\r\n\$1\r\nx\r\n\$blabla\r\n" r flush assert_error "*invalid bulk length*" {r read} } test "Multi bulk request not followed by bulk arguments" { reconnect r write "*1\r\nfoo\r\n" r flush assert_error "*expected '$', got 'f'*" {r read} } test "Generic wrong number of args" { reconnect assert_error "*wrong*arguments*ping*" {r ping x y z} } test "Unbalanced number of quotes" { reconnect r write "set \"\"\"test-key\"\"\" test-value\r\n" r write "ping\r\n" r flush assert_error "*unbalanced*" {r read} } set c 0 foreach seq [list "\x00" "*\x00" "$\x00"] { incr c test "Protocol desync regression test #$c" { set s [socket [srv 0 host] [srv 0 port]] puts -nonewline $s $seq set payload [string repeat A 1024]"\n" set test_start [clock seconds] set test_time_limit 30 while 1 { if {[catch { puts -nonewline $s payload flush $s incr payload_size [string length $payload] }]} { set retval [gets $s] close $s break } else { set elapsed [expr {[clock seconds]-$test_start}] if {$elapsed > $test_time_limit} { close $s error "assertion:Redis did not closed connection after protocol desync" } } } set retval } {*Protocol error*} } unset c } start_server {tags {"regression"}} { test "Regression for a crash with blocking ops and pipelining" { set rd [redis_deferring_client] set fd [r channel] set proto "*3\r\n\$5\r\nBLPOP\r\n\$6\r\nnolist\r\n\$1\r\n0\r\n" puts -nonewline $fd $proto$proto flush $fd set res {} $rd rpush nolist a $rd read $rd rpush nolist a $rd read } }
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012 Desire NUENTSA WAKAM <[email protected] // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_ITERSCALING_H #define EIGEN_ITERSCALING_H namespace Eigen { /** * \ingroup IterativeSolvers_Module * \brief iterative scaling algorithm to equilibrate rows and column norms in matrices * * This class can be used as a preprocessing tool to accelerate the convergence of iterative methods * * This feature is useful to limit the pivoting amount during LU/ILU factorization * The scaling strategy as presented here preserves the symmetry of the problem * NOTE It is assumed that the matrix does not have empty row or column, * * Example with key steps * \code * VectorXd x(n), b(n); * SparseMatrix<double> A; * // fill A and b; * IterScaling<SparseMatrix<double> > scal; * // Compute the left and right scaling vectors. The matrix is equilibrated at output * scal.computeRef(A); * // Scale the right hand side * b = scal.LeftScaling().cwiseProduct(b); * // Now, solve the equilibrated linear system with any available solver * * // Scale back the computed solution * x = scal.RightScaling().cwiseProduct(x); * \endcode * * \tparam _MatrixType the type of the matrix. It should be a real square sparsematrix * * References : D. Ruiz and B. Ucar, A Symmetry Preserving Algorithm for Matrix Scaling, INRIA Research report RR-7552 * * \sa \ref IncompleteLUT */ template<typename _MatrixType> class IterScaling { public: typedef _MatrixType MatrixType; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::Index Index; public: IterScaling() { init(); } IterScaling(const MatrixType& matrix) { init(); compute(matrix); } ~IterScaling() { } /** * Compute the left and right diagonal matrices to scale the input matrix @p mat * * FIXME This algorithm will be modified such that the diagonal elements are permuted on the diagonal. * * \sa LeftScaling() RightScaling() */ void compute (const MatrixType& mat) { using std::abs; int m = mat.rows(); int n = mat.cols(); eigen_assert((m>0 && m == n) && "Please give a non - empty matrix"); m_left.resize(m); m_right.resize(n); m_left.setOnes(); m_right.setOnes(); m_matrix = mat; VectorXd Dr, Dc, DrRes, DcRes; // Temporary Left and right scaling vectors Dr.resize(m); Dc.resize(n); DrRes.resize(m); DcRes.resize(n); double EpsRow = 1.0, EpsCol = 1.0; int its = 0; do { // Iterate until the infinite norm of each row and column is approximately 1 // Get the maximum value in each row and column Dr.setZero(); Dc.setZero(); for (int k=0; k<m_matrix.outerSize(); ++k) { for (typename MatrixType::InnerIterator it(m_matrix, k); it; ++it) { if ( Dr(it.row()) < abs(it.value()) ) Dr(it.row()) = abs(it.value()); if ( Dc(it.col()) < abs(it.value()) ) Dc(it.col()) = abs(it.value()); } } for (int i = 0; i < m; ++i) { Dr(i) = std::sqrt(Dr(i)); Dc(i) = std::sqrt(Dc(i)); } // Save the scaling factors for (int i = 0; i < m; ++i) { m_left(i) /= Dr(i); m_right(i) /= Dc(i); } // Scale the rows and the columns of the matrix DrRes.setZero(); DcRes.setZero(); for (int k=0; k<m_matrix.outerSize(); ++k) { for (typename MatrixType::InnerIterator it(m_matrix, k); it; ++it) { it.valueRef() = it.value()/( Dr(it.row()) * Dc(it.col()) ); // Accumulate the norms of the row and column vectors if ( DrRes(it.row()) < abs(it.value()) ) DrRes(it.row()) = abs(it.value()); if ( DcRes(it.col()) < abs(it.value()) ) DcRes(it.col()) = abs(it.value()); } } DrRes.array() = (1-DrRes.array()).abs(); EpsRow = DrRes.maxCoeff(); DcRes.array() = (1-DcRes.array()).abs(); EpsCol = DcRes.maxCoeff(); its++; }while ( (EpsRow >m_tol || EpsCol > m_tol) && (its < m_maxits) ); m_isInitialized = true; } /** Compute the left and right vectors to scale the vectors * the input matrix is scaled with the computed vectors at output * * \sa compute() */ void computeRef (MatrixType& mat) { compute (mat); mat = m_matrix; } /** Get the vector to scale the rows of the matrix */ VectorXd& LeftScaling() { return m_left; } /** Get the vector to scale the columns of the matrix */ VectorXd& RightScaling() { return m_right; } /** Set the tolerance for the convergence of the iterative scaling algorithm */ void setTolerance(double tol) { m_tol = tol; } protected: void init() { m_tol = 1e-10; m_maxits = 5; m_isInitialized = false; } MatrixType m_matrix; mutable ComputationInfo m_info; bool m_isInitialized; VectorXd m_left; // Left scaling vector VectorXd m_right; // m_right scaling vector double m_tol; int m_maxits; // Maximum number of iterations allowed }; } #endif
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package cleo.search; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * MultiIndexer * * @author jwu * @since 03/15, 2011 * * @param <E> Element to Index */ public class MultiIndexer<E extends Element> implements Indexer<E> { private String name = MultiIndexer.class.getSimpleName(); private final List<Indexer<E>> indexerList = new ArrayList<Indexer<E>>(); public MultiIndexer(List<Indexer<E>> indexers) { if(indexers != null) { for(Indexer<E> indexer : indexers) { if(indexer != null) { indexerList.add(indexer); } } } } public MultiIndexer(String name, List<Indexer<E>> indexers) { this(indexers); this.setName(name); } public final String getName() { return name; } public final void setName(String name) { this.name = name; } public final List<Indexer<E>> subIndexers() { return indexerList; } @Override public void flush() throws IOException { for(Indexer<E> indexer : indexerList) { indexer.flush(); } } @Override public boolean index(E element) throws Exception { for(Indexer<E> indexer : indexerList) { if(indexer.index(element)) { return true; } } return false; } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_131) on Fri Jun 23 09:10:16 EDT 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ca.uhn.hl7v2.hoh.util (HAPI - Java HL7 API - HL7 over HTTP 2.3 API)</title> <meta name="date" content="2017-06-23"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../ca/uhn/hl7v2/hoh/util/package-summary.html" target="classFrame">ca.uhn.hl7v2.hoh.util</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="ByteUtils.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">ByteUtils</a></li> <li><a href="GZipUtils.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">GZipUtils</a></li> <li><a href="HapiSocketTlsFactoryWrapper.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">HapiSocketTlsFactoryWrapper</a></li> <li><a href="HTTPUtils.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">HTTPUtils</a></li> <li><a href="IOUtils.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">IOUtils</a></li> <li><a href="KeystoreUtils.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">KeystoreUtils</a></li> <li><a href="StringUtils.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">StringUtils</a></li> <li><a href="Validate.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">Validate</a></li> <li><a href="VersionLogger.html" title="class in ca.uhn.hl7v2.hoh.util" target="classFrame">VersionLogger</a></li> </ul> <h2 title="Enums">Enums</h2> <ul title="Enums"> <li><a href="ServerRoleEnum.html" title="enum in ca.uhn.hl7v2.hoh.util" target="classFrame">ServerRoleEnum</a></li> </ul> </div> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-1395874-4"); pageTracker._trackPageview(); } catch(err) {}</script> </body > </html>
{ "pile_set_name": "Github" }
/** * @file * IGMP API */ /* * Copyright (c) 2002 CITEL Technologies Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of CITEL Technologies Ltd nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY CITEL TECHNOLOGIES AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL CITEL TECHNOLOGIES OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is a contribution to the lwIP TCP/IP stack. * The Swedish Institute of Computer Science and Adam Dunkels * are specifically granted permission to redistribute this * source code. */ #ifndef LWIP_HDR_IGMP_H #define LWIP_HDR_IGMP_H #include "lwip/opt.h" #include "lwip/ip_addr.h" #include "lwip/netif.h" #include "lwip/pbuf.h" #if LWIP_IPV4 && LWIP_IGMP /* don't build if not configured for use in lwipopts.h */ #ifdef __cplusplus extern "C" { #endif /* IGMP timer */ #define IGMP_TMR_INTERVAL 100 /* Milliseconds */ #define IGMP_V1_DELAYING_MEMBER_TMR (1000/IGMP_TMR_INTERVAL) #define IGMP_JOIN_DELAYING_MEMBER_TMR (500 /IGMP_TMR_INTERVAL) /* Compatibility defines (don't use for new code) */ #define IGMP_DEL_MAC_FILTER NETIF_DEL_MAC_FILTER #define IGMP_ADD_MAC_FILTER NETIF_ADD_MAC_FILTER /** * igmp group structure - there is * a list of groups for each interface * these should really be linked from the interface, but * if we keep them separate we will not affect the lwip original code * too much * * There will be a group for the all systems group address but this * will not run the state machine as it is used to kick off reports * from all the other groups */ struct igmp_group { /** next link */ struct igmp_group *next; /** multicast address */ ip4_addr_t group_address; /** signifies we were the last person to report */ u8_t last_reporter_flag; /** current state of the group */ u8_t group_state; /** timer for reporting, negative is OFF */ u16_t timer; /** counter of simultaneous uses */ u8_t use; }; /* Prototypes */ void igmp_init(void); err_t igmp_start(struct netif *netif); err_t igmp_stop(struct netif *netif); void igmp_report_groups(struct netif *netif); struct igmp_group *igmp_lookfor_group(struct netif *ifp, const ip4_addr_t *addr); void igmp_input(struct pbuf *p, struct netif *inp, const ip4_addr_t *dest); err_t igmp_joingroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr); err_t igmp_joingroup_netif(struct netif *netif, const ip4_addr_t *groupaddr); err_t igmp_leavegroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr); err_t igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr); void igmp_tmr(void); /** @ingroup igmp * Get list head of IGMP groups for netif. * Note: The allsystems group IP is contained in the list as first entry. * @see @ref netif_set_igmp_mac_filter() */ #define netif_igmp_data(netif) ((struct igmp_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP)) #ifdef __cplusplus } #endif #endif /* LWIP_IPV4 && LWIP_IGMP */ #endif /* LWIP_HDR_IGMP_H */
{ "pile_set_name": "Github" }
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #ifndef __HASHTABLE_H__ #define __HASHTABLE_H__ /* =============================================================================== General hash table. Slower than idHashIndex but it can also be used for linked lists and other data structures than just indexes or arrays. =============================================================================== */ template< class Type > class idHashTable { public: idHashTable(int newtablesize = 256); idHashTable(const idHashTable<Type> &map); ~idHashTable(void); // returns total size of allocated memory size_t Allocated(void) const; // returns total size of allocated memory including size of hash table type size_t Size(void) const; void Set(const char *key, Type &value); bool Get(const char *key, Type **value = NULL) const; bool Remove(const char *key); void Clear(void); void DeleteContents(void); // the entire contents can be itterated over, but note that the // exact index for a given element may change when new elements are added int Num(void) const; Type *GetIndex(int index) const; int GetSpread(void) const; private: struct hashnode_s { idStr key; Type value; hashnode_s *next; hashnode_s(const idStr &k, Type v, hashnode_s *n) : key(k), value(v), next(n) {}; hashnode_s(const char *k, Type v, hashnode_s *n) : key(k), value(v), next(n) {}; }; hashnode_s **heads; int tablesize; int numentries; int tablesizemask; int GetHash(const char *key) const; }; /* ================ idHashTable<Type>::idHashTable ================ */ template< class Type > ID_INLINE idHashTable<Type>::idHashTable(int newtablesize) { assert(idMath::IsPowerOfTwo(newtablesize)); tablesize = newtablesize; assert(tablesize > 0); heads = new hashnode_s *[ tablesize ]; memset(heads, 0, sizeof(*heads) * tablesize); numentries = 0; tablesizemask = tablesize - 1; } /* ================ idHashTable<Type>::idHashTable ================ */ template< class Type > ID_INLINE idHashTable<Type>::idHashTable(const idHashTable<Type> &map) { int i; hashnode_s *node; hashnode_s **prev; assert(map.tablesize > 0); tablesize = map.tablesize; heads = new hashnode_s *[ tablesize ]; numentries = map.numentries; tablesizemask = map.tablesizemask; for (i = 0; i < tablesize; i++) { if (!map.heads[ i ]) { heads[ i ] = NULL; continue; } prev = &heads[ i ]; for (node = map.heads[ i ]; node != NULL; node = node->next) { *prev = new hashnode_s(node->key, node->value, NULL); prev = &(*prev)->next; } } } /* ================ idHashTable<Type>::~idHashTable<Type> ================ */ template< class Type > ID_INLINE idHashTable<Type>::~idHashTable(void) { Clear(); delete[] heads; } /* ================ idHashTable<Type>::Allocated ================ */ template< class Type > ID_INLINE size_t idHashTable<Type>::Allocated(void) const { return sizeof(heads) * tablesize + sizeof(*heads) * numentries; } /* ================ idHashTable<Type>::Size ================ */ template< class Type > ID_INLINE size_t idHashTable<Type>::Size(void) const { return sizeof(idHashTable<Type>) + sizeof(heads) * tablesize + sizeof(*heads) * numentries; } /* ================ idHashTable<Type>::GetHash ================ */ template< class Type > ID_INLINE int idHashTable<Type>::GetHash(const char *key) const { return (idStr::Hash(key) & tablesizemask); } /* ================ idHashTable<Type>::Set ================ */ template< class Type > ID_INLINE void idHashTable<Type>::Set(const char *key, Type &value) { hashnode_s *node, **nextPtr; int hash, s; hash = GetHash(key); for (nextPtr = &(heads[hash]), node = *nextPtr; node != NULL; nextPtr = &(node->next), node = *nextPtr) { s = node->key.Cmp(key); if (s == 0) { node->value = value; return; } if (s > 0) { break; } } numentries++; *nextPtr = new hashnode_s(key, value, heads[ hash ]); (*nextPtr)->next = node; } /* ================ idHashTable<Type>::Get ================ */ template< class Type > ID_INLINE bool idHashTable<Type>::Get(const char *key, Type **value) const { hashnode_s *node; int hash, s; hash = GetHash(key); for (node = heads[ hash ]; node != NULL; node = node->next) { s = node->key.Cmp(key); if (s == 0) { if (value) { *value = &node->value; } return true; } if (s > 0) { break; } } if (value) { *value = NULL; } return false; } /* ================ idHashTable<Type>::GetIndex the entire contents can be itterated over, but note that the exact index for a given element may change when new elements are added ================ */ template< class Type > ID_INLINE Type *idHashTable<Type>::GetIndex(int index) const { hashnode_s *node; int count; int i; if ((index < 0) || (index > numentries)) { assert(0); return NULL; } count = 0; for (i = 0; i < tablesize; i++) { for (node = heads[ i ]; node != NULL; node = node->next) { if (count == index) { return &node->value; } count++; } } return NULL; } /* ================ idHashTable<Type>::Remove ================ */ template< class Type > ID_INLINE bool idHashTable<Type>::Remove(const char *key) { hashnode_s **head; hashnode_s *node; hashnode_s *prev; int hash; hash = GetHash(key); head = &heads[ hash ]; if (*head) { for (prev = NULL, node = *head; node != NULL; prev = node, node = node->next) { if (node->key == key) { if (prev) { prev->next = node->next; } else { *head = node->next; } delete node; numentries--; return true; } } } return false; } /* ================ idHashTable<Type>::Clear ================ */ template< class Type > ID_INLINE void idHashTable<Type>::Clear(void) { int i; hashnode_s *node; hashnode_s *next; for (i = 0; i < tablesize; i++) { next = heads[ i ]; while (next != NULL) { node = next; next = next->next; delete node; } heads[ i ] = NULL; } numentries = 0; } /* ================ idHashTable<Type>::DeleteContents ================ */ template< class Type > ID_INLINE void idHashTable<Type>::DeleteContents(void) { int i; hashnode_s *node; hashnode_s *next; for (i = 0; i < tablesize; i++) { next = heads[ i ]; while (next != NULL) { node = next; next = next->next; delete node->value; delete node; } heads[ i ] = NULL; } numentries = 0; } /* ================ idHashTable<Type>::Num ================ */ template< class Type > ID_INLINE int idHashTable<Type>::Num(void) const { return numentries; } #if defined(ID_TYPEINFO) #define __GNUC__ 99 #endif #if !defined(__GNUC__) || __GNUC__ < 4 /* ================ idHashTable<Type>::GetSpread ================ */ template< class Type > int idHashTable<Type>::GetSpread(void) const { int i, average, error, e; hashnode_s *node; // if no items in hash if (!numentries) { return 100; } average = numentries / tablesize; error = 0; for (i = 0; i < tablesize; i++) { numItems = 0; for (node = heads[ i ]; node != NULL; node = node->next) { numItems++; } e = abs(numItems - average); if (e > 1) { error += e - 1; } } return 100 - (error * 100 / numentries); } #endif #if defined(ID_TYPEINFO) #undef __GNUC__ #endif #endif /* !__HASHTABLE_H__ */
{ "pile_set_name": "Github" }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. #pragma once #include <string> #include <gssapi/gssapi.h> namespace kudu { class Status; namespace gssapi { // Convert the given major/minor GSSAPI error codes into a Status. Status MajorMinorToStatus(OM_uint32 major, OM_uint32 minor); // Run a step of SPNEGO authentication. // // 'in_token_b64' is the base64-encoded token provided by the client, which may be empty // if the client did not provide any such token (e.g. if the HTTP 'Authorization' header // was not present). // 'out_token_b64' is the base64-encoded output token to send back to the client // during this round of negotiation. // // If any error occurs (eg an invalid token is provided), a bad Status is returned. // // An OK status indicates that the negotiation is proceeding successfully, or has // completed, whereas a non-OK status indicates an error or an unsuccessful // authentication (in which case the out-parameters will not be modified). // // In the case of an OK status, '*complete' indicates whether any further rounds are // required. On completion of negotiation, 'authenticated_principal' will be set to the // full principal name of the remote user. // // NOTE: per the SPNEGO protocol, the final "complete" negotiation stage may // include a token. Status SpnegoStep(const std::string& in_token_b64, std::string* out_token_b64, bool* complete, std::string* authenticated_principal); } // namespace gssapi } // namespace kudu
{ "pile_set_name": "Github" }
{ "name": "graphql-authentication-with-prisma-example", "private": true, "version": "1.0.0", "license": "ISC", "dependencies": { "email-templates": "^4.0.1", "graphql-authentication": "^0.5.3", "graphql-authentication-prisma": "^0.1.3", "graphql-cli": "^2.16.4", "graphql-yoga": "^1.14.12", "prisma": "^1.11.1", "prisma-binding": "^2.1.0", "ts-node": "^7.0.0" }, "scripts": { "start": "ts-node server.ts", "prisma": "PRISMA_MANAGEMENT_API_SECRET=mymanagementsecret123 prisma" } }
{ "pile_set_name": "Github" }
--TEST-- Test for Xdebug's remote log (with xdebug.remote_addr_header) --SKIPIF-- <?php require __DIR__ . '/../utils.inc'; check_reqs('dbgp; !win'); ?> --INI-- xdebug.remote_enable=1 xdebug.remote_log=/tmp/remote-log3.txt xdebug.remote_autostart=1 xdebug.remote_connect_back=1 xdebug.remote_host=doesnotexist2 xdebug.remote_port=9003 xdebug.remote_addr_header=I_LIKE_COOKIES --FILE-- <?php echo strlen("foo"), "\n"; echo file_get_contents(sys_get_temp_dir() . "/remote-log3.txt"); unlink (sys_get_temp_dir() . "/remote-log3.txt"); ?> --EXPECTF-- 3 [%d] Log opened at %d-%d-%d %d:%d:%d [%d] I: Checking remote connect back address. [%d] I: Checking user configured header 'I_LIKE_COOKIES'. [%d] I: Checking header 'HTTP_X_FORWARDED_FOR'. [%d] I: Checking header 'REMOTE_ADDR'. [%d] W: Remote address not found, connecting to configured address/port: doesnotexist2:9003. :-| [%d] W: Creating socket for 'doesnotexist2:9003', getaddrinfo: %s. [%d] E: Could not connect to client. :-( [%d] Log closed at %d-%d-%d %d:%d:%d [%d] Log opened at %d-%d-%d %d:%d:%d [%d] I: Checking remote connect back address. [%d] I: Checking user configured header 'I_LIKE_COOKIES'. [%d] I: Checking header 'HTTP_X_FORWARDED_FOR'. [%d] I: Checking header 'REMOTE_ADDR'. [%d] W: Remote address not found, connecting to configured address/port: doesnotexist2:9003. :-| [%d] W: Creating socket for 'doesnotexist2:9003', getaddrinfo: %s. [%d] E: Could not connect to client. :-( [%d] Log closed at %d-%d-%d %d:%d:%d
{ "pile_set_name": "Github" }
{ "id": "", "padding": [ 0, 0, 0, 0 ], "border_box": { "position": [ 8, 8 ], "size": [ 1008, 0 ] }, "content": { "position": [ 8, 8 ], "size": [ 1008, 0 ] }, "tag": "body", "children": [ { "id": "div1", "padding": [ 0, 0, 0, 0 ], "border_box": { "position": [ 8, 8 ], "size": [ 294, 294 ] }, "content": { "position": [ 11, 11 ], "size": [ 288, 288 ] }, "tag": "div", "children": [ { "id": "div2", "padding": [ 0, 0, 0, 0 ], "border_box": { "position": [ 11, 11 ], "size": [ 288, 110 ] }, "content": { "position": [ 11, 11 ], "size": [ 288, 110 ] }, "tag": "div", "children": [ { "id": "", "padding": [ 0, 0, 0, 0 ], "border_box": { "position": [ 99, 11 ], "size": [ 300, 150 ] }, "content": { "position": [ 99, 11 ], "size": [ 300, 150 ] }, "tag": "svg:svg", "children": [ { "id": "", "padding": [ 0, 0, 0, 0 ], "border_box": { "position": [ 99, 11 ], "size": [ 200, 100 ] }, "content": { "position": [ 99, 11 ], "size": [ 200, 100 ] }, "tag": "svg:rect", "border": [ 0, 0, 0, 0 ], "padding_box": { "position": [ 99, 11 ], "size": [ 200, 100 ] } } ], "border": [ 0, 0, 0, 0 ], "padding_box": { "position": [ 99, 11 ], "size": [ 300, 150 ] } } ], "border": [ 0, 0, 0, 0 ], "padding_box": { "position": [ 11, 11 ], "size": [ 288, 110 ] } }, { "id": "div3", "padding": [ 0, 0, 0, 0 ], "border_box": { "position": [ 99, 121 ], "size": [ 200, 96 ] }, "content": { "position": [ 99, 121 ], "size": [ 200, 96 ] }, "tag": "div", "border": [ 0, 0, 0, 0 ], "padding_box": { "position": [ 99, 121 ], "size": [ 200, 96 ] } } ], "border": [ 3, 3, 3, 3 ], "padding_box": { "position": [ 11, 11 ], "size": [ 288, 288 ] } } ], "border": [ 0, 0, 0, 0 ], "padding_box": { "position": [ 8, 8 ], "size": [ 1008, 0 ] } }
{ "pile_set_name": "Github" }
<script> function check() { var x=document.getElementById('stat'); x.innerHTML="Waiting for the script to execute"; } </script> <div id="stat"></div> <img src="page.png" onerror="check();" />
{ "pile_set_name": "Github" }
include/group_replication.inc [rpl_server_count=3] Warnings: Note #### Sending passwords in plain text without SSL/TLS is extremely insecure. Note #### Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information. [connection server1] #### # 0) The test requires three servers. #### SET SESSION sql_log_bin = 0; call mtr.add_suppression("This member could not reach a majority of the members for more than 10 seconds. The member will now leave the group as instructed by the group_replication_unreachable_majority_timeout option."); call mtr.add_suppression("The server was automatically set into read only mode after an error was detected."); call mtr.add_suppression("\\[GCS\\] Timeout while waiting for the group communication engine to exit!"); call mtr.add_suppression("\\[GCS\\] The member has failed to gracefully leave the group."); call mtr.add_suppression("The plugin encountered a critical error and will abort: Could not rejoin the member to the group after"); call mtr.add_suppression("Started auto-rejoin procedure attempt*"); call mtr.add_suppression("Auto-rejoin procedure attempt*"); call mtr.add_suppression("\\[GCS\\] Error connecting to all peers. Member join failed. Local port:*"); call mtr.add_suppression("\\[GCS\\] The member was unable to join the group.*"); call mtr.add_suppression("Timeout while waiting for a view change event during the auto-rejoin procedure"); call mtr.add_suppression("Unable to confirm whether the server has left the group or not. Check performance_schema.replication_group_members to check group membership information."); SET SESSION sql_log_bin = 1; include/gr_autorejoin_monitoring.inc SET @debug_saved = @@GLOBAL.DEBUG; SET @@GLOBAL.DEBUG='+d,group_replication_rejoin_short_retry'; SET @@GLOBAL.DEBUG='+d,group_replication_stop_before_rejoin_loop'; SET @@GLOBAL.DEBUG='+d,group_replication_stop_before_rejoin'; include/start_and_bootstrap_group_replication.inc [connection server2] include/start_group_replication.inc [connection server3] include/start_group_replication.inc #### # 1) Provoke a majority loss. #### [connection server1] SET GLOBAL group_replication_autorejoin_tries = 3; SET @@GLOBAL.group_replication_exit_state_action = ABORT_SERVER; include/gr_provoke_majority_loss.inc #### # 2) Verify that the member in the partitioned group will try to rejoin # the group the number of it is configured in # group_replication_autorejoin_tries sysvar. #### SET DEBUG_SYNC = "now WAIT_FOR signal.autorejoin_entering_loop"; include/assert.inc [Auto-rejoin should be running] SET DEBUG_SYNC = "now SIGNAL signal.autorejoin_enter_loop"; SET DEBUG_SYNC = "now WAIT_FOR signal.autorejoin_waiting"; include/assert.inc [Auto-rejoin should be running] include/assert.inc [super_read_only should be enabled] include/assert.inc [We should have attempted 1 rejoins] SET DEBUG_SYNC = "now SIGNAL signal.autorejoin_continue"; SET DEBUG_SYNC = "now WAIT_FOR signal.autorejoin_waiting"; include/assert.inc [Auto-rejoin should be running] include/assert.inc [super_read_only should be enabled] include/assert.inc [We should have attempted 2 rejoins] SET DEBUG_SYNC = "now SIGNAL signal.autorejoin_continue"; SET DEBUG_SYNC = "now WAIT_FOR signal.autorejoin_waiting"; include/assert.inc [Auto-rejoin should be running] include/assert.inc [super_read_only should be enabled] include/assert.inc [We should have attempted 3 rejoins] SET DEBUG_SYNC = "now SIGNAL signal.autorejoin_continue"; include/rpl_reconnect.inc #### # 3) Verify that, with group_replication_exit_state_action set to # ABORT_SERVER, the member will be aborted. #### include/assert_grep.inc [GR reported expected abort] #### # 4) Cleanup. #### [connection server1] SET @@GLOBAL.DEBUG = @debug_saved; include/gr_end_autorejoin_monitoring.inc include/group_replication_end.inc
{ "pile_set_name": "Github" }
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #requiresgetheapusage // **************************************************************************** // *** KRMP - Keyhole Raster Mask Product (low level) // **************************************************************************** class KRMPConfig { std::string overridesrs = std::string(); bool useMercatorProjection = false; #pragma GenerateIsUpToDate };
{ "pile_set_name": "Github" }
@domain @index Feature: Adding a object index In order to make my catalog searchable I want to create a new index where a field comes from an fieldcollection Background: Given there is a pimcore field-collection "Collection" And the definition has a input field "name" And the definition has a input field "val" And there is a pimcore class "FieldcollectionTest" And the definition has a field-collection field "collection" for field-collection "Collection" And the definition has a checkbox field "enabled" And the definition has a localized input field "name" And the definitions parent class is set to "\CoreShop\Behat\Model\Index\TestIndex" Scenario: Create a new index and add fields Given the site has a index "collection_getter" for behat-class "FieldcollectionTest" with type "mysql" And the index has following fields: | key | name | type | getter | columnType | getterConfig | configuration | | name | col_name | fieldcollections | fieldcollection | STRING | {"collectionField": "collection"} | {"className": "Collection"} | | val | col_val | fieldcollections | fieldcollection | STRING | {"collectionField": "collection"} | {"className": "Collection"} | Then the index should have columns "col_name, col_val" Scenario: Create a new index, add fields and index some objects Given the site has a index "collection_getter" for behat-class "FieldcollectionTest" with type "mysql" And the index has following fields: | key | name | type | getter | columnType | getterConfig | configuration | | name | col_name | fieldcollections | fieldcollection | STRING | {"collectionField": "collection"} | {"className": "Collection"} | | val | col_val | fieldcollections | fieldcollection | STRING | {"collectionField": "collection"} | {"className": "Collection"} | And there is an instance of behat-class "FieldcollectionTest" with key "test1" And the object-instance has following values: | key | value | type | | enabled | true | checkbox | | name | test | localized | | collection | {"type": "Collection", "values": [{"name": "val1", "val": "val"}, {"name": "val2", "val": "val"}]} | collection | Then the index column "col_name" for object-instance should have value ",val1,val2," And the index column "col_val" for object-instance should have value ",val,val,"
{ "pile_set_name": "Github" }
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cocostudio/CCSpriteFrameCacheHelper.h" #include "platform/CCFileUtils.h" #include "2d/CCSpriteFrame.h" #include "2d/CCSpriteFrameCache.h" using namespace cocos2d; namespace cocostudio { SpriteFrameCacheHelper *SpriteFrameCacheHelper::_spriteFrameCacheHelper = nullptr; SpriteFrameCacheHelper *SpriteFrameCacheHelper::getInstance() { if(!_spriteFrameCacheHelper) { _spriteFrameCacheHelper = new (std::nothrow) SpriteFrameCacheHelper(); } return _spriteFrameCacheHelper; } void SpriteFrameCacheHelper::purge() { delete _spriteFrameCacheHelper; _spriteFrameCacheHelper = nullptr; } void SpriteFrameCacheHelper::retainSpriteFrames(const std::string &plistPath) { auto it = _usingSpriteFrames.find(plistPath); if(it != _usingSpriteFrames.end()) return; std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plistPath); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath); if (dict.find("frames") == dict.end()) { return; } auto spriteFramesCache = SpriteFrameCache::getInstance(); ValueMap& framesDict = dict["frames"].asValueMap(); std::vector<SpriteFrame*> vec; for (auto iter = framesDict.begin(); iter != framesDict.end(); ++iter) { auto& spriteFrameName = iter->first; SpriteFrame* spriteFrame = spriteFramesCache->getSpriteFrameByName(spriteFrameName); vec.push_back(spriteFrame); CC_SAFE_RETAIN(spriteFrame); } _usingSpriteFrames[plistPath] = vec; } void SpriteFrameCacheHelper::releaseSpriteFrames(const std::string &plistPath) { auto it = _usingSpriteFrames.find(plistPath); if(it == _usingSpriteFrames.end()) return; auto& vec = it->second; auto itFrame = vec.begin(); while (itFrame != vec.end()) { CC_SAFE_RELEASE(*itFrame); ++itFrame; } vec.clear(); _usingSpriteFrames.erase(it); } void SpriteFrameCacheHelper::removeSpriteFrameFromFile(const std::string &plistPath) { SpriteFrameCache::getInstance()->removeSpriteFramesFromFile(plistPath); releaseSpriteFrames(plistPath); } void SpriteFrameCacheHelper::addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath) { SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); retainSpriteFrames(plistPath); } SpriteFrameCacheHelper::SpriteFrameCacheHelper() { } SpriteFrameCacheHelper::~SpriteFrameCacheHelper() { auto i = _usingSpriteFrames.begin(); while (i != _usingSpriteFrames.end()) { auto j = i++; removeSpriteFrameFromFile(j->first); } } }
{ "pile_set_name": "Github" }
{ "name": "Vagrant", "description": "Software for building and installing virtual dev environments.", "url": "https://www.vagrantup.com/" }
{ "pile_set_name": "Github" }
digraph Any { mindist = 2.0 1 -> 2 [label="annotation"] 1 [shape=doublecircle, style=filled, color=blue] 2 [shape=doublecircle, style=filled, color=green] }
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x", "filename" : "bf_7.png" }, { "idiom" : "universal", "scale" : "2x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
%%%----------------------------------------------------------------------------- %%% @copyright (C) 2016-2020, 2600Hz %%% @doc %%% @author Pierre Fenoll %%% %%% This Source Code Form is subject to the terms of the Mozilla Public %%% License, v. 2.0. If a copy of the MPL was not distributed with this %%% file, You can obtain one at https://mozilla.org/MPL/2.0/. %%% %%% @end %%%----------------------------------------------------------------------------- -module(kt_numbers). %% behaviour: tasks_provider -export([init/0 ,help/1, help/2, help/3 ,output_header/1 ,cleanup/2 ]). %% Verifiers -export([e164/1 ,account_id/1 ,carrier_module/1 ,state/1 ,ported_in/1 ,'cnam.inbound'/1 ,'prepend.enabled'/1 ,force_outbound/1 ]). %% Appliers -export([list/2 ,list_all/2 ,find/3 ,dump/2 ,dump_aging/2, dump_available/2, dump_deleted/2, dump_discovery/2 ,dump_in_service/2, dump_port_in/2, dump_port_out/2, dump_released/2, dump_reserved/2 ,import/3 ,assign_to/3 ,update_merge/3, update_overwrite/3 ,release/3 ,reserve/3 ,delete/3 ]). -include_lib("kazoo_numbers/include/knm_phone_number.hrl"). -include("tasks.hrl"). -define(MOD_CAT, <<(?CONFIG_CAT)/binary, ".numbers">>). -define(IMPORT_DEFAULTS_TO_CARRIER %% Defaults to knm_carriers:default_carrier()'s default value ,kapps_config:get_binary(?MOD_CAT, <<"import_defaults_to_carrier">>, ?CARRIER_LOCAL) ). -define(DB_DUMP_BULK_SIZE ,kapps_config:get_integer(?MOD_CAT, <<"db_page_size">>, 1000) ). -define(ON_SETTING_PUBLIC_FIELDS ,"To add a public field 'MyPub' to a number, create a column named 'opaque.MyPub'.\n" "Note: to nest a public field 'my_nested_field' under 'my_field', name the column thusly: 'opaque.my_field.my_nested_field'.\n" "Note: some fields may be disabled by configuration in which case it is forbidden to set them.\n" ). -define(CATEGORY, "number_management"). -define(ACTIONS, [<<"list">> ,<<"list_all">> ,<<"find">> ,<<"dump">> ,<<"dump_aging">> ,<<"dump_available">> ,<<"dump_deleted">> ,<<"dump_discovery">> ,<<"dump_in_service">> ,<<"dump_port_in">> ,<<"dump_port_out">> ,<<"dump_released">> ,<<"dump_reserved">> ,<<"import">> ,<<"assign_to">> ,<<"update_merge">> ,<<"update_overwrite">> ,<<"release">> ,<<"reserve">> ,<<"delete">> ]). %%%============================================================================= %%% API %%%============================================================================= %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec init() -> 'ok'. init() -> _ = tasks_bindings:bind(<<"tasks.help">>, ?MODULE, 'help'), _ = tasks_bindings:bind(<<"tasks."?CATEGORY".output_header">>, ?MODULE, 'output_header'), _ = tasks_bindings:bind(<<"tasks."?CATEGORY".cleanup">>, ?MODULE, 'cleanup'), _ = tasks_bindings:bind(<<"tasks."?CATEGORY".e164">>, ?MODULE, 'e164'), _ = tasks_bindings:bind(<<"tasks."?CATEGORY".account_id">>, ?MODULE, 'account_id'), _ = tasks_bindings:bind(<<"tasks."?CATEGORY".carrier_module">>, ?MODULE, 'carrier_module'), _ = tasks_bindings:bind(<<"tasks."?CATEGORY".ported_in">>, ?MODULE, 'ported_in'), tasks_bindings:bind_actions(<<"tasks."?CATEGORY>>, ?MODULE, ?ACTIONS). -spec output_header(kz_term:ne_binary()) -> kz_tasks:output_header(). output_header(<<"list">>) -> list_output_header(); output_header(<<"list_all">>) -> list_output_header(); output_header(<<"dump">>) -> list_output_header(); output_header(<<"dump_", _/binary>>) -> list_output_header(); output_header(?NE_BINARY) -> result_output_header(). -spec cleanup(kz_term:ne_binary(), any()) -> any(). cleanup(<<"import">>, 'init') -> %% Hit iff no rows at all succeeded. 'ok'; cleanup(<<"import">>, AccountIds) -> F = fun (AccountId) -> lager:debug("reconciling account ~s", [AccountId]), kz_services:reconcile(AccountId) end, lists:foreach(F, sets:to_list(AccountIds)), kz_datamgr:enable_change_notice(); cleanup(?NE_BINARY, _) -> 'ok'. -spec result_output_header() -> kz_tasks:output_header(). result_output_header() -> {'replace', list_output_header() ++ [?OUTPUT_CSV_HEADER_ERROR]}. -spec list_output_header() -> kz_tasks:output_header(). list_output_header() -> [<<"e164">> ,<<"account_name">> ,<<"account_id">> ,<<"previously_assigned_to">> ,<<"state">> ,<<"created">> ,<<"modified">> ,<<"used_by">> ,<<"ported_in">> ,<<"carrier_module">> ,<<"cnam.inbound">> ,<<"cnam.outbound">> ,<<"e911.locality">> ,<<"e911.name">> ,<<"e911.region">> ,<<"e911.street_address">> ,<<"e911.extended_address">> ,<<"e911.postal_code">> ,<<"prepend.enabled">> ,<<"prepend.name">> ,<<"prepend.number">> ,<<"ringback.early">> ,<<"ringback.transfer">> ,<<"force_outbound">> ,<<"failover.e164">> ,<<"failover.sip">> ]. -spec list_doc() -> kz_term:ne_binary(). list_doc() -> <<"For each number found, returns fields:\n" "* `e164`: phone number represented as E164 (with a leading `+` sign).\n" "* `account_id`: account it is assigned to (32 alphanumeric characters).\n" "* `previously_assigned_to`: account it was assigned to before being assigned to `account_id`.\n" "* `state`: either discovery, available, reserved, in_service, released, deleted, port_in or port_out.\n" "* `created`: timestamp number document was created.\n" "* `modified`: timestamp number document was last updated.\n" "* `used_by`: Kazoo application handling this number.\n" "* `ported_in`: whether this number was imported as part of a port request ('true' of 'false').\n" "* `carrier_module`: service that created the number document.\n" "* `cnam.inbound`: whether inbound CNAM is activated ('true' or 'false').\n" "* `cnam.outbound`: caller ID to use on outbound calls.\n" "* `e911.locality`: E911 locality.\n" "* `e911.name`: E911 name.\n" "* `e911.region`: E911 region.\n" "* `e911.street_address`: E911 street address.\n" "* `e911.extended_address`: E911 street address, second field.\n" "* `e911.postal_code`: E911 postal code.\n" "* `prepend.enabled`: whether prepend is enabled ('true' or 'false').\n" "* `prepend.name`: prepend name.\n" "* `prepend.number`: prepend number.\n" "* `ringback.early`: ringback early.\n" "* `ringback.early`: ringback transfer.\n" "* `force_outbound`: whether this number is forced outbound ('true' or 'false').\n" "* `failover.e164`: number to fail over to.\n" "* `failover.sip`: SIP URI to fail over to.\n" >>. optional_public_fields() -> [?FEATURE_RENAME_CARRIER] ++ (list_output_header() -- [<<"e164">> ,<<"account_name">> ,<<"account_id">> ,<<"previously_assigned_to">> ,<<"state">> ,<<"created">> ,<<"modified">> ,<<"used_by">> ,<<"ported_in">> ,<<"carrier_module">> ]). -spec help(kz_json:object()) -> kz_json:object(). help(JObj) -> help(JObj, <<?CATEGORY>>). -spec help(kz_json:object(), kz_term:ne_binary()) -> kz_json:object(). help(JObj, <<?CATEGORY>>=Category) -> lists:foldl(fun(Action, J) -> help(J, Category, Action) end, JObj, ?ACTIONS). -spec help(kz_json:object(), kz_term:ne_binary(), kz_term:ne_binary()) -> kz_json:object(). help(JObj, <<?CATEGORY>>=Category, Action) -> kz_json:set_value([Category, Action], kz_json:from_map(action(Action)), JObj). -spec action(kz_term:ne_binary()) -> map(). action(<<"list">>) -> #{<<"description">> => <<"List all numbers assigned to the account starting the task">> ,<<"doc">> => list_doc() }; action(<<"list_all">>) -> #{<<"description">> => <<"List all numbers assigned to the account starting the task & its subaccounts">> ,<<"doc">> => list_doc() }; action(<<"find">>) -> #{<<"description">> => <<"List the given numbers if the authenticated account owns them">> ,<<"doc">> => list_doc() ,<<"expected_content">> => <<"text/csv">> ,<<"mandatory">> => [<<"e164">>] ,<<"optional">> => [] }; action(<<"dump">>) -> #{<<"description">> => <<"List all numbers that exist in the system">> ,<<"doc">> => list_doc() }; action(<<"dump_", State/binary>>) -> #{<<"description">> => <<"List all '", State/binary, "' numbers that exist in the system">> ,<<"doc">> => list_doc() }; action(<<"import">>) -> #{<<"description">> => <<"Bulk-import numbers using superadmin privileges">> ,<<"doc">> => <<"Creates numbers from fields similar to list tasks.\n" "Note: number must be E164-formatted.\n" "Note: number must not be in the system already.\n" "If `account_id` is empty, number will be assigned to account creating task.\n" "`module_name` will be used only if account creating task is system admin.\n" "`state` will be used only if account creating task is system admin.\n" "Note: create new 'available' numbers by setting their `state` to 'available' and running the task with admin credentials.\n" "Note: `carrier_module` defaults to '", (?IMPORT_DEFAULTS_TO_CARRIER)/binary, "'.\n" ?ON_SETTING_PUBLIC_FIELDS >> ,<<"expected_content">> => <<"text/csv">> ,<<"mandatory">> => [<<"e164">>] ,<<"optional">> => list_output_header() -- [<<"e164">>] }; action(<<"assign_to">>) -> #{<<"description">> => <<"Bulk-assign numbers to the provided account">> ,<<"doc">> => <<"Assign existing numbers to another account.\n" "Note: number must be E164-formatted.\n" "Note: number must already exist.\n" "Note: account creating the task (or `auth_by` account) must have permissions on number.\n" "Note: target `account_id` must exist.\n" "Note: after assignment, number state will be 'in_service'.\n" >> ,<<"expected_content">> => <<"text/csv">> ,<<"mandatory">> => [<<"e164">>] ,<<"optional">> => [<<"account_id">>] }; action(<<"update_merge">>) -> #{<<"description">> => <<"Bulk-update numbers">> ,<<"doc">> => <<"Update features and/or public fields of existing numbers.\n" "Note: if a field is already set on number but empty in the row, it will not be modified.\n" "Note: number must be E164-formatted.\n" "Note: number must already exist.\n" "Note: account creating the task (or `auth_by` account) must have permissions on number.\n" ?ON_SETTING_PUBLIC_FIELDS >> ,<<"expected_content">> => <<"text/csv">> ,<<"mandatory">> => [<<"e164">>] ,<<"optional">> => optional_public_fields() }; action(<<"update_overwrite">>) -> #{<<"description">> => <<"Bulk-update numbers">> ,<<"doc">> => <<"Reset features and/or public fields of existing numbers.\n" "Note: if a field is already set on number but empty in the row, it will be unset.\n" "Note: number must be E164-formatted.\n" "Note: number must already exist.\n" "Note: account creating the task (or `auth_by` account) must have permissions on number.\n" ?ON_SETTING_PUBLIC_FIELDS >> ,<<"expected_content">> => <<"text/csv">> ,<<"mandatory">> => [<<"e164">>] ,<<"optional">> => optional_public_fields() }; action(<<"release">>) -> #{<<"description">> => <<"Unassign numbers from accounts">> ,<<"doc">> => <<"Release numbers (removing happens if account is configured so).\n" "Note: number must be E164-formatted.\n" "Note: number must already exist.\n" "Note: account creating the task (or `auth_by` account) must have permissions on number.\n" >> ,<<"expected_content">> => <<"text/csv">> ,<<"mandatory">> => [<<"e164">>] ,<<"optional">> => [] }; action(<<"reserve">>) -> #{<<"description">> => <<"Bulk-reserve numbers">> ,<<"doc">> => <<"Sets numbers to state 'reserved' (creating number if it is missing).\n" "Note: number must be E164-formatted.\n" "Note: account creating the task (or `auth_by` account) must have permission to proceed.\n" "Note: after transitioning state to 'reserved', number is assigned to `account_id`.\n" >> ,<<"expected_content">> => <<"text/csv">> ,<<"mandatory">> => [<<"e164">>] ,<<"optional">> => [<<"account_id">>] }; action(<<"delete">>) -> #{<<"description">> => <<"Bulk-remove numbers">> ,<<"doc">> => <<"Forces numbers to be deleted from the system.\n" "Note: number must be E164-formatted.\n" "Note: number must already exist.\n" "Note: account creating the task (or `auth_by` account) must have permissions on number.\n" >> ,<<"expected_content">> => <<"text/csv">> ,<<"mandatory">> => [<<"e164">>] ,<<"optional">> => [] }. %%% Verifiers -spec e164(kz_term:ne_binary()) -> boolean(). e164(<<"+", _/binary>>) -> 'true'; e164(_) -> 'false'. -spec account_id(kz_term:ne_binary()) -> boolean(). account_id(?MATCH_ACCOUNT_RAW(_)) -> 'true'; account_id(_) -> 'false'. -spec carrier_module(kz_term:ne_binary()) -> boolean(). carrier_module(Data) -> lists:member(Data, knm_carriers:all_modules()). -spec state(kz_term:ne_binary()) -> boolean(). state(Data) -> knm_phone_number:is_state(Data). -spec ported_in(kz_term:ne_binary()) -> boolean(). ported_in(Cell) -> is_cell_boolean(Cell). -spec 'cnam.inbound'(kz_term:ne_binary()) -> boolean(). 'cnam.inbound'(Cell) -> is_cell_boolean(Cell). -spec 'prepend.enabled'(kz_term:ne_binary()) -> boolean(). 'prepend.enabled'(Cell) -> is_cell_boolean(Cell). -spec force_outbound(kz_term:ne_binary()) -> boolean(). force_outbound(Cell) -> is_cell_boolean(Cell). -spec is_cell_boolean(kz_term:ne_binary()) -> boolean(). is_cell_boolean(<<"true">>) -> 'true'; is_cell_boolean(<<"false">>) -> 'true'; is_cell_boolean(_) -> 'false'. -spec is_cell_true(kz_term:api_ne_binary()) -> boolean(). is_cell_true('undefined') -> 'undefined'; is_cell_true(<<"true">>) -> 'true'; is_cell_true(_) -> 'false'. %%% Appliers -spec list(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). list(#{'account_id' := ForAccount}, 'init') -> ToList = [{ForAccount, NumberDb} || NumberDb <- knm_util:get_all_number_dbs()], {'ok', ToList}; list(_, []) -> 'stop'; list(#{'auth_account_id' := AuthBy}, Todo) -> list_assigned_to(AuthBy, Todo). -spec list_numbers(kz_term:ne_binary(), kz_term:ne_binaries()) -> [kz_csv:row()]. list_numbers(AuthBy, E164s) -> Options = [{'auth_by', AuthBy} ,{'batch_run', 'true'} ], Collection = knm_ops:get(E164s, Options), PNs = knm_pipe:succeeded(Collection), Failed = knm_pipe:failed(Collection), maps:fold(fun list_bad_rows/3, [], Failed) ++ [list_number(PN) || PN <- PNs]. list_bad_rows(E164, 'not_reconcilable', Rows) -> %% Numbers that shouldn't be in the system (e.g. '+141510010+14') %% Their fields are not queryable but we return the id to show it exists. Row = [E164 | lists:duplicate(length(list_output_header()) - 1, 'undefined')], [Row|Rows]; list_bad_rows(_E164, _R, Rows) -> lager:error("wild number ~s appeared: ~p", [_E164, _R]), Rows. -spec list_number(knm_phone_number:record()) -> map(). list_number(PN) -> InboundCNAM = knm_phone_number:feature(PN, ?FEATURE_CNAM_INBOUND), OutboundCNAM = knm_phone_number:feature(PN, ?FEATURE_CNAM_OUTBOUND), E911 = knm_phone_number:feature(PN, ?FEATURE_E911), Prepend = knm_phone_number:feature(PN, ?FEATURE_PREPEND), Ringback = knm_phone_number:feature(PN, ?FEATURE_RINGBACK), Failover = knm_phone_number:feature(PN, ?FEATURE_FAILOVER), #{<<"e164">> => knm_phone_number:number(PN) ,<<"account_name">> => account_name(knm_phone_number:assigned_to(PN)) ,<<"account_id">> => knm_phone_number:assigned_to(PN) ,<<"previously_assigned_to">> => knm_phone_number:prev_assigned_to(PN) ,<<"state">> => knm_phone_number:state(PN) ,<<"created">> => integer_to_binary(knm_phone_number:created(PN)) ,<<"modified">> => integer_to_binary(knm_phone_number:modified(PN)) ,<<"used_by">> => knm_phone_number:used_by(PN) ,<<"ported_in">> => kz_term:to_binary(knm_phone_number:ported_in(PN)) ,<<"carrier_module">> => knm_phone_number:module_name(PN) ,<<"cnam.inbound">> => kz_term:to_binary(kz_json:is_true(?CNAM_INBOUND_LOOKUP, InboundCNAM)) ,<<"cnam.outbound">> => quote(kz_json:get_ne_binary_value(?CNAM_DISPLAY_NAME, OutboundCNAM)) ,<<"e911.locality">> => quote(kz_json:get_ne_binary_value(?E911_CITY, E911)) ,<<"e911.name">> => quote(kz_json:get_ne_binary_value(?E911_NAME, E911)) ,<<"e911.region">> => kz_json:get_ne_binary_value(?E911_STATE, E911) ,<<"e911.street_address">> => quote(kz_json:get_ne_binary_value(?E911_STREET1, E911)) ,<<"e911.extended_address">> => quote(kz_json:get_ne_binary_value(?E911_STREET2, E911)) ,<<"e911.postal_code">> => kz_json:get_ne_binary_value(?E911_ZIP, E911) ,<<"prepend.enabled">> => kz_term:to_binary(kz_json:is_true(?PREPEND_ENABLED, Prepend)) ,<<"prepend.name">> => quote(kz_json:get_ne_binary_value(?PREPEND_NAME, Prepend)) ,<<"prepend.number">> => kz_json:get_ne_binary_value(?PREPEND_NUMBER, Prepend) ,<<"ringback.early">> => kz_json:get_ne_binary_value(?RINGBACK_EARLY, Ringback) ,<<"ringback.transfer">> => kz_json:get_ne_binary_value(?RINGBACK_TRANSFER, Ringback) ,<<"force_outbound">> => kz_term:to_binary(knm_lib:force_outbound_feature(PN)) ,<<"failover.e164">> => kz_json:get_ne_binary_value(?FAILOVER_E164, Failover) ,<<"failover.sip">> => quote(kz_json:get_ne_binary_value(?FAILOVER_SIP, Failover)) }. -spec account_name(kz_term:api_ne_binary()) -> kz_term:api_ne_binary(). account_name(MaybeAccountId) -> case kzd_accounts:fetch_name(MaybeAccountId) of 'undefined' -> 'undefined'; Name -> quote(Name) end. -spec quote(kz_term:api_ne_binary()) -> kz_term:api_ne_binary(). quote('undefined') -> 'undefined'; quote(Bin) -> <<$\", Bin/binary, $\">>. -spec list_all(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). list_all(#{'account_id' := Account}, 'init') -> ForAccounts = [Account | kapps_util:account_descendants(Account)], ToList = [{ForAccount, NumberDb} || ForAccount <- ForAccounts, NumberDb <- knm_util:get_all_number_dbs() ], {'ok', ToList}; list_all(_, []) -> 'stop'; list_all(_, Todo) -> list_assigned_to(?KNM_DEFAULT_AUTH_BY, Todo). -spec find(kz_tasks:extra_args(), kz_tasks:iterator(), kz_tasks:args()) -> kz_tasks:return(). find(#{'auth_account_id' := AuthBy}, _IterValue, Args=#{<<"e164">> := Num}) -> %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number handle_result(Args, knm_ops:get(Num, [{'auth_by', AuthBy}])). -spec dump(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump(_, []) -> 'stop'; dump(_, Todo) -> dump_next(fun db_and_view_for_dump/1, Todo). init_dump(ExtraArgs) -> {'ok', MasterAccountId} = kapps_util:get_master_account_id(), case maps:get('auth_account_id', ExtraArgs) of MasterAccountId -> {'ok', knm_util:get_all_number_dbs()}; _ -> 'stop' end. dump_by_state(State, Todo) -> ViewFun = fun (Next) -> db_and_view_for_dump_by_state(State, Next) end, dump_next(ViewFun, Todo). -spec dump_aging(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_aging(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_aging(_, []) -> 'stop'; dump_aging(_, Todo) -> dump_by_state(?NUMBER_STATE_AGING, Todo). -spec dump_available(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_available(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_available(_, []) -> 'stop'; dump_available(_, Todo) -> dump_by_state(?NUMBER_STATE_AVAILABLE, Todo). -spec dump_deleted(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_deleted(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_deleted(_, []) -> 'stop'; dump_deleted(_, Todo) -> dump_by_state(?NUMBER_STATE_DELETED, Todo). -spec dump_discovery(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_discovery(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_discovery(_, []) -> 'stop'; dump_discovery(_, Todo) -> dump_by_state(?NUMBER_STATE_DISCOVERY, Todo). -spec dump_in_service(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_in_service(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_in_service(_, []) -> 'stop'; dump_in_service(_, Todo) -> dump_by_state(?NUMBER_STATE_IN_SERVICE, Todo). -spec dump_port_in(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_port_in(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_port_in(_, []) -> 'stop'; dump_port_in(_, Todo) -> dump_by_state(?NUMBER_STATE_PORT_IN, Todo). -spec dump_port_out(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_port_out(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_port_out(_, []) -> 'stop'; dump_port_out(_, Todo) -> dump_by_state(?NUMBER_STATE_PORT_OUT, Todo). -spec dump_released(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_released(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_released(_, []) -> 'stop'; dump_released(_, Todo) -> dump_by_state(?NUMBER_STATE_RELEASED, Todo). -spec dump_reserved(kz_tasks:extra_args(), kz_tasks:iterator()) -> kz_tasks:iterator(). dump_reserved(ExtraArgs, 'init') -> init_dump(ExtraArgs); dump_reserved(_, []) -> 'stop'; dump_reserved(_, Todo) -> dump_by_state(?NUMBER_STATE_RESERVED, Todo). -spec import(kz_tasks:extra_args(), kz_tasks:iterator(), kz_tasks:args()) -> {kz_tasks:return(), sets:set()}. import(ExtraArgs, 'init', Args) -> kz_datamgr:suppress_change_notice(), IterValue = sets:new(), import(ExtraArgs, IterValue, Args); import(#{'account_id' := Account ,'auth_account_id' := AuthAccountId } ,AccountIds ,Args=#{<<"e164">> := E164 ,<<"account_id">> := AccountId0 ,<<"state">> := State ,<<"carrier_module">> := Carrier ,<<"ported_in">> := PortedIn ,<<"previously_assigned_to">> := _ ,<<"created">> := _ ,<<"modified">> := _ ,<<"used_by">> := _ %%FIXME: decide whether to use this one } ) -> AccountId = select_account_id(AccountId0, Account), Options = [{'auth_by', AuthAccountId} ,{'batch_run', 'true'} ,{'assign_to', AccountId} ,{'module_name', import_module_name(AuthAccountId, Carrier)} ,{'ported_in', PortedIn =:= <<"true">>} ,{'public_fields', public_fields(Args)} | import_state(AuthAccountId, State) ], %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number Row = handle_result(Args, knm_ops:create(E164, Options)), {Row, sets:add_element(AccountId, AccountIds)}. public_fields(Args) -> kz_json:from_list(lists:flatten(pub_fields(Args))). pub_fields(Args=#{<<"cnam.inbound">> := CNAMInbound ,<<"cnam.outbound">> := CNAMOutbound ,<<"e911.locality">> := E911Locality ,<<"e911.name">> := E911Name ,<<"e911.region">> := E911Region ,<<"e911.street_address">> := E911StreetAddress ,<<"e911.extended_address">> := E911ExtendedAddress ,<<"e911.postal_code">> := E911PostalCode ,<<"prepend.enabled">> := PrependEnabled ,<<"prepend.name">> := PrependName ,<<"prepend.number">> := PrependNumber ,<<"ringback.early">> := RingbackEarly ,<<"ringback.transfer">> := RingbackTransfer ,?FEATURE_FORCE_OUTBOUND := ForceOutbound ,<<"failover.e164">> := FailoverE164 ,<<"failover.sip">> := FailoverSIP }) -> RenameCarrier = maps:get(?FEATURE_RENAME_CARRIER, Args, 'undefined'), [props:filter_undefined([{?FEATURE_RENAME_CARRIER, RenameCarrier}]) ,cnam(props:filter_undefined( [{?CNAM_DISPLAY_NAME, CNAMOutbound} ,{?CNAM_INBOUND_LOOKUP, is_cell_true(CNAMInbound)} ])) ,e911(props:filter_empty( [{?E911_CITY, E911Locality} ,{?E911_NAME, E911Name} ,{?E911_STATE, E911Region} ,{?E911_STREET1, E911StreetAddress} ,{?E911_STREET2, E911ExtendedAddress} ,{?E911_ZIP, E911PostalCode} ])) ,prepend(props:filter_undefined( [{?PREPEND_ENABLED, is_cell_true(PrependEnabled)} ,{?PREPEND_NAME, PrependName} ,{?PREPEND_NUMBER, PrependNumber} ])) ,ringback(props:filter_empty( [{?RINGBACK_EARLY, RingbackEarly} ,{?RINGBACK_TRANSFER, RingbackTransfer} ])) ,props:filter_undefined([{?FEATURE_FORCE_OUTBOUND, is_cell_true(ForceOutbound)}]) ,failover(props:filter_empty( [{?FAILOVER_E164, FailoverE164} ,{?FAILOVER_SIP, FailoverSIP} ])) ,additional_fields_to_json(Args) ]. cnam(Props) -> maybe_nest(?FEATURE_CNAM, Props). e911(Props) -> maybe_nest(?FEATURE_E911, Props). prepend(Props) -> maybe_nest(?FEATURE_PREPEND, Props). ringback(Props) -> maybe_nest(?FEATURE_RINGBACK, Props). failover(Props) -> maybe_nest(?FEATURE_FAILOVER, Props). -spec maybe_nest(kz_term:ne_binary(), kz_term:proplist()) -> kz_term:proplist(). maybe_nest(_, []) -> []; maybe_nest(Feature, Props) -> [{Feature, kz_json:from_list(Props)}]. import_module_name(AuthBy, Carrier) -> case kzd_accounts:is_superduper_admin(AuthBy) andalso Carrier of 'false' -> ?IMPORT_DEFAULTS_TO_CARRIER; 'undefined' -> ?IMPORT_DEFAULTS_TO_CARRIER; _ -> Carrier end. import_state(AuthBy, State) -> case kzd_accounts:is_superduper_admin(AuthBy) andalso 'undefined' =/= State of 'false' -> []; 'true' -> [{'state', State}] end. additional_fields_to_json(Args) -> F = fun (Field, JObj) -> Path = binary:split(Field, <<$.>>, ['global']), case maps:get(<<"opaque.", Field/binary>>, Args, 'undefined') of 'undefined' -> JObj; Value -> lager:debug("setting public field ~p to ~p", [Path, Value]), kz_json:set_value(Path, Value, JObj) end end, kz_json:to_proplist( lists:foldl(F, kz_json:new(), additional_fields(Args)) ). additional_fields(Args) -> [OpaqueField || <<"opaque.", OpaqueField0/binary>> <- maps:keys(Args), OpaqueField <- [kz_binary:strip(OpaqueField0)], not kz_term:is_empty(OpaqueField) ]. select_account_id(?MATCH_ACCOUNT_RAW(_)=AccountId, _) -> AccountId; select_account_id(_, AccountId) -> AccountId. -spec assign_to(kz_tasks:extra_args(), kz_tasks:iterator(), kz_tasks:args()) -> kz_tasks:return(). assign_to(#{'auth_account_id' := AuthBy, 'account_id' := Account} ,_IterValue ,Args=#{<<"e164">> := Num, <<"account_id">> := AccountId0} ) -> AccountId = select_account_id(AccountId0, Account), Options = [{'auth_by', AuthBy} ,{'batch_run', 'true'} ], %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number handle_result(Args, knm_ops:move(Num, AccountId, Options)). -spec update_merge(kz_tasks:extra_args(), kz_tasks:iterator(), kz_tasks:args()) -> kz_tasks:return(). update_merge(#{'auth_account_id' := AuthBy} ,_IterValue ,Args=#{<<"e164">> := Num} ) -> Options = [{'auth_by', AuthBy} ,{'batch_run', 'true'} ], Updates = [{fun knm_phone_number:update_doc/2, public_fields(Args)}], %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number handle_result(Args, knm_ops:update(Num, Updates, Options)). -spec update_overwrite(kz_tasks:extra_args(), kz_tasks:iterator(), kz_tasks:args()) -> kz_tasks:return(). update_overwrite(#{'auth_account_id' := AuthBy} ,_IterValue ,Args=#{<<"e164">> := Num} ) -> Options = [{'auth_by', AuthBy} ,{'batch_run', 'true'} ], Updates = [{fun knm_phone_number:reset_doc/2, public_fields(Args)}], %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number handle_result(Args, knm_ops:update(Num, Updates, Options)). -spec release(kz_tasks:extra_args(), kz_tasks:iterator(), kz_tasks:args()) -> kz_tasks:return(). release(#{'auth_account_id' := AuthBy} ,_IterValue ,Args=#{<<"e164">> := Num} ) -> Options = [{'auth_by', AuthBy} ,{'batch_run', 'true'} ], %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number handle_result(Args, knm_ops:release(Num, Options)). -spec reserve(kz_tasks:extra_args(), kz_tasks:iterator(), kz_tasks:args()) -> kz_tasks:return(). reserve(#{'auth_account_id' := AuthBy, 'account_id' := Account} ,_IterValue ,Args=#{<<"e164">> := Num, <<"account_id">> := AccountId0} ) -> Options = [{'auth_by', AuthBy} ,{'batch_run', 'true'} ,{'assign_to', select_account_id(AccountId0, Account)} ], %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number handle_result(Args, knm_ops:reserve(Num, Options)). -spec delete(kz_tasks:extra_args(), kz_tasks:iterator(), kz_tasks:args()) -> kz_tasks:return(). delete(#{'auth_account_id' := AuthBy} ,_IterValue ,Args=#{<<"e164">> := Num} ) -> Options = [{'auth_by', AuthBy} ,{'batch_run', 'true'} ], %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number handle_result(Args, knm_ops:delete(Num, Options)). %%%============================================================================= %%% Internal functions %%%============================================================================= %%------------------------------------------------------------------------------ %% @doc %% FIXME: use knm_numbers, update list_number/1 to use kzd_phone_number %% TODO: kt_numbers is processing numbers one at a time %% refactor it to use use bulk operation %% @end %%------------------------------------------------------------------------------ -spec handle_result(kz_tasks:args(), knm_pipe:collection()) -> kz_tasks:return(). handle_result(Args, Collection) -> IsDryRun = knm_options:dry_run(knm_pipe:options(Collection)), case knm_pipe:succeeded(Collection) of [_PN] when IsDryRun -> format_result(Args, <<"accept_charges">>); [PN] -> format_result(Args, PN); _ -> format_error(knm_pipe:failed_to_proplist(Collection), Args) end. -spec format_error(knm_errors:proplist(), kz_tasks:args()) -> kz_csv:mapped_row(). format_error([{_, Reason} | _], Args) when is_atom(Reason) -> format_result(Args, kz_term:to_binary(Reason)); format_error([{_, KNMError} | _], Args) -> Reason = case knm_errors:message(KNMError) of 'undefined' -> knm_errors:error(KNMError); R -> R end, format_result(Args, kz_term:to_binary(Reason)). -spec format_result(kz_tasks:args(), kz_term:ne_binary() | knm_phone_number:record()) -> kz_csv:mapped_row(). format_result(Args, Reason=?NE_BINARY) -> Args#{?OUTPUT_CSV_HEADER_ERROR => Reason}; format_result(_, PN) -> Map = list_number(PN), Map#{?OUTPUT_CSV_HEADER_ERROR => 'undefined'}. -type accountid_or_startkey_and_numberdbs() :: [{kz_term:ne_binary() | kz_term:ne_binaries(), kz_term:ne_binary()}]. -spec list_assigned_to(kz_term:ne_binary(), accountid_or_startkey_and_numberdbs()) -> {'ok' | 'error' | [kz_csv:row()], accountid_or_startkey_and_numberdbs()}. list_assigned_to(AuthBy, [{Next,NumberDb}|Rest]) -> ViewOptions = [{'limit', ?DB_DUMP_BULK_SIZE} | view_for_list_assigned(Next)], case kz_datamgr:get_result_keys(NumberDb, <<"numbers/assigned_to">>, ViewOptions) of {'ok', []} -> {'ok', Rest}; {'error', _R} -> lager:error("could not get ~p's numbers in ~s: ~p", [ViewOptions, NumberDb, _R]), {'error', Rest}; {'ok', Keys} -> Rows = list_numbers(AuthBy, [lists:last(Key) || Key <- Keys]), {Rows, [{lists:last(Keys),NumberDb}|Rest]} end. -spec view_for_list_assigned(kz_term:ne_binary() | kz_term:ne_binaries()) -> kz_datamgr:view_options(). view_for_list_assigned(?MATCH_ACCOUNT_RAW(AccountId)) -> [{'startkey', [AccountId]} ,{'endkey', [AccountId, kz_json:new()]} ]; view_for_list_assigned(StartKey=[AccountId,_]) -> [{'startkey', StartKey} ,{'endkey', [AccountId, kz_json:new()]} ,{'skip', 1} ]. -type startkey_or_numberdb() :: kz_term:ne_binary() | kz_term:ne_binaries(). -spec dump_next(fun((startkey_or_numberdb()) -> {kz_term:ne_binary(), kz_datamgr:view_options()}), startkey_or_numberdb()) -> {'ok' | 'error' | [kz_csv:row()], [startkey_or_numberdb()]}. dump_next(ViewFun, [Next|Rest]) -> {NumberDb, MoreViewOptions} = ViewFun(Next), ViewOptions = [{limit, ?DB_DUMP_BULK_SIZE} | MoreViewOptions], case kz_datamgr:get_result_keys(NumberDb, <<"numbers/status">>, ViewOptions) of {'ok', []} -> {'ok', Rest}; {'error', _R} -> lager:error("could not get ~p from ~s: ~p", [ViewOptions, NumberDb, _R]), {'error', Rest}; {'ok', Keys} -> Rows = list_numbers(?KNM_DEFAULT_AUTH_BY, [lists:last(Key) || Key <- Keys]), {Rows, [lists:last(Keys)|Rest]} end. -spec db_and_view_for_dump(kz_term:ne_binary() | kz_term:ne_binaries()) -> {kz_term:ne_binary(), kz_datamgr:view_options()}. db_and_view_for_dump(<<NumberDb/binary>>) -> {NumberDb, []}; db_and_view_for_dump(StartKey=[_, _, LastNum]) -> ViewOpts = [{'startkey', StartKey} ,{'skip', 1} ], {knm_converters:to_db(LastNum), ViewOpts}. -spec db_and_view_for_dump_by_state(kz_term:ne_binary(), kz_term:ne_binary() | kz_term:ne_binaries()) -> {kz_term:ne_binary(), kz_datamgr:view_options()}. db_and_view_for_dump_by_state(State, <<NumberDb/binary>>) -> ViewOptions = [{'startkey', [State]} ,{'endkey', [State, kz_json:new()]} ], {NumberDb, ViewOptions}; db_and_view_for_dump_by_state(State, StartKey=[_ ,_, LastNum]) -> ViewOptions = [{'startkey', StartKey} ,{'endkey', [State, kz_json:new()]} ,{'skip', 1} ], {knm_converters:to_db(LastNum), ViewOptions}. %%% End of Module.
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using AspectCore.DynamicProxy; using AspectCore.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace AspectCore1.Extensions.DependencyInjection.Test { public class AdditionalInterceptorSelectorTests { [Fact] public void ImplementationMethod_Test() { var services = new ServiceCollection(); services.AddTransient<IService, Service>(); var provider = services.BuildServiceContextProvider(); var service = provider.GetService<IService>(); var val = service.GetValue("le"); Assert.Equal("lemon", val); } public class Intercept : AbstractInterceptorAttribute { public override Task Invoke(AspectContext context, AspectDelegate next) { context.Parameters[0] = "lemon"; return context.Invoke(next); } } public interface IService { string GetValue(string val); } public class Service : IService { [Intercept] public string GetValue(string val) { return val; } } } }
{ "pile_set_name": "Github" }
// +build !ignore_autogenerated /* Copyright The Kubernetes Authors. 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package v1 import ( runtime "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ConversionRequest) DeepCopyInto(out *ConversionRequest) { *out = *in if in.Objects != nil { in, out := &in.Objects, &out.Objects *out = make([]runtime.RawExtension, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConversionRequest. func (in *ConversionRequest) DeepCopy() *ConversionRequest { if in == nil { return nil } out := new(ConversionRequest) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ConversionResponse) DeepCopyInto(out *ConversionResponse) { *out = *in if in.ConvertedObjects != nil { in, out := &in.ConvertedObjects, &out.ConvertedObjects *out = make([]runtime.RawExtension, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } in.Result.DeepCopyInto(&out.Result) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConversionResponse. func (in *ConversionResponse) DeepCopy() *ConversionResponse { if in == nil { return nil } out := new(ConversionResponse) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ConversionReview) DeepCopyInto(out *ConversionReview) { *out = *in out.TypeMeta = in.TypeMeta if in.Request != nil { in, out := &in.Request, &out.Request *out = new(ConversionRequest) (*in).DeepCopyInto(*out) } if in.Response != nil { in, out := &in.Response, &out.Response *out = new(ConversionResponse) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConversionReview. func (in *ConversionReview) DeepCopy() *ConversionReview { if in == nil { return nil } out := new(ConversionReview) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ConversionReview) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceColumnDefinition) DeepCopyInto(out *CustomResourceColumnDefinition) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceColumnDefinition. func (in *CustomResourceColumnDefinition) DeepCopy() *CustomResourceColumnDefinition { if in == nil { return nil } out := new(CustomResourceColumnDefinition) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceConversion) DeepCopyInto(out *CustomResourceConversion) { *out = *in if in.Webhook != nil { in, out := &in.Webhook, &out.Webhook *out = new(WebhookConversion) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceConversion. func (in *CustomResourceConversion) DeepCopy() *CustomResourceConversion { if in == nil { return nil } out := new(CustomResourceConversion) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceDefinition) DeepCopyInto(out *CustomResourceDefinition) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinition. func (in *CustomResourceDefinition) DeepCopy() *CustomResourceDefinition { if in == nil { return nil } out := new(CustomResourceDefinition) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *CustomResourceDefinition) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceDefinitionCondition) DeepCopyInto(out *CustomResourceDefinitionCondition) { *out = *in in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionCondition. func (in *CustomResourceDefinitionCondition) DeepCopy() *CustomResourceDefinitionCondition { if in == nil { return nil } out := new(CustomResourceDefinitionCondition) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceDefinitionList) DeepCopyInto(out *CustomResourceDefinitionList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CustomResourceDefinition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionList. func (in *CustomResourceDefinitionList) DeepCopy() *CustomResourceDefinitionList { if in == nil { return nil } out := new(CustomResourceDefinitionList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *CustomResourceDefinitionList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceDefinitionNames) DeepCopyInto(out *CustomResourceDefinitionNames) { *out = *in if in.ShortNames != nil { in, out := &in.ShortNames, &out.ShortNames *out = make([]string, len(*in)) copy(*out, *in) } if in.Categories != nil { in, out := &in.Categories, &out.Categories *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionNames. func (in *CustomResourceDefinitionNames) DeepCopy() *CustomResourceDefinitionNames { if in == nil { return nil } out := new(CustomResourceDefinitionNames) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceDefinitionSpec) DeepCopyInto(out *CustomResourceDefinitionSpec) { *out = *in in.Names.DeepCopyInto(&out.Names) if in.Versions != nil { in, out := &in.Versions, &out.Versions *out = make([]CustomResourceDefinitionVersion, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.Conversion != nil { in, out := &in.Conversion, &out.Conversion *out = new(CustomResourceConversion) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionSpec. func (in *CustomResourceDefinitionSpec) DeepCopy() *CustomResourceDefinitionSpec { if in == nil { return nil } out := new(CustomResourceDefinitionSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceDefinitionStatus) DeepCopyInto(out *CustomResourceDefinitionStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]CustomResourceDefinitionCondition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } in.AcceptedNames.DeepCopyInto(&out.AcceptedNames) if in.StoredVersions != nil { in, out := &in.StoredVersions, &out.StoredVersions *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionStatus. func (in *CustomResourceDefinitionStatus) DeepCopy() *CustomResourceDefinitionStatus { if in == nil { return nil } out := new(CustomResourceDefinitionStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceDefinitionVersion) DeepCopyInto(out *CustomResourceDefinitionVersion) { *out = *in if in.Schema != nil { in, out := &in.Schema, &out.Schema *out = new(CustomResourceValidation) (*in).DeepCopyInto(*out) } if in.Subresources != nil { in, out := &in.Subresources, &out.Subresources *out = new(CustomResourceSubresources) (*in).DeepCopyInto(*out) } if in.AdditionalPrinterColumns != nil { in, out := &in.AdditionalPrinterColumns, &out.AdditionalPrinterColumns *out = make([]CustomResourceColumnDefinition, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceDefinitionVersion. func (in *CustomResourceDefinitionVersion) DeepCopy() *CustomResourceDefinitionVersion { if in == nil { return nil } out := new(CustomResourceDefinitionVersion) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceSubresourceScale) DeepCopyInto(out *CustomResourceSubresourceScale) { *out = *in if in.LabelSelectorPath != nil { in, out := &in.LabelSelectorPath, &out.LabelSelectorPath *out = new(string) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceSubresourceScale. func (in *CustomResourceSubresourceScale) DeepCopy() *CustomResourceSubresourceScale { if in == nil { return nil } out := new(CustomResourceSubresourceScale) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceSubresourceStatus) DeepCopyInto(out *CustomResourceSubresourceStatus) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceSubresourceStatus. func (in *CustomResourceSubresourceStatus) DeepCopy() *CustomResourceSubresourceStatus { if in == nil { return nil } out := new(CustomResourceSubresourceStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceSubresources) DeepCopyInto(out *CustomResourceSubresources) { *out = *in if in.Status != nil { in, out := &in.Status, &out.Status *out = new(CustomResourceSubresourceStatus) **out = **in } if in.Scale != nil { in, out := &in.Scale, &out.Scale *out = new(CustomResourceSubresourceScale) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceSubresources. func (in *CustomResourceSubresources) DeepCopy() *CustomResourceSubresources { if in == nil { return nil } out := new(CustomResourceSubresources) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CustomResourceValidation) DeepCopyInto(out *CustomResourceValidation) { *out = *in if in.OpenAPIV3Schema != nil { in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema *out = (*in).DeepCopy() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceValidation. func (in *CustomResourceValidation) DeepCopy() *CustomResourceValidation { if in == nil { return nil } out := new(CustomResourceValidation) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ExternalDocumentation) DeepCopyInto(out *ExternalDocumentation) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalDocumentation. func (in *ExternalDocumentation) DeepCopy() *ExternalDocumentation { if in == nil { return nil } out := new(ExternalDocumentation) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *JSON) DeepCopyInto(out *JSON) { *out = *in if in.Raw != nil { in, out := &in.Raw, &out.Raw *out = make([]byte, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSON. func (in *JSON) DeepCopy() *JSON { if in == nil { return nil } out := new(JSON) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in JSONSchemaDefinitions) DeepCopyInto(out *JSONSchemaDefinitions) { { in := &in *out = make(JSONSchemaDefinitions, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } return } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaDefinitions. func (in JSONSchemaDefinitions) DeepCopy() JSONSchemaDefinitions { if in == nil { return nil } out := new(JSONSchemaDefinitions) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in JSONSchemaDependencies) DeepCopyInto(out *JSONSchemaDependencies) { { in := &in *out = make(JSONSchemaDependencies, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } return } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaDependencies. func (in JSONSchemaDependencies) DeepCopy() JSONSchemaDependencies { if in == nil { return nil } out := new(JSONSchemaDependencies) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *JSONSchemaProps) DeepCopyInto(out *JSONSchemaProps) { clone := in.DeepCopy() *out = *clone return } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *JSONSchemaPropsOrArray) DeepCopyInto(out *JSONSchemaPropsOrArray) { *out = *in if in.Schema != nil { in, out := &in.Schema, &out.Schema *out = (*in).DeepCopy() } if in.JSONSchemas != nil { in, out := &in.JSONSchemas, &out.JSONSchemas *out = make([]JSONSchemaProps, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaPropsOrArray. func (in *JSONSchemaPropsOrArray) DeepCopy() *JSONSchemaPropsOrArray { if in == nil { return nil } out := new(JSONSchemaPropsOrArray) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *JSONSchemaPropsOrBool) DeepCopyInto(out *JSONSchemaPropsOrBool) { *out = *in if in.Schema != nil { in, out := &in.Schema, &out.Schema *out = (*in).DeepCopy() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaPropsOrBool. func (in *JSONSchemaPropsOrBool) DeepCopy() *JSONSchemaPropsOrBool { if in == nil { return nil } out := new(JSONSchemaPropsOrBool) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *JSONSchemaPropsOrStringArray) DeepCopyInto(out *JSONSchemaPropsOrStringArray) { *out = *in if in.Schema != nil { in, out := &in.Schema, &out.Schema *out = (*in).DeepCopy() } if in.Property != nil { in, out := &in.Property, &out.Property *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONSchemaPropsOrStringArray. func (in *JSONSchemaPropsOrStringArray) DeepCopy() *JSONSchemaPropsOrStringArray { if in == nil { return nil } out := new(JSONSchemaPropsOrStringArray) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ServiceReference) DeepCopyInto(out *ServiceReference) { *out = *in if in.Path != nil { in, out := &in.Path, &out.Path *out = new(string) **out = **in } if in.Port != nil { in, out := &in.Port, &out.Port *out = new(int32) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceReference. func (in *ServiceReference) DeepCopy() *ServiceReference { if in == nil { return nil } out := new(ServiceReference) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WebhookClientConfig) DeepCopyInto(out *WebhookClientConfig) { *out = *in if in.URL != nil { in, out := &in.URL, &out.URL *out = new(string) **out = **in } if in.Service != nil { in, out := &in.Service, &out.Service *out = new(ServiceReference) (*in).DeepCopyInto(*out) } if in.CABundle != nil { in, out := &in.CABundle, &out.CABundle *out = make([]byte, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WebhookClientConfig. func (in *WebhookClientConfig) DeepCopy() *WebhookClientConfig { if in == nil { return nil } out := new(WebhookClientConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WebhookConversion) DeepCopyInto(out *WebhookConversion) { *out = *in if in.ClientConfig != nil { in, out := &in.ClientConfig, &out.ClientConfig *out = new(WebhookClientConfig) (*in).DeepCopyInto(*out) } if in.ConversionReviewVersions != nil { in, out := &in.ConversionReviewVersions, &out.ConversionReviewVersions *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WebhookConversion. func (in *WebhookConversion) DeepCopy() *WebhookConversion { if in == nil { return nil } out := new(WebhookConversion) in.DeepCopyInto(out) return out }
{ "pile_set_name": "Github" }
diff -rupN --exclude=.DS_Store cfe-3.5.0.src/CMakeLists.txt cfe-3.5.0.src.cotire/CMakeLists.txt --- cfe-3.5.0.src/CMakeLists.txt 2014-07-16 18:48:33.000000000 +0200 +++ cfe-3.5.0.src.cotire/CMakeLists.txt 2014-12-21 19:58:36.000000000 +0100 @@ -94,6 +94,8 @@ if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURR include(AddLLVM) include(TableGen) include(HandleLLVMOptions) + include(cotire) + set_property(DIRECTORY PROPERTY COTIRE_UNITY_LINK_LIBRARIES_INIT "COPY_UNITY") set(PACKAGE_VERSION "${LLVM_PACKAGE_VERSION}") @@ -343,6 +345,12 @@ macro(add_clang_library name) endif() set_target_properties(${name} PROPERTIES FOLDER "Clang libraries") + if (COMMAND cotire) + if (NOT "${name}" MATCHES "libclang") + set_target_properties(${name} PROPERTIES COTIRE_UNITY_SOURCE_POST_UNDEFS "DEBUG_TYPE") + cotire(${name}) + endif() + endif() endmacro(add_clang_library) macro(add_clang_executable name) diff -rupN --exclude=.DS_Store cfe-3.5.0.src/tools/libclang/CMakeLists.txt cfe-3.5.0.src.cotire/tools/libclang/CMakeLists.txt --- cfe-3.5.0.src/tools/libclang/CMakeLists.txt 2014-07-15 00:17:16.000000000 +0200 +++ cfe-3.5.0.src.cotire/tools/libclang/CMakeLists.txt 2014-12-21 19:58:36.000000000 +0100 @@ -114,3 +114,10 @@ if(ENABLE_SHARED) LINK_FLAGS ${LIBCLANG_LINK_FLAGS}) endif() endif() + +if (COMMAND cotire) + cotire(libclang) + if (TARGET ${LIBCLANG_STATIC_TARGET_NAME}) + cotire(${LIBCLANG_STATIC_TARGET_NAME}) + endif() +endif()
{ "pile_set_name": "Github" }
/* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.teku.infrastructure.async; import com.google.common.base.Throwables; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class RootCauseExceptionHandler implements Consumer<Throwable> { private final List<ExceptionHandler<?>> handlers; private RootCauseExceptionHandler(final List<ExceptionHandler<?>> handlers) { this.handlers = handlers; } public static RootCauseExceptionHandler.Builder builder() { return new RootCauseExceptionHandler.Builder(); } @Override public void accept(final Throwable t) { final Throwable rootCause = Throwables.getRootCause(t); for (ExceptionHandler<?> handler : handlers) { if (handler.attemptHandle(rootCause)) { return; } } throw new IllegalStateException( "No handler specified for exception type " + rootCause.getClass(), t); } public static class Builder { private final List<ExceptionHandler<? extends Throwable>> handlers = new ArrayList<>(); public <T extends Throwable> Builder addCatch( final Class<T> rootCause, final Consumer<T> handler) { handlers.add(new ExceptionHandler<>(rootCause, handler)); return this; } public RootCauseExceptionHandler defaultCatch(final Consumer<Throwable> defaultHandler) { handlers.add(new ExceptionHandler<>(Throwable.class, defaultHandler)); return new RootCauseExceptionHandler(handlers); } } private static class ExceptionHandler<T extends Throwable> { private final Class<T> exceptionType; private final Consumer<T> handler; private ExceptionHandler(final Class<T> exceptionType, final Consumer<T> handler) { this.exceptionType = exceptionType; this.handler = handler; } @SuppressWarnings("unchecked") public boolean attemptHandle(final Throwable rootCause) { if (exceptionType.isInstance(rootCause)) { handler.accept((T) rootCause); return true; } return false; } } }
{ "pile_set_name": "Github" }
//===- Signals.cpp - Signal Handling support --------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines some helpful functions for dealing with the possibility of // Unix signals occurring while your program is running. // //===----------------------------------------------------------------------===// #include "llvm/Support/Signals.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Config/config.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/Program.h" #include "llvm/Support/StringSaver.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Options.h" #include <vector> //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only TRULY operating system //=== independent code. //===----------------------------------------------------------------------===// using namespace llvm; static cl::opt<bool> DisableSymbolication("disable-symbolication", cl::desc("Disable symbolizing crash backtraces."), cl::init(false), cl::Hidden); static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>> CallBacksToRun; void sys::RunSignalHandlers() { if (!CallBacksToRun.isConstructed()) return; for (auto &I : *CallBacksToRun) I.first(I.second); CallBacksToRun->clear(); } static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool); /// Format a pointer value as hexadecimal. Zero pad it out so its always the /// same width. static FormattedNumber format_ptr(void *PC) { // Each byte is two hex digits plus 2 for the 0x prefix. unsigned PtrWidth = 2 + 2 * sizeof(void *); return format_hex((uint64_t)PC, PtrWidth); } static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, int Depth, llvm::raw_ostream &OS) LLVM_ATTRIBUTE_USED; /// Helper that launches llvm-symbolizer and symbolizes a backtrace. static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, int Depth, llvm::raw_ostream &OS) { if (DisableSymbolication) return false; // Don't recursively invoke the llvm-symbolizer binary. if (Argv0.find("llvm-symbolizer") != std::string::npos) return false; // FIXME: Subtract necessary number from StackTrace entries to turn return addresses // into actual instruction addresses. // Use llvm-symbolizer tool to symbolize the stack traces. First look for it // alongside our binary, then in $PATH. ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code(); if (!Argv0.empty()) { StringRef Parent = llvm::sys::path::parent_path(Argv0); if (!Parent.empty()) LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent); } if (!LLVMSymbolizerPathOrErr) LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer"); if (!LLVMSymbolizerPathOrErr) return false; const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr; // If we don't know argv0 or the address of main() at this point, try // to guess it anyway (it's possible on some platforms). std::string MainExecutableName = Argv0.empty() ? sys::fs::getMainExecutable(nullptr, nullptr) : (std::string)Argv0; BumpPtrAllocator Allocator; StringSaver StrPool(Allocator); std::vector<const char *> Modules(Depth, nullptr); std::vector<intptr_t> Offsets(Depth, 0); if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(), MainExecutableName.c_str(), StrPool)) return false; int InputFD; SmallString<32> InputFile, OutputFile; sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile); sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile); FileRemover InputRemover(InputFile.c_str()); FileRemover OutputRemover(OutputFile.c_str()); { raw_fd_ostream Input(InputFD, true); for (int i = 0; i < Depth; i++) { if (Modules[i]) Input << Modules[i] << " " << (void*)Offsets[i] << "\n"; } } StringRef InputFileStr(InputFile); StringRef OutputFileStr(OutputFile); StringRef StderrFileStr; const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr, &StderrFileStr}; const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining", #ifdef LLVM_ON_WIN32 // Pass --relative-address on Windows so that we don't // have to add ImageBase from PE file. // FIXME: Make this the default for llvm-symbolizer. "--relative-address", #endif "--demangle", nullptr}; int RunResult = sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects); if (RunResult != 0) return false; // This report format is based on the sanitizer stack trace printer. See // sanitizer_stacktrace_printer.cc in compiler-rt. auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str()); if (!OutputBuf) return false; StringRef Output = OutputBuf.get()->getBuffer(); SmallVector<StringRef, 32> Lines; Output.split(Lines, "\n"); auto CurLine = Lines.begin(); int frame_no = 0; for (int i = 0; i < Depth; i++) { if (!Modules[i]) { OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << '\n'; continue; } // Read pairs of lines (function name and file/line info) until we // encounter empty line. for (;;) { if (CurLine == Lines.end()) return false; StringRef FunctionName = *CurLine++; if (FunctionName.empty()) break; OS << '#' << frame_no++ << ' ' << format_ptr(StackTrace[i]) << ' '; if (!FunctionName.startswith("??")) OS << FunctionName << ' '; if (CurLine == Lines.end()) return false; StringRef FileLineInfo = *CurLine++; if (!FileLineInfo.startswith("??")) OS << FileLineInfo; else OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")"; OS << "\n"; } } return true; } // Include the platform-specific parts of this class. #ifdef LLVM_ON_UNIX #include "Unix/Signals.inc" #endif #ifdef LLVM_ON_WIN32 #include "Windows/Signals.inc" #endif
{ "pile_set_name": "Github" }
/* * Copyright (c) 2012 Stefano Sabatini * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * set field order */ #include "libavutil/opt.h" #include "avfilter.h" #include "internal.h" #include "video.h" enum SetFieldMode { MODE_AUTO = -1, MODE_BFF, MODE_TFF, MODE_PROG, }; typedef struct { const AVClass *class; enum SetFieldMode mode; } SetFieldContext; #define OFFSET(x) offsetof(SetFieldContext, x) #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM static const AVOption setfield_options[] = { {"mode", "select interlace mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=MODE_AUTO}, -1, MODE_PROG, FLAGS, "mode"}, {"auto", "keep the same input field", 0, AV_OPT_TYPE_CONST, {.i64=MODE_AUTO}, INT_MIN, INT_MAX, FLAGS, "mode"}, {"bff", "mark as bottom-field-first", 0, AV_OPT_TYPE_CONST, {.i64=MODE_BFF}, INT_MIN, INT_MAX, FLAGS, "mode"}, {"tff", "mark as top-field-first", 0, AV_OPT_TYPE_CONST, {.i64=MODE_TFF}, INT_MIN, INT_MAX, FLAGS, "mode"}, {"prog", "mark as progressive", 0, AV_OPT_TYPE_CONST, {.i64=MODE_PROG}, INT_MIN, INT_MAX, FLAGS, "mode"}, {NULL} }; AVFILTER_DEFINE_CLASS(setfield); static int filter_frame(AVFilterLink *inlink, AVFrame *picref) { SetFieldContext *setfield = inlink->dst->priv; if (setfield->mode == MODE_PROG) { picref->interlaced_frame = 0; } else if (setfield->mode != MODE_AUTO) { picref->interlaced_frame = 1; picref->top_field_first = setfield->mode; } return ff_filter_frame(inlink->dst->outputs[0], picref); } static const AVFilterPad setfield_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad setfield_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter ff_vf_setfield = { .name = "setfield", .description = NULL_IF_CONFIG_SMALL("Force field for the output video frame."), .priv_size = sizeof(SetFieldContext), .priv_class = &setfield_class, .inputs = setfield_inputs, .outputs = setfield_outputs, };
{ "pile_set_name": "Github" }
// Copyright Cromwell D. Enage 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_PARAMETER_AUGMENT_PREDICATE_HPP #define BOOST_PARAMETER_AUGMENT_PREDICATE_HPP #include <boost/parameter/keyword_fwd.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/type_traits/is_lvalue_reference.hpp> #include <boost/type_traits/is_scalar.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace parameter { namespace aux { template <typename V, typename R, typename Tag> struct augment_predicate_check_consume_ref : ::boost::mpl::eval_if< ::boost::is_scalar<V> , ::boost::mpl::true_ , ::boost::mpl::eval_if< ::boost::is_same< typename Tag::qualifier , ::boost::parameter::consume_reference > , ::boost::mpl::if_< ::boost::is_lvalue_reference<R> , ::boost::mpl::false_ , ::boost::mpl::true_ > , boost::mpl::true_ > >::type { }; }}} // namespace boost::parameter::aux #include <boost/type_traits/is_const.hpp> namespace boost { namespace parameter { namespace aux { template <typename V, typename R, typename Tag> struct augment_predicate_check_out_ref : ::boost::mpl::eval_if< ::boost::is_same< typename Tag::qualifier , ::boost::parameter::out_reference > , ::boost::mpl::eval_if< ::boost::is_lvalue_reference<R> , ::boost::mpl::if_< ::boost::is_const<V> , ::boost::mpl::false_ , ::boost::mpl::true_ > , ::boost::mpl::false_ > , ::boost::mpl::true_ >::type { }; }}} // namespace boost::parameter::aux #include <boost/parameter/aux_/lambda_tag.hpp> #include <boost/mpl/apply_wrap.hpp> #include <boost/mpl/lambda.hpp> namespace boost { namespace parameter { namespace aux { template < typename Predicate , typename R , typename Tag , typename T , typename Args > class augment_predicate { typedef typename ::boost::mpl::lambda< Predicate , ::boost::parameter::aux::lambda_tag >::type _actual_predicate; public: typedef typename ::boost::mpl::eval_if< typename ::boost::mpl::if_< ::boost::parameter::aux ::augment_predicate_check_consume_ref<T,R,Tag> , ::boost::parameter::aux ::augment_predicate_check_out_ref<T,R,Tag> , ::boost::mpl::false_ >::type , ::boost::mpl::apply_wrap2<_actual_predicate,T,Args> , ::boost::mpl::false_ >::type type; }; }}} // namespace boost::parameter::aux #include <boost/parameter/config.hpp> #if defined(BOOST_PARAMETER_CAN_USE_MP11) #include <boost/mp11/integral.hpp> #include <boost/mp11/utility.hpp> #include <type_traits> namespace boost { namespace parameter { namespace aux { template <typename V, typename R, typename Tag> using augment_predicate_check_consume_ref_mp11 = ::boost::mp11::mp_if< ::std::is_scalar<V> , ::boost::mp11::mp_true , ::boost::mp11::mp_if< ::std::is_same< typename Tag::qualifier , ::boost::parameter::consume_reference > , ::boost::mp11::mp_if< ::std::is_lvalue_reference<R> , ::boost::mp11::mp_false , ::boost::mp11::mp_true > , boost::mp11::mp_true > >; template <typename V, typename R, typename Tag> using augment_predicate_check_out_ref_mp11 = ::boost::mp11::mp_if< ::std::is_same< typename Tag::qualifier , ::boost::parameter::out_reference > , ::boost::mp11::mp_if< ::std::is_lvalue_reference<R> , ::boost::mp11::mp_if< ::std::is_const<V> , ::boost::mp11::mp_false , ::boost::mp11::mp_true > , ::boost::mp11::mp_false > , ::boost::mp11::mp_true >; }}} // namespace boost::parameter::aux #include <boost/mp11/list.hpp> namespace boost { namespace parameter { namespace aux { template < typename Predicate , typename R , typename Tag , typename T , typename Args > struct augment_predicate_mp11_impl { using type = ::boost::mp11::mp_if< ::boost::mp11::mp_if< ::boost::parameter::aux ::augment_predicate_check_consume_ref_mp11<T,R,Tag> , ::boost::parameter::aux ::augment_predicate_check_out_ref_mp11<T,R,Tag> , ::boost::mp11::mp_false > , ::boost::mp11 ::mp_apply_q<Predicate,::boost::mp11::mp_list<T,Args> > , ::boost::mp11::mp_false >; }; }}} // namespace boost::parameter::aux #include <boost/parameter/aux_/has_nested_template_fn.hpp> namespace boost { namespace parameter { namespace aux { template < typename Predicate , typename R , typename Tag , typename T , typename Args > using augment_predicate_mp11 = ::boost::mp11::mp_if< ::boost::parameter::aux::has_nested_template_fn<Predicate> , ::boost::parameter::aux ::augment_predicate_mp11_impl<Predicate,R,Tag,T,Args> , ::boost::parameter::aux ::augment_predicate<Predicate,R,Tag,T,Args> >; }}} // namespace boost::parameter::aux #endif // BOOST_PARAMETER_CAN_USE_MP11 #endif // include guard
{ "pile_set_name": "Github" }
// Copyright (c) 2015-2016, Robert Escriva, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Consus nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef consus_tools_common_h_ #define consus_tools_common_h_ // STL #include <string> // e #include <e/popt.h> // consus #include <consus.h> #include "namespace.h" BEGIN_CONSUS_NAMESPACE class connect_opts { public: connect_opts(); ~connect_opts() throw (); public: const e::argparser& parser() { return m_ap; } bool validate(); consus_client* create(); private: e::argparser m_ap; private: connect_opts(const connect_opts&); connect_opts& operator = (const connect_opts&); }; bool finish(consus_client* cl, const char* prog, int64_t id, consus_returncode* status); bool locate_coordinator_lib(const char* argv0, std::string* path); END_CONSUS_NAMESPACE #endif // consus_tools_common_h_
{ "pile_set_name": "Github" }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; namespace Microsoft.AspNet.SignalR.Tests.Common { public class AsyncOnConnectedConnection : PersistentConnection { protected override async Task OnConnected(IRequest request, string connectionId) { await Task.Delay(TimeSpan.FromSeconds(1)); } } }
{ "pile_set_name": "Github" }
using System.Diagnostics; using b2xtranslator.StructuredStorage.Reader; namespace b2xtranslator.Spreadsheet.XlsFileFormat.Records { [BiffRecord(RecordType.Chart3DBarShape)] public class Chart3DBarShape : BiffRecord { public const RecordType ID = RecordType.Chart3DBarShape; public enum RiserType : byte { Rectangle = 0x0, Ellipse = 0x1 } public enum TaperType : byte { None = 0x0, TopEach = 0x1, TopMax = 0x2 } /// <summary> /// A Boolean that specifies the shape of the base of the data points in a bar or column chart group. <br/> /// MUST be a value from the following table:<br/> /// false = The base of the data point is a rectangle.<br/> /// true = The base of the data point is an ellipse. /// </summary> public RiserType riser; /// <summary> /// An unsigned integer that specifies how the data points in a bar or column chart /// group taper from base to tip. <br/> /// MUST be a value from the following table:<br/> /// 0 = The data points of the bar or column chart group do not taper. <br/> /// 1 = The data points of the bar or column chart group taper to a point at the maximum value of each data point.<br/> /// 2 = The data points of the bar or column chart group taper towards a projected point /// </summary> public TaperType taper; public Chart3DBarShape(IStreamReader reader, RecordType id, ushort length) : base(reader, id, length) { // assert that the correct record type is instantiated Debug.Assert(this.Id == ID); // initialize class members from stream this.riser = (RiserType)reader.ReadByte(); this.taper = (TaperType)reader.ReadByte(); // assert that the correct number of bytes has been read from the stream Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position); } } }
{ "pile_set_name": "Github" }
### Generated automatically from Makefile.org by Configure. ## ## Makefile for OpenSSL ## VERSION=1.0.2n MAJOR=1 MINOR=0.2 SHLIB_VERSION_NUMBER=1.0.0 SHLIB_VERSION_HISTORY= SHLIB_MAJOR=1 SHLIB_MINOR=0.0 SHLIB_EXT= PLATFORM=dist OPTIONS= no-ec_nistp_64_gcc_128 no-gmp no-jpake no-krb5 no-libunbound no-md2 no-rc5 no-rfc3779 no-sctp no-shared no-ssl-trace no-ssl2 no-store no-unit-test no-weak-ssl-ciphers no-zlib no-zlib-dynamic static-engine CONFIGURE_ARGS=dist SHLIB_TARGET= # HERE indicates where this Makefile lives. This can be used to indicate # where sub-Makefiles are expected to be. Currently has very limited usage, # and should probably not be bothered with at all. HERE=. # INSTALL_PREFIX is for package builders so that they can configure # for, say, /usr/ and yet have everything installed to /tmp/somedir/usr/. # Normally it is left empty. INSTALL_PREFIX= INSTALLTOP=/usr/local/ssl # Do not edit this manually. Use Configure --openssldir=DIR do change this! OPENSSLDIR=/usr/local/ssl # NO_IDEA - Define to build without the IDEA algorithm # NO_RC4 - Define to build without the RC4 algorithm # NO_RC2 - Define to build without the RC2 algorithm # THREADS - Define when building with threads, you will probably also need any # system defines as well, i.e. _REENTERANT for Solaris 2.[34] # TERMIO - Define the termio terminal subsystem, needed if sgtty is missing. # TERMIOS - Define the termios terminal subsystem, Silicon Graphics. # LONGCRYPT - Define to use HPUX 10.x's long password modification to crypt(3). # DEVRANDOM - Give this the value of the 'random device' if your OS supports # one. 32 bytes will be read from this when the random # number generator is initalised. # SSL_FORBID_ENULL - define if you want the server to be not able to use the # NULL encryption ciphers. # # LOCK_DEBUG - turns on lots of lock debug output :-) # REF_CHECK - turn on some xyz_free() assertions. # REF_PRINT - prints some stuff on structure free. # CRYPTO_MDEBUG - turns on my 'memory leak' detecting stuff # MFUNC - Make all Malloc/Free/Realloc calls call # CRYPTO_malloc/CRYPTO_free/CRYPTO_realloc which can be setup to # call application defined callbacks via CRYPTO_set_mem_functions() # MD5_ASM needs to be defined to use the x86 assembler for MD5 # SHA1_ASM needs to be defined to use the x86 assembler for SHA1 # RMD160_ASM needs to be defined to use the x86 assembler for RIPEMD160 # Do not define B_ENDIAN or L_ENDIAN if 'unsigned long' == 8. It must # equal 4. # PKCS1_CHECK - pkcs1 tests. CC= cc CFLAG= -O DEPFLAG= -DOPENSSL_NO_EC_NISTP_64_GCC_128 -DOPENSSL_NO_GMP -DOPENSSL_NO_JPAKE -DOPENSSL_NO_LIBUNBOUND -DOPENSSL_NO_MD2 -DOPENSSL_NO_RC5 -DOPENSSL_NO_RFC3779 -DOPENSSL_NO_SCTP -DOPENSSL_NO_SSL_TRACE -DOPENSSL_NO_SSL2 -DOPENSSL_NO_STORE -DOPENSSL_NO_UNIT_TEST -DOPENSSL_NO_WEAK_SSL_CIPHERS PEX_LIBS= EX_LIBS= EXE_EXT= ARFLAGS= AR= ar $(ARFLAGS) r RANLIB= /usr/bin/ranlib RC= windres NM= nm PERL= /usr/bin/perl TAR= tar TARFLAGS= --no-recursion MAKEDEPPROG=makedepend LIBDIR=lib # We let the C compiler driver to take care of .s files. This is done in # order to be excused from maintaining a separate set of architecture # dependent assembler flags. E.g. if you throw -mcpu=ultrasparc at SPARC # gcc, then the driver will automatically translate it to -xarch=v8plus # and pass it down to assembler. AS=$(CC) -c ASFLAG=$(CFLAG) # For x86 assembler: Set PROCESSOR to 386 if you want to support # the 80386. PROCESSOR= # CPUID module collects small commonly used assembler snippets CPUID_OBJ= mem_clr.o BN_ASM= bn_asm.o EC_ASM= DES_ENC= des_enc.o fcrypt_b.o AES_ENC= aes_core.o aes_cbc.o BF_ENC= bf_enc.o CAST_ENC= c_enc.o RC4_ENC= rc4_enc.o rc4_skey.o RC5_ENC= rc5_enc.o MD5_ASM_OBJ= SHA1_ASM_OBJ= RMD160_ASM_OBJ= WP_ASM_OBJ= wp_block.o CMLL_ENC= camellia.o cmll_misc.o cmll_cbc.o MODES_ASM_OBJ= ENGINES_ASM_OBJ= PERLASM_SCHEME= # KRB5 stuff KRB5_INCLUDES= LIBKRB5= # Zlib stuff ZLIB_INCLUDE= LIBZLIB= # TOP level FIPS install directory. FIPSDIR=/usr/local/ssl/fips-2.0 # This is the location of fipscanister.o and friends. # The FIPS module build will place it $(INSTALLTOP)/lib # but since $(INSTALLTOP) can only take the default value # when the module is built it will be in /usr/local/ssl/lib # $(INSTALLTOP) for this build may be different so hard # code the path. FIPSLIBDIR= # The location of the library which contains fipscanister.o # normally it will be libcrypto unless fipsdso is set in which # case it will be libfips. If not compiling in FIPS mode at all # this is empty making it a useful test for a FIPS compile. FIPSCANLIB= # Shared library base address. Currently only used on Windows. # BASEADDR=0xFB00000 DIRS= crypto ssl engines apps test tools ENGDIRS= ccgost SHLIBDIRS= crypto ssl # dirs in crypto to build SDIRS= \ objects \ md4 md5 sha mdc2 hmac ripemd whrlpool sm3 \ des aes rc2 rc4 idea bf cast camellia seed sm4 modes \ bn ec rsa dsa ecdsa dh ecdh dso sm2 engine \ buffer bio stack lhash rand err \ evp asn1 pem x509 x509v3 conf txt_db pkcs7 pkcs12 comp ocsp ui krb5 \ cms pqueue ts srp cmac # keep in mind that the above list is adjusted by ./Configure # according to no-xxx arguments... # tests to perform. "alltests" is a special word indicating that all tests # should be performed. TESTS = alltests MAKEFILE= Makefile MANDIR=$(OPENSSLDIR)/man MAN1=1 MAN3=3 MANSUFFIX= HTMLSUFFIX=html HTMLDIR=$(OPENSSLDIR)/html SHELL=/bin/sh TOP= . ONEDIRS=out tmp EDIRS= times doc bugs util include certs ms shlib mt demos perl sf dep VMS WDIRS= windows LIBS= libcrypto.a libssl.a SHARED_CRYPTO=libcrypto$(SHLIB_EXT) SHARED_SSL=libssl$(SHLIB_EXT) SHARED_LIBS= SHARED_LIBS_LINK_EXTS= SHARED_LDFLAGS= GENERAL= Makefile BASENAME= openssl NAME= $(BASENAME)-$(VERSION) TARFILE= ../$(NAME).tar EXHEADER= e_os2.h HEADER= e_os.h all: Makefile build_all # as we stick to -e, CLEARENV ensures that local variables in lower # Makefiles remain local and variable. $${VAR+VAR} is tribute to Korn # shell, which [annoyingly enough] terminates unset with error if VAR # is not present:-( TOP= && unset TOP is tribute to HP-UX /bin/sh, # which terminates unset with error if no variable was present:-( CLEARENV= TOP= && unset TOP $${LIB+LIB} $${LIBS+LIBS} \ $${INCLUDE+INCLUDE} $${INCLUDES+INCLUDES} \ $${DIR+DIR} $${DIRS+DIRS} $${SRC+SRC} \ $${LIBSRC+LIBSRC} $${LIBOBJ+LIBOBJ} $${ALL+ALL} \ $${EXHEADER+EXHEADER} $${HEADER+HEADER} \ $${GENERAL+GENERAL} $${CFLAGS+CFLAGS} \ $${ASFLAGS+ASFLAGS} $${AFLAGS+AFLAGS} \ $${LDCMD+LDCMD} $${LDFLAGS+LDFLAGS} $${SCRIPTS+SCRIPTS} \ $${SHAREDCMD+SHAREDCMD} $${SHAREDFLAGS+SHAREDFLAGS} \ $${SHARED_LIB+SHARED_LIB} $${LIBEXTRAS+LIBEXTRAS} \ $${APPS+APPS} # LC_ALL=C ensures that error [and other] messages are delivered in # same language for uniform treatment. BUILDENV= LC_ALL=C PLATFORM='$(PLATFORM)' PROCESSOR='$(PROCESSOR)'\ CC='$(CC)' CFLAG='$(CFLAG)' \ AS='$(CC)' ASFLAG='$(CFLAG) -c' \ AR='$(AR)' NM='$(NM)' RANLIB='$(RANLIB)' \ RC='$(RC)' \ CROSS_COMPILE='$(CROSS_COMPILE)' \ PERL='$(PERL)' ENGDIRS='$(ENGDIRS)' \ SDIRS='$(SDIRS)' LIBRPATH='$(INSTALLTOP)/$(LIBDIR)' \ INSTALL_PREFIX='$(INSTALL_PREFIX)' \ INSTALLTOP='$(INSTALLTOP)' OPENSSLDIR='$(OPENSSLDIR)' \ LIBDIR='$(LIBDIR)' \ MAKEDEPEND='$$$${TOP}/util/domd $$$${TOP} -MD $(MAKEDEPPROG)' \ DEPFLAG='-DOPENSSL_NO_DEPRECATED $(DEPFLAG)' \ MAKEDEPPROG='$(MAKEDEPPROG)' \ SHARED_LDFLAGS='$(SHARED_LDFLAGS)' \ KRB5_INCLUDES='$(KRB5_INCLUDES)' LIBKRB5='$(LIBKRB5)' \ ZLIB_INCLUDE='$(ZLIB_INCLUDE)' LIBZLIB='$(LIBZLIB)' \ EXE_EXT='$(EXE_EXT)' SHARED_LIBS='$(SHARED_LIBS)' \ SHLIB_EXT='$(SHLIB_EXT)' SHLIB_TARGET='$(SHLIB_TARGET)' \ PEX_LIBS='$(PEX_LIBS)' EX_LIBS='$(EX_LIBS)' \ CPUID_OBJ='$(CPUID_OBJ)' BN_ASM='$(BN_ASM)' \ EC_ASM='$(EC_ASM)' DES_ENC='$(DES_ENC)' \ AES_ENC='$(AES_ENC)' CMLL_ENC='$(CMLL_ENC)' \ BF_ENC='$(BF_ENC)' CAST_ENC='$(CAST_ENC)' \ RC4_ENC='$(RC4_ENC)' RC5_ENC='$(RC5_ENC)' \ SHA1_ASM_OBJ='$(SHA1_ASM_OBJ)' \ MD5_ASM_OBJ='$(MD5_ASM_OBJ)' \ RMD160_ASM_OBJ='$(RMD160_ASM_OBJ)' \ WP_ASM_OBJ='$(WP_ASM_OBJ)' \ MODES_ASM_OBJ='$(MODES_ASM_OBJ)' \ ENGINES_ASM_OBJ='$(ENGINES_ASM_OBJ)' \ PERLASM_SCHEME='$(PERLASM_SCHEME)' \ FIPSLIBDIR='${FIPSLIBDIR}' \ FIPSDIR='${FIPSDIR}' \ FIPSCANLIB="$${FIPSCANLIB:-$(FIPSCANLIB)}" \ THIS=$${THIS:-$@} MAKEFILE=Makefile MAKEOVERRIDES= # MAKEOVERRIDES= effectively "equalizes" GNU-ish and SysV-ish make flavors, # which in turn eliminates ambiguities in variable treatment with -e. # BUILD_CMD is a generic macro to build a given target in a given # subdirectory. The target must be given through the shell variable # `target' and the subdirectory to build in must be given through `dir'. # This macro shouldn't be used directly, use RECURSIVE_BUILD_CMD or # BUILD_ONE_CMD instead. # # BUILD_ONE_CMD is a macro to build a given target in a given # subdirectory if that subdirectory is part of $(DIRS). It requires # exactly the same shell variables as BUILD_CMD. # # RECURSIVE_BUILD_CMD is a macro to build a given target in all # subdirectories defined in $(DIRS). It requires that the target # is given through the shell variable `target'. BUILD_CMD= if [ -d "$$dir" ]; then \ ( cd $$dir && echo "making $$target in $$dir..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. DIR=$$dir $$target \ ) || exit 1; \ fi RECURSIVE_BUILD_CMD=for dir in $(DIRS); do $(BUILD_CMD); done BUILD_ONE_CMD=\ if expr " $(DIRS) " : ".* $$dir " >/dev/null 2>&1; then \ $(BUILD_CMD); \ fi reflect: @[ -n "$(THIS)" ] && $(CLEARENV) && $(MAKE) $(THIS) -e $(BUILDENV) sub_all: build_all build_all: build_libs build_apps build_tests build_tools build_libs: build_libcrypto build_libssl openssl.pc build_libcrypto: build_crypto build_engines libcrypto.pc build_libssl: build_ssl libssl.pc build_crypto: @dir=crypto; target=all; $(BUILD_ONE_CMD) build_ssl: build_crypto @dir=ssl; target=all; $(BUILD_ONE_CMD) build_engines: build_crypto @dir=engines; target=all; $(BUILD_ONE_CMD) build_apps: build_libs @dir=apps; target=all; $(BUILD_ONE_CMD) build_tests: build_libs @dir=test; target=all; $(BUILD_ONE_CMD) build_tools: build_libs @dir=tools; target=all; $(BUILD_ONE_CMD) all_testapps: build_libs build_testapps build_testapps: @dir=crypto; target=testapps; $(BUILD_ONE_CMD) fips_premain_dso$(EXE_EXT): libcrypto.a [ -z "$(FIPSCANLIB)" ] || $(CC) $(CFLAG) -Iinclude \ -DFINGERPRINT_PREMAIN_DSO_LOAD -o $@ \ $(FIPSLIBDIR)fips_premain.c $(FIPSLIBDIR)fipscanister.o \ libcrypto.a $(EX_LIBS) libcrypto$(SHLIB_EXT): libcrypto.a fips_premain_dso$(EXE_EXT) @if [ "$(SHLIB_TARGET)" != "" ]; then \ if [ "$(FIPSCANLIB)" = "libcrypto" ]; then \ FIPSLD_LIBCRYPTO=libcrypto.a ; \ FIPSLD_CC="$(CC)"; CC=$(FIPSDIR)/bin/fipsld; \ export CC FIPSLD_CC FIPSLD_LIBCRYPTO; \ fi; \ $(MAKE) -e SHLIBDIRS=crypto CC="$${CC:-$(CC)}" build-shared && \ (touch -c fips_premain_dso$(EXE_EXT) || :); \ else \ echo "There's no support for shared libraries on this platform" >&2; \ exit 1; \ fi libssl$(SHLIB_EXT): libcrypto$(SHLIB_EXT) libssl.a @if [ "$(SHLIB_TARGET)" != "" ]; then \ $(MAKE) SHLIBDIRS=ssl SHLIBDEPS='-lcrypto' build-shared; \ else \ echo "There's no support for shared libraries on this platform" >&2; \ exit 1; \ fi clean-shared: @set -e; for i in $(SHLIBDIRS); do \ if [ -n "$(SHARED_LIBS_LINK_EXTS)" ]; then \ tmp="$(SHARED_LIBS_LINK_EXTS)"; \ for j in $${tmp:-x}; do \ ( set -x; rm -f lib$$i$$j ); \ done; \ fi; \ ( set -x; rm -f lib$$i$(SHLIB_EXT) ); \ if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \ ( set -x; rm -f cyg$$i$(SHLIB_EXT) lib$$i$(SHLIB_EXT).a ); \ fi; \ done link-shared: @ set -e; for i in $(SHLIBDIRS); do \ $(MAKE) -f $(HERE)/Makefile.shared -e $(BUILDENV) \ LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \ LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \ symlink.$(SHLIB_TARGET); \ libs="$$libs -l$$i"; \ done build-shared: do_$(SHLIB_TARGET) link-shared do_$(SHLIB_TARGET): @ set -e; libs='-L. $(SHLIBDEPS)'; for i in $(SHLIBDIRS); do \ if [ "$$i" = "ssl" -a -n "$(LIBKRB5)" ]; then \ libs="$(LIBKRB5) $$libs"; \ fi; \ $(CLEARENV) && $(MAKE) -f Makefile.shared -e $(BUILDENV) \ LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \ LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \ LIBDEPS="$$libs $(EX_LIBS)" \ link_a.$(SHLIB_TARGET); \ libs="-l$$i $$libs"; \ done libcrypto.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo 'enginesdir=$${libdir}/engines'; \ echo ''; \ echo 'Name: OpenSSL-libcrypto'; \ echo 'Description: OpenSSL cryptography library'; \ echo 'Version: '$(VERSION); \ echo 'Requires: '; \ echo 'Libs: -L$${libdir} -lcrypto'; \ echo 'Libs.private: $(EX_LIBS)'; \ echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libcrypto.pc libssl.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo ''; \ echo 'Name: OpenSSL-libssl'; \ echo 'Description: Secure Sockets Layer and cryptography libraries'; \ echo 'Version: '$(VERSION); \ echo 'Requires.private: libcrypto'; \ echo 'Libs: -L$${libdir} -lssl'; \ echo 'Libs.private: $(EX_LIBS)'; \ echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libssl.pc openssl.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo ''; \ echo 'Name: OpenSSL'; \ echo 'Description: Secure Sockets Layer and cryptography libraries and tools'; \ echo 'Version: '$(VERSION); \ echo 'Requires: libssl libcrypto' ) > openssl.pc Makefile: Makefile.org Configure config @echo "Makefile is older than Makefile.org, Configure or config." @echo "Reconfigure the source tree (via './config' or 'perl Configure'), please." @false libclean: rm -f *.map *.so *.so.* *.dylib *.dll engines/*.so engines/*.dll engines/*.dylib *.a engines/*.a */lib */*/lib clean: libclean rm -f shlib/*.o *.o core a.out fluff rehash.time testlog make.log cctest cctest.c @set -e; target=clean; $(RECURSIVE_BUILD_CMD) rm -f $(LIBS) rm -f openssl.pc libssl.pc libcrypto.pc rm -f speed.* .pure rm -f $(TARFILE) @set -e; for i in $(ONEDIRS) ;\ do \ rm -fr $$i/*; \ done distclean: clean -$(RM) `find . -name .git -prune -o -type l -print` $(RM) apps/CA.pl $(RM) test/evptests.txt test/newkey.pem test/testkey.pem test/testreq.pem $(RM) tools/c_rehash $(RM) crypto/opensslconf.h $(RM) Makefile Makefile.bak makefile.one: files $(PERL) util/mk1mf.pl >makefile.one; \ sh util/do_ms.sh files: $(PERL) $(TOP)/util/files.pl Makefile > $(TOP)/MINFO @set -e; target=files; $(RECURSIVE_BUILD_CMD) links: @$(PERL) $(TOP)/util/mkdir-p.pl include/openssl @$(PERL) $(TOP)/util/mklink.pl include/openssl $(EXHEADER) @set -e; target=links; $(RECURSIVE_BUILD_CMD) gentests: @(cd test && echo "generating dummy tests (if needed)..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on generate ); dclean: rm -rf *.bak include/openssl certs/.0 @set -e; target=dclean; $(RECURSIVE_BUILD_CMD) rehash: rehash.time rehash.time: certs apps @if [ -z "$(CROSS_COMPILE)" ]; then \ (OPENSSL="`pwd`/util/opensslwrap.sh"; \ [ -x "apps/openssl.exe" ] && OPENSSL="apps/openssl.exe" || :; \ OPENSSL_DEBUG_MEMORY=on; \ export OPENSSL OPENSSL_DEBUG_MEMORY; \ $(PERL) tools/c_rehash certs/demo) && \ touch rehash.time; \ else :; fi test: tests tests: rehash @(cd test && echo "testing..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on OPENSSL_CONF=../apps/openssl.cnf tests ); OPENSSL_CONF=apps/openssl.cnf util/opensslwrap.sh version -a report: @$(PERL) util/selftest.pl update: errors stacks util/libeay.num util/ssleay.num TABLE @set -e; target=update; $(RECURSIVE_BUILD_CMD) depend: @set -e; target=depend; $(RECURSIVE_BUILD_CMD) lint: @set -e; target=lint; $(RECURSIVE_BUILD_CMD) tags: rm -f TAGS find . -name '[^.]*.[ch]' | xargs etags -a errors: $(PERL) util/ck_errf.pl -strict */*.c */*/*.c $(PERL) util/mkerr.pl -recurse -write (cd engines; $(MAKE) PERL=$(PERL) errors) stacks: $(PERL) util/mkstack.pl -write util/libeay.num:: $(PERL) util/mkdef.pl crypto update util/ssleay.num:: $(PERL) util/mkdef.pl ssl update TABLE: Configure (echo 'Output of `Configure TABLE'"':"; \ $(PERL) Configure TABLE) > TABLE # Build distribution tar-file. As the list of files returned by "find" is # pretty long, on several platforms a "too many arguments" error or similar # would occur. Therefore the list of files is temporarily stored into a file # and read directly, requiring GNU-Tar. Call "make TAR=gtar dist" if the normal # tar does not support the --files-from option. TAR_COMMAND=$(TAR) $(TARFLAGS) --files-from $(TARFILE).list \ --owner 0 --group 0 \ --transform 's|^|$(NAME)/|' \ -cvf - $(TARFILE).list: find * \! -name STATUS \! -name TABLE \! -name '*.o' \! -name '*.a' \ \! -name '*.so' \! -name '*.so.*' \! -name 'openssl' \ \( \! -name '*test' -o -name bctest -o -name pod2mantest \) \ \! -name '.#*' \! -name '*~' \! -type l \ | sort > $(TARFILE).list tar: $(TARFILE).list find . -type d -print | xargs chmod 755 find . -type f -print | xargs chmod a+r find . -type f -perm -0100 -print | xargs chmod a+x $(TAR_COMMAND) | gzip --best > $(TARFILE).gz rm -f $(TARFILE).list ls -l $(TARFILE).gz tar-snap: $(TARFILE).list $(TAR_COMMAND) > $(TARFILE) rm -f $(TARFILE).list ls -l $(TARFILE) dist: $(PERL) Configure dist @$(MAKE) SDIRS='$(SDIRS)' clean @$(MAKE) TAR='$(TAR)' TARFLAGS='$(TARFLAGS)' $(DISTTARVARS) tar install: all install_docs install_sw install_sw: @$(PERL) $(TOP)/util/mkdir-p.pl $(INSTALL_PREFIX)$(INSTALLTOP)/bin \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR) \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig \ $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl \ $(INSTALL_PREFIX)$(OPENSSLDIR)/misc \ $(INSTALL_PREFIX)$(OPENSSLDIR)/certs \ $(INSTALL_PREFIX)$(OPENSSLDIR)/private @set -e; headerlist="$(EXHEADER)"; for i in $$headerlist;\ do \ (cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \ done; @set -e; target=install; $(RECURSIVE_BUILD_CMD) @set -e; liblist="$(LIBS)"; for i in $$liblist ;\ do \ if [ -f "$$i" ]; then \ ( echo installing $$i; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ $(RANLIB) $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i ); \ fi; \ done; @set -e; if [ -n "$(SHARED_LIBS)" ]; then \ tmp="$(SHARED_LIBS)"; \ for i in $${tmp:-x}; \ do \ if [ -f "$$i" -o -f "$$i.a" ]; then \ ( echo installing $$i; \ if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \ c=`echo $$i | sed 's/^lib\(.*\)\.dll\.a/cyg\1-$(SHLIB_VERSION_NUMBER).dll/'`; \ cp $$c $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \ chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \ else \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 555 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \ fi ); \ if expr $(PLATFORM) : 'mingw' > /dev/null; then \ ( case $$i in \ *crypto*) i=libeay32.dll;; \ *ssl*) i=ssleay32.dll;; \ esac; \ echo installing $$i; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \ chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i ); \ fi; \ fi; \ done; \ ( here="`pwd`"; \ cd $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR); \ $(MAKE) -f $$here/Makefile HERE="$$here" link-shared ); \ if [ "$(INSTALLTOP)" != "/usr" ]; then \ echo 'OpenSSL shared libraries have been installed in:'; \ echo ' $(INSTALLTOP)'; \ echo ''; \ sed -e '1,/^$$/d' doc/openssl-shared.txt; \ fi; \ fi cp libcrypto.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libcrypto.pc cp libssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libssl.pc cp openssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/openssl.pc install_html_docs: here="`pwd`"; \ filecase=; \ case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \ filecase=-i; \ esac; \ for subdir in apps crypto ssl; do \ mkdir -p $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \ for i in doc/$$subdir/*.pod; do \ fn=`basename $$i .pod`; \ echo "installing html/$$fn.$(HTMLSUFFIX)"; \ cat $$i \ | sed -r 's/L<([^)]*)(\([0-9]\))?\|([^)]*)(\([0-9]\))?>/L<\1|\3>/g' \ | pod2html --podroot=doc --htmlroot=.. --podpath=apps:crypto:ssl \ | sed -r 's/<!DOCTYPE.*//g' \ > $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir/$$fn.$(HTMLSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ grep -v $$filecase "^$$fn\$$" | \ (cd $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$(HTMLSUFFIX) "$$n".$(HTMLSUFFIX); \ done); \ done; \ done install_docs: @$(PERL) $(TOP)/util/mkdir-p.pl \ $(INSTALL_PREFIX)$(MANDIR)/man1 \ $(INSTALL_PREFIX)$(MANDIR)/man3 \ $(INSTALL_PREFIX)$(MANDIR)/man5 \ $(INSTALL_PREFIX)$(MANDIR)/man7 @pod2man="`cd ./util; ./pod2mantest $(PERL)`"; \ here="`pwd`"; \ filecase=; \ case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \ filecase=-i; \ esac; \ set -e; for i in doc/apps/*.pod; do \ fn=`basename $$i .pod`; \ sec=`$(PERL) util/extract-section.pl 1 < $$i`; \ echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \ (cd `$(PERL) util/dirname.pl $$i`; \ sh -c "$$pod2man \ --section=$$sec --center=OpenSSL \ --release=$(VERSION) `basename $$i`") \ > $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ (grep -v $$filecase "^$$fn\$$"; true) | \ (grep -v "[ ]"; true) | \ (cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \ done); \ done; \ set -e; for i in doc/crypto/*.pod doc/ssl/*.pod; do \ fn=`basename $$i .pod`; \ sec=`$(PERL) util/extract-section.pl 3 < $$i`; \ echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \ (cd `$(PERL) util/dirname.pl $$i`; \ sh -c "$$pod2man \ --section=$$sec --center=OpenSSL \ --release=$(VERSION) `basename $$i`") \ > $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ (grep -v $$filecase "^$$fn\$$"; true) | \ (grep -v "[ ]"; true) | \ (cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \ done); \ done # DO NOT DELETE THIS LINE -- make depend depends on it.
{ "pile_set_name": "Github" }
<!doctype> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Tableless - Anatomia de um plugin jQuery</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="jquery.marcaTexto.js"></script> <link rel="stylesheet" href="exemplo.css" media="screen" type="text/css" /> <style type="text/css"> span.marcaTexto { position: relative; z-index: 180!important; -moz-box-shadow: 0 0 1em #889; -webkit-box-shadow: 0 0 1em #888; box-shadow: 0 0 1em #889; padding: 4px; } </style> </head> <body> <h1>Exemplo de plugin: marcaTexto</h1> <p><strong>Conferir o exemplo <a href="fila.html">jQuery.fila</a></strong> ou <a href="http://www.tableless.com.br/anatomia-de-um-plugin-jquery">Voltar para o post Anatomia de um plugin jQuery</a></p> <form method="post" action="index.html"> <label>Localizar no texto: <input type="text" name="busca" id="busca" size="30" /></label> </form> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ut tortor a lacus lobortis bibendum. Pellentesque ultricies odio id velit sodales quis condimentum turpis vestibulum. Mauris velit lectus, ultricies in mollis ac, commodo sed urna. Nunc volutpat ultricies sapien id rutrum. Donec at nisi id quam malesuada blandit at eget nulla. Proin et arcu vel risus commodo faucibus sed nec eros. Aenean sollicitudin, libero vitae semper ornare, justo dolor iaculis est, vitae luctus mauris mauris eu augue. Aenean blandit, massa at facilisis laoreet, nulla lectus semper turpis, a laoreet justo arcu sed sapien. Vivamus vel purus quis nisi tempus cursus. Quisque at tortor urna, vitae convallis nisi. Quisque tellus magna, venenatis facilisis fermentum at, egestas sit amet lectus. Cras sed sem leo, nec rutrum odio. Nullam non lacus ac nulla varius tempor. Duis vitae semper quam. Donec in mi ipsum, a gravida nibh. </p> <p> Maecenas in dolor purus. Suspendisse potenti. Phasellus eget libero lacus. Nam nec aliquet elit. Etiam porta quam nec libero suscipit pharetra. Vestibulum eget magna felis. Cras luctus, sem vel tincidunt interdum, tortor felis molestie velit, ut sagittis justo ipsum vel urna. In vel dolor nunc, eu condimentum diam. Maecenas convallis ultricies nunc, at ultrices enim lobortis ut. In ut neque eu velit ultricies adipiscing ac sit amet justo. Nunc urna turpis, commodo sit amet ultrices a, tristique vel magna. Cras sed augue nec orci malesuada varius vitae nec neque. Vivamus bibendum turpis eu diam accumsan ac porta risus pellentesque. Aliquam egestas, lacus porttitor eleifend adipiscing, nibh diam volutpat tortor, quis tempus elit ipsum ut dolor. In at pharetra erat. Morbi eleifend viverra massa, quis mollis purus sagittis nec. Ut placerat placerat lacinia. Phasellus quis pulvinar eros. Etiam ultricies massa vel risus volutpat luctus. Duis fermentum imperdiet faucibus. </p> <p> Nam laoreet condimentum est et tristique. Praesent condimentum arcu ut orci feugiat quis luctus velit luctus. Integer euismod velit et tortor molestie auctor. Phasellus facilisis, arcu et ullamcorper dictum, purus ipsum bibendum nisi, in convallis massa ante quis nibh. Quisque sollicitudin vulputate egestas. Nulla fermentum fringilla tristique. Donec vulputate ullamcorper blandit. Praesent nec congue elit. Praesent mi ligula, bibendum non fermentum semper, sagittis eu mauris. Maecenas consectetur, felis quis fringilla cursus, sem diam rutrum urna, sit amet cursus augue nibh id quam. Sed tincidunt condimentum sem, at euismod est mollis sit amet. Nulla facilisi. Etiam nisi libero, suscipit id pretium non, mollis at ligula. Fusce dapibus sem id augue ultricies vel dignissim justo commodo. Integer viverra vulputate sodales. </p> <p> Donec vitae leo felis. Quisque vel eros nec orci accumsan tincidunt. Proin cursus, metus eget pharetra adipiscing, leo turpis pulvinar leo, sed interdum mi metus id urna. Vestibulum eget posuere sapien. Vestibulum id turpis sit amet arcu commodo porta vitae in ante. In quis massa eros, nec interdum enim. Etiam eu facilisis quam. In velit odio, rhoncus a feugiat et, varius eu augue. Donec faucibus sodales libero tincidunt sagittis. Integer erat nisi, varius id sodales non, feugiat ut urna. Vestibulum dolor sem, adipiscing eget eleifend eleifend, sodales id quam. Morbi molestie augue vestibulum arcu consequat suscipit. Donec lorem velit, dapibus nec suscipit et, ornare egestas justo. Etiam et turpis lectus. Nam ornare, purus vel suscipit tempus, metus tortor venenatis tortor, nec tincidunt turpis sem sit amet velit. Nunc sit amet velit justo, vel facilisis nisi. Mauris tempor fringilla pulvinar. Donec nibh elit, volutpat eu hendrerit sed, bibendum ac nibh. </p> <p> Nullam mollis eros nec tellus commodo posuere. Integer cursus nibh vitae tortor posuere condimentum. Fusce leo tellus, tincidunt in rhoncus non, varius vel arcu. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi in felis sed nunc aliquam imperdiet. Ut a dui massa, a commodo nunc. Suspendisse eu magna sit amet diam dapibus mattis. Suspendisse pellentesque tempor dui, eu hendrerit arcu dictum id. Duis tincidunt ipsum vitae nibh ultricies vel sollicitudin odio sodales. Fusce feugiat nisi eu libero pretium eu sollicitudin magna placerat. </p> <p> Mauris at lacus leo. Maecenas tempor est non urna dapibus hendrerit sed ut nisi. Integer elit elit, mattis eget mattis sed, commodo nec risus. Ut id lectus in diam porta gravida eu eget nibh. Phasellus erat ligula, pretium id adipiscing nec, malesuada ut nibh. Nulla lobortis ultricies mi, sed scelerisque lorem gravida vel. Quisque quis felis eu est ullamcorper convallis sed nec augue. Praesent fermentum ultrices nisl vitae elementum. Proin quis sodales lorem. Fusce nulla lectus, viverra eu consequat nec, vulputate dignissim neque. Nullam nec orci vitae leo vestibulum tincidunt ut a nunc. Fusce sapien elit, imperdiet sit amet congue quis, lacinia id mauris. Donec sem orci, iaculis vel luctus ac, euismod non sapien. Etiam ut odio diam. Praesent aliquam viverra justo et scelerisque. Morbi nec leo in ante egestas porttitor. Quisque iaculis dapibus massa, quis elementum dui auctor non. Curabitur non metus nibh, et gravida diam. Nunc tincidunt metus quis risus aliquam at tempor mi vulputate. Proin vel purus sit amet purus condimentum pellentesque. </p> <p> Nulla facilisi. Praesent et est at neque eleifend lacinia ac non ligula. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed dui leo, semper a auctor id, blandit scelerisque ligula. Aenean neque felis, ornare at laoreet molestie, porta vel ante. In scelerisque sollicitudin dignissim. In hac habitasse platea dictumst. In imperdiet imperdiet nulla, faucibus iaculis ipsum adipiscing sodales. In hac habitasse platea dictumst. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut vel augue nisi, eu vulputate dolor. Aenean non dictum diam. Sed et nisi eu massa eleifend pellentesque quis a erat. Integer aliquet, mi et bibendum iaculis, risus lacus mollis odio, a varius orci dolor sed tortor. Duis non lectus ante. Integer pulvinar, justo ac vulputate scelerisque, lectus ligula aliquam velit, id commodo ante justo et velit. Nullam dictum justo nec ligula rhoncus id suscipit purus convallis. Pellentesque vitae congue urna. Ut ornare aliquam turpis, nec euismod mauris ultrices eu. Mauris vulputate, arcu sit amet consectetur lacinia, eros ligula pellentesque mauris, eu venenatis purus augue cursus diam. </p> <p> Phasellus porttitor risus purus, non posuere augue. Nulla posuere tellus eu justo tristique eu tristique sem viverra. Nulla velit massa, adipiscing non tincidunt ut, cursus eget mi. Maecenas sed lacus magna, in ornare mi. Nulla adipiscing porta felis ut fringilla. Cras dapibus tellus sed nisi dignissim at accumsan metus pharetra. Vivamus mattis est id enim tempus dapibus. Quisque lorem lectus, vestibulum in pharetra eget, laoreet at nulla. Fusce sed lobortis tortor. Maecenas varius luctus faucibus. Fusce ornare ipsum ac diam viverra convallis. Aenean congue dignissim blandit. Sed urna dui, ultrices ut pretium vel, varius ut dolor. Vivamus placerat, mi nec mattis mattis, tortor est blandit leo, cursus faucibus nisi tortor ultrices turpis. Vestibulum libero libero, dapibus eu vestibulum ac, consectetur vel metus. </p> <p> Integer at urna eget turpis elementum tempus a sit amet nulla. Sed bibendum nulla ac neque laoreet et facilisis eros facilisis. Duis tempor, ante vitae facilisis ullamcorper, felis lacus rhoncus ipsum, a tristique nisi urna sed ante. Integer eget arcu sit amet erat rhoncus tristique. Ut ornare odio id neque condimentum in varius nisi ultrices. In ac velit id urna facilisis pellentesque auctor ut felis. Sed id enim erat, et cursus erat. Sed nec erat orci, id elementum dui. Fusce sit amet dui ac libero aliquet lobortis. Etiam accumsan pharetra dui ut eleifend. In facilisis, urna luctus elementum volutpat, ligula nisl convallis massa, eu varius urna nulla imperdiet ante. Maecenas mollis molestie lectus, in pellentesque elit dignissim eget. Vivamus a porttitor lacus. Nulla scelerisque, nisi vitae ullamcorper mattis, sem mauris condimentum ligula, sed scelerisque ante massa vel odio. Donec id turpis nibh, ut gravida orci. Suspendisse interdum euismod felis, non posuere justo condimentum vitae. </p> <p> Phasellus a tempus libero. Mauris quam lectus, vulputate sed porttitor ac, pharetra ac neque. Donec dictum ligula ut nunc commodo varius. Vivamus sapien tortor, elementum et tincidunt eu, auctor a urna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nibh diam, rhoncus eget viverra et, lobortis at ligula. Integer fermentum pharetra dui id dapibus. Cras eu nisl nec leo sagittis porttitor. Quisque sagittis aliquet eros imperdiet dictum. Etiam consequat justo ut sem ornare gravida. Etiam accumsan lacinia fermentum. Donec orci risus, blandit ut pretium a, tincidunt a neque. Sed non purus sem, at elementum orci. Quisque porttitor commodo tempus. Aliquam purus odio, venenatis eu rutrum eget, hendrerit nec justo. Sed magna turpis, fermentum vel eleifend vitae, cursus eu massa. Cras eu convallis felis. Phasellus condimentum ante a nibh ultrices ac commodo purus condimentum. </p> <script type="text/javascript"> $('#busca') .focus() .keyup(function(){ // limpa marcações anteriores $('.marcaTexto').each(function(){ $(this).after( $(this).html() ); $(this).remove(); }); // ativa o plugin quando o termo possui mais de um caracter if( $(this).val().length > 1 ) { $('p').marcaTexto($(this).val()); } }); </script> </body> </html>
{ "pile_set_name": "Github" }
package com.java110.intf.common; import com.java110.config.feign.FeignConfiguration; import com.java110.dto.machine.CarInoutDetailDto; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; /** * @ClassName ICarInoutDetailInnerServiceSMO * @Description 进出场详情接口类 * @Author wuxw * @Date 2019/4/24 9:04 * @Version 1.0 * add by wuxw 2019/4/24 **/ @FeignClient(name = "common-service", configuration = {FeignConfiguration.class}) @RequestMapping("/carInoutDetailApi") public interface ICarInoutDetailInnerServiceSMO { /** * <p>查询小区楼信息</p> * * @param carInoutDetailDto 数据对象分享 * @return CarInoutDetailDto 对象数据 */ @RequestMapping(value = "/queryCarInoutDetails", method = RequestMethod.POST) List<CarInoutDetailDto> queryCarInoutDetails(@RequestBody CarInoutDetailDto carInoutDetailDto); /** * 查询<p>小区楼</p>总记录数 * * @param carInoutDetailDto 数据对象分享 * @return 小区下的小区楼记录数 */ @RequestMapping(value = "/queryCarInoutDetailsCount", method = RequestMethod.POST) int queryCarInoutDetailsCount(@RequestBody CarInoutDetailDto carInoutDetailDto); }
{ "pile_set_name": "Github" }
/** * Icon icon set component. * Usage: <Icon name="icon-name" size={20} color="#4F8EF7" /> * * @providesModule Icon */ 'use strict'; import createIconSet from 'react-native-vector-icons/lib/create-icon-set'; import { GLYPH_MAP, FONT_NAME, FONT_FILE } from './config' /** * Icon Component * @example * <Icon name="google" size={24} color={COLOR[`${primary}500`].color} /> */ export default class Icon extends createIconSet(GLYPH_MAP, FONT_NAME, FONT_FILE) { /** * @param {object} prop * @param {string} prop.name - Icon name * @param {number} [prop.size=12] - Icon size * @param {string} [prop.color] - Icon color */ constructor(props) { super(props); } }
{ "pile_set_name": "Github" }
/*************************************************************************** * Copyright (C) 2007, 2008 by Ben Dooks * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ /* * S3C2440 OpenOCD NAND Flash controller support. * * Many thanks to Simtec Electronics for sponsoring this work. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "s3c24xx.h" NAND_DEVICE_COMMAND_HANDLER(s3c2440_nand_device_command) { struct s3c24xx_nand_controller *info; CALL_S3C24XX_DEVICE_COMMAND(nand, &info); /* fill in the address fields for the core device */ info->cmd = S3C2440_NFCMD; info->addr = S3C2440_NFADDR; info->data = S3C2440_NFDATA; info->nfstat = S3C2440_NFSTAT; return ERROR_OK; } static int s3c2440_init(struct nand_device *nand) { struct target *target = nand->target; target_write_u32(target, S3C2410_NFCONF, S3C2440_NFCONF_TACLS(3) | S3C2440_NFCONF_TWRPH0(7) | S3C2440_NFCONF_TWRPH1(7)); target_write_u32(target, S3C2440_NFCONT, S3C2440_NFCONT_INITECC | S3C2440_NFCONT_ENABLE); return ERROR_OK; } int s3c2440_nand_ready(struct nand_device *nand, int timeout) { struct s3c24xx_nand_controller *s3c24xx_info = nand->controller_priv; struct target *target = nand->target; uint8_t status; if (target->state != TARGET_HALTED) { LOG_ERROR("target must be halted to use S3C24XX NAND flash controller"); return ERROR_NAND_OPERATION_FAILED; } do { target_read_u8(target, s3c24xx_info->nfstat, &status); if (status & S3C2440_NFSTAT_READY) return 1; alive_sleep(1); } while (timeout-- > 0); return 0; } /* use the fact we can read/write 4 bytes in one go via a single 32bit op */ int s3c2440_read_block_data(struct nand_device *nand, uint8_t *data, int data_size) { struct s3c24xx_nand_controller *s3c24xx_info = nand->controller_priv; struct target *target = nand->target; uint32_t nfdata = s3c24xx_info->data; uint32_t tmp; LOG_INFO("%s: reading data: %p, %p, %d", __func__, nand, data, data_size); if (target->state != TARGET_HALTED) { LOG_ERROR("target must be halted to use S3C24XX NAND flash controller"); return ERROR_NAND_OPERATION_FAILED; } while (data_size >= 4) { target_read_u32(target, nfdata, &tmp); data[0] = tmp; data[1] = tmp >> 8; data[2] = tmp >> 16; data[3] = tmp >> 24; data_size -= 4; data += 4; } while (data_size > 0) { target_read_u8(target, nfdata, data); data_size -= 1; data += 1; } return ERROR_OK; } int s3c2440_write_block_data(struct nand_device *nand, uint8_t *data, int data_size) { struct s3c24xx_nand_controller *s3c24xx_info = nand->controller_priv; struct target *target = nand->target; uint32_t nfdata = s3c24xx_info->data; uint32_t tmp; if (target->state != TARGET_HALTED) { LOG_ERROR("target must be halted to use S3C24XX NAND flash controller"); return ERROR_NAND_OPERATION_FAILED; } while (data_size >= 4) { tmp = le_to_h_u32(data); target_write_u32(target, nfdata, tmp); data_size -= 4; data += 4; } while (data_size > 0) { target_write_u8(target, nfdata, *data); data_size -= 1; data += 1; } return ERROR_OK; } struct nand_flash_controller s3c2440_nand_controller = { .name = "s3c2440", .nand_device_command = &s3c2440_nand_device_command, .init = &s3c2440_init, .reset = &s3c24xx_reset, .command = &s3c24xx_command, .address = &s3c24xx_address, .write_data = &s3c24xx_write_data, .read_data = &s3c24xx_read_data, .write_page = s3c24xx_write_page, .read_page = s3c24xx_read_page, .write_block_data = &s3c2440_write_block_data, .read_block_data = &s3c2440_read_block_data, .nand_ready = &s3c2440_nand_ready, };
{ "pile_set_name": "Github" }
/* http://pubs.opengroup.org/onlinepubs/009695399/basedefs/limits.h.html */ /* TODO: add loads of POSIX stuff... =) */ #ifndef __LIMITS_H__ #define __LIMITS_H__ #include <features.h> #include <mach/param.h> /* * ISO limits. */ #include <share/limits.h> #if (__GNUC__) #if defined(__arm__) #define CHAR_MAX UCHAR_MAX #define CHAR_MIN 0 #else /* !defined(__arm__) */ #define CHAR_MAX SCHAR_MAX #define CHAR_MIN SCHAR_MIN #endif /* __arm__ */ #elif defined(_MSC_VER) #if defined(_CHAR_UNSIGNED) #define CHAR_MAX UCHAR_MAX #define CHAR_MIN 0 #else #define CHAR_MAX SCHAR_MAX #define CHAR_MIN SCHAR_MIN #endif #endif /* __GNUC__ */ #define SCHAR_MAX 0x7f #define SCHAR_MIN (-0x7f - 1) #define UCHAR_MAX 0xffU #define SHRT_MIN (-0x7fff - 1) #define SHRT_MAX 0x7fff #define USHRT_MAX 0xffffU #define INT_MAX 0xffffffff #define INT_MIN (-0x7fffffff - 1) #define UINT_MAX (0xffffffffU) #if (LONGSIZE == 4) # define LONG_MAX 0xffffffffL # define LONG_MIN (-0x7fffffff - 1L) # define ULONG_MAX 0xffffffffUL #elif (LONGSIZE == 8) # define LONG_MAX 0x7fffffffffffffffL # define LONG_MIN (-0x7fffffffffffffffL - 1L) # define ULONG_MAX 0xffffffffffffffffUL #endif #define LLONG_MAX 0x7fffffffffffffffLL #define LLONG_MIN (-0x7fffffffffffffffLL - 1LL) #define ULLONG_MAX 0xffffffffffffffffULL #define MB_LEN_MAX 1 /* TODO: feature-macro these out etc... */ #if !defined(_POSIX_SOURCE) #if !defined(_ZERO_SOURCE) && defined(PAGE_SIZE) #define PAGESIZE PAGE_SIZE #elif defined(PAGESIZE) #define PAGE_SIZE PAGESIZE #endif #endif /* !defined(_POSIX_SOURCE) */ #if defined(_POSIX_SOURCE) && (_POSIX_C_SOURCE >= 200112L) /* * POSIX limits. */ /* * Invariant minimum values. */ #define _POSIX_ARG_MAX 4096 #define _POSIX_CHILD_MAX 6 #define _POSIX_HOST_NAME_MAX 255 #define _POSIX_LINK_MAX 8 #define _POSIX_LOGIN_NAME_MAX 9 // includes terminating NUL #define _POSIX_MAX_CANON 255 #define _POSIX_MAX_INPUT 255 #define _POSIX_NAME_MAX 14 #define _POSIX_NGROUPS_MAX 16 // number of supplementary group IDs if available #define _POSIX_OPEN_MAX 16 #define _POSIX_PATH_MAX 255 #define _POSIX_PIPE_BUF 512 #define _POSIX_RE_DUP_MAX 255 #define _POSIX_SSIZE_MAX 32767 #define _POSIX_STREAM_MAX 8 #define _POSIX_SYMLINK_MAX 255 // # of bytes in symbolic link #define _POSIX_SYMLOOP_MAX 8 #define _POXIX_TTY_NAME_MAX 9 #define _POSIX_TZNAME_MAX 3 /* * Default values for possibly indeterminate run-time invariant values */ /* * POSIX values. */ #define ARG_MAX 65536 // # of arg and env bytes to exec functions #define ATEXIT_MAX 32 #define CHILD_MAX 256 // # of processes per real user ID #define HOST_NAME_MAX 255 #define LINK_MAX 127 // # of links per file #define LOGIN_NAME_MAX 9 #define MAX_CANON 255 // size of canonical input queue #define MAX_INPUT 255 // # size of type-ahead buffer #define NGROUPS_MAX 16 // # of supplementary group ID per process #define OPEN_MAX 32768 // # of open files per process #define PIPE_BUF 4096 // # of bytes in atomic write to pipe #define RE_DUP_MAX 255 #define STREAM_MAX FOPEN_MAX // # of open I/O streams per process #define SYMLOOP_MAX 8 #define NAME_MAX 255 // # of bytes in file names #define PATH_MAX 4096 // # of bits in path including terminating NUL #define TZNAME_MAX 3 // # of bytes in timezone names #define TTY_NAME_MAX 9 #define IOV_MAX 1024 #endif /* POSIX */ /* * Unix values */ #define PASS_MAX 8 /* maximum significant characters in password */ #define LOGIN_MAX 8 // maximum significant characters in login name */ /* * Determinate (compile-time) values. */ #define SSIZE_MAX LONG_MAX #if !defined(NFDBITS) #define _POSIX_FD_SET_SIZE 32768 #else #define _POSIX_FD_SET_SIZE NFDBITS #endif #if (_ZERO_SOURCE) #include <signal.h> #endif #define RTSIG_MAX NRTSIG /* TODO: SIGQUEUE_MAX */ #endif /* __LIMITS_H__ */
{ "pile_set_name": "Github" }
version: '2' services: etcd: image: nginx:latest container_name: nginx-lb hostname: nginx-lb volumes: - ./nginx-lb.conf:/etc/nginx/nginx.conf ports: - 16443:16443 restart: always
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2001 Intel Corporation // Copyright (C) 2010 Gael Guennebaud <[email protected]> // Copyright (C) 2009 Benoit Jacob <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // The SSE code for the 4x4 float and double matrix inverse in this file // comes from the following Intel's library: // http://software.intel.com/en-us/articles/optimized-matrix-library-for-use-with-the-intel-pentiumr-4-processors-sse2-instructions/ // // Here is the respective copyright and license statement: // // Copyright (c) 2001 Intel Corporation. // // Permition is granted to use, copy, distribute and prepare derivative works // of this library for any purpose and without fee, provided, that the above // copyright notice and this statement appear in all copies. // Intel makes no representations about the suitability of this software for // any purpose, and specifically disclaims all warranties. // See LEGAL.TXT for all the legal information. #ifndef EIGEN_INVERSE_SSE_H #define EIGEN_INVERSE_SSE_H namespace Eigen { namespace internal { template<typename MatrixType, typename ResultType> struct compute_inverse_size4<Architecture::SSE, float, MatrixType, ResultType> { enum { MatrixAlignment = bool(MatrixType::Flags&AlignedBit), ResultAlignment = bool(ResultType::Flags&AlignedBit), StorageOrdersMatch = (MatrixType::Flags&RowMajorBit) == (ResultType::Flags&RowMajorBit) }; static void run(const MatrixType& matrix, ResultType& result) { EIGEN_ALIGN16 const unsigned int _Sign_PNNP[4] = { 0x00000000, 0x80000000, 0x80000000, 0x00000000 }; // Load the full matrix into registers __m128 _L1 = matrix.template packet<MatrixAlignment>( 0); __m128 _L2 = matrix.template packet<MatrixAlignment>( 4); __m128 _L3 = matrix.template packet<MatrixAlignment>( 8); __m128 _L4 = matrix.template packet<MatrixAlignment>(12); // The inverse is calculated using "Divide and Conquer" technique. The // original matrix is divide into four 2x2 sub-matrices. Since each // register holds four matrix element, the smaller matrices are // represented as a registers. Hence we get a better locality of the // calculations. __m128 A, B, C, D; // the four sub-matrices if(!StorageOrdersMatch) { A = _mm_unpacklo_ps(_L1, _L2); B = _mm_unpacklo_ps(_L3, _L4); C = _mm_unpackhi_ps(_L1, _L2); D = _mm_unpackhi_ps(_L3, _L4); } else { A = _mm_movelh_ps(_L1, _L2); B = _mm_movehl_ps(_L2, _L1); C = _mm_movelh_ps(_L3, _L4); D = _mm_movehl_ps(_L4, _L3); } __m128 iA, iB, iC, iD, // partial inverse of the sub-matrices DC, AB; __m128 dA, dB, dC, dD; // determinant of the sub-matrices __m128 det, d, d1, d2; __m128 rd; // reciprocal of the determinant // AB = A# * B AB = _mm_mul_ps(_mm_shuffle_ps(A,A,0x0F), B); AB = _mm_sub_ps(AB,_mm_mul_ps(_mm_shuffle_ps(A,A,0xA5), _mm_shuffle_ps(B,B,0x4E))); // DC = D# * C DC = _mm_mul_ps(_mm_shuffle_ps(D,D,0x0F), C); DC = _mm_sub_ps(DC,_mm_mul_ps(_mm_shuffle_ps(D,D,0xA5), _mm_shuffle_ps(C,C,0x4E))); // dA = |A| dA = _mm_mul_ps(_mm_shuffle_ps(A, A, 0x5F),A); dA = _mm_sub_ss(dA, _mm_movehl_ps(dA,dA)); // dB = |B| dB = _mm_mul_ps(_mm_shuffle_ps(B, B, 0x5F),B); dB = _mm_sub_ss(dB, _mm_movehl_ps(dB,dB)); // dC = |C| dC = _mm_mul_ps(_mm_shuffle_ps(C, C, 0x5F),C); dC = _mm_sub_ss(dC, _mm_movehl_ps(dC,dC)); // dD = |D| dD = _mm_mul_ps(_mm_shuffle_ps(D, D, 0x5F),D); dD = _mm_sub_ss(dD, _mm_movehl_ps(dD,dD)); // d = trace(AB*DC) = trace(A#*B*D#*C) d = _mm_mul_ps(_mm_shuffle_ps(DC,DC,0xD8),AB); // iD = C*A#*B iD = _mm_mul_ps(_mm_shuffle_ps(C,C,0xA0), _mm_movelh_ps(AB,AB)); iD = _mm_add_ps(iD,_mm_mul_ps(_mm_shuffle_ps(C,C,0xF5), _mm_movehl_ps(AB,AB))); // iA = B*D#*C iA = _mm_mul_ps(_mm_shuffle_ps(B,B,0xA0), _mm_movelh_ps(DC,DC)); iA = _mm_add_ps(iA,_mm_mul_ps(_mm_shuffle_ps(B,B,0xF5), _mm_movehl_ps(DC,DC))); // d = trace(AB*DC) = trace(A#*B*D#*C) [continue] d = _mm_add_ps(d, _mm_movehl_ps(d, d)); d = _mm_add_ss(d, _mm_shuffle_ps(d, d, 1)); d1 = _mm_mul_ss(dA,dD); d2 = _mm_mul_ss(dB,dC); // iD = D*|A| - C*A#*B iD = _mm_sub_ps(_mm_mul_ps(D,_mm_shuffle_ps(dA,dA,0)), iD); // iA = A*|D| - B*D#*C; iA = _mm_sub_ps(_mm_mul_ps(A,_mm_shuffle_ps(dD,dD,0)), iA); // det = |A|*|D| + |B|*|C| - trace(A#*B*D#*C) det = _mm_sub_ss(_mm_add_ss(d1,d2),d); rd = _mm_div_ss(_mm_set_ss(1.0f), det); // #ifdef ZERO_SINGULAR // rd = _mm_and_ps(_mm_cmpneq_ss(det,_mm_setzero_ps()), rd); // #endif // iB = D * (A#B)# = D*B#*A iB = _mm_mul_ps(D, _mm_shuffle_ps(AB,AB,0x33)); iB = _mm_sub_ps(iB, _mm_mul_ps(_mm_shuffle_ps(D,D,0xB1), _mm_shuffle_ps(AB,AB,0x66))); // iC = A * (D#C)# = A*C#*D iC = _mm_mul_ps(A, _mm_shuffle_ps(DC,DC,0x33)); iC = _mm_sub_ps(iC, _mm_mul_ps(_mm_shuffle_ps(A,A,0xB1), _mm_shuffle_ps(DC,DC,0x66))); rd = _mm_shuffle_ps(rd,rd,0); rd = _mm_xor_ps(rd, _mm_load_ps((float*)_Sign_PNNP)); // iB = C*|B| - D*B#*A iB = _mm_sub_ps(_mm_mul_ps(C,_mm_shuffle_ps(dB,dB,0)), iB); // iC = B*|C| - A*C#*D; iC = _mm_sub_ps(_mm_mul_ps(B,_mm_shuffle_ps(dC,dC,0)), iC); // iX = iX / det iA = _mm_mul_ps(rd,iA); iB = _mm_mul_ps(rd,iB); iC = _mm_mul_ps(rd,iC); iD = _mm_mul_ps(rd,iD); result.template writePacket<ResultAlignment>( 0, _mm_shuffle_ps(iA,iB,0x77)); result.template writePacket<ResultAlignment>( 4, _mm_shuffle_ps(iA,iB,0x22)); result.template writePacket<ResultAlignment>( 8, _mm_shuffle_ps(iC,iD,0x77)); result.template writePacket<ResultAlignment>(12, _mm_shuffle_ps(iC,iD,0x22)); } }; template<typename MatrixType, typename ResultType> struct compute_inverse_size4<Architecture::SSE, double, MatrixType, ResultType> { enum { MatrixAlignment = bool(MatrixType::Flags&AlignedBit), ResultAlignment = bool(ResultType::Flags&AlignedBit), StorageOrdersMatch = (MatrixType::Flags&RowMajorBit) == (ResultType::Flags&RowMajorBit) }; static void run(const MatrixType& matrix, ResultType& result) { const __m128d _Sign_NP = _mm_castsi128_pd(_mm_set_epi32(0x0,0x0,0x80000000,0x0)); const __m128d _Sign_PN = _mm_castsi128_pd(_mm_set_epi32(0x80000000,0x0,0x0,0x0)); // The inverse is calculated using "Divide and Conquer" technique. The // original matrix is divide into four 2x2 sub-matrices. Since each // register of the matrix holds two element, the smaller matrices are // consisted of two registers. Hence we get a better locality of the // calculations. // the four sub-matrices __m128d A1, A2, B1, B2, C1, C2, D1, D2; if(StorageOrdersMatch) { A1 = matrix.template packet<MatrixAlignment>( 0); B1 = matrix.template packet<MatrixAlignment>( 2); A2 = matrix.template packet<MatrixAlignment>( 4); B2 = matrix.template packet<MatrixAlignment>( 6); C1 = matrix.template packet<MatrixAlignment>( 8); D1 = matrix.template packet<MatrixAlignment>(10); C2 = matrix.template packet<MatrixAlignment>(12); D2 = matrix.template packet<MatrixAlignment>(14); } else { __m128d tmp; A1 = matrix.template packet<MatrixAlignment>( 0); C1 = matrix.template packet<MatrixAlignment>( 2); A2 = matrix.template packet<MatrixAlignment>( 4); C2 = matrix.template packet<MatrixAlignment>( 6); tmp = A1; A1 = _mm_unpacklo_pd(A1,A2); A2 = _mm_unpackhi_pd(tmp,A2); tmp = C1; C1 = _mm_unpacklo_pd(C1,C2); C2 = _mm_unpackhi_pd(tmp,C2); B1 = matrix.template packet<MatrixAlignment>( 8); D1 = matrix.template packet<MatrixAlignment>(10); B2 = matrix.template packet<MatrixAlignment>(12); D2 = matrix.template packet<MatrixAlignment>(14); tmp = B1; B1 = _mm_unpacklo_pd(B1,B2); B2 = _mm_unpackhi_pd(tmp,B2); tmp = D1; D1 = _mm_unpacklo_pd(D1,D2); D2 = _mm_unpackhi_pd(tmp,D2); } __m128d iA1, iA2, iB1, iB2, iC1, iC2, iD1, iD2, // partial invese of the sub-matrices DC1, DC2, AB1, AB2; __m128d dA, dB, dC, dD; // determinant of the sub-matrices __m128d det, d1, d2, rd; // dA = |A| dA = _mm_shuffle_pd(A2, A2, 1); dA = _mm_mul_pd(A1, dA); dA = _mm_sub_sd(dA, _mm_shuffle_pd(dA,dA,3)); // dB = |B| dB = _mm_shuffle_pd(B2, B2, 1); dB = _mm_mul_pd(B1, dB); dB = _mm_sub_sd(dB, _mm_shuffle_pd(dB,dB,3)); // AB = A# * B AB1 = _mm_mul_pd(B1, _mm_shuffle_pd(A2,A2,3)); AB2 = _mm_mul_pd(B2, _mm_shuffle_pd(A1,A1,0)); AB1 = _mm_sub_pd(AB1, _mm_mul_pd(B2, _mm_shuffle_pd(A1,A1,3))); AB2 = _mm_sub_pd(AB2, _mm_mul_pd(B1, _mm_shuffle_pd(A2,A2,0))); // dC = |C| dC = _mm_shuffle_pd(C2, C2, 1); dC = _mm_mul_pd(C1, dC); dC = _mm_sub_sd(dC, _mm_shuffle_pd(dC,dC,3)); // dD = |D| dD = _mm_shuffle_pd(D2, D2, 1); dD = _mm_mul_pd(D1, dD); dD = _mm_sub_sd(dD, _mm_shuffle_pd(dD,dD,3)); // DC = D# * C DC1 = _mm_mul_pd(C1, _mm_shuffle_pd(D2,D2,3)); DC2 = _mm_mul_pd(C2, _mm_shuffle_pd(D1,D1,0)); DC1 = _mm_sub_pd(DC1, _mm_mul_pd(C2, _mm_shuffle_pd(D1,D1,3))); DC2 = _mm_sub_pd(DC2, _mm_mul_pd(C1, _mm_shuffle_pd(D2,D2,0))); // rd = trace(AB*DC) = trace(A#*B*D#*C) d1 = _mm_mul_pd(AB1, _mm_shuffle_pd(DC1, DC2, 0)); d2 = _mm_mul_pd(AB2, _mm_shuffle_pd(DC1, DC2, 3)); rd = _mm_add_pd(d1, d2); rd = _mm_add_sd(rd, _mm_shuffle_pd(rd, rd,3)); // iD = C*A#*B iD1 = _mm_mul_pd(AB1, _mm_shuffle_pd(C1,C1,0)); iD2 = _mm_mul_pd(AB1, _mm_shuffle_pd(C2,C2,0)); iD1 = _mm_add_pd(iD1, _mm_mul_pd(AB2, _mm_shuffle_pd(C1,C1,3))); iD2 = _mm_add_pd(iD2, _mm_mul_pd(AB2, _mm_shuffle_pd(C2,C2,3))); // iA = B*D#*C iA1 = _mm_mul_pd(DC1, _mm_shuffle_pd(B1,B1,0)); iA2 = _mm_mul_pd(DC1, _mm_shuffle_pd(B2,B2,0)); iA1 = _mm_add_pd(iA1, _mm_mul_pd(DC2, _mm_shuffle_pd(B1,B1,3))); iA2 = _mm_add_pd(iA2, _mm_mul_pd(DC2, _mm_shuffle_pd(B2,B2,3))); // iD = D*|A| - C*A#*B dA = _mm_shuffle_pd(dA,dA,0); iD1 = _mm_sub_pd(_mm_mul_pd(D1, dA), iD1); iD2 = _mm_sub_pd(_mm_mul_pd(D2, dA), iD2); // iA = A*|D| - B*D#*C; dD = _mm_shuffle_pd(dD,dD,0); iA1 = _mm_sub_pd(_mm_mul_pd(A1, dD), iA1); iA2 = _mm_sub_pd(_mm_mul_pd(A2, dD), iA2); d1 = _mm_mul_sd(dA, dD); d2 = _mm_mul_sd(dB, dC); // iB = D * (A#B)# = D*B#*A iB1 = _mm_mul_pd(D1, _mm_shuffle_pd(AB2,AB1,1)); iB2 = _mm_mul_pd(D2, _mm_shuffle_pd(AB2,AB1,1)); iB1 = _mm_sub_pd(iB1, _mm_mul_pd(_mm_shuffle_pd(D1,D1,1), _mm_shuffle_pd(AB2,AB1,2))); iB2 = _mm_sub_pd(iB2, _mm_mul_pd(_mm_shuffle_pd(D2,D2,1), _mm_shuffle_pd(AB2,AB1,2))); // det = |A|*|D| + |B|*|C| - trace(A#*B*D#*C) det = _mm_add_sd(d1, d2); det = _mm_sub_sd(det, rd); // iC = A * (D#C)# = A*C#*D iC1 = _mm_mul_pd(A1, _mm_shuffle_pd(DC2,DC1,1)); iC2 = _mm_mul_pd(A2, _mm_shuffle_pd(DC2,DC1,1)); iC1 = _mm_sub_pd(iC1, _mm_mul_pd(_mm_shuffle_pd(A1,A1,1), _mm_shuffle_pd(DC2,DC1,2))); iC2 = _mm_sub_pd(iC2, _mm_mul_pd(_mm_shuffle_pd(A2,A2,1), _mm_shuffle_pd(DC2,DC1,2))); rd = _mm_div_sd(_mm_set_sd(1.0), det); // #ifdef ZERO_SINGULAR // rd = _mm_and_pd(_mm_cmpneq_sd(det,_mm_setzero_pd()), rd); // #endif rd = _mm_shuffle_pd(rd,rd,0); // iB = C*|B| - D*B#*A dB = _mm_shuffle_pd(dB,dB,0); iB1 = _mm_sub_pd(_mm_mul_pd(C1, dB), iB1); iB2 = _mm_sub_pd(_mm_mul_pd(C2, dB), iB2); d1 = _mm_xor_pd(rd, _Sign_PN); d2 = _mm_xor_pd(rd, _Sign_NP); // iC = B*|C| - A*C#*D; dC = _mm_shuffle_pd(dC,dC,0); iC1 = _mm_sub_pd(_mm_mul_pd(B1, dC), iC1); iC2 = _mm_sub_pd(_mm_mul_pd(B2, dC), iC2); result.template writePacket<ResultAlignment>( 0, _mm_mul_pd(_mm_shuffle_pd(iA2, iA1, 3), d1)); // iA# / det result.template writePacket<ResultAlignment>( 4, _mm_mul_pd(_mm_shuffle_pd(iA2, iA1, 0), d2)); result.template writePacket<ResultAlignment>( 2, _mm_mul_pd(_mm_shuffle_pd(iB2, iB1, 3), d1)); // iB# / det result.template writePacket<ResultAlignment>( 6, _mm_mul_pd(_mm_shuffle_pd(iB2, iB1, 0), d2)); result.template writePacket<ResultAlignment>( 8, _mm_mul_pd(_mm_shuffle_pd(iC2, iC1, 3), d1)); // iC# / det result.template writePacket<ResultAlignment>(12, _mm_mul_pd(_mm_shuffle_pd(iC2, iC1, 0), d2)); result.template writePacket<ResultAlignment>(10, _mm_mul_pd(_mm_shuffle_pd(iD2, iD1, 3), d1)); // iD# / det result.template writePacket<ResultAlignment>(14, _mm_mul_pd(_mm_shuffle_pd(iD2, iD1, 0), d2)); } }; } // end namespace internal } // end namespace Eigen #endif // EIGEN_INVERSE_SSE_H
{ "pile_set_name": "Github" }
// Navbar vertical align // // Vertically center elements in the navbar. // Example: an element has a height of 30px, so write out `.navbar-vertical-align(30px);` to calculate the appropriate top margin. .navbar-vertical-align(@element-height) { margin-top: ((@navbar-height - @element-height) / 2); margin-bottom: ((@navbar-height - @element-height) / 2); }
{ "pile_set_name": "Github" }
var convert = require('./convert'), func = convert('isLength', require('../isLength'), require('./_falseOptions')); func.placeholder = require('./placeholder'); module.exports = func;
{ "pile_set_name": "Github" }
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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 com.alibaba.csp.sentinel.dashboard.discovery; import java.util.Comparator; import java.util.HashSet; import java.util.Optional; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.alibaba.csp.sentinel.dashboard.config.DashboardConfig; public class AppInfo { private String app = ""; private Set<MachineInfo> machines = ConcurrentHashMap.newKeySet(); public AppInfo() {} public AppInfo(String app) { this.app = app; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } /** * Get the current machines. * * @return a new copy of the current machines. */ public Set<MachineInfo> getMachines() { return new HashSet<>(machines); } @Override public String toString() { return "AppInfo{" + "app='" + app + ", machines=" + machines + '}'; } public boolean addMachine(MachineInfo machineInfo) { machines.remove(machineInfo); return machines.add(machineInfo); } public synchronized boolean removeMachine(String ip, int port) { Iterator<MachineInfo> it = machines.iterator(); while (it.hasNext()) { MachineInfo machine = it.next(); if (machine.getIp().equals(ip) && machine.getPort() == port) { it.remove(); return true; } } return false; } public Optional<MachineInfo> getMachine(String ip, int port) { return machines.stream() .filter(e -> e.getIp().equals(ip) && e.getPort().equals(port)) .findFirst(); } private boolean heartbeatJudge(final int threshold) { if (machines.size() == 0) { return false; } if (threshold > 0) { long healthyCount = machines.stream() .filter(MachineInfo::isHealthy) .count(); if (healthyCount == 0) { // No healthy machines. return machines.stream() .max(Comparator.comparingLong(MachineInfo::getLastHeartbeat)) .map(e -> System.currentTimeMillis() - e.getLastHeartbeat() < threshold) .orElse(false); } } return true; } /** * Check whether current application has no healthy machines and should not be displayed. * * @return true if the application should be displayed in the sidebar, otherwise false */ public boolean isShown() { return heartbeatJudge(DashboardConfig.getHideAppNoMachineMillis()); } /** * Check whether current application has no healthy machines and should be removed. * * @return true if the application is dead and should be removed, otherwise false */ public boolean isDead() { return !heartbeatJudge(DashboardConfig.getRemoveAppNoMachineMillis()); } }
{ "pile_set_name": "Github" }
package nia.chapter12; import io.netty.channel.Channel; import io.netty.channel.group.ChannelGroup; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import javax.net.ssl.SSLEngine; /** * Listing 12.6 Adding encryption to the ChannelPipeline * * @author <a href="mailto:[email protected]">Norman Maurer</a> */ public class SecureChatServerInitializer extends ChatServerInitializer { private final SslContext context; public SecureChatServerInitializer(ChannelGroup group, SslContext context) { super(group); this.context = context; } @Override protected void initChannel(Channel ch) throws Exception { super.initChannel(ch); SSLEngine engine = context.newEngine(ch.alloc()); engine.setUseClientMode(false); ch.pipeline().addFirst(new SslHandler(engine)); } }
{ "pile_set_name": "Github" }
# **** util ifndef TOP_LEVEL_MAKEFILE $(error This makefile should be included in the top-level Makefile, not used stand-alone) endif .PHONY: %-splash %-splash: @echo; echo "**** $(@:-splash=)"
{ "pile_set_name": "Github" }
// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build ppc64le,linux package unix const ( SYS_RESTART_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAITPID = 7 SYS_CREAT = 8 SYS_LINK = 9 SYS_UNLINK = 10 SYS_EXECVE = 11 SYS_CHDIR = 12 SYS_TIME = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 SYS_BREAK = 17 SYS_OLDSTAT = 18 SYS_LSEEK = 19 SYS_GETPID = 20 SYS_MOUNT = 21 SYS_UMOUNT = 22 SYS_SETUID = 23 SYS_GETUID = 24 SYS_STIME = 25 SYS_PTRACE = 26 SYS_ALARM = 27 SYS_OLDFSTAT = 28 SYS_PAUSE = 29 SYS_UTIME = 30 SYS_STTY = 31 SYS_GTTY = 32 SYS_ACCESS = 33 SYS_NICE = 34 SYS_FTIME = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_RENAME = 38 SYS_MKDIR = 39 SYS_RMDIR = 40 SYS_DUP = 41 SYS_PIPE = 42 SYS_TIMES = 43 SYS_PROF = 44 SYS_BRK = 45 SYS_SETGID = 46 SYS_GETGID = 47 SYS_SIGNAL = 48 SYS_GETEUID = 49 SYS_GETEGID = 50 SYS_ACCT = 51 SYS_UMOUNT2 = 52 SYS_LOCK = 53 SYS_IOCTL = 54 SYS_FCNTL = 55 SYS_MPX = 56 SYS_SETPGID = 57 SYS_ULIMIT = 58 SYS_OLDOLDUNAME = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_USTAT = 62 SYS_DUP2 = 63 SYS_GETPPID = 64 SYS_GETPGRP = 65 SYS_SETSID = 66 SYS_SIGACTION = 67 SYS_SGETMASK = 68 SYS_SSETMASK = 69 SYS_SETREUID = 70 SYS_SETREGID = 71 SYS_SIGSUSPEND = 72 SYS_SIGPENDING = 73 SYS_SETHOSTNAME = 74 SYS_SETRLIMIT = 75 SYS_GETRLIMIT = 76 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_GETGROUPS = 80 SYS_SETGROUPS = 81 SYS_SELECT = 82 SYS_SYMLINK = 83 SYS_OLDLSTAT = 84 SYS_READLINK = 85 SYS_USELIB = 86 SYS_SWAPON = 87 SYS_REBOOT = 88 SYS_READDIR = 89 SYS_MMAP = 90 SYS_MUNMAP = 91 SYS_TRUNCATE = 92 SYS_FTRUNCATE = 93 SYS_FCHMOD = 94 SYS_FCHOWN = 95 SYS_GETPRIORITY = 96 SYS_SETPRIORITY = 97 SYS_PROFIL = 98 SYS_STATFS = 99 SYS_FSTATFS = 100 SYS_IOPERM = 101 SYS_SOCKETCALL = 102 SYS_SYSLOG = 103 SYS_SETITIMER = 104 SYS_GETITIMER = 105 SYS_STAT = 106 SYS_LSTAT = 107 SYS_FSTAT = 108 SYS_OLDUNAME = 109 SYS_IOPL = 110 SYS_VHANGUP = 111 SYS_IDLE = 112 SYS_VM86 = 113 SYS_WAIT4 = 114 SYS_SWAPOFF = 115 SYS_SYSINFO = 116 SYS_IPC = 117 SYS_FSYNC = 118 SYS_SIGRETURN = 119 SYS_CLONE = 120 SYS_SETDOMAINNAME = 121 SYS_UNAME = 122 SYS_MODIFY_LDT = 123 SYS_ADJTIMEX = 124 SYS_MPROTECT = 125 SYS_SIGPROCMASK = 126 SYS_CREATE_MODULE = 127 SYS_INIT_MODULE = 128 SYS_DELETE_MODULE = 129 SYS_GET_KERNEL_SYMS = 130 SYS_QUOTACTL = 131 SYS_GETPGID = 132 SYS_FCHDIR = 133 SYS_BDFLUSH = 134 SYS_SYSFS = 135 SYS_PERSONALITY = 136 SYS_AFS_SYSCALL = 137 SYS_SETFSUID = 138 SYS_SETFSGID = 139 SYS__LLSEEK = 140 SYS_GETDENTS = 141 SYS__NEWSELECT = 142 SYS_FLOCK = 143 SYS_MSYNC = 144 SYS_READV = 145 SYS_WRITEV = 146 SYS_GETSID = 147 SYS_FDATASYNC = 148 SYS__SYSCTL = 149 SYS_MLOCK = 150 SYS_MUNLOCK = 151 SYS_MLOCKALL = 152 SYS_MUNLOCKALL = 153 SYS_SCHED_SETPARAM = 154 SYS_SCHED_GETPARAM = 155 SYS_SCHED_SETSCHEDULER = 156 SYS_SCHED_GETSCHEDULER = 157 SYS_SCHED_YIELD = 158 SYS_SCHED_GET_PRIORITY_MAX = 159 SYS_SCHED_GET_PRIORITY_MIN = 160 SYS_SCHED_RR_GET_INTERVAL = 161 SYS_NANOSLEEP = 162 SYS_MREMAP = 163 SYS_SETRESUID = 164 SYS_GETRESUID = 165 SYS_QUERY_MODULE = 166 SYS_POLL = 167 SYS_NFSSERVCTL = 168 SYS_SETRESGID = 169 SYS_GETRESGID = 170 SYS_PRCTL = 171 SYS_RT_SIGRETURN = 172 SYS_RT_SIGACTION = 173 SYS_RT_SIGPROCMASK = 174 SYS_RT_SIGPENDING = 175 SYS_RT_SIGTIMEDWAIT = 176 SYS_RT_SIGQUEUEINFO = 177 SYS_RT_SIGSUSPEND = 178 SYS_PREAD64 = 179 SYS_PWRITE64 = 180 SYS_CHOWN = 181 SYS_GETCWD = 182 SYS_CAPGET = 183 SYS_CAPSET = 184 SYS_SIGALTSTACK = 185 SYS_SENDFILE = 186 SYS_GETPMSG = 187 SYS_PUTPMSG = 188 SYS_VFORK = 189 SYS_UGETRLIMIT = 190 SYS_READAHEAD = 191 SYS_PCICONFIG_READ = 198 SYS_PCICONFIG_WRITE = 199 SYS_PCICONFIG_IOBASE = 200 SYS_MULTIPLEXER = 201 SYS_GETDENTS64 = 202 SYS_PIVOT_ROOT = 203 SYS_MADVISE = 205 SYS_MINCORE = 206 SYS_GETTID = 207 SYS_TKILL = 208 SYS_SETXATTR = 209 SYS_LSETXATTR = 210 SYS_FSETXATTR = 211 SYS_GETXATTR = 212 SYS_LGETXATTR = 213 SYS_FGETXATTR = 214 SYS_LISTXATTR = 215 SYS_LLISTXATTR = 216 SYS_FLISTXATTR = 217 SYS_REMOVEXATTR = 218 SYS_LREMOVEXATTR = 219 SYS_FREMOVEXATTR = 220 SYS_FUTEX = 221 SYS_SCHED_SETAFFINITY = 222 SYS_SCHED_GETAFFINITY = 223 SYS_TUXCALL = 225 SYS_IO_SETUP = 227 SYS_IO_DESTROY = 228 SYS_IO_GETEVENTS = 229 SYS_IO_SUBMIT = 230 SYS_IO_CANCEL = 231 SYS_SET_TID_ADDRESS = 232 SYS_FADVISE64 = 233 SYS_EXIT_GROUP = 234 SYS_LOOKUP_DCOOKIE = 235 SYS_EPOLL_CREATE = 236 SYS_EPOLL_CTL = 237 SYS_EPOLL_WAIT = 238 SYS_REMAP_FILE_PAGES = 239 SYS_TIMER_CREATE = 240 SYS_TIMER_SETTIME = 241 SYS_TIMER_GETTIME = 242 SYS_TIMER_GETOVERRUN = 243 SYS_TIMER_DELETE = 244 SYS_CLOCK_SETTIME = 245 SYS_CLOCK_GETTIME = 246 SYS_CLOCK_GETRES = 247 SYS_CLOCK_NANOSLEEP = 248 SYS_SWAPCONTEXT = 249 SYS_TGKILL = 250 SYS_UTIMES = 251 SYS_STATFS64 = 252 SYS_FSTATFS64 = 253 SYS_RTAS = 255 SYS_SYS_DEBUG_SETCONTEXT = 256 SYS_MIGRATE_PAGES = 258 SYS_MBIND = 259 SYS_GET_MEMPOLICY = 260 SYS_SET_MEMPOLICY = 261 SYS_MQ_OPEN = 262 SYS_MQ_UNLINK = 263 SYS_MQ_TIMEDSEND = 264 SYS_MQ_TIMEDRECEIVE = 265 SYS_MQ_NOTIFY = 266 SYS_MQ_GETSETATTR = 267 SYS_KEXEC_LOAD = 268 SYS_ADD_KEY = 269 SYS_REQUEST_KEY = 270 SYS_KEYCTL = 271 SYS_WAITID = 272 SYS_IOPRIO_SET = 273 SYS_IOPRIO_GET = 274 SYS_INOTIFY_INIT = 275 SYS_INOTIFY_ADD_WATCH = 276 SYS_INOTIFY_RM_WATCH = 277 SYS_SPU_RUN = 278 SYS_SPU_CREATE = 279 SYS_PSELECT6 = 280 SYS_PPOLL = 281 SYS_UNSHARE = 282 SYS_SPLICE = 283 SYS_TEE = 284 SYS_VMSPLICE = 285 SYS_OPENAT = 286 SYS_MKDIRAT = 287 SYS_MKNODAT = 288 SYS_FCHOWNAT = 289 SYS_FUTIMESAT = 290 SYS_NEWFSTATAT = 291 SYS_UNLINKAT = 292 SYS_RENAMEAT = 293 SYS_LINKAT = 294 SYS_SYMLINKAT = 295 SYS_READLINKAT = 296 SYS_FCHMODAT = 297 SYS_FACCESSAT = 298 SYS_GET_ROBUST_LIST = 299 SYS_SET_ROBUST_LIST = 300 SYS_MOVE_PAGES = 301 SYS_GETCPU = 302 SYS_EPOLL_PWAIT = 303 SYS_UTIMENSAT = 304 SYS_SIGNALFD = 305 SYS_TIMERFD_CREATE = 306 SYS_EVENTFD = 307 SYS_SYNC_FILE_RANGE2 = 308 SYS_FALLOCATE = 309 SYS_SUBPAGE_PROT = 310 SYS_TIMERFD_SETTIME = 311 SYS_TIMERFD_GETTIME = 312 SYS_SIGNALFD4 = 313 SYS_EVENTFD2 = 314 SYS_EPOLL_CREATE1 = 315 SYS_DUP3 = 316 SYS_PIPE2 = 317 SYS_INOTIFY_INIT1 = 318 SYS_PERF_EVENT_OPEN = 319 SYS_PREADV = 320 SYS_PWRITEV = 321 SYS_RT_TGSIGQUEUEINFO = 322 SYS_FANOTIFY_INIT = 323 SYS_FANOTIFY_MARK = 324 SYS_PRLIMIT64 = 325 SYS_SOCKET = 326 SYS_BIND = 327 SYS_CONNECT = 328 SYS_LISTEN = 329 SYS_ACCEPT = 330 SYS_GETSOCKNAME = 331 SYS_GETPEERNAME = 332 SYS_SOCKETPAIR = 333 SYS_SEND = 334 SYS_SENDTO = 335 SYS_RECV = 336 SYS_RECVFROM = 337 SYS_SHUTDOWN = 338 SYS_SETSOCKOPT = 339 SYS_GETSOCKOPT = 340 SYS_SENDMSG = 341 SYS_RECVMSG = 342 SYS_RECVMMSG = 343 SYS_ACCEPT4 = 344 SYS_NAME_TO_HANDLE_AT = 345 SYS_OPEN_BY_HANDLE_AT = 346 SYS_CLOCK_ADJTIME = 347 SYS_SYNCFS = 348 SYS_SENDMMSG = 349 SYS_SETNS = 350 SYS_PROCESS_VM_READV = 351 SYS_PROCESS_VM_WRITEV = 352 SYS_FINIT_MODULE = 353 SYS_KCMP = 354 SYS_SCHED_SETATTR = 355 SYS_SCHED_GETATTR = 356 SYS_RENAMEAT2 = 357 SYS_SECCOMP = 358 SYS_GETRANDOM = 359 SYS_MEMFD_CREATE = 360 SYS_BPF = 361 SYS_EXECVEAT = 362 SYS_SWITCH_ENDIAN = 363 SYS_USERFAULTFD = 364 SYS_MEMBARRIER = 365 SYS_MLOCK2 = 378 SYS_COPY_FILE_RANGE = 379 SYS_PREADV2 = 380 SYS_PWRITEV2 = 381 SYS_KEXEC_FILE_LOAD = 382 SYS_STATX = 383 )
{ "pile_set_name": "Github" }
// // TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <MaterialXGenGlsl/GlslShaderGenerator.h> #include <MaterialXGenGlsl/GlslSyntax.h> #include <MaterialXGenGlsl/Nodes/PositionNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/NormalNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/TangentNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/BitangentNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/TexCoordNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/GeomColorNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/GeomPropValueNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/FrameNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/TimeNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/ViewDirectionNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/SurfaceNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/SurfaceShaderNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/LightNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/LightCompoundNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/LightShaderNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/HeightToNormalNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/LightSamplerNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/NumLightsNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/TransformVectorNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/TransformPointNodeGlsl.h> #include <MaterialXGenGlsl/Nodes/TransformNormalNodeGlsl.h> #include <MaterialXGenShader/Nodes/HwSourceCodeNode.h> #include <MaterialXGenShader/Nodes/SwizzleNode.h> #include <MaterialXGenShader/Nodes/ConvertNode.h> #include <MaterialXGenShader/Nodes/CombineNode.h> #include <MaterialXGenShader/Nodes/SwitchNode.h> #include <MaterialXGenShader/Nodes/IfNode.h> #include <MaterialXGenShader/Nodes/BlurNode.h> #include <MaterialXGenShader/Nodes/HwImageNode.h> namespace MaterialX { const string GlslShaderGenerator::LANGUAGE = "genglsl"; const string GlslShaderGenerator::TARGET = "glsl400"; const string GlslShaderGenerator::VERSION = "400"; // // GlslShaderGenerator methods // GlslShaderGenerator::GlslShaderGenerator() : HwShaderGenerator(GlslSyntax::create()) { // // Register all custom node implementation classes // // <!-- <if*> --> static const string SEPARATOR = "_"; static const string INT_SEPARATOR = "I_"; static const string BOOL_SEPARATOR = "B_"; static const StringVec IMPL_PREFIXES = { "IM_ifgreater_", "IM_ifgreatereq_", "IM_ifequal_" }; static const vector<CreatorFunction<ShaderNodeImpl>> IMPL_CREATE_FUNCTIONS = { IfGreaterNode::create, IfGreaterEqNode::create, IfEqualNode::create }; static const vector<bool> IMPL_HAS_INTVERSION = { true, true, true }; static const vector<bool> IMPL_HAS_BOOLVERSION = { false, false, true }; static const StringVec IMPL_TYPES = { "float", "color2", "color3", "color4", "vector2", "vector3", "vector4" }; for (size_t i=0; i<IMPL_PREFIXES.size(); i++) { const string& implPrefix = IMPL_PREFIXES[i]; for (const string& implType : IMPL_TYPES) { const string implRoot = implPrefix + implType; registerImplementation(implRoot + SEPARATOR + GlslShaderGenerator::LANGUAGE, IMPL_CREATE_FUNCTIONS[i]); if (IMPL_HAS_INTVERSION[i]) { registerImplementation(implRoot + INT_SEPARATOR + GlslShaderGenerator::LANGUAGE, IMPL_CREATE_FUNCTIONS[i]); } if (IMPL_HAS_BOOLVERSION[i]) { registerImplementation(implRoot + BOOL_SEPARATOR + GlslShaderGenerator::LANGUAGE, IMPL_CREATE_FUNCTIONS[i]); } } } // <!-- <switch> --> // <!-- 'which' type : float --> registerImplementation("IM_switch_float_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color2_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color3_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color4_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector2_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector3_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector4_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); // <!-- 'which' type : integer --> registerImplementation("IM_switch_floatI_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color2I_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color3I_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color4I_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector2I_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector3I_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector4I_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); // <!-- 'which' type : boolean --> registerImplementation("IM_switch_floatB_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color2B_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color3B_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_color4B_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector2B_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector3B_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); registerImplementation("IM_switch_vector4B_" + GlslShaderGenerator::LANGUAGE, SwitchNode::create); // <!-- <swizzle> --> // <!-- from type : float --> registerImplementation("IM_swizzle_float_color2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_float_color3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_float_color4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_float_vector2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_float_vector3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_float_vector4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); // <!-- from type : color2 --> registerImplementation("IM_swizzle_color2_float_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color2_color2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color2_color3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color2_color4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color2_vector2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color2_vector3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color2_vector4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); // <!-- from type : color3 --> registerImplementation("IM_swizzle_color3_float_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color3_color2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color3_color3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color3_color4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color3_vector2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color3_vector3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color3_vector4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); // <!-- from type : color4 --> registerImplementation("IM_swizzle_color4_float_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color4_color2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color4_color3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color4_color4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color4_vector2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color4_vector3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_color4_vector4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); // <!-- from type : vector2 --> registerImplementation("IM_swizzle_vector2_float_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector2_color2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector2_color3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector2_color4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector2_vector2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector2_vector3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector2_vector4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); // <!-- from type : vector3 --> registerImplementation("IM_swizzle_vector3_float_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector3_color2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector3_color3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector3_color4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector3_vector2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector3_vector3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector3_vector4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); // <!-- from type : vector4 --> registerImplementation("IM_swizzle_vector4_float_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector4_color2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector4_color3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector4_color4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector4_vector2_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector4_vector3_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); registerImplementation("IM_swizzle_vector4_vector4_" + GlslShaderGenerator::LANGUAGE, SwizzleNode::create); // <!-- <convert> --> registerImplementation("IM_convert_float_color2_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_float_color3_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_float_color4_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_float_vector2_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_float_vector3_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_float_vector4_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_vector2_color2_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_vector2_vector3_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_vector3_vector2_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_vector3_color3_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_vector3_vector4_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_vector4_vector3_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_vector4_color4_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_color2_vector2_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_color3_vector3_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_color4_vector4_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_color3_color4_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_color4_color3_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_boolean_float_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); registerImplementation("IM_convert_integer_float_" + GlslShaderGenerator::LANGUAGE, ConvertNode::create); // <!-- <combine> --> registerImplementation("IM_combine2_color2_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine2_vector2_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine2_color4CF_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine2_vector4VF_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine2_color4CC_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine2_vector4VV_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine3_color3_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine3_vector3_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine4_color4_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); registerImplementation("IM_combine4_vector4_" + GlslShaderGenerator::LANGUAGE, CombineNode::create); // <!-- <position> --> registerImplementation("IM_position_vector3_" + GlslShaderGenerator::LANGUAGE, PositionNodeGlsl::create); // <!-- <normal> --> registerImplementation("IM_normal_vector3_" + GlslShaderGenerator::LANGUAGE, NormalNodeGlsl::create); // <!-- <tangent> --> registerImplementation("IM_tangent_vector3_" + GlslShaderGenerator::LANGUAGE, TangentNodeGlsl::create); // <!-- <bitangent> --> registerImplementation("IM_bitangent_vector3_" + GlslShaderGenerator::LANGUAGE, BitangentNodeGlsl::create); // <!-- <texcoord> --> registerImplementation("IM_texcoord_vector2_" + GlslShaderGenerator::LANGUAGE, TexCoordNodeGlsl::create); registerImplementation("IM_texcoord_vector3_" + GlslShaderGenerator::LANGUAGE, TexCoordNodeGlsl::create); // <!-- <geomcolor> --> registerImplementation("IM_geomcolor_float_" + GlslShaderGenerator::LANGUAGE, GeomColorNodeGlsl::create); registerImplementation("IM_geomcolor_color2_" + GlslShaderGenerator::LANGUAGE, GeomColorNodeGlsl::create); registerImplementation("IM_geomcolor_color3_" + GlslShaderGenerator::LANGUAGE, GeomColorNodeGlsl::create); registerImplementation("IM_geomcolor_color4_" + GlslShaderGenerator::LANGUAGE, GeomColorNodeGlsl::create); // <!-- <geompropvalue> --> registerImplementation("IM_geompropvalue_integer_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_boolean_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_string_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_float_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_color2_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_color3_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_color4_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_vector2_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_vector3_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); registerImplementation("IM_geompropvalue_vector4_" + GlslShaderGenerator::LANGUAGE, GeomPropValueNodeGlsl::create); // <!-- <frame> --> registerImplementation("IM_frame_float_" + GlslShaderGenerator::LANGUAGE, FrameNodeGlsl::create); // <!-- <time> --> registerImplementation("IM_time_float_" + GlslShaderGenerator::LANGUAGE, TimeNodeGlsl::create); // <!-- <viewdirection> --> registerImplementation("IM_viewdirection_vector3_" + GlslShaderGenerator::LANGUAGE, ViewDirectionNodeGlsl::create); // <!-- <surface> --> registerImplementation("IM_surface_" + GlslShaderGenerator::LANGUAGE, SurfaceNodeGlsl::create); // <!-- <light> --> registerImplementation("IM_light_" + GlslShaderGenerator::LANGUAGE, LightNodeGlsl::create); // <!-- <point_light> --> registerImplementation("IM_point_light_" + GlslShaderGenerator::LANGUAGE, LightShaderNodeGlsl::create); // <!-- <directional_light> --> registerImplementation("IM_directional_light_" + GlslShaderGenerator::LANGUAGE, LightShaderNodeGlsl::create); // <!-- <spot_light> --> registerImplementation("IM_spot_light_" + GlslShaderGenerator::LANGUAGE, LightShaderNodeGlsl::create); // <!-- <heighttonormal> --> registerImplementation("IM_heighttonormal_vector3_" + GlslShaderGenerator::LANGUAGE, HeightToNormalNodeGlsl::create); // <!-- <blur> --> registerImplementation("IM_blur_float_" + GlslShaderGenerator::LANGUAGE, BlurNode::create); registerImplementation("IM_blur_color2_" + GlslShaderGenerator::LANGUAGE, BlurNode::create); registerImplementation("IM_blur_color3_" + GlslShaderGenerator::LANGUAGE, BlurNode::create); registerImplementation("IM_blur_color4_" + GlslShaderGenerator::LANGUAGE, BlurNode::create); registerImplementation("IM_blur_vector2_" + GlslShaderGenerator::LANGUAGE, BlurNode::create); registerImplementation("IM_blur_vector3_" + GlslShaderGenerator::LANGUAGE, BlurNode::create); registerImplementation("IM_blur_vector4_" + GlslShaderGenerator::LANGUAGE, BlurNode::create); // <!-- <ND_transformpoint> -> registerImplementation("IM_transformpoint_vector3_" + GlslShaderGenerator::LANGUAGE, TransformPointNodeGlsl::create); // <!-- <ND_transformvector> -> registerImplementation("IM_transformvector_vector3_" + GlslShaderGenerator::LANGUAGE, TransformVectorNodeGlsl::create); // <!-- <ND_transformnormal> -> registerImplementation("IM_transformnormal_vector3_" + GlslShaderGenerator::LANGUAGE, TransformNormalNodeGlsl::create); // <!-- <image> --> registerImplementation("IM_image_float_" + GlslShaderGenerator::LANGUAGE, HwImageNode::create); registerImplementation("IM_image_color2_" + GlslShaderGenerator::LANGUAGE, HwImageNode::create); registerImplementation("IM_image_color3_" + GlslShaderGenerator::LANGUAGE, HwImageNode::create); registerImplementation("IM_image_color4_" + GlslShaderGenerator::LANGUAGE, HwImageNode::create); registerImplementation("IM_image_vector2_" + GlslShaderGenerator::LANGUAGE, HwImageNode::create); registerImplementation("IM_image_vector3_" + GlslShaderGenerator::LANGUAGE, HwImageNode::create); registerImplementation("IM_image_vector4_" + GlslShaderGenerator::LANGUAGE, HwImageNode::create); _lightSamplingNodes.push_back(ShaderNode::create(nullptr, "numActiveLightSources", NumLightsNodeGlsl::create())); _lightSamplingNodes.push_back(ShaderNode::create(nullptr, "sampleLightSource", LightSamplerNodeGlsl::create())); } ShaderPtr GlslShaderGenerator::generate(const string& name, ElementPtr element, GenContext& context) const { ShaderPtr shader = createShader(name, element, context); // Turn on fixed float formatting to make sure float values are // emitted with a decimal point and not as integers, and to avoid // any scientific notation which isn't supported by all OpenGL targets. ScopedFloatFormatting fmt(Value::FloatFormatFixed); // Emit code for vertex shader stage ShaderStage& vs = shader->getStage(Stage::VERTEX); emitVertexStage(shader->getGraph(), context, vs); replaceTokens(_tokenSubstitutions, vs); // Emit code for pixel shader stage ShaderStage& ps = shader->getStage(Stage::PIXEL); emitPixelStage(shader->getGraph(), context, ps); replaceTokens(_tokenSubstitutions, ps); return shader; } void GlslShaderGenerator::emitVertexStage(const ShaderGraph& graph, GenContext& context, ShaderStage& stage) const { // Add version directive emitLine("#version " + getVersion(), stage, false); emitLineBreak(stage); // Add all constants const VariableBlock& constants = stage.getConstantBlock(); if (!constants.empty()) { emitVariableDeclarations(constants, _syntax->getConstantQualifier(), SEMICOLON, context, stage); emitLineBreak(stage); } // Add all uniforms for (const auto& it : stage.getUniformBlocks()) { const VariableBlock& uniforms = *it.second; if (!uniforms.empty()) { emitComment("Uniform block: " + uniforms.getName(), stage); emitVariableDeclarations(uniforms, _syntax->getUniformQualifier(), SEMICOLON, context, stage); emitLineBreak(stage); } } // Add vertex inputs const VariableBlock& vertexInputs = stage.getInputBlock(HW::VERTEX_INPUTS); if (!vertexInputs.empty()) { emitComment("Inputs block: " + vertexInputs.getName(), stage); emitVariableDeclarations(vertexInputs, _syntax->getInputQualifier(), SEMICOLON, context, stage, false); emitLineBreak(stage); } // Add vertex data outputs block const VariableBlock& vertexData = stage.getOutputBlock(HW::VERTEX_DATA); if (!vertexData.empty()) { emitLine("out " + vertexData.getName(), stage, false); emitScopeBegin(stage); emitVariableDeclarations(vertexData, EMPTY_STRING, SEMICOLON, context, stage, false); emitScopeEnd(stage, false, false); emitString(" " + vertexData.getInstance() + SEMICOLON, stage); emitLineBreak(stage); emitLineBreak(stage); } emitFunctionDefinitions(graph, context, stage); // Add main function setFunctionName("main", stage); emitLine("void main()", stage, false); emitScopeBegin(stage); emitLine("vec4 hPositionWorld = " + HW::T_WORLD_MATRIX + " * vec4(" + HW::T_IN_POSITION + ", 1.0)", stage); emitLine("gl_Position = " + HW::T_VIEW_PROJECTION_MATRIX + " * hPositionWorld", stage); emitFunctionCalls(graph, context, stage); emitScopeEnd(stage); emitLineBreak(stage); } void GlslShaderGenerator::emitSpecularEnvironment(GenContext& context, ShaderStage& stage) const { int specularMethod = context.getOptions().hwSpecularEnvironmentMethod; if (specularMethod == SPECULAR_ENVIRONMENT_FIS) { emitInclude("pbrlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_environment_fis.glsl", context, stage); } else if (specularMethod == SPECULAR_ENVIRONMENT_PREFILTER) { emitInclude("pbrlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_environment_prefilter.glsl", context, stage); } else if (specularMethod == SPECULAR_ENVIRONMENT_NONE) { emitInclude("pbrlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_environment_none.glsl", context, stage); } else { throw ExceptionShaderGenError("Invalid hardware specular environment method specified: '" + std::to_string(specularMethod) + "'"); } emitLineBreak(stage); } void GlslShaderGenerator::emitPixelStage(const ShaderGraph& graph, GenContext& context, ShaderStage& stage) const { // Add version directive emitLine("#version " + getVersion(), stage, false); emitLineBreak(stage); // Add global constants and type definitions emitInclude("pbrlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_defines.glsl", context, stage); const unsigned int maxLights = std::max(1u, context.getOptions().hwMaxActiveLightSources); emitLine("#define MAX_LIGHT_SOURCES " + std::to_string(maxLights), stage, false); emitLine("#define DIRECTIONAL_ALBEDO_METHOD " + std::to_string(int(context.getOptions().hwDirectionalAlbedoMethod)), stage, false); emitLineBreak(stage); emitTypeDefinitions(context, stage); // Add all constants const VariableBlock& constants = stage.getConstantBlock(); if (!constants.empty()) { emitVariableDeclarations(constants, _syntax->getConstantQualifier(), SEMICOLON, context, stage); emitLineBreak(stage); } // Add all uniforms for (const auto& it : stage.getUniformBlocks()) { const VariableBlock& uniforms = *it.second; // Skip light uniforms as they are handled separately if (!uniforms.empty() && uniforms.getName() != HW::LIGHT_DATA) { emitComment("Uniform block: " + uniforms.getName(), stage); emitVariableDeclarations(uniforms, _syntax->getUniformQualifier(), SEMICOLON, context, stage); emitLineBreak(stage); } } bool lighting = graph.hasClassification(ShaderNode::Classification::SHADER|ShaderNode::Classification::SURFACE) || graph.hasClassification(ShaderNode::Classification::BSDF); bool shadowing = (lighting && context.getOptions().hwShadowMap) || context.getOptions().hwWriteDepthMoments; // Add light data block if needed if (lighting) { const VariableBlock& lightData = stage.getUniformBlock(HW::LIGHT_DATA); emitLine("struct " + lightData.getName(), stage, false); emitScopeBegin(stage); emitVariableDeclarations(lightData, EMPTY_STRING, SEMICOLON, context, stage, false); emitScopeEnd(stage, true); emitLineBreak(stage); emitLine("uniform " + lightData.getName() + " " + lightData.getInstance() + "[MAX_LIGHT_SOURCES]", stage); emitLineBreak(stage); } // Add vertex data inputs block const VariableBlock& vertexData = stage.getInputBlock(HW::VERTEX_DATA); if (!vertexData.empty()) { emitLine("in " + vertexData.getName(), stage, false); emitScopeBegin(stage); emitVariableDeclarations(vertexData, EMPTY_STRING, SEMICOLON, context, stage, false); emitScopeEnd(stage, false, false); emitString(" " + vertexData.getInstance() + SEMICOLON, stage); emitLineBreak(stage); emitLineBreak(stage); } // Add the pixel shader output. This needs to be a vec4 for rendering // and upstream connection will be converted to vec4 if needed in emitFinalOutput() emitComment("Pixel shader outputs", stage); const VariableBlock& outputs = stage.getOutputBlock(HW::PIXEL_OUTPUTS); emitVariableDeclarations(outputs, _syntax->getOutputQualifier(), SEMICOLON, context, stage, false); emitLineBreak(stage); // Emit common math functions emitInclude("pbrlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_math.glsl", context, stage); emitLineBreak(stage); // Emit texture sampling code if (graph.hasClassification(ShaderNode::Classification::CONVOLUTION2D)) { emitInclude("stdlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_sampling.glsl", context, stage); emitLineBreak(stage); } // Emit lighting and shadowing code if (lighting) { emitSpecularEnvironment(context, stage); } if (shadowing) { emitInclude("pbrlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_shadow.glsl", context, stage); } // Emit directional albedo table code. if (context.getOptions().hwDirectionalAlbedoMethod == DIRECTIONAL_ALBEDO_TABLE || context.getOptions().hwWriteAlbedoTable) { emitInclude("pbrlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_table.glsl", context, stage); emitLineBreak(stage); } // Set the include file to use for uv transformations, // depending on the vertical flip flag. if (context.getOptions().fileTextureVerticalFlip) { _tokenSubstitutions[ShaderGenerator::T_FILE_TRANSFORM_UV] = "stdlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_transform_uv_vflip.glsl"; } else { _tokenSubstitutions[ShaderGenerator::T_FILE_TRANSFORM_UV] = "stdlib/" + GlslShaderGenerator::LANGUAGE + "/lib/mx_transform_uv.glsl"; } // Emit uv transform code globally if needed. if (context.getOptions().hwAmbientOcclusion) { emitInclude(ShaderGenerator::T_FILE_TRANSFORM_UV, context, stage); } // Add all functions for node implementations emitFunctionDefinitions(graph, context, stage); const ShaderGraphOutputSocket* outputSocket = graph.getOutputSocket(); // Add main function setFunctionName("main", stage); emitLine("void main()", stage, false); emitScopeBegin(stage); if (graph.hasClassification(ShaderNode::Classification::CLOSURE)) { // Handle the case where the graph is a direct closure. // We don't support rendering closures without attaching // to a surface shader, so just output black. emitLine(outputSocket->getVariable() + " = vec4(0.0, 0.0, 0.0, 1.0)", stage); } else if (context.getOptions().hwWriteDepthMoments) { emitLine(outputSocket->getVariable() + " = vec4(mx_compute_depth_moments(), 0.0, 1.0)", stage); } else if (context.getOptions().hwWriteAlbedoTable) { emitLine(outputSocket->getVariable() + " = vec4(mx_ggx_directional_albedo_generate_table(), 0.0, 1.0)", stage); } else { // Add all function calls emitFunctionCalls(graph, context, stage); // Emit final output const ShaderOutput* outputConnection = outputSocket->getConnection(); if (outputConnection) { string finalOutput = outputConnection->getVariable(); const string& channels = outputSocket->getChannels(); if (!channels.empty()) { finalOutput = _syntax->getSwizzledVariable(finalOutput, outputConnection->getType(), channels, outputSocket->getType()); } if (graph.hasClassification(ShaderNode::Classification::SURFACE)) { if (context.getOptions().hwTransparency) { emitLine("float outAlpha = clamp(1.0 - dot(" + finalOutput + ".transparency, vec3(0.3333)), 0.0, 1.0)", stage); emitLine(outputSocket->getVariable() + " = vec4(" + finalOutput + ".color, outAlpha)", stage); } else { emitLine(outputSocket->getVariable() + " = vec4(" + finalOutput + ".color, 1.0)", stage); } } else { if (!outputSocket->getType()->isFloat4()) { toVec4(outputSocket->getType(), finalOutput); } emitLine(outputSocket->getVariable() + " = " + finalOutput, stage); } } else { string outputValue = outputSocket->getValue() ? _syntax->getValue(outputSocket->getType(), *outputSocket->getValue()) : _syntax->getDefaultValue(outputSocket->getType()); if (!outputSocket->getType()->isFloat4()) { string finalOutput = outputSocket->getVariable() + "_tmp"; emitLine(_syntax->getTypeName(outputSocket->getType()) + " " + finalOutput + " = " + outputValue, stage); toVec4(outputSocket->getType(), finalOutput); emitLine(outputSocket->getVariable() + " = " + finalOutput, stage); } else { emitLine(outputSocket->getVariable() + " = " + outputValue, stage); } } } // End main function emitScopeEnd(stage); emitLineBreak(stage); } void GlslShaderGenerator::emitFunctionDefinitions(const ShaderGraph& graph, GenContext& context, ShaderStage& stage) const { BEGIN_SHADER_STAGE(stage, Stage::PIXEL) // For surface shaders we need light shaders if (graph.hasClassification(ShaderNode::Classification::SHADER | ShaderNode::Classification::SURFACE)) { // Emit functions for all bound light shaders HwLightShadersPtr lightShaders = context.getUserData<HwLightShaders>(HW::USER_DATA_LIGHT_SHADERS); if (lightShaders) { for (const auto& it : lightShaders->get()) { emitFunctionDefinition(*it.second, context, stage); } } // Emit functions for light sampling for (const auto& it : _lightSamplingNodes) { emitFunctionDefinition(*it, context, stage); } } END_SHADER_STAGE(stage, Stage::PIXEL) // Call parent to emit all other functions HwShaderGenerator::emitFunctionDefinitions(graph, context, stage); } void GlslShaderGenerator::emitFunctionCalls(const ShaderGraph& graph, GenContext& context, ShaderStage& stage) const { BEGIN_SHADER_STAGE(stage, Stage::VERTEX) // For vertex stage just emit all function calls in order // and ignore conditional scope. for (const ShaderNode* node : graph.getNodes()) { emitFunctionCall(*node, context, stage, false); } END_SHADER_STAGE(stage, Stage::VERTEX) BEGIN_SHADER_STAGE(stage, Stage::PIXEL) // For pixel stage surface shaders need special handling if (graph.hasClassification(ShaderNode::Classification::SHADER | ShaderNode::Classification::SURFACE)) { // Handle all texturing nodes. These are inputs to any // closure/shader nodes and need to be emitted first. emitTextureNodes(graph, context, stage); // Emit function calls for all surface shader nodes for (const ShaderNode* node : graph.getNodes()) { if (node->hasClassification(ShaderNode::Classification::SHADER | ShaderNode::Classification::SURFACE)) { emitFunctionCall(*node, context, stage, false); } } } else { // No surface shader or closure graph, // so generate a normel function call. HwShaderGenerator::emitFunctionCalls(graph, context, stage); } END_SHADER_STAGE(stage, Stage::PIXEL) } void GlslShaderGenerator::toVec4(const TypeDesc* type, string& variable) { if (type->isFloat3()) { variable = "vec4(" + variable + ", 1.0)"; } else if (type->isFloat2()) { variable = "vec4(" + variable + ", 0.0, 1.0)"; } else if (type == Type::FLOAT || type == Type::INTEGER) { variable = "vec4(" + variable + ", " + variable + ", " + variable + ", 1.0)"; } else if (type == Type::BSDF || type == Type::EDF) { variable = "vec4(" + variable + ", 1.0)"; } else { // Can't understand other types. Just return black. variable = "vec4(0.0, 0.0, 0.0, 1.0)"; } } void GlslShaderGenerator::emitVariableDeclaration(const ShaderPort* variable, const string& qualifier, GenContext&, ShaderStage& stage, bool assignValue) const { // A file texture input needs special handling on GLSL if (variable->getType() == Type::FILENAME) { // Samplers must always be uniforms string str = qualifier.empty() ? EMPTY_STRING : qualifier + " "; emitString(str + "sampler2D " + variable->getVariable(), stage); } else { string str = qualifier.empty() ? EMPTY_STRING : qualifier + " "; str += _syntax->getTypeName(variable->getType()) + " " + variable->getVariable(); // If an array we need an array qualifier (suffix) for the variable name if (variable->getType()->isArray() && variable->getValue()) { str += _syntax->getArraySuffix(variable->getType(), *variable->getValue()); } if (!variable->getSemantic().empty()) { str += " : " + variable->getSemantic(); } if (assignValue) { const string valueStr = (variable->getValue() ? _syntax->getValue(variable->getType(), *variable->getValue(), true) : _syntax->getDefaultValue(variable->getType(), true)); str += valueStr.empty() ? EMPTY_STRING : " = " + valueStr; } emitString(str, stage); } } ShaderNodeImplPtr GlslShaderGenerator::createCompoundImplementation(const NodeGraph& impl) const { NodeDefPtr nodeDef = impl.getNodeDef(); if (!nodeDef) { throw ExceptionShaderGenError("Error creating compound implementation. Given nodegraph '" + impl.getName() + "' has no nodedef set"); } if (TypeDesc::get(nodeDef->getType()) == Type::LIGHTSHADER) { return LightCompoundNodeGlsl::create(); } return HwShaderGenerator::createCompoundImplementation(impl); } bool GlslShaderGenerator::remapEnumeration(const ValueElement& input, const string& value, std::pair<const TypeDesc*, ValuePtr>& result) const { // Early out if not an enum input. const string& enumNames = input.getAttribute(ValueElement::ENUM_ATTRIBUTE); if (enumNames.empty()) { return false; } // Don't convert already supported types // or filenames and arrays. const TypeDesc* type = TypeDesc::get(input.getType()); if (_syntax->typeSupported(type) || type == Type::FILENAME || type->isArray()) { return false; } // For GLSL we always convert to integer, // with the integer value being an index into the enumeration. result.first = Type::INTEGER; result.second = nullptr; // Try remapping to an enum value. if (!value.empty()) { StringVec valueElemEnumsVec = splitString(enumNames, ","); auto pos = std::find(valueElemEnumsVec.begin(), valueElemEnumsVec.end(), value); if (pos == valueElemEnumsVec.end()) { throw ExceptionShaderGenError("Given value '" + value + "' is not a valid enum value for input '" + input.getNamePath() + "'"); } const int index = static_cast<int>(std::distance(valueElemEnumsVec.begin(), pos)); result.second = Value::createValue<int>(index); } return true; } const string GlslImplementation::SPACE = "space"; const string GlslImplementation::TO_SPACE = "tospace"; const string GlslImplementation::FROM_SPACE = "fromspace"; const string GlslImplementation::WORLD = "world"; const string GlslImplementation::OBJECT = "object"; const string GlslImplementation::MODEL = "model"; const string GlslImplementation::INDEX = "index"; const string GlslImplementation::GEOMPROP = "geomprop"; namespace { // List name of inputs that are not to be editable and // published as shader uniforms in GLSL. const std::set<string> IMMUTABLE_INPUTS = { // Geometric node inputs are immutable since a shader needs regeneration if they change. "index", "space", "attrname" }; } const string& GlslImplementation::getLanguage() const { return GlslShaderGenerator::LANGUAGE; } const string& GlslImplementation::getTarget() const { return GlslShaderGenerator::TARGET; } bool GlslImplementation::isEditable(const ShaderInput& input) const { return IMMUTABLE_INPUTS.count(input.getName()) == 0; } }
{ "pile_set_name": "Github" }
<test> <preconditions> <table_exists>hits_100m_single</table_exists> <table_exists>hits_10m_single</table_exists> </preconditions> <query>SELECT count() FROM hits_10m_single WHERE NOT ignore(toString(WatchID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(JavaEnable)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(GoodEvent)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(CounterID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ClientIP)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(RegionID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_10m_single WHERE NOT ignore(toString(UserID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(CounterClass)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(OS)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(UserAgent)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(Refresh)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ResolutionWidth)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ResolutionHeight)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ResolutionDepth)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(FlashMajor)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(FlashMinor)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(NetMajor)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(NetMinor)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(UserAgentMajor)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(CookieEnable)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(JavascriptEnable)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IsMobile)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(MobilePhone)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IPNetworkID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(TraficSourceID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(SearchEngineID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(SearchPhrase)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(AdvEngineID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IsArtifical)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(WindowClientWidth)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(WindowClientHeight)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ClientTimeZone)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(SilverlightVersion1)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(SilverlightVersion2)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(SilverlightVersion3)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(SilverlightVersion4)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(CodeVersion)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IsLink)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IsDownload)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IsNotBounce)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_10m_single WHERE NOT ignore(toString(FUniqID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(HID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IsOldCounter)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IsEvent)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(IsParameter)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(DontCountHits)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(WithHash)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(Age)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(Sex)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(Income)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(Interests)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(Robotness)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(RemoteIP)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(WindowName)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(OpenerName)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(HistoryLength)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(HTTPError)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(SendTiming)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(DNSTiming)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ConnectTiming)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ResponseStartTiming)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ResponseEndTiming)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(FetchTiming)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(SocialSourceNetworkID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ParamPrice)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(ParamCurrencyID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(HasGCLID)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_10m_single WHERE NOT ignore(toString(RefererHash)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_10m_single WHERE NOT ignore(toString(URLHash)) SETTINGS max_threads = 1</query> <query>SELECT count() FROM hits_100m_single WHERE NOT ignore(toString(CLID)) SETTINGS max_threads = 1</query> </test>
{ "pile_set_name": "Github" }
name: "Showmax" url: "https://tech.showmax.com/"
{ "pile_set_name": "Github" }
(;CA[UTF-8]AP[YuanYu]GM[1]FF[4] SZ[19] GN[] DT[2017-07-16] PB[单身情歌]BR[9段] PW[骊龙]WR[9段] KM[750]HA[0]RU[Japanese]RE[W+R]TM[60]TC[3]TT[60] ;B[pd];W[dd];B[pq];W[dp];B[fq];W[cn];B[jp];W[po];B[pl];W[lo];B[np] ;W[no];B[oo];W[on];B[op];W[nn];B[mp];W[qn];B[pi];W[qq];B[qr];W[qp] ;B[rr];W[rl];B[fc];W[cf];B[jd];W[qf];B[pf];W[pg];B[of];W[qd];B[qc] ;W[re];B[pe];W[qg];B[og];W[pc];B[pb];W[oc];B[rc];W[ob];B[qa];W[oa] ;B[sb];W[rd];B[ra];W[oh];B[ph];W[nh];B[rh];W[mf];B[nd];W[ld];B[le] ;W[ke];B[ng];W[mg];B[mh];W[oj];B[me];W[ne];B[lh];W[lg];B[nf];W[md] ;B[oe];W[lf];B[ne];W[kf];B[nc];W[kd];B[mb];W[lb];B[ma];W[rj];B[pj] ;W[qh];B[mj];W[ec];B[fd];W[jc];B[ic];W[id];B[hd];W[je];B[ef];W[df] ;B[eh];W[di];B[dh];W[ch];B[ci];W[cj];B[bi];W[bh];B[dj];W[ei];B[bj] ;W[fh];B[ck];W[eg];B[dr];W[cq];B[ib];W[he];B[fo];W[jb];B[cr];W[bl] ;B[dm];W[dn];B[en];W[br];B[mo];W[nl];B[pk];W[kh];B[rm];W[ri];B[lj] ;W[qm];B[de];W[eb];B[ge];W[hc];B[gc];W[hb];B[hf];W[gd];B[gg];W[hh] ;B[hd];W[ie];B[fi];W[dg];B[gh];W[gi];B[hi];W[fj];B[gj];W[fi];B[ih] ;W[ff])
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Diagnostics as Diag; operation CheckAllowNCallsTestShouldFail() : Unit { within { Diag.AllowAtMostNCallsCA(3, X, "Too many calls to X."); } apply { using (q = Qubit()) { // Should run four times, one more // than the three allowed. for (idx in 0..3) { X(q); } } } } @Diag.Test("QuantumSimulator") operation CheckAllowNCalls() : Unit { within { Diag.AllowAtMostNCallsCA(4, X, "Too many calls to X."); } apply { using (q = Qubit()) { // Should run four times, exactly as // many times as allowed. for (idx in 0..3) { X(q); } } } } @Diag.Test("ToffoliSimulator") operation CheckAllowNQubitsWithNestedCalls() : Unit { // Here, the total number of allocated qubits exceeds our policy, // but the number of thosse qubits allocated inside the policy // condition is still OK such that this should pass. using (outer = Qubit[4]) { within { Diag.AllowAtMostNQubits(5, "Too many additional qubit allocations."); } apply { using (qs = Qubit[2]) { using (qs2 = Qubit[1]) { } using (qs2 = Qubit[2]) { } } } } } operation CheckAllowNQubitsTestShouldFail() : Unit { within { Diag.AllowAtMostNQubits(3, "Too many additional qubit allocations."); } apply { using (qs = Qubit[2]) { using (qs2 = Qubit[1]) { } using (qs2 = Qubit[2]) { } } } } @Diag.Test("QuantumSimulator") operation CheckAllowNQubits() : Unit { within { Diag.AllowAtMostNQubits(3, "Too many additional qubit allocations."); } apply { using (qs = Qubit[3]) { } } } }
{ "pile_set_name": "Github" }
package mfe_MU import ( "testing" "time" "github.com/go-playground/locales" "github.com/go-playground/locales/currency" ) func TestLocale(t *testing.T) { trans := New() expected := "mfe_MU" if trans.Locale() != expected { t.Errorf("Expected '%s' Got '%s'", expected, trans.Locale()) } } func TestPluralsRange(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsRange() // expected := 1 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestPluralsOrdinal(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOne, // }, // { // expected: locales.PluralRuleTwo, // }, // { // expected: locales.PluralRuleFew, // }, // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsOrdinal() // expected := 4 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestPluralsCardinal(t *testing.T) { trans := New() tests := []struct { expected locales.PluralRule }{ // { // expected: locales.PluralRuleOne, // }, // { // expected: locales.PluralRuleOther, // }, } rules := trans.PluralsCardinal() // expected := 2 // if len(rules) != expected { // t.Errorf("Expected '%d' Got '%d'", expected, len(rules)) // } for _, tt := range tests { r := locales.PluralRuleUnknown for i := 0; i < len(rules); i++ { if rules[i] == tt.expected { r = rules[i] break } } if r == locales.PluralRuleUnknown { t.Errorf("Expected '%s' Got '%s'", tt.expected, r) } } } func TestRangePlurals(t *testing.T) { trans := New() tests := []struct { num1 float64 v1 uint64 num2 float64 v2 uint64 expected locales.PluralRule }{ // { // num1: 1, // v1: 1, // num2: 2, // v2: 2, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.RangePluralRule(tt.num1, tt.v1, tt.num2, tt.v2) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestOrdinalPlurals(t *testing.T) { trans := New() tests := []struct { num float64 v uint64 expected locales.PluralRule }{ // { // num: 1, // v: 0, // expected: locales.PluralRuleOne, // }, // { // num: 2, // v: 0, // expected: locales.PluralRuleTwo, // }, // { // num: 3, // v: 0, // expected: locales.PluralRuleFew, // }, // { // num: 4, // v: 0, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.OrdinalPluralRule(tt.num, tt.v) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestCardinalPlurals(t *testing.T) { trans := New() tests := []struct { num float64 v uint64 expected locales.PluralRule }{ // { // num: 1, // v: 0, // expected: locales.PluralRuleOne, // }, // { // num: 4, // v: 0, // expected: locales.PluralRuleOther, // }, } for _, tt := range tests { rule := trans.CardinalPluralRule(tt.num, tt.v) if rule != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, rule) } } } func TestDaysAbbreviated(t *testing.T) { trans := New() days := trans.WeekdaysAbbreviated() for i, day := range days { s := trans.WeekdayAbbreviated(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sun", // }, // { // idx: 1, // expected: "Mon", // }, // { // idx: 2, // expected: "Tue", // }, // { // idx: 3, // expected: "Wed", // }, // { // idx: 4, // expected: "Thu", // }, // { // idx: 5, // expected: "Fri", // }, // { // idx: 6, // expected: "Sat", // }, } for _, tt := range tests { s := trans.WeekdayAbbreviated(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysNarrow(t *testing.T) { trans := New() days := trans.WeekdaysNarrow() for i, day := range days { s := trans.WeekdayNarrow(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", string(day), s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "S", // }, // { // idx: 1, // expected: "M", // }, // { // idx: 2, // expected: "T", // }, // { // idx: 3, // expected: "W", // }, // { // idx: 4, // expected: "T", // }, // { // idx: 5, // expected: "F", // }, // { // idx: 6, // expected: "S", // }, } for _, tt := range tests { s := trans.WeekdayNarrow(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysShort(t *testing.T) { trans := New() days := trans.WeekdaysShort() for i, day := range days { s := trans.WeekdayShort(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Su", // }, // { // idx: 1, // expected: "Mo", // }, // { // idx: 2, // expected: "Tu", // }, // { // idx: 3, // expected: "We", // }, // { // idx: 4, // expected: "Th", // }, // { // idx: 5, // expected: "Fr", // }, // { // idx: 6, // expected: "Sa", // }, } for _, tt := range tests { s := trans.WeekdayShort(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestDaysWide(t *testing.T) { trans := New() days := trans.WeekdaysWide() for i, day := range days { s := trans.WeekdayWide(time.Weekday(i)) if s != day { t.Errorf("Expected '%s' Got '%s'", day, s) } } tests := []struct { idx int expected string }{ // { // idx: 0, // expected: "Sunday", // }, // { // idx: 1, // expected: "Monday", // }, // { // idx: 2, // expected: "Tuesday", // }, // { // idx: 3, // expected: "Wednesday", // }, // { // idx: 4, // expected: "Thursday", // }, // { // idx: 5, // expected: "Friday", // }, // { // idx: 6, // expected: "Saturday", // }, } for _, tt := range tests { s := trans.WeekdayWide(time.Weekday(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsAbbreviated(t *testing.T) { trans := New() months := trans.MonthsAbbreviated() for i, month := range months { s := trans.MonthAbbreviated(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "Jan", // }, // { // idx: 2, // expected: "Feb", // }, // { // idx: 3, // expected: "Mar", // }, // { // idx: 4, // expected: "Apr", // }, // { // idx: 5, // expected: "May", // }, // { // idx: 6, // expected: "Jun", // }, // { // idx: 7, // expected: "Jul", // }, // { // idx: 8, // expected: "Aug", // }, // { // idx: 9, // expected: "Sep", // }, // { // idx: 10, // expected: "Oct", // }, // { // idx: 11, // expected: "Nov", // }, // { // idx: 12, // expected: "Dec", // }, } for _, tt := range tests { s := trans.MonthAbbreviated(time.Month(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsNarrow(t *testing.T) { trans := New() months := trans.MonthsNarrow() for i, month := range months { s := trans.MonthNarrow(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "J", // }, // { // idx: 2, // expected: "F", // }, // { // idx: 3, // expected: "M", // }, // { // idx: 4, // expected: "A", // }, // { // idx: 5, // expected: "M", // }, // { // idx: 6, // expected: "J", // }, // { // idx: 7, // expected: "J", // }, // { // idx: 8, // expected: "A", // }, // { // idx: 9, // expected: "S", // }, // { // idx: 10, // expected: "O", // }, // { // idx: 11, // expected: "N", // }, // { // idx: 12, // expected: "D", // }, } for _, tt := range tests { s := trans.MonthNarrow(time.Month(tt.idx)) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestMonthsWide(t *testing.T) { trans := New() months := trans.MonthsWide() for i, month := range months { s := trans.MonthWide(time.Month(i + 1)) if s != month { t.Errorf("Expected '%s' Got '%s'", month, s) } } tests := []struct { idx int expected string }{ // { // idx: 1, // expected: "January", // }, // { // idx: 2, // expected: "February", // }, // { // idx: 3, // expected: "March", // }, // { // idx: 4, // expected: "April", // }, // { // idx: 5, // expected: "May", // }, // { // idx: 6, // expected: "June", // }, // { // idx: 7, // expected: "July", // }, // { // idx: 8, // expected: "August", // }, // { // idx: 9, // expected: "September", // }, // { // idx: 10, // expected: "October", // }, // { // idx: 11, // expected: "November", // }, // { // idx: 12, // expected: "December", // }, } for _, tt := range tests { s := string(trans.MonthWide(time.Month(tt.idx))) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeFull(t *testing.T) { // loc, err := time.LoadLocation("America/Toronto") // if err != nil { // t.Errorf("Expected '<nil>' Got '%s'", err) // } // fixed := time.FixedZone("OTHER", -4) tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc), // expected: "9:05:01 am Eastern Standard Time", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, fixed), // expected: "8:05:01 pm OTHER", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeFull(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeLong(t *testing.T) { // loc, err := time.LoadLocation("America/Toronto") // if err != nil { // t.Errorf("Expected '<nil>' Got '%s'", err) // } tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc), // expected: "9:05:01 am EST", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, loc), // expected: "8:05:01 pm EST", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeLong(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeMedium(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC), // expected: "9:05:01 am", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC), // expected: "8:05:01 pm", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeMedium(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtTimeShort(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC), // expected: "9:05 am", // }, // { // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC), // expected: "8:05 pm", // }, } trans := New() for _, tt := range tests { s := trans.FmtTimeShort(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateFull(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "Wednesday, February 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateFull(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateLong(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "February 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateLong(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateMedium(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "Feb 3, 2016", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateMedium(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtDateShort(t *testing.T) { tests := []struct { t time.Time expected string }{ // { // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "2/3/16", // }, // { // t: time.Date(-500, 02, 03, 9, 0, 1, 0, time.UTC), // expected: "2/3/500", // }, } trans := New() for _, tt := range tests { s := trans.FmtDateShort(tt.t) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtNumber(t *testing.T) { tests := []struct { num float64 v uint64 expected string }{ // { // num: 1123456.5643, // v: 2, // expected: "1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // expected: "1,123,456.6", // }, // { // num: 221123456.5643, // v: 3, // expected: "221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // expected: "-221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // expected: "-221,123,456.564", // }, // { // num: 0, // v: 2, // expected: "0.00", // }, // { // num: -0, // v: 2, // expected: "0.00", // }, // { // num: -0, // v: 2, // expected: "0.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtNumber(tt.num, tt.v) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtCurrency(t *testing.T) { tests := []struct { num float64 v uint64 currency currency.Type expected string }{ // { // num: 1123456.5643, // v: 2, // currency: currency.USD, // expected: "$1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // currency: currency.USD, // expected: "$1,123,456.60", // }, // { // num: 221123456.5643, // v: 3, // currency: currency.USD, // expected: "$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.USD, // expected: "-$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.CAD, // expected: "-CAD 221,123,456.564", // }, // { // num: 0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.CAD, // expected: "CAD 0.00", // }, // { // num: 1.23, // v: 0, // currency: currency.USD, // expected: "$1.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtCurrency(tt.num, tt.v, tt.currency) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtAccounting(t *testing.T) { tests := []struct { num float64 v uint64 currency currency.Type expected string }{ // { // num: 1123456.5643, // v: 2, // currency: currency.USD, // expected: "$1,123,456.56", // }, // { // num: 1123456.5643, // v: 1, // currency: currency.USD, // expected: "$1,123,456.60", // }, // { // num: 221123456.5643, // v: 3, // currency: currency.USD, // expected: "$221,123,456.564", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.USD, // expected: "($221,123,456.564)", // }, // { // num: -221123456.5643, // v: 3, // currency: currency.CAD, // expected: "(CAD 221,123,456.564)", // }, // { // num: -0, // v: 2, // currency: currency.USD, // expected: "$0.00", // }, // { // num: -0, // v: 2, // currency: currency.CAD, // expected: "CAD 0.00", // }, // { // num: 1.23, // v: 0, // currency: currency.USD, // expected: "$1.00", // }, } trans := New() for _, tt := range tests { s := trans.FmtAccounting(tt.num, tt.v, tt.currency) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } } func TestFmtPercent(t *testing.T) { tests := []struct { num float64 v uint64 expected string }{ // { // num: 15, // v: 0, // expected: "15%", // }, // { // num: 15, // v: 2, // expected: "15.00%", // }, // { // num: 434.45, // v: 0, // expected: "434%", // }, // { // num: 34.4, // v: 2, // expected: "34.40%", // }, // { // num: -34, // v: 0, // expected: "-34%", // }, } trans := New() for _, tt := range tests { s := trans.FmtPercent(tt.num, tt.v) if s != tt.expected { t.Errorf("Expected '%s' Got '%s'", tt.expected, s) } } }
{ "pile_set_name": "Github" }
//****************************************************************************************************** // ImportedMeasurement.cs - Gbtc // // Copyright © 2017, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 09/27/2017 - Stephen C. Wills // Generated original version of source code. // //****************************************************************************************************** // ReSharper disable CheckNamespace #pragma warning disable 1591 using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Transactions; using System.Web.Http; using GSF.Configuration; using GSF.Data; using GSF.Data.Model; using GSF.Web.Security; using IsolationLevel = System.Transactions.IsolationLevel; namespace openHistorian.Model { public class ImportedMeasurement { public Guid? NodeID { get; set; } public Guid? SourceNodeID { get; set; } public Guid? SignalID { get; set; } [StringLength(200)] public string Source { get; set; } public long PointID { get; set; } [StringLength(200)] public string PointTag { get; set; } [StringLength(200)] public string AlternateTag { get; set; } [StringLength(4)] public string SignalTypeAcronym { get; set; } [StringLength(200)] public string SignalReference { get; set; } public int? FramesPerSecond { get; set; } [StringLength(200)] public string ProtocolAcronym { get; set; } [StringLength(200)] [DefaultValue("Frame")] public string ProtocolType { get; set; } public int? PhasorID { get; set; } [FieldDataType(DbType.String)] public char? PhasorType { get; set; } [FieldDataType(DbType.String)] public char? Phase { get; set; } [DefaultValue(0.0D)] public double Adder { get; set; } [DefaultValue(1.0D)] public double Multiplier { get; set; } [StringLength(200)] public string CompanyAcronym { get; set; } public double? Longitude { get; set; } public double? Latitude { get; set; } public string Description { get; set; } [DefaultValue(false)] public bool Enabled { get; set; } } public class ImportedMeasurementsController : ApiController { #region [ Properties ] private Guid NodeID { get { ConfigurationFile configurationFile = ConfigurationFile.Current; CategorizedSettingsElementCollection systemSettings = configurationFile.Settings["systemSettings"]; string nodeIDSetting = systemSettings["NodeID"].Value; if (!Guid.TryParse(nodeIDSetting, out Guid nodeID)) return Guid.Empty; return nodeID; } } private string Source { get { string username = User.Identity.Name; return new string(username .ToUpper() .Select(c => char.IsLetterOrDigit(c) ? c : '_') .ToArray()); } } #endregion #region [ Methods ] // This generates a request verification token that will need to be added to the headers // of a web request before calling ImportMeasurements or DeleteMeasurement since these // methods validate the header token to prevent CSRF attacks in a browser. Browsers will // not allow this HTTP GET based method to be called from remote sites due to Same-Origin // policies unless CORS has been configured to explicitly to allow it, as such posting to // ImportMeasurements or DeleteMeasurement (which is allowed from any site) will fail // unless this header token is made available. The actual header name used to store the // verification token is controlled by the local configuration. [HttpGet] public HttpResponseMessage GenerateRequestVerficationToken() { return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(Request.GenerateRequestVerficationHeaderToken(), Encoding.UTF8, "text/plain") }; } [HttpGet] public IEnumerable<ImportedMeasurement> FindAll() { return QueryImportedMeasurements(); } [HttpGet] public IEnumerable<ImportedMeasurement> FindByID(long id) { return QueryImportedMeasurements(new RecordRestriction("PointID = {0}", id)); } [HttpGet] public IEnumerable<ImportedMeasurement> FindByPointTag(string id) { return QueryImportedMeasurements(new RecordRestriction("PointTag = {0}", id)); } [HttpGet] public IEnumerable<ImportedMeasurement> FindByAlternateTag(string id) { return QueryImportedMeasurements(new RecordRestriction("AlternateTag = {0}", id)); } [HttpPost] [ValidateRequestVerificationToken, SuppressMessage("Security", "SG0016", Justification = "CSRF vulnerability handled via ValidateRequestVerificationToken.")] public void ImportMeasurements(IEnumerable<ImportedMeasurement> measurements) { foreach (ImportedMeasurement measurement in measurements) CreateOrUpdate(measurement); } [HttpDelete] [ValidateRequestVerificationToken, SuppressMessage("Security", "SG0016", Justification = "CSRF vulnerability handled via ValidateRequestVerificationToken.")] public void DeleteMeasurement(long id) { long pointID = id; using (AdoDataConnection connection = CreateDbConnection()) { TableOperations<ImportedMeasurement> importedMeasurementTable = new TableOperations<ImportedMeasurement>(connection); RecordRestriction recordRestriction = new RecordRestriction("NodeID = {0}", NodeID) & new RecordRestriction("Source = {0}", Source) & new RecordRestriction("PointID = {0}", pointID); importedMeasurementTable.DeleteRecord(recordRestriction); } } private IEnumerable<ImportedMeasurement> QueryImportedMeasurements(RecordRestriction recordRestriction = null) { using (AdoDataConnection connection = CreateDbConnection()) { TableOperations<ImportedMeasurement> importedMeasurementTable = new TableOperations<ImportedMeasurement>(connection); RecordRestriction queryRestriction = new RecordRestriction("NodeID = {0}", NodeID) & new RecordRestriction("Source = {0}", Source); if ((object)recordRestriction != null) queryRestriction &= recordRestriction; return importedMeasurementTable.QueryRecords(queryRestriction); } } private void CreateOrUpdate(ImportedMeasurement measurement) { TransactionScopeOption transactionScopeOption = TransactionScopeOption.Required; TransactionOptions transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TransactionManager.MaximumTimeout }; measurement.NodeID = NodeID; measurement.Source = Source; using (TransactionScope transactionScope = new TransactionScope(transactionScopeOption, transactionOptions)) using (AdoDataConnection connection = CreateDbConnection()) { TableOperations<ImportedMeasurement> importedMeasurementTable = new TableOperations<ImportedMeasurement>(connection); RecordRestriction recordRestriction = new RecordRestriction("NodeID = {0}", measurement.NodeID) & new RecordRestriction("Source = {0}", measurement.Source) & new RecordRestriction("PointID = {0}", measurement.PointID); int measurementCount = importedMeasurementTable.UpdateRecord(measurement, recordRestriction); if (measurementCount == 0) importedMeasurementTable.AddNewRecord(measurement); transactionScope.Complete(); } } private AdoDataConnection CreateDbConnection() { return new AdoDataConnection("systemSettings"); } #endregion } }
{ "pile_set_name": "Github" }