text
stringlengths
2
97.5k
meta
dict
<template> <form class="TransactionFormMultiSignature flex flex-col" @submit.prevent > <ListDivided v-if="senderLabel" :is-floating-label="true" > <ListDividedItem :label="$t('TRANSACTION.SENDER')" item-value-class="w-full" > <span class="break-words"> {{ senderLabel }} </span> <span v-if="senderLabel !== currentWallet.address" class="text-sm text-theme-page-text-light" > {{ currentWallet.address }} </span> </ListDividedItem> </ListDivided> <div v-if="step === 1" class="TransactionFormMultiSignature__step-1" > <MenuTab ref="menutab" v-model="currentTab" class="TransactionModalMultiSignature__menu-tabs" > <MenuTabItem v-for="(tab, id) in tabs" :key="id" :tab="id" :label="tab.text" class="TransactionFormMultiSignature__menu-tab flex-1" /> </MenuTab> <div class="flex flex-row"> <div v-if="addressTab" class="TransactionFormMultiSignature__address-tab flex-1" > <InputAddress ref="address" v-model="$v.address.$model" :label="$t('COMMON.ADDRESS')" :pub-key-hash="walletNetwork.version" :show-suggestions="true" :is-disabled="!currentWallet" :is-required="false" :is-invalid="!!addressWarning" :helper-text="addressWarning" name="address" class="TransactionFormMultiSignature__address" /> </div> <div v-else-if="publicKeyTab" class="flex-1" > <InputPublicKey ref="publicKey" v-model="$v.publicKey.$model" :is-required="false" :warning-text="publicKeyWarning" class="TransactionFormMultiSignature__public-key" /> </div> <ButtonGeneric :disabled="!validStep1" :label="$t('TRANSACTION.MULTI_SIGNATURE.BUTTON_ADD')" class="TransactionFormMultiSignature__add py-1 flex-inline h-8 mt-4 ml-4" @click="addPublicKey" /> </div> <TransactionMultiSignatureList :items="$v.form.publicKeys.$model" :show-count="true" class="TransactionModalMultiSignature__public-keys mt-4" @remove="emitRemovePublicKey" /> </div> <div v-if="step === 2"> <InputText ref="minKeys" v-model="$v.form.minKeys.$model" :label="$t('TRANSACTION.MULTI_SIGNATURE.MIN_KEYS')" :helper-text="minKeysError" :is-invalid="!!minKeysError" name="minKeys" type="number" class="TransactionFormMultiSignature__min-keys mb-5" /> <InputFee ref="fee" :currency="walletNetwork.token" :transaction-type="$options.transactionType" :is-disabled="!currentWallet" :wallet="currentWallet" :wallet-network="walletNetwork" class="TransactionFormMultiSignature__fee" @input="onFee" /> <div v-if="currentWallet.isLedger" class="TransactionFormMultiSignature__ledger-notice mt-10" > {{ $t('TRANSACTION.LEDGER_SIGN_NOTICE') }} </div> <InputPassword v-else-if="currentWallet.passphrase" ref="password" v-model="$v.form.walletPassword.$model" :label="$t('TRANSACTION.PASSWORD')" :is-required="true" class="TransactionFormMultiSignature__password mt-4" /> <PassphraseInput v-else ref="passphrase" v-model="$v.form.passphrase.$model" :address="currentWallet.address" :pub-key-hash="walletNetwork.version" :is-disabled="!currentWallet" class="TransactionFormMultiSignature__passphrase mt-4" /> <PassphraseInput v-if="currentWallet.secondPublicKey" ref="secondPassphrase" v-model="$v.form.secondPassphrase.$model" :label="$t('TRANSACTION.SECOND_PASSPHRASE')" :pub-key-hash="walletNetwork.version" :public-key="currentWallet.secondPublicKey" class="TransactionFormMultiSignature__second-passphrase mt-5" /> </div> <footer class="mt-4 flex justify-between items-center"> <div class="self-start"> <button :disabled="step === 1" class="TransactionFormMultiSignature__prev blue-button" @click="previousStep" > {{ $t('COMMON.PREV') }} </button> <button :disabled="!isFormValid" class="TransactionFormMultiSignature__next blue-button" @click="nextStep" > {{ $t('COMMON.NEXT') }} </button> </div> </footer> <ModalLoader :message="$t('ENCRYPTION.DECRYPTING')" :visible="showEncryptLoader" /> <ModalLoader :message="$t('TRANSACTION.LEDGER_SIGN_WAIT')" :visible="showLedgerLoader" /> </form> </template> <script> import { required } from 'vuelidate/lib/validators' import { TRANSACTION_TYPES } from '@config' import { ButtonGeneric } from '@/components/Button' import { InputAddress, InputFee, InputPublicKey, InputPassword, InputText } from '@/components/Input' import { ListDivided, ListDividedItem } from '@/components/ListDivided' import { MenuTab, MenuTabItem } from '@/components/Menu' import { ModalLoader } from '@/components/Modal' import { PassphraseInput } from '@/components/Passphrase' import TransactionMultiSignatureList from '@/components/Transaction/TransactionMultiSignatureList' import mixin from './mixin' export default { name: 'TransactionFormMultiSignature', transactionType: TRANSACTION_TYPES.GROUP_1.MULTI_SIGNATURE, components: { ButtonGeneric, InputAddress, InputFee, InputPassword, InputPublicKey, InputText, ListDivided, ListDividedItem, MenuTab, MenuTabItem, ModalLoader, PassphraseInput, TransactionMultiSignatureList }, mixins: [mixin], data: () => ({ step: 1, currentTab: 0, address: '', publicKey: '', form: { publicKeys: [], minKeys: null, fee: 0, passphrase: '', walletPassword: '' } }), computed: { addressTab () { return this.currentTab === 0 }, publicKeyTab () { return this.currentTab === 1 }, tabs () { return [ { text: this.$t('TRANSACTION.MULTI_SIGNATURE.TAB.ADDRESS') }, { text: this.$t('TRANSACTION.MULTI_SIGNATURE.TAB.PUBLIC_KEY') } ] }, validStep1 () { if (this.addressTab) { if (!this.$v.address.$dirty || this.$v.address.$invalid || this.addressWarning || this.address.replace(/\s+/, '') === '') { return false } } else { if (!this.$v.publicKey.$dirty || this.$v.publicKey.$invalid || this.publicKeyWarning || this.publicKey.replace(/\s+/, '') === '') { return false } } return true }, isFormValid () { if (this.step === 1) { return !this.$v.form.publicKeys.$invalid } return !this.$v.form.$invalid }, addressWarning () { if (!this.$v.address.$dirty) { return null } if (this.form.publicKeys.some(key => key.address === this.$v.address.$model)) { return this.$t('TRANSACTION.MULTI_SIGNATURE.ERROR_DUPLICATE') } return null }, publicKeyWarning () { if (!this.$v.publicKey.$dirty) { return null } if (this.form.publicKeys.some(key => key.publicKey === this.$v.publicKey.$model)) { return this.$t('TRANSACTION.MULTI_SIGNATURE.ERROR_DUPLICATE') } return null }, maximumPublicKeys () { if (!this.session_network.constants || !this.session_network.constants.maxMultiSignatureParticipants) { return 16 } return this.session_network.constants.maxMultiSignatureParticipants }, minKeysError () { if (this.$v.form.minKeys.$dirty && this.$v.form.minKeys.$error) { if (!this.$v.form.minKeys.required) { return this.$t('VALIDATION.REQUIRED', [this.$t('TRANSACTION.MULTI_SIGNATURE.MIN_KEYS')]) } else if (!this.$v.form.minKeys.belowMaximum) { return this.$t('TRANSACTION.MULTI_SIGNATURE.ERROR_MIN_KEYS_TOO_HIGH') } else if (!this.$v.form.minKeys.aboveMinimum) { return this.$t('TRANSACTION.MULTI_SIGNATURE.ERROR_MIN_KEYS_TOO_LOW') } } return null } }, mounted () { this.form.publicKeys.push({ address: this.currentWallet.address, publicKey: this.currentWallet.publicKey }) this.updateMinKeys() }, methods: { getTransactionData () { const transactionData = { address: this.currentWallet.address, publicKeys: this.form.publicKeys.map(key => key.publicKey), minKeys: this.form.minKeys, passphrase: this.form.passphrase, fee: this.getFee(), wif: this.form.wif, networkWif: this.walletNetwork.wif } if (this.currentWallet.secondPublicKey) { transactionData.secondPassphrase = this.form.secondPassphrase } return transactionData }, async buildTransaction (transactionData, isAdvancedFee = false, returnObject = false) { const transaction = await this.$client.buildMultiSignature(transactionData, isAdvancedFee, returnObject) if (!returnObject) { transaction.multiSignature = transaction.asset.multiSignature } return transaction }, transactionError () { this.$error(this.$t('TRANSACTION.ERROR.VALIDATION.MULTI_SIGNATURE')) }, async addPublicKey () { const entry = { address: null, publicKey: null } if (this.addressTab) { entry.address = this.address let wallet = this.$store.getters['wallet/byAddress'](this.address) if (wallet && wallet.publicKey) { entry.publicKey = wallet.publicKey } else { wallet = await this.$client.fetchWallet(this.address) if (wallet && wallet.publicKey) { entry.publicKey = wallet.publicKey } else { this.$error(this.$t('TRANSACTION.MULTI_SIGNATURE.ERROR_PUBLIC_KEY_NOT_FOUND')) return } } this.$refs.address.reset() } else { entry.publicKey = this.publicKey this.$refs.publicKey.reset() } const existingEntry = this.form.publicKeys.find(key => key.publicKey === entry.publicKey) if (existingEntry) { if (entry.address && !existingEntry.address) { existingEntry.address = entry.address } this.$error(this.$t('TRANSACTION.MULTI_SIGNATURE.ERROR_PUBLIC_KEY_EXISTS')) return } this.form.publicKeys.push(entry) this.updateMinKeys() }, updateMinKeys () { this.$v.form.minKeys.$model = this.form.publicKeys.length }, previousStep () { if (this.step === 2) { this.step = 1 } }, nextStep () { if (this.step === 1) { this.step = 2 } else { this.form.fee = this.$refs.fee.fee this.onSubmit() } }, onFee (fee) { this.$set(this.form, 'fee', fee) }, emitRemovePublicKey (index) { this.$v.form.publicKeys.$model = [ ...this.form.publicKeys.slice(0, index), ...this.form.publicKeys.slice(index + 1) ] } }, validations: { publicKey: { isValid () { if (this.$refs.publicKey) { return !this.$refs.publicKey.$v.$invalid } return false } }, address: { isValid () { if (this.$refs.address) { return !this.$refs.address.$v.$invalid } return false } }, form: { publicKeys: { notEmpty () { return !!this.form.publicKeys.length }, aboveMinimum () { return this.form.publicKeys.length > 1 }, belowMaximum () { return this.form.publicKeys.length < this.maximumPublicKeys } }, minKeys: { required, belowMaximum (value) { return value <= this.form.publicKeys.length }, aboveMinimum (value) { return value >= 1 } }, fee: mixin.validators.fee, passphrase: mixin.validators.passphrase, secondPassphrase: mixin.validators.secondPassphrase, walletPassword: mixin.validators.walletPassword } } } </script> <style> .TransactionModalMultiSignature__menu-tabs .MenuTab__nav { @apply .rounded-lg; } .TransactionModalMultiSignature__menu-tabs .MenuTab__nav__items { @apply .flex; } .TransactionModalMultiSignature__menu-tabs .MenuTab__nav__item { @apply .flex-1; } .TransactionModalMultiSignature__menu-tabs .MenuTab__nav__item:first-child { @apply .rounded-l; } .TransactionModalMultiSignature__menu-tabs .MenuTab__nav__item:last-child { @apply .rounded-r; } .TransactionModalMultiSignature__menu-tabs .MenuTab__content { @apply .hidden; } </style>
{ "pile_set_name": "Github" }
# Distribution maintainers file # # This file describes who runs the docker/distribution project and how. # This is a living document - if you see something out of date or missing, speak up! # # It is structured to be consumable by both humans and programs. # To extract its contents programmatically, use any TOML-compliant parser. # [Rules] [Rules.maintainers] title = "What is a maintainer?" text = """ There are different types of maintainers, with different responsibilities, but all maintainers have 3 things in common: 1) They share responsibility in the project's success. 2) They have made a long-term, recurring time investment to improve the project. 3) They spend that time doing whatever needs to be done, not necessarily what is the most interesting or fun. Maintainers are often under-appreciated, because their work is harder to appreciate. It's easy to appreciate a really cool and technically advanced feature. It's harder to appreciate the absence of bugs, the slow but steady improvement in stability, or the reliability of a release process. But those things distinguish a good project from a great one. """ [Rules.reviewer] title = "What is a reviewer?" text = """ A reviewer is a core role within the project. They share in reviewing issues and pull requests and their LGTM count towards the required LGTM count to merge a code change into the project. Reviewers are part of the organization but do not have write access. Becoming a reviewer is a core aspect in the journey to becoming a maintainer. """ [Rules.adding-maintainers] title = "How are maintainers added?" text = """ Maintainers are first and foremost contributors that have shown they are committed to the long term success of a project. Contributors wanting to become maintainers are expected to be deeply involved in contributing code, pull request review, and triage of issues in the project for more than three months. Just contributing does not make you a maintainer, it is about building trust with the current maintainers of the project and being a person that they can depend on and trust to make decisions in the best interest of the project. Periodically, the existing maintainers curate a list of contributors that have shown regular activity on the project over the prior months. From this list, maintainer candidates are selected and proposed on the maintainers mailing list. After a candidate has been announced on the maintainers mailing list, the existing maintainers are given five business days to discuss the candidate, raise objections and cast their vote. Candidates must be approved by at least 66% of the current maintainers by adding their vote on the mailing list. Only maintainers of the repository that the candidate is proposed for are allowed to vote. If a candidate is approved, a maintainer will contact the candidate to invite the candidate to open a pull request that adds the contributor to the MAINTAINERS file. The candidate becomes a maintainer once the pull request is merged. """ [Rules.stepping-down-policy] title = "Stepping down policy" text = """ Life priorities, interests, and passions can change. If you're a maintainer but feel you must remove yourself from the list, inform other maintainers that you intend to step down, and if possible, help find someone to pick up your work. At the very least, ensure your work can be continued where you left off. After you've informed other maintainers, create a pull request to remove yourself from the MAINTAINERS file. """ [Rules.inactive-maintainers] title = "Removal of inactive maintainers" text = """ Similar to the procedure for adding new maintainers, existing maintainers can be removed from the list if they do not show significant activity on the project. Periodically, the maintainers review the list of maintainers and their activity over the last three months. If a maintainer has shown insufficient activity over this period, a neutral person will contact the maintainer to ask if they want to continue being a maintainer. If the maintainer decides to step down as a maintainer, they open a pull request to be removed from the MAINTAINERS file. If the maintainer wants to remain a maintainer, but is unable to perform the required duties they can be removed with a vote of at least 66% of the current maintainers. An e-mail is sent to the mailing list, inviting maintainers of the project to vote. The voting period is five business days. Issues related to a maintainer's performance should be discussed with them among the other maintainers so that they are not surprised by a pull request removing them. """ [Rules.decisions] title = "How are decisions made?" text = """ Short answer: EVERYTHING IS A PULL REQUEST. distribution is an open-source project with an open design philosophy. This means that the repository is the source of truth for EVERY aspect of the project, including its philosophy, design, road map, and APIs. *If it's part of the project, it's in the repo. If it's in the repo, it's part of the project.* As a result, all decisions can be expressed as changes to the repository. An implementation change is a change to the source code. An API change is a change to the API specification. A philosophy change is a change to the philosophy manifesto, and so on. All decisions affecting distribution, big and small, follow the same 3 steps: * Step 1: Open a pull request. Anyone can do this. * Step 2: Discuss the pull request. Anyone can do this. * Step 3: Merge or refuse the pull request. Who does this depends on the nature of the pull request and which areas of the project it affects. """ [Rules.DCO] title = "Helping contributors with the DCO" text = """ The [DCO or `Sign your work`]( https://github.com/moby/moby/blob/master/CONTRIBUTING.md#sign-your-work) requirement is not intended as a roadblock or speed bump. Some distribution contributors are not as familiar with `git`, or have used a web based editor, and thus asking them to `git commit --amend -s` is not the best way forward. In this case, maintainers can update the commits based on clause (c) of the DCO. The most trivial way for a contributor to allow the maintainer to do this, is to add a DCO signature in a pull requests's comment, or a maintainer can simply note that the change is sufficiently trivial that it does not substantially change the existing contribution - i.e., a spelling change. When you add someone's DCO, please also add your own to keep a log. """ [Rules."no direct push"] title = "I'm a maintainer. Should I make pull requests too?" text = """ Yes. Nobody should ever push to master directly. All changes should be made through a pull request. """ [Rules.tsc] title = "Conflict Resolution and technical disputes" text = """ distribution defers to the [Technical Steering Committee](https://github.com/moby/tsc) for escalations and resolution on disputes for technical matters." """ [Rules.meta] title = "How is this process changed?" text = "Just like everything else: by making a pull request :)" # Current project organization [Org] [Org.Maintainers] people = [ "dmcgowan", "dmp42", "stevvooe", ] [Org.Reviewers] people = [ "manishtomar", "caervs", "davidswu", "RobbKistler" ] [people] # A reference list of all people associated with the project. # All other sections should refer to people by their canonical key # in the people section. # ADD YOURSELF HERE IN ALPHABETICAL ORDER [people.caervs] Name = "Ryan Abrams" Email = "rdabrams@gmail.com" GitHub = "caervs" [people.davidswu] Name = "David Wu" Email = "dwu7401@gmail.com" GitHub = "davidswu" [people.dmcgowan] Name = "Derek McGowan" Email = "derek@mcgstyle.net" GitHub = "dmcgowan" [people.dmp42] Name = "Olivier Gambier" Email = "olivier@docker.com" GitHub = "dmp42" [people.manishtomar] Name = "Manish Tomar" Email = "manish.tomar@docker.com" GitHub = "manishtomar" [people.RobbKistler] Name = "Robb Kistler" Email = "robb.kistler@docker.com" GitHub = "RobbKistler" [people.stevvooe] Name = "Stephen Day" Email = "stephen.day@docker.com" GitHub = "stevvooe"
{ "pile_set_name": "Github" }
resource "aws_instance" "web" {} resource "aws_instance" "db" { depends_on = ["aws_instance.web"] }
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) by Jaroslav Kysela <perex@perex.cz> */ #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/time.h> #include <sound/core.h> #include <sound/gus.h> extern void snd_gf1_timers_init(struct snd_gus_card * gus); extern void snd_gf1_timers_done(struct snd_gus_card * gus); extern int snd_gf1_synth_init(struct snd_gus_card * gus); extern void snd_gf1_synth_done(struct snd_gus_card * gus); /* * ok.. default interrupt handlers... */ static void snd_gf1_default_interrupt_handler_midi_out(struct snd_gus_card * gus) { snd_gf1_uart_cmd(gus, gus->gf1.uart_cmd &= ~0x20); } static void snd_gf1_default_interrupt_handler_midi_in(struct snd_gus_card * gus) { snd_gf1_uart_cmd(gus, gus->gf1.uart_cmd &= ~0x80); } static void snd_gf1_default_interrupt_handler_timer1(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, gus->gf1.timer_enabled &= ~4); } static void snd_gf1_default_interrupt_handler_timer2(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, gus->gf1.timer_enabled &= ~8); } static void snd_gf1_default_interrupt_handler_wave_and_volume(struct snd_gus_card * gus, struct snd_gus_voice * voice) { snd_gf1_i_ctrl_stop(gus, 0x00); snd_gf1_i_ctrl_stop(gus, 0x0d); } static void snd_gf1_default_interrupt_handler_dma_write(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, 0x41, 0x00); } static void snd_gf1_default_interrupt_handler_dma_read(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, 0x49, 0x00); } void snd_gf1_set_default_handlers(struct snd_gus_card * gus, unsigned int what) { if (what & SNDRV_GF1_HANDLER_MIDI_OUT) gus->gf1.interrupt_handler_midi_out = snd_gf1_default_interrupt_handler_midi_out; if (what & SNDRV_GF1_HANDLER_MIDI_IN) gus->gf1.interrupt_handler_midi_in = snd_gf1_default_interrupt_handler_midi_in; if (what & SNDRV_GF1_HANDLER_TIMER1) gus->gf1.interrupt_handler_timer1 = snd_gf1_default_interrupt_handler_timer1; if (what & SNDRV_GF1_HANDLER_TIMER2) gus->gf1.interrupt_handler_timer2 = snd_gf1_default_interrupt_handler_timer2; if (what & SNDRV_GF1_HANDLER_VOICE) { struct snd_gus_voice *voice; voice = &gus->gf1.voices[what & 0xffff]; voice->handler_wave = voice->handler_volume = snd_gf1_default_interrupt_handler_wave_and_volume; voice->handler_effect = NULL; voice->volume_change = NULL; } if (what & SNDRV_GF1_HANDLER_DMA_WRITE) gus->gf1.interrupt_handler_dma_write = snd_gf1_default_interrupt_handler_dma_write; if (what & SNDRV_GF1_HANDLER_DMA_READ) gus->gf1.interrupt_handler_dma_read = snd_gf1_default_interrupt_handler_dma_read; } /* */ static void snd_gf1_clear_regs(struct snd_gus_card * gus) { unsigned long flags; spin_lock_irqsave(&gus->reg_lock, flags); inb(GUSP(gus, IRQSTAT)); snd_gf1_write8(gus, 0x41, 0); /* DRAM DMA Control Register */ snd_gf1_write8(gus, 0x45, 0); /* Timer Control */ snd_gf1_write8(gus, 0x49, 0); /* Sampling Control Register */ spin_unlock_irqrestore(&gus->reg_lock, flags); } static void snd_gf1_look_regs(struct snd_gus_card * gus) { unsigned long flags; spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_look8(gus, 0x41); /* DRAM DMA Control Register */ snd_gf1_look8(gus, 0x49); /* Sampling Control Register */ inb(GUSP(gus, IRQSTAT)); snd_gf1_read8(gus, 0x0f); /* IRQ Source Register */ spin_unlock_irqrestore(&gus->reg_lock, flags); } /* * put selected GF1 voices to initial stage... */ void snd_gf1_smart_stop_voice(struct snd_gus_card * gus, unsigned short voice) { unsigned long flags; spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_select_voice(gus, voice); #if 0 printk(KERN_DEBUG " -%i- smart stop voice - volume = 0x%x\n", voice, snd_gf1_i_read16(gus, SNDRV_GF1_VW_VOLUME)); #endif snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL); snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL); spin_unlock_irqrestore(&gus->reg_lock, flags); } void snd_gf1_stop_voice(struct snd_gus_card * gus, unsigned short voice) { unsigned long flags; spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_select_voice(gus, voice); #if 0 printk(KERN_DEBUG " -%i- stop voice - volume = 0x%x\n", voice, snd_gf1_i_read16(gus, SNDRV_GF1_VW_VOLUME)); #endif snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL); snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL); if (gus->gf1.enh_mode) snd_gf1_write8(gus, SNDRV_GF1_VB_ACCUMULATOR, 0); spin_unlock_irqrestore(&gus->reg_lock, flags); #if 0 snd_gf1_lfo_shutdown(gus, voice, ULTRA_LFO_VIBRATO); snd_gf1_lfo_shutdown(gus, voice, ULTRA_LFO_TREMOLO); #endif } static void snd_gf1_clear_voices(struct snd_gus_card * gus, unsigned short v_min, unsigned short v_max) { unsigned long flags; unsigned int daddr; unsigned short i, w_16; daddr = gus->gf1.default_voice_address << 4; for (i = v_min; i <= v_max; i++) { #if 0 if (gus->gf1.syn_voices) gus->gf1.syn_voices[i].flags = ~VFLG_DYNAMIC; #endif spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_select_voice(gus, i); snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL); /* Voice Control Register = voice stop */ snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL); /* Volume Ramp Control Register = ramp off */ if (gus->gf1.enh_mode) snd_gf1_write8(gus, SNDRV_GF1_VB_MODE, gus->gf1.memory ? 0x02 : 0x82); /* Deactivate voice */ w_16 = snd_gf1_read8(gus, SNDRV_GF1_VB_ADDRESS_CONTROL) & 0x04; snd_gf1_write16(gus, SNDRV_GF1_VW_FREQUENCY, 0x400); snd_gf1_write_addr(gus, SNDRV_GF1_VA_START, daddr, w_16); snd_gf1_write_addr(gus, SNDRV_GF1_VA_END, daddr, w_16); snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_START, 0); snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_END, 0); snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_RATE, 0); snd_gf1_write16(gus, SNDRV_GF1_VW_VOLUME, 0); snd_gf1_write_addr(gus, SNDRV_GF1_VA_CURRENT, daddr, w_16); snd_gf1_write8(gus, SNDRV_GF1_VB_PAN, 7); if (gus->gf1.enh_mode) { snd_gf1_write8(gus, SNDRV_GF1_VB_ACCUMULATOR, 0); snd_gf1_write16(gus, SNDRV_GF1_VW_EFFECT_VOLUME, 0); snd_gf1_write16(gus, SNDRV_GF1_VW_EFFECT_VOLUME_FINAL, 0); } spin_unlock_irqrestore(&gus->reg_lock, flags); #if 0 snd_gf1_lfo_shutdown(gus, i, ULTRA_LFO_VIBRATO); snd_gf1_lfo_shutdown(gus, i, ULTRA_LFO_TREMOLO); #endif } } void snd_gf1_stop_voices(struct snd_gus_card * gus, unsigned short v_min, unsigned short v_max) { unsigned long flags; short i, ramp_ok; unsigned short ramp_end; if (!in_interrupt()) { /* this can't be done in interrupt */ for (i = v_min, ramp_ok = 0; i <= v_max; i++) { spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_select_voice(gus, i); ramp_end = snd_gf1_read16(gus, 9) >> 8; if (ramp_end > SNDRV_GF1_MIN_OFFSET) { ramp_ok++; snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_RATE, 20); /* ramp rate */ snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_START, SNDRV_GF1_MIN_OFFSET); /* ramp start */ snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_END, ramp_end); /* ramp end */ snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_CONTROL, 0x40); /* ramp down */ if (gus->gf1.enh_mode) { snd_gf1_delay(gus); snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_CONTROL, 0x40); } } spin_unlock_irqrestore(&gus->reg_lock, flags); } msleep_interruptible(50); } snd_gf1_clear_voices(gus, v_min, v_max); } static void snd_gf1_alloc_voice_use(struct snd_gus_card * gus, struct snd_gus_voice * pvoice, int type, int client, int port) { pvoice->use = 1; switch (type) { case SNDRV_GF1_VOICE_TYPE_PCM: gus->gf1.pcm_alloc_voices++; pvoice->pcm = 1; break; case SNDRV_GF1_VOICE_TYPE_SYNTH: pvoice->synth = 1; pvoice->client = client; pvoice->port = port; break; case SNDRV_GF1_VOICE_TYPE_MIDI: pvoice->midi = 1; pvoice->client = client; pvoice->port = port; break; } } struct snd_gus_voice *snd_gf1_alloc_voice(struct snd_gus_card * gus, int type, int client, int port) { struct snd_gus_voice *pvoice; unsigned long flags; int idx; spin_lock_irqsave(&gus->voice_alloc, flags); if (type == SNDRV_GF1_VOICE_TYPE_PCM) { if (gus->gf1.pcm_alloc_voices >= gus->gf1.pcm_channels) { spin_unlock_irqrestore(&gus->voice_alloc, flags); return NULL; } } for (idx = 0; idx < 32; idx++) { pvoice = &gus->gf1.voices[idx]; if (!pvoice->use) { snd_gf1_alloc_voice_use(gus, pvoice, type, client, port); spin_unlock_irqrestore(&gus->voice_alloc, flags); return pvoice; } } for (idx = 0; idx < 32; idx++) { pvoice = &gus->gf1.voices[idx]; if (pvoice->midi && !pvoice->client) { snd_gf1_clear_voices(gus, pvoice->number, pvoice->number); snd_gf1_alloc_voice_use(gus, pvoice, type, client, port); spin_unlock_irqrestore(&gus->voice_alloc, flags); return pvoice; } } spin_unlock_irqrestore(&gus->voice_alloc, flags); return NULL; } void snd_gf1_free_voice(struct snd_gus_card * gus, struct snd_gus_voice *voice) { unsigned long flags; void (*private_free)(struct snd_gus_voice *voice); if (voice == NULL || !voice->use) return; snd_gf1_set_default_handlers(gus, SNDRV_GF1_HANDLER_VOICE | voice->number); snd_gf1_clear_voices(gus, voice->number, voice->number); spin_lock_irqsave(&gus->voice_alloc, flags); private_free = voice->private_free; voice->private_free = NULL; voice->private_data = NULL; if (voice->pcm) gus->gf1.pcm_alloc_voices--; voice->use = voice->pcm = 0; voice->sample_ops = NULL; spin_unlock_irqrestore(&gus->voice_alloc, flags); if (private_free) private_free(voice); } /* * call this function only by start of driver */ int snd_gf1_start(struct snd_gus_card * gus) { unsigned long flags; unsigned int i; snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 0); /* reset GF1 */ udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 1); /* disable IRQ & DAC */ udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_JOYSTICK_DAC_LEVEL, gus->joystick_dac); snd_gf1_set_default_handlers(gus, SNDRV_GF1_HANDLER_ALL); for (i = 0; i < 32; i++) { gus->gf1.voices[i].number = i; snd_gf1_set_default_handlers(gus, SNDRV_GF1_HANDLER_VOICE | i); } snd_gf1_uart_cmd(gus, 0x03); /* huh.. this cleanup took me some time... */ if (gus->gf1.enh_mode) { /* enhanced mode !!!! */ snd_gf1_i_write8(gus, SNDRV_GF1_GB_GLOBAL_MODE, snd_gf1_i_look8(gus, SNDRV_GF1_GB_GLOBAL_MODE) | 0x01); snd_gf1_i_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x01); } snd_gf1_clear_regs(gus); snd_gf1_select_active_voices(gus); snd_gf1_delay(gus); gus->gf1.default_voice_address = gus->gf1.memory > 0 ? 0 : 512 - 8; /* initialize LFOs & clear LFOs memory */ if (gus->gf1.enh_mode && gus->gf1.memory) { gus->gf1.hw_lfo = 1; gus->gf1.default_voice_address += 1024; } else { gus->gf1.sw_lfo = 1; } #if 0 snd_gf1_lfo_init(gus); #endif if (gus->gf1.memory > 0) for (i = 0; i < 4; i++) snd_gf1_poke(gus, gus->gf1.default_voice_address + i, 0); snd_gf1_clear_regs(gus); snd_gf1_clear_voices(gus, 0, 31); snd_gf1_look_regs(gus); udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 7); /* Reset Register = IRQ enable, DAC enable */ udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 7); /* Reset Register = IRQ enable, DAC enable */ if (gus->gf1.enh_mode) { /* enhanced mode !!!! */ snd_gf1_i_write8(gus, SNDRV_GF1_GB_GLOBAL_MODE, snd_gf1_i_look8(gus, SNDRV_GF1_GB_GLOBAL_MODE) | 0x01); snd_gf1_i_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x01); } while ((snd_gf1_i_read8(gus, SNDRV_GF1_GB_VOICES_IRQ) & 0xc0) != 0xc0); spin_lock_irqsave(&gus->reg_lock, flags); outb(gus->gf1.active_voice = 0, GUSP(gus, GF1PAGE)); outb(gus->mix_cntrl_reg, GUSP(gus, MIXCNTRLREG)); spin_unlock_irqrestore(&gus->reg_lock, flags); snd_gf1_timers_init(gus); snd_gf1_look_regs(gus); snd_gf1_mem_init(gus); snd_gf1_mem_proc_init(gus); #ifdef CONFIG_SND_DEBUG snd_gus_irq_profile_init(gus); #endif #if 0 if (gus->pnp_flag) { if (gus->chip.playback_fifo_size > 0) snd_gf1_i_write16(gus, SNDRV_GF1_GW_FIFO_RECORD_BASE_ADDR, gus->chip.playback_fifo_block->ptr >> 8); if (gus->chip.record_fifo_size > 0) snd_gf1_i_write16(gus, SNDRV_GF1_GW_FIFO_PLAY_BASE_ADDR, gus->chip.record_fifo_block->ptr >> 8); snd_gf1_i_write16(gus, SNDRV_GF1_GW_FIFO_SIZE, gus->chip.interwave_fifo_reg); } #endif return 0; } /* * call this function only by shutdown of driver */ int snd_gf1_stop(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, 0); /* stop all timers */ snd_gf1_stop_voices(gus, 0, 31); /* stop all voices */ snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 1); /* disable IRQ & DAC */ snd_gf1_timers_done(gus); snd_gf1_mem_done(gus); #if 0 snd_gf1_lfo_done(gus); #endif return 0; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Generated with glade 3.22.1 --> <!-- Copyright (C) 2020 Alexandros Theodotou <alex at zrythm dot org> This file is part of Zrythm Zrythm is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zrythm 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zrythm. If not, see <https://www.gnu.org/licenses/>. --> <interface> <requires lib="gtk+" version="3.20"/> <template class="PortInfoDialogWidget" parent="GtkDialog"> <property name="can_focus">False</property> <property name="type_hint">dialog</property> <child> <placeholder/> </child> <child internal-child="vbox"> <object class="GtkBox"> <property name="can_focus">False</property> <property name="orientation">vertical</property> <property name="spacing">2</property> <child internal-child="action_area"> <object class="GtkButtonBox"> <property name="can_focus">False</property> <property name="layout_style">end</property> <child> <placeholder/> </child> <child> <placeholder/> </child> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label_xalign">0</property> <property name="shadow_type">none</property> <child> <object class="GtkAlignment"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="left_padding">12</property> <child> <object class="GtkGrid"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkLabel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Name</property> <attributes> <attribute name="weight" value="bold"/> </attributes> <style> <class name="port_info_label"/> </style> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkLabel" id="name_lbl"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">label</property> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkLabel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Full designation</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">1</property> </packing> </child> <child> <object class="GtkLabel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Range</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">4</property> </packing> </child> <child> <object class="GtkLabel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Flags</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">3</property> </packing> </child> <child> <object class="GtkBox" id="flags_box"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <placeholder/> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">3</property> </packing> </child> <child> <object class="GtkLabel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Type</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">2</property> </packing> </child> <child> <object class="GtkLabel" id="full_designation_lbl"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">label</property> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">1</property> </packing> </child> <child> <object class="GtkLabel" id="type_lbl"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">label</property> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">2</property> </packing> </child> <child> <object class="GtkLabel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Default value</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">5</property> </packing> </child> <child> <object class="GtkLabel" id="default_value_lbl"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">label</property> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">5</property> </packing> </child> <child> <object class="GtkLabel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Current value</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">6</property> </packing> </child> <child> <object class="GtkLabel" id="current_val_lbl"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">label</property> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">6</property> </packing> </child> <child> <object class="GtkLabel" id="range_lbl"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">label</property> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">4</property> </packing> </child> <child> <placeholder/> </child> <child> <placeholder/> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Port Info</property> </object> </child> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> </object> </child> </template> </interface>
{ "pile_set_name": "Github" }
/* * Copyright (C)2009-2015 D. R. Commander. 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 libjpeg-turbo Project 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 HOLDERS 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 __TURBOJPEG_H__ #define __TURBOJPEG_H__ #if defined(_WIN32) && defined(DLLDEFINE) #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT #endif #define DLLCALL /** * @addtogroup TurboJPEG * TurboJPEG API. This API provides an interface for generating, decoding, and * transforming planar YUV and JPEG images in memory. * * @anchor YUVnotes * YUV Image Format Notes * ---------------------- * Technically, the JPEG format uses the YCbCr colorspace (which is technically * not a colorspace but a color transform), but per the convention of the * digital video community, the TurboJPEG API uses "YUV" to refer to an image * format consisting of Y, Cb, and Cr image planes. * * Each plane is simply a 2D array of bytes, each byte representing the value * of one of the components (Y, Cb, or Cr) at a particular location in the * image. The width and height of each plane are determined by the image * width, height, and level of chrominance subsampling. The luminance plane * width is the image width padded to the nearest multiple of the horizontal * subsampling factor (2 in the case of 4:2:0 and 4:2:2, 4 in the case of * 4:1:1, 1 in the case of 4:4:4 or grayscale.) Similarly, the luminance plane * height is the image height padded to the nearest multiple of the vertical * subsampling factor (2 in the case of 4:2:0 or 4:4:0, 1 in the case of 4:4:4 * or grayscale.) This is irrespective of any additional padding that may be * specified as an argument to the various YUV functions. The chrominance * plane width is equal to the luminance plane width divided by the horizontal * subsampling factor, and the chrominance plane height is equal to the * luminance plane height divided by the vertical subsampling factor. * * For example, if the source image is 35 x 35 pixels and 4:2:2 subsampling is * used, then the luminance plane would be 36 x 35 bytes, and each of the * chrominance planes would be 18 x 35 bytes. If you specify a line padding of * 4 bytes on top of this, then the luminance plane would be 36 x 35 bytes, and * each of the chrominance planes would be 20 x 35 bytes. * * @{ */ /** * The number of chrominance subsampling options */ #define TJ_NUMSAMP 6 /** * Chrominance subsampling options. * When pixels are converted from RGB to YCbCr (see #TJCS_YCbCr) or from CMYK * to YCCK (see #TJCS_YCCK) as part of the JPEG compression process, some of * the Cb and Cr (chrominance) components can be discarded or averaged together * to produce a smaller image with little perceptible loss of image clarity * (the human eye is more sensitive to small changes in brightness than to * small changes in color.) This is called "chrominance subsampling". */ enum TJSAMP { /** * 4:4:4 chrominance subsampling (no chrominance subsampling). The JPEG or * YUV image will contain one chrominance component for every pixel in the * source image. */ TJSAMP_444=0, /** * 4:2:2 chrominance subsampling. The JPEG or YUV image will contain one * chrominance component for every 2x1 block of pixels in the source image. */ TJSAMP_422, /** * 4:2:0 chrominance subsampling. The JPEG or YUV image will contain one * chrominance component for every 2x2 block of pixels in the source image. */ TJSAMP_420, /** * Grayscale. The JPEG or YUV image will contain no chrominance components. */ TJSAMP_GRAY, /** * 4:4:0 chrominance subsampling. The JPEG or YUV image will contain one * chrominance component for every 1x2 block of pixels in the source image. * * @note 4:4:0 subsampling is not fully accelerated in libjpeg-turbo. */ TJSAMP_440, /** * 4:1:1 chrominance subsampling. The JPEG or YUV image will contain one * chrominance component for every 4x1 block of pixels in the source image. * JPEG images compressed with 4:1:1 subsampling will be almost exactly the * same size as those compressed with 4:2:0 subsampling, and in the * aggregate, both subsampling methods produce approximately the same * perceptual quality. However, 4:1:1 is better able to reproduce sharp * horizontal features. * * @note 4:1:1 subsampling is not fully accelerated in libjpeg-turbo. */ TJSAMP_411 }; /** * MCU block width (in pixels) for a given level of chrominance subsampling. * MCU block sizes: * - 8x8 for no subsampling or grayscale * - 16x8 for 4:2:2 * - 8x16 for 4:4:0 * - 16x16 for 4:2:0 * - 32x8 for 4:1:1 */ static const int tjMCUWidth[TJ_NUMSAMP] = {8, 16, 16, 8, 8, 32}; /** * MCU block height (in pixels) for a given level of chrominance subsampling. * MCU block sizes: * - 8x8 for no subsampling or grayscale * - 16x8 for 4:2:2 * - 8x16 for 4:4:0 * - 16x16 for 4:2:0 * - 32x8 for 4:1:1 */ static const int tjMCUHeight[TJ_NUMSAMP] = {8, 8, 16, 8, 16, 8}; /** * The number of pixel formats */ #define TJ_NUMPF 12 /** * Pixel formats */ enum TJPF { /** * RGB pixel format. The red, green, and blue components in the image are * stored in 3-byte pixels in the order R, G, B from lowest to highest byte * address within each pixel. */ TJPF_RGB=0, /** * BGR pixel format. The red, green, and blue components in the image are * stored in 3-byte pixels in the order B, G, R from lowest to highest byte * address within each pixel. */ TJPF_BGR, /** * RGBX pixel format. The red, green, and blue components in the image are * stored in 4-byte pixels in the order R, G, B from lowest to highest byte * address within each pixel. The X component is ignored when compressing * and undefined when decompressing. */ TJPF_RGBX, /** * BGRX pixel format. The red, green, and blue components in the image are * stored in 4-byte pixels in the order B, G, R from lowest to highest byte * address within each pixel. The X component is ignored when compressing * and undefined when decompressing. */ TJPF_BGRX, /** * XBGR pixel format. The red, green, and blue components in the image are * stored in 4-byte pixels in the order R, G, B from highest to lowest byte * address within each pixel. The X component is ignored when compressing * and undefined when decompressing. */ TJPF_XBGR, /** * XRGB pixel format. The red, green, and blue components in the image are * stored in 4-byte pixels in the order B, G, R from highest to lowest byte * address within each pixel. The X component is ignored when compressing * and undefined when decompressing. */ TJPF_XRGB, /** * Grayscale pixel format. Each 1-byte pixel represents a luminance * (brightness) level from 0 to 255. */ TJPF_GRAY, /** * RGBA pixel format. This is the same as @ref TJPF_RGBX, except that when * decompressing, the X component is guaranteed to be 0xFF, which can be * interpreted as an opaque alpha channel. */ TJPF_RGBA, /** * BGRA pixel format. This is the same as @ref TJPF_BGRX, except that when * decompressing, the X component is guaranteed to be 0xFF, which can be * interpreted as an opaque alpha channel. */ TJPF_BGRA, /** * ABGR pixel format. This is the same as @ref TJPF_XBGR, except that when * decompressing, the X component is guaranteed to be 0xFF, which can be * interpreted as an opaque alpha channel. */ TJPF_ABGR, /** * ARGB pixel format. This is the same as @ref TJPF_XRGB, except that when * decompressing, the X component is guaranteed to be 0xFF, which can be * interpreted as an opaque alpha channel. */ TJPF_ARGB, /** * CMYK pixel format. Unlike RGB, which is an additive color model used * primarily for display, CMYK (Cyan/Magenta/Yellow/Key) is a subtractive * color model used primarily for printing. In the CMYK color model, the * value of each color component typically corresponds to an amount of cyan, * magenta, yellow, or black ink that is applied to a white background. In * order to convert between CMYK and RGB, it is necessary to use a color * management system (CMS.) A CMS will attempt to map colors within the * printer's gamut to perceptually similar colors in the display's gamut and * vice versa, but the mapping is typically not 1:1 or reversible, nor can it * be defined with a simple formula. Thus, such a conversion is out of scope * for a codec library. However, the TurboJPEG API allows for compressing * CMYK pixels into a YCCK JPEG image (see #TJCS_YCCK) and decompressing YCCK * JPEG images into CMYK pixels. */ TJPF_CMYK }; /** * Red offset (in bytes) for a given pixel format. This specifies the number * of bytes that the red component is offset from the start of the pixel. For * instance, if a pixel of format TJ_BGRX is stored in <tt>char pixel[]</tt>, * then the red component will be <tt>pixel[tjRedOffset[TJ_BGRX]]</tt>. */ static const int tjRedOffset[TJ_NUMPF] = {0, 2, 0, 2, 3, 1, 0, 0, 2, 3, 1, -1}; /** * Green offset (in bytes) for a given pixel format. This specifies the number * of bytes that the green component is offset from the start of the pixel. * For instance, if a pixel of format TJ_BGRX is stored in * <tt>char pixel[]</tt>, then the green component will be * <tt>pixel[tjGreenOffset[TJ_BGRX]]</tt>. */ static const int tjGreenOffset[TJ_NUMPF] = {1, 1, 1, 1, 2, 2, 0, 1, 1, 2, 2, -1}; /** * Blue offset (in bytes) for a given pixel format. This specifies the number * of bytes that the Blue component is offset from the start of the pixel. For * instance, if a pixel of format TJ_BGRX is stored in <tt>char pixel[]</tt>, * then the blue component will be <tt>pixel[tjBlueOffset[TJ_BGRX]]</tt>. */ static const int tjBlueOffset[TJ_NUMPF] = {2, 0, 2, 0, 1, 3, 0, 2, 0, 1, 3, -1}; /** * Pixel size (in bytes) for a given pixel format. */ static const int tjPixelSize[TJ_NUMPF] = {3, 3, 4, 4, 4, 4, 1, 4, 4, 4, 4, 4}; /** * The number of JPEG colorspaces */ #define TJ_NUMCS 5 /** * JPEG colorspaces */ enum TJCS { /** * RGB colorspace. When compressing the JPEG image, the R, G, and B * components in the source image are reordered into image planes, but no * colorspace conversion or subsampling is performed. RGB JPEG images can be * decompressed to any of the extended RGB pixel formats or grayscale, but * they cannot be decompressed to YUV images. */ TJCS_RGB=0, /** * YCbCr colorspace. YCbCr is not an absolute colorspace but rather a * mathematical transformation of RGB designed solely for storage and * transmission. YCbCr images must be converted to RGB before they can * actually be displayed. In the YCbCr colorspace, the Y (luminance) * component represents the black & white portion of the original image, and * the Cb and Cr (chrominance) components represent the color portion of the * original image. Originally, the analog equivalent of this transformation * allowed the same signal to drive both black & white and color televisions, * but JPEG images use YCbCr primarily because it allows the color data to be * optionally subsampled for the purposes of reducing bandwidth or disk * space. YCbCr is the most common JPEG colorspace, and YCbCr JPEG images * can be compressed from and decompressed to any of the extended RGB pixel * formats or grayscale, or they can be decompressed to YUV planar images. */ TJCS_YCbCr, /** * Grayscale colorspace. The JPEG image retains only the luminance data (Y * component), and any color data from the source image is discarded. * Grayscale JPEG images can be compressed from and decompressed to any of * the extended RGB pixel formats or grayscale, or they can be decompressed * to YUV planar images. */ TJCS_GRAY, /** * CMYK colorspace. When compressing the JPEG image, the C, M, Y, and K * components in the source image are reordered into image planes, but no * colorspace conversion or subsampling is performed. CMYK JPEG images can * only be decompressed to CMYK pixels. */ TJCS_CMYK, /** * YCCK colorspace. YCCK (AKA "YCbCrK") is not an absolute colorspace but * rather a mathematical transformation of CMYK designed solely for storage * and transmission. It is to CMYK as YCbCr is to RGB. CMYK pixels can be * reversibly transformed into YCCK, and as with YCbCr, the chrominance * components in the YCCK pixels can be subsampled without incurring major * perceptual loss. YCCK JPEG images can only be compressed from and * decompressed to CMYK pixels. */ TJCS_YCCK }; /** * The uncompressed source/destination image is stored in bottom-up (Windows, * OpenGL) order, not top-down (X11) order. */ #define TJFLAG_BOTTOMUP 2 /** * When decompressing an image that was compressed using chrominance * subsampling, use the fastest chrominance upsampling algorithm available in * the underlying codec. The default is to use smooth upsampling, which * creates a smooth transition between neighboring chrominance components in * order to reduce upsampling artifacts in the decompressed image. */ #define TJFLAG_FASTUPSAMPLE 256 /** * Disable buffer (re)allocation. If passed to #tjCompress2() or * #tjTransform(), this flag will cause those functions to generate an error if * the JPEG image buffer is invalid or too small rather than attempting to * allocate or reallocate that buffer. This reproduces the behavior of earlier * versions of TurboJPEG. */ #define TJFLAG_NOREALLOC 1024 /** * Use the fastest DCT/IDCT algorithm available in the underlying codec. The * default if this flag is not specified is implementation-specific. For * example, the implementation of TurboJPEG for libjpeg[-turbo] uses the fast * algorithm by default when compressing, because this has been shown to have * only a very slight effect on accuracy, but it uses the accurate algorithm * when decompressing, because this has been shown to have a larger effect. */ #define TJFLAG_FASTDCT 2048 /** * Use the most accurate DCT/IDCT algorithm available in the underlying codec. * The default if this flag is not specified is implementation-specific. For * example, the implementation of TurboJPEG for libjpeg[-turbo] uses the fast * algorithm by default when compressing, because this has been shown to have * only a very slight effect on accuracy, but it uses the accurate algorithm * when decompressing, because this has been shown to have a larger effect. */ #define TJFLAG_ACCURATEDCT 4096 /** * The number of transform operations */ #define TJ_NUMXOP 8 /** * Transform operations for #tjTransform() */ enum TJXOP { /** * Do not transform the position of the image pixels */ TJXOP_NONE=0, /** * Flip (mirror) image horizontally. This transform is imperfect if there * are any partial MCU blocks on the right edge (see #TJXOPT_PERFECT.) */ TJXOP_HFLIP, /** * Flip (mirror) image vertically. This transform is imperfect if there are * any partial MCU blocks on the bottom edge (see #TJXOPT_PERFECT.) */ TJXOP_VFLIP, /** * Transpose image (flip/mirror along upper left to lower right axis.) This * transform is always perfect. */ TJXOP_TRANSPOSE, /** * Transverse transpose image (flip/mirror along upper right to lower left * axis.) This transform is imperfect if there are any partial MCU blocks in * the image (see #TJXOPT_PERFECT.) */ TJXOP_TRANSVERSE, /** * Rotate image clockwise by 90 degrees. This transform is imperfect if * there are any partial MCU blocks on the bottom edge (see * #TJXOPT_PERFECT.) */ TJXOP_ROT90, /** * Rotate image 180 degrees. This transform is imperfect if there are any * partial MCU blocks in the image (see #TJXOPT_PERFECT.) */ TJXOP_ROT180, /** * Rotate image counter-clockwise by 90 degrees. This transform is imperfect * if there are any partial MCU blocks on the right edge (see * #TJXOPT_PERFECT.) */ TJXOP_ROT270 }; /** * This option will cause #tjTransform() to return an error if the transform is * not perfect. Lossless transforms operate on MCU blocks, whose size depends * on the level of chrominance subsampling used (see #tjMCUWidth * and #tjMCUHeight.) If the image's width or height is not evenly divisible * by the MCU block size, then there will be partial MCU blocks on the right * and/or bottom edges. It is not possible to move these partial MCU blocks to * the top or left of the image, so any transform that would require that is * "imperfect." If this option is not specified, then any partial MCU blocks * that cannot be transformed will be left in place, which will create * odd-looking strips on the right or bottom edge of the image. */ #define TJXOPT_PERFECT 1 /** * This option will cause #tjTransform() to discard any partial MCU blocks that * cannot be transformed. */ #define TJXOPT_TRIM 2 /** * This option will enable lossless cropping. See #tjTransform() for more * information. */ #define TJXOPT_CROP 4 /** * This option will discard the color data in the input image and produce * a grayscale output image. */ #define TJXOPT_GRAY 8 /** * This option will prevent #tjTransform() from outputting a JPEG image for * this particular transform (this can be used in conjunction with a custom * filter to capture the transformed DCT coefficients without transcoding * them.) */ #define TJXOPT_NOOUTPUT 16 /** * Scaling factor */ typedef struct { /** * Numerator */ int num; /** * Denominator */ int denom; } tjscalingfactor; /** * Cropping region */ typedef struct { /** * The left boundary of the cropping region. This must be evenly divisible * by the MCU block width (see #tjMCUWidth.) */ int x; /** * The upper boundary of the cropping region. This must be evenly divisible * by the MCU block height (see #tjMCUHeight.) */ int y; /** * The width of the cropping region. Setting this to 0 is the equivalent of * setting it to the width of the source JPEG image - x. */ int w; /** * The height of the cropping region. Setting this to 0 is the equivalent of * setting it to the height of the source JPEG image - y. */ int h; } tjregion; /** * Lossless transform */ typedef struct tjtransform { /** * Cropping region */ tjregion r; /** * One of the @ref TJXOP "transform operations" */ int op; /** * The bitwise OR of one of more of the @ref TJXOPT_CROP "transform options" */ int options; /** * Arbitrary data that can be accessed within the body of the callback * function */ void *data; /** * A callback function that can be used to modify the DCT coefficients * after they are losslessly transformed but before they are transcoded to a * new JPEG image. This allows for custom filters or other transformations * to be applied in the frequency domain. * * @param coeffs pointer to an array of transformed DCT coefficients. (NOTE: * this pointer is not guaranteed to be valid once the callback returns, so * applications wishing to hand off the DCT coefficients to another function * or library should make a copy of them within the body of the callback.) * * @param arrayRegion #tjregion structure containing the width and height of * the array pointed to by <tt>coeffs</tt> as well as its offset relative to * the component plane. TurboJPEG implementations may choose to split each * component plane into multiple DCT coefficient arrays and call the callback * function once for each array. * * @param planeRegion #tjregion structure containing the width and height of * the component plane to which <tt>coeffs</tt> belongs * * @param componentID ID number of the component plane to which * <tt>coeffs</tt> belongs (Y, Cb, and Cr have, respectively, ID's of 0, 1, * and 2 in typical JPEG images.) * * @param transformID ID number of the transformed image to which * <tt>coeffs</tt> belongs. This is the same as the index of the transform * in the <tt>transforms</tt> array that was passed to #tjTransform(). * * @param transform a pointer to a #tjtransform structure that specifies the * parameters and/or cropping region for this transform * * @return 0 if the callback was successful, or -1 if an error occurred. */ int (*customFilter)(short *coeffs, tjregion arrayRegion, tjregion planeRegion, int componentIndex, int transformIndex, struct tjtransform *transform); } tjtransform; /** * TurboJPEG instance handle */ typedef void* tjhandle; /** * Pad the given width to the nearest 32-bit boundary */ #define TJPAD(width) (((width)+3)&(~3)) /** * Compute the scaled value of <tt>dimension</tt> using the given scaling * factor. This macro performs the integer equivalent of <tt>ceil(dimension * * scalingFactor)</tt>. */ #define TJSCALED(dimension, scalingFactor) ((dimension * scalingFactor.num \ + scalingFactor.denom - 1) / scalingFactor.denom) #ifdef __cplusplus extern "C" { #endif /** * Create a TurboJPEG compressor instance. * * @return a handle to the newly-created instance, or NULL if an error * occurred (see #tjGetErrorStr().) */ DLLEXPORT tjhandle DLLCALL tjInitCompress(void); /** * Compress an RGB, grayscale, or CMYK image into a JPEG image. * * @param handle a handle to a TurboJPEG compressor or transformer instance * * @param srcBuf pointer to an image buffer containing RGB, grayscale, or * CMYK pixels to be compressed * * @param width width (in pixels) of the source image * * @param pitch bytes per line in the source image. Normally, this should be * <tt>width * #tjPixelSize[pixelFormat]</tt> if the image is unpadded, or * <tt>#TJPAD(width * #tjPixelSize[pixelFormat])</tt> if each line of the image * is padded to the nearest 32-bit boundary, as is the case for Windows * bitmaps. You can also be clever and use this parameter to skip lines, etc. * Setting this parameter to 0 is the equivalent of setting it to * <tt>width * #tjPixelSize[pixelFormat]</tt>. * * @param height height (in pixels) of the source image * * @param pixelFormat pixel format of the source image (see @ref TJPF * "Pixel formats".) * * @param jpegBuf address of a pointer to an image buffer that will receive the * JPEG image. TurboJPEG has the ability to reallocate the JPEG buffer * to accommodate the size of the JPEG image. Thus, you can choose to: * -# pre-allocate the JPEG buffer with an arbitrary size using #tjAlloc() and * let TurboJPEG grow the buffer as needed, * -# set <tt>*jpegBuf</tt> to NULL to tell TurboJPEG to allocate the buffer * for you, or * -# pre-allocate the buffer to a "worst case" size determined by calling * #tjBufSize(). This should ensure that the buffer never has to be * re-allocated (setting #TJFLAG_NOREALLOC guarantees this.) * . * If you choose option 1, <tt>*jpegSize</tt> should be set to the size of your * pre-allocated buffer. In any case, unless you have set #TJFLAG_NOREALLOC, * you should always check <tt>*jpegBuf</tt> upon return from this function, as * it may have changed. * * @param jpegSize pointer to an unsigned long variable that holds the size of * the JPEG image buffer. If <tt>*jpegBuf</tt> points to a pre-allocated * buffer, then <tt>*jpegSize</tt> should be set to the size of the buffer. * Upon return, <tt>*jpegSize</tt> will contain the size of the JPEG image (in * bytes.) If <tt>*jpegBuf</tt> points to a JPEG image buffer that is being * reused from a previous call to one of the JPEG compression functions, then * <tt>*jpegSize</tt> is ignored. * * @param jpegSubsamp the level of chrominance subsampling to be used when * generating the JPEG image (see @ref TJSAMP * "Chrominance subsampling options".) * * @param jpegQual the image quality of the generated JPEG image (1 = worst, * 100 = best) * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjCompress2(tjhandle handle, const unsigned char *srcBuf, int width, int pitch, int height, int pixelFormat, unsigned char **jpegBuf, unsigned long *jpegSize, int jpegSubsamp, int jpegQual, int flags); /** * Compress a YUV planar image into a JPEG image. * * @param handle a handle to a TurboJPEG compressor or transformer instance * * @param srcBuf pointer to an image buffer containing a YUV planar image to be * compressed. The size of this buffer should match the value returned by * #tjBufSizeYUV2() for the given image width, height, padding, and level of * chrominance subsampling. The Y, U (Cb), and V (Cr) image planes should be * stored sequentially in the source buffer (refer to @ref YUVnotes * "YUV Image Format Notes".) * * @param width width (in pixels) of the source image. If the width is not an * even multiple of the MCU block width (see #tjMCUWidth), then an intermediate * buffer copy will be performed within TurboJPEG. * * @param pad the line padding used in the source image. For instance, if each * line in each plane of the YUV image is padded to the nearest multiple of 4 * bytes, then <tt>pad</tt> should be set to 4. * * @param height height (in pixels) of the source image. If the height is not * an even multiple of the MCU block height (see #tjMCUHeight), then an * intermediate buffer copy will be performed within TurboJPEG. * * @param subsamp the level of chrominance subsampling used in the source * image (see @ref TJSAMP "Chrominance subsampling options".) * * @param jpegBuf address of a pointer to an image buffer that will receive the * JPEG image. TurboJPEG has the ability to reallocate the JPEG buffer to * accommodate the size of the JPEG image. Thus, you can choose to: * -# pre-allocate the JPEG buffer with an arbitrary size using #tjAlloc() and * let TurboJPEG grow the buffer as needed, * -# set <tt>*jpegBuf</tt> to NULL to tell TurboJPEG to allocate the buffer * for you, or * -# pre-allocate the buffer to a "worst case" size determined by calling * #tjBufSize(). This should ensure that the buffer never has to be * re-allocated (setting #TJFLAG_NOREALLOC guarantees this.) * . * If you choose option 1, <tt>*jpegSize</tt> should be set to the size of your * pre-allocated buffer. In any case, unless you have set #TJFLAG_NOREALLOC, * you should always check <tt>*jpegBuf</tt> upon return from this function, as * it may have changed. * * @param jpegSize pointer to an unsigned long variable that holds the size of * the JPEG image buffer. If <tt>*jpegBuf</tt> points to a pre-allocated * buffer, then <tt>*jpegSize</tt> should be set to the size of the buffer. * Upon return, <tt>*jpegSize</tt> will contain the size of the JPEG image (in * bytes.) If <tt>*jpegBuf</tt> points to a JPEG image buffer that is being * reused from a previous call to one of the JPEG compression functions, then * <tt>*jpegSize</tt> is ignored. * * @param jpegQual the image quality of the generated JPEG image (1 = worst, * 100 = best) * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjCompressFromYUV(tjhandle handle, const unsigned char *srcBuf, int width, int pad, int height, int subsamp, unsigned char **jpegBuf, unsigned long *jpegSize, int jpegQual, int flags); /** * Compress a set of Y, U (Cb), and V (Cr) image planes into a JPEG image. * * @param handle a handle to a TurboJPEG compressor or transformer instance * * @param srcPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes * (or just a Y plane, if compressing a grayscale image) that contain a YUV * image to be compressed. These planes can be contiguous or non-contiguous in * memory. The size of each plane should match the value returned by * #tjPlaneSizeYUV() for the given image width, height, strides, and level of * chrominance subsampling. Refer to @ref YUVnotes "YUV Image Format Notes" * for more details. * * @param width width (in pixels) of the source image. If the width is not an * even multiple of the MCU block width (see #tjMCUWidth), then an intermediate * buffer copy will be performed within TurboJPEG. * * @param strides an array of integers, each specifying the number of bytes per * line in the corresponding plane of the YUV source image. Setting the stride * for any plane to 0 is the same as setting it to the plane width (see * @ref YUVnotes "YUV Image Format Notes".) If <tt>strides</tt> is NULL, then * the strides for all planes will be set to their respective plane widths. * You can adjust the strides in order to specify an arbitrary amount of line * padding in each plane or to create a JPEG image from a subregion of a larger * YUV planar image. * * @param height height (in pixels) of the source image. If the height is not * an even multiple of the MCU block height (see #tjMCUHeight), then an * intermediate buffer copy will be performed within TurboJPEG. * * @param subsamp the level of chrominance subsampling used in the source * image (see @ref TJSAMP "Chrominance subsampling options".) * * @param jpegBuf address of a pointer to an image buffer that will receive the * JPEG image. TurboJPEG has the ability to reallocate the JPEG buffer to * accommodate the size of the JPEG image. Thus, you can choose to: * -# pre-allocate the JPEG buffer with an arbitrary size using #tjAlloc() and * let TurboJPEG grow the buffer as needed, * -# set <tt>*jpegBuf</tt> to NULL to tell TurboJPEG to allocate the buffer * for you, or * -# pre-allocate the buffer to a "worst case" size determined by calling * #tjBufSize(). This should ensure that the buffer never has to be * re-allocated (setting #TJFLAG_NOREALLOC guarantees this.) * . * If you choose option 1, <tt>*jpegSize</tt> should be set to the size of your * pre-allocated buffer. In any case, unless you have set #TJFLAG_NOREALLOC, * you should always check <tt>*jpegBuf</tt> upon return from this function, as * it may have changed. * * @param jpegSize pointer to an unsigned long variable that holds the size of * the JPEG image buffer. If <tt>*jpegBuf</tt> points to a pre-allocated * buffer, then <tt>*jpegSize</tt> should be set to the size of the buffer. * Upon return, <tt>*jpegSize</tt> will contain the size of the JPEG image (in * bytes.) If <tt>*jpegBuf</tt> points to a JPEG image buffer that is being * reused from a previous call to one of the JPEG compression functions, then * <tt>*jpegSize</tt> is ignored. * * @param jpegQual the image quality of the generated JPEG image (1 = worst, * 100 = best) * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjCompressFromYUVPlanes(tjhandle handle, const unsigned char **srcPlanes, int width, const int *strides, int height, int subsamp, unsigned char **jpegBuf, unsigned long *jpegSize, int jpegQual, int flags); /** * The maximum size of the buffer (in bytes) required to hold a JPEG image with * the given parameters. The number of bytes returned by this function is * larger than the size of the uncompressed source image. The reason for this * is that the JPEG format uses 16-bit coefficients, and it is thus possible * for a very high-quality JPEG image with very high-frequency content to * expand rather than compress when converted to the JPEG format. Such images * represent a very rare corner case, but since there is no way to predict the * size of a JPEG image prior to compression, the corner case has to be * handled. * * @param width width (in pixels) of the image * * @param height height (in pixels) of the image * * @param jpegSubsamp the level of chrominance subsampling to be used when * generating the JPEG image (see @ref TJSAMP * "Chrominance subsampling options".) * * @return the maximum size of the buffer (in bytes) required to hold the * image, or -1 if the arguments are out of bounds. */ DLLEXPORT unsigned long DLLCALL tjBufSize(int width, int height, int jpegSubsamp); /** * The size of the buffer (in bytes) required to hold a YUV planar image with * the given parameters. * * @param width width (in pixels) of the image * * @param pad the width of each line in each plane of the image is padded to * the nearest multiple of this number of bytes (must be a power of 2.) * * @param height height (in pixels) of the image * * @param subsamp level of chrominance subsampling in the image (see * @ref TJSAMP "Chrominance subsampling options".) * * @return the size of the buffer (in bytes) required to hold the image, or * -1 if the arguments are out of bounds. */ DLLEXPORT unsigned long DLLCALL tjBufSizeYUV2(int width, int pad, int height, int subsamp); /** * The size of the buffer (in bytes) required to hold a YUV image plane with * the given parameters. * * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr) * * @param width width (in pixels) of the YUV image. NOTE: this is the width of * the whole image, not the plane width. * * @param stride bytes per line in the image plane. Setting this to 0 is the * equivalent of setting it to the plane width. * * @param height height (in pixels) of the YUV image. NOTE: this is the height * of the whole image, not the plane height. * * @param subsamp level of chrominance subsampling in the image (see * @ref TJSAMP "Chrominance subsampling options".) * * @return the size of the buffer (in bytes) required to hold the YUV image * plane, or -1 if the arguments are out of bounds. */ DLLEXPORT unsigned long DLLCALL tjPlaneSizeYUV(int componentID, int width, int stride, int height, int subsamp); /** * The plane width of a YUV image plane with the given parameters. Refer to * @ref YUVnotes "YUV Image Format Notes" for a description of plane width. * * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr) * * @param width width (in pixels) of the YUV image * * @param subsamp level of chrominance subsampling in the image (see * @ref TJSAMP "Chrominance subsampling options".) * * @return the plane width of a YUV image plane with the given parameters, or * -1 if the arguments are out of bounds. */ DLLEXPORT int tjPlaneWidth(int componentID, int width, int subsamp); /** * The plane height of a YUV image plane with the given parameters. Refer to * @ref YUVnotes "YUV Image Format Notes" for a description of plane height. * * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr) * * @param height height (in pixels) of the YUV image * * @param subsamp level of chrominance subsampling in the image (see * @ref TJSAMP "Chrominance subsampling options".) * * @return the plane height of a YUV image plane with the given parameters, or * -1 if the arguments are out of bounds. */ DLLEXPORT int tjPlaneHeight(int componentID, int height, int subsamp); /** * Encode an RGB or grayscale image into a YUV planar image. This function * uses the accelerated color conversion routines in the underlying * codec but does not execute any of the other steps in the JPEG compression * process. * * @param handle a handle to a TurboJPEG compressor or transformer instance * * @param srcBuf pointer to an image buffer containing RGB or grayscale pixels * to be encoded * * @param width width (in pixels) of the source image * * @param pitch bytes per line in the source image. Normally, this should be * <tt>width * #tjPixelSize[pixelFormat]</tt> if the image is unpadded, or * <tt>#TJPAD(width * #tjPixelSize[pixelFormat])</tt> if each line of the image * is padded to the nearest 32-bit boundary, as is the case for Windows * bitmaps. You can also be clever and use this parameter to skip lines, etc. * Setting this parameter to 0 is the equivalent of setting it to * <tt>width * #tjPixelSize[pixelFormat]</tt>. * * @param height height (in pixels) of the source image * * @param pixelFormat pixel format of the source image (see @ref TJPF * "Pixel formats".) * * @param dstBuf pointer to an image buffer that will receive the YUV image. * Use #tjBufSizeYUV2() to determine the appropriate size for this buffer based * on the image width, height, padding, and level of chrominance subsampling. * The Y, U (Cb), and V (Cr) image planes will be stored sequentially in the * buffer (refer to @ref YUVnotes "YUV Image Format Notes".) * * @param pad the width of each line in each plane of the YUV image will be * padded to the nearest multiple of this number of bytes (must be a power of * 2.) To generate images suitable for X Video, <tt>pad</tt> should be set to * 4. * * @param subsamp the level of chrominance subsampling to be used when * generating the YUV image (see @ref TJSAMP * "Chrominance subsampling options".) To generate images suitable for X * Video, <tt>subsamp</tt> should be set to @ref TJSAMP_420. This produces an * image compatible with the I420 (AKA "YUV420P") format. * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjEncodeYUV3(tjhandle handle, const unsigned char *srcBuf, int width, int pitch, int height, int pixelFormat, unsigned char *dstBuf, int pad, int subsamp, int flags); /** * Encode an RGB or grayscale image into separate Y, U (Cb), and V (Cr) image * planes. This function uses the accelerated color conversion routines in the * underlying codec but does not execute any of the other steps in the JPEG * compression process. * * @param handle a handle to a TurboJPEG compressor or transformer instance * * @param srcBuf pointer to an image buffer containing RGB or grayscale pixels * to be encoded * * @param width width (in pixels) of the source image * * @param pitch bytes per line in the source image. Normally, this should be * <tt>width * #tjPixelSize[pixelFormat]</tt> if the image is unpadded, or * <tt>#TJPAD(width * #tjPixelSize[pixelFormat])</tt> if each line of the image * is padded to the nearest 32-bit boundary, as is the case for Windows * bitmaps. You can also be clever and use this parameter to skip lines, etc. * Setting this parameter to 0 is the equivalent of setting it to * <tt>width * #tjPixelSize[pixelFormat]</tt>. * * @param height height (in pixels) of the source image * * @param pixelFormat pixel format of the source image (see @ref TJPF * "Pixel formats".) * * @param dstPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes * (or just a Y plane, if generating a grayscale image) that will receive the * encoded image. These planes can be contiguous or non-contiguous in memory. * Use #tjPlaneSizeYUV() to determine the appropriate size for each plane based * on the image width, height, strides, and level of chrominance subsampling. * Refer to @ref YUVnotes "YUV Image Format Notes" for more details. * * @param strides an array of integers, each specifying the number of bytes per * line in the corresponding plane of the output image. Setting the stride for * any plane to 0 is the same as setting it to the plane width (see * @ref YUVnotes "YUV Image Format Notes".) If <tt>strides</tt> is NULL, then * the strides for all planes will be set to their respective plane widths. * You can adjust the strides in order to add an arbitrary amount of line * padding to each plane or to encode an RGB or grayscale image into a * subregion of a larger YUV planar image. * * @param subsamp the level of chrominance subsampling to be used when * generating the YUV image (see @ref TJSAMP * "Chrominance subsampling options".) To generate images suitable for X * Video, <tt>subsamp</tt> should be set to @ref TJSAMP_420. This produces an * image compatible with the I420 (AKA "YUV420P") format. * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjEncodeYUVPlanes(tjhandle handle, const unsigned char *srcBuf, int width, int pitch, int height, int pixelFormat, unsigned char **dstPlanes, int *strides, int subsamp, int flags); /** * Create a TurboJPEG decompressor instance. * * @return a handle to the newly-created instance, or NULL if an error * occurred (see #tjGetErrorStr().) */ DLLEXPORT tjhandle DLLCALL tjInitDecompress(void); /** * Retrieve information about a JPEG image without decompressing it. * * @param handle a handle to a TurboJPEG decompressor or transformer instance * * @param jpegBuf pointer to a buffer containing a JPEG image * * @param jpegSize size of the JPEG image (in bytes) * * @param width pointer to an integer variable that will receive the width (in * pixels) of the JPEG image * * @param height pointer to an integer variable that will receive the height * (in pixels) of the JPEG image * * @param jpegSubsamp pointer to an integer variable that will receive the * level of chrominance subsampling used when the JPEG image was compressed * (see @ref TJSAMP "Chrominance subsampling options".) * * @param jpegColorspace pointer to an integer variable that will receive one * of the JPEG colorspace constants, indicating the colorspace of the JPEG * image (see @ref TJCS "JPEG colorspaces".) * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjDecompressHeader3(tjhandle handle, const unsigned char *jpegBuf, unsigned long jpegSize, int *width, int *height, int *jpegSubsamp, int *jpegColorspace); /** * Returns a list of fractional scaling factors that the JPEG decompressor in * this implementation of TurboJPEG supports. * * @param numscalingfactors pointer to an integer variable that will receive * the number of elements in the list * * @return a pointer to a list of fractional scaling factors, or NULL if an * error is encountered (see #tjGetErrorStr().) */ DLLEXPORT tjscalingfactor* DLLCALL tjGetScalingFactors(int *numscalingfactors); /** * Decompress a JPEG image to an RGB, grayscale, or CMYK image. * * @param handle a handle to a TurboJPEG decompressor or transformer instance * * @param jpegBuf pointer to a buffer containing the JPEG image to decompress * * @param jpegSize size of the JPEG image (in bytes) * * @param dstBuf pointer to an image buffer that will receive the decompressed * image. This buffer should normally be <tt>pitch * scaledHeight</tt> bytes * in size, where <tt>scaledHeight</tt> can be determined by calling * #TJSCALED() with the JPEG image height and one of the scaling factors * returned by #tjGetScalingFactors(). The <tt>dstBuf</tt> pointer may also be * used to decompress into a specific region of a larger buffer. * * @param width desired width (in pixels) of the destination image. If this is * different than the width of the JPEG image being decompressed, then * TurboJPEG will use scaling in the JPEG decompressor to generate the largest * possible image that will fit within the desired width. If <tt>width</tt> is * set to 0, then only the height will be considered when determining the * scaled image size. * * @param pitch bytes per line in the destination image. Normally, this is * <tt>scaledWidth * #tjPixelSize[pixelFormat]</tt> if the decompressed image * is unpadded, else <tt>#TJPAD(scaledWidth * #tjPixelSize[pixelFormat])</tt> * if each line of the decompressed image is padded to the nearest 32-bit * boundary, as is the case for Windows bitmaps. (NOTE: <tt>scaledWidth</tt> * can be determined by calling #TJSCALED() with the JPEG image width and one * of the scaling factors returned by #tjGetScalingFactors().) You can also be * clever and use the pitch parameter to skip lines, etc. Setting this * parameter to 0 is the equivalent of setting it to * <tt>scaledWidth * #tjPixelSize[pixelFormat]</tt>. * * @param height desired height (in pixels) of the destination image. If this * is different than the height of the JPEG image being decompressed, then * TurboJPEG will use scaling in the JPEG decompressor to generate the largest * possible image that will fit within the desired height. If <tt>height</tt> * is set to 0, then only the width will be considered when determining the * scaled image size. * * @param pixelFormat pixel format of the destination image (see @ref * TJPF "Pixel formats".) * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjDecompress2(tjhandle handle, const unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, int width, int pitch, int height, int pixelFormat, int flags); /** * Decompress a JPEG image to a YUV planar image. This function performs JPEG * decompression but leaves out the color conversion step, so a planar YUV * image is generated instead of an RGB image. * * @param handle a handle to a TurboJPEG decompressor or transformer instance * * @param jpegBuf pointer to a buffer containing the JPEG image to decompress * * @param jpegSize size of the JPEG image (in bytes) * * @param dstBuf pointer to an image buffer that will receive the YUV image. * Use #tjBufSizeYUV2() to determine the appropriate size for this buffer based * on the image width, height, padding, and level of subsampling. The Y, * U (Cb), and V (Cr) image planes will be stored sequentially in the buffer * (refer to @ref YUVnotes "YUV Image Format Notes".) * * @param width desired width (in pixels) of the YUV image. If this is * different than the width of the JPEG image being decompressed, then * TurboJPEG will use scaling in the JPEG decompressor to generate the largest * possible image that will fit within the desired width. If <tt>width</tt> is * set to 0, then only the height will be considered when determining the * scaled image size. If the scaled width is not an even multiple of the MCU * block width (see #tjMCUWidth), then an intermediate buffer copy will be * performed within TurboJPEG. * * @param pad the width of each line in each plane of the YUV image will be * padded to the nearest multiple of this number of bytes (must be a power of * 2.) To generate images suitable for X Video, <tt>pad</tt> should be set to * 4. * * @param height desired height (in pixels) of the YUV image. If this is * different than the height of the JPEG image being decompressed, then * TurboJPEG will use scaling in the JPEG decompressor to generate the largest * possible image that will fit within the desired height. If <tt>height</tt> * is set to 0, then only the width will be considered when determining the * scaled image size. If the scaled height is not an even multiple of the MCU * block height (see #tjMCUHeight), then an intermediate buffer copy will be * performed within TurboJPEG. * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjDecompressToYUV2(tjhandle handle, const unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, int width, int pad, int height, int flags); /** * Decompress a JPEG image into separate Y, U (Cb), and V (Cr) image * planes. This function performs JPEG decompression but leaves out the color * conversion step, so a planar YUV image is generated instead of an RGB image. * * @param handle a handle to a TurboJPEG decompressor or transformer instance * * @param jpegBuf pointer to a buffer containing the JPEG image to decompress * * @param jpegSize size of the JPEG image (in bytes) * * @param dstPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes * (or just a Y plane, if decompressing a grayscale image) that will receive * the YUV image. These planes can be contiguous or non-contiguous in memory. * Use #tjPlaneSizeYUV() to determine the appropriate size for each plane based * on the scaled image width, scaled image height, strides, and level of * chrominance subsampling. Refer to @ref YUVnotes "YUV Image Format Notes" * for more details. * * @param width desired width (in pixels) of the YUV image. If this is * different than the width of the JPEG image being decompressed, then * TurboJPEG will use scaling in the JPEG decompressor to generate the largest * possible image that will fit within the desired width. If <tt>width</tt> is * set to 0, then only the height will be considered when determining the * scaled image size. If the scaled width is not an even multiple of the MCU * block width (see #tjMCUWidth), then an intermediate buffer copy will be * performed within TurboJPEG. * * @param strides an array of integers, each specifying the number of bytes per * line in the corresponding plane of the output image. Setting the stride for * any plane to 0 is the same as setting it to the scaled plane width (see * @ref YUVnotes "YUV Image Format Notes".) If <tt>strides</tt> is NULL, then * the strides for all planes will be set to their respective scaled plane * widths. You can adjust the strides in order to add an arbitrary amount of * line padding to each plane or to decompress the JPEG image into a subregion * of a larger YUV planar image. * * @param height desired height (in pixels) of the YUV image. If this is * different than the height of the JPEG image being decompressed, then * TurboJPEG will use scaling in the JPEG decompressor to generate the largest * possible image that will fit within the desired height. If <tt>height</tt> * is set to 0, then only the width will be considered when determining the * scaled image size. If the scaled height is not an even multiple of the MCU * block height (see #tjMCUHeight), then an intermediate buffer copy will be * performed within TurboJPEG. * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjDecompressToYUVPlanes(tjhandle handle, const unsigned char *jpegBuf, unsigned long jpegSize, unsigned char **dstPlanes, int width, int *strides, int height, int flags); /** * Decode a YUV planar image into an RGB or grayscale image. This function * uses the accelerated color conversion routines in the underlying * codec but does not execute any of the other steps in the JPEG decompression * process. * * @param handle a handle to a TurboJPEG decompressor or transformer instance * * @param srcBuf pointer to an image buffer containing a YUV planar image to be * decoded. The size of this buffer should match the value returned by * #tjBufSizeYUV2() for the given image width, height, padding, and level of * chrominance subsampling. The Y, U (Cb), and V (Cr) image planes should be * stored sequentially in the source buffer (refer to @ref YUVnotes * "YUV Image Format Notes".) * * @param pad Use this parameter to specify that the width of each line in each * plane of the YUV source image is padded to the nearest multiple of this * number of bytes (must be a power of 2.) * * @param subsamp the level of chrominance subsampling used in the YUV source * image (see @ref TJSAMP "Chrominance subsampling options".) * * @param dstBuf pointer to an image buffer that will receive the decoded * image. This buffer should normally be <tt>pitch * height</tt> bytes in * size, but the <tt>dstBuf</tt> pointer can also be used to decode into a * specific region of a larger buffer. * * @param width width (in pixels) of the source and destination images * * @param pitch bytes per line in the destination image. Normally, this should * be <tt>width * #tjPixelSize[pixelFormat]</tt> if the destination image is * unpadded, or <tt>#TJPAD(width * #tjPixelSize[pixelFormat])</tt> if each line * of the destination image should be padded to the nearest 32-bit boundary, as * is the case for Windows bitmaps. You can also be clever and use the pitch * parameter to skip lines, etc. Setting this parameter to 0 is the equivalent * of setting it to <tt>width * #tjPixelSize[pixelFormat]</tt>. * * @param height height (in pixels) of the source and destination images * * @param pixelFormat pixel format of the destination image (see @ref TJPF * "Pixel formats".) * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjDecodeYUV(tjhandle handle, const unsigned char *srcBuf, int pad, int subsamp, unsigned char *dstBuf, int width, int pitch, int height, int pixelFormat, int flags); /** * Decode a set of Y, U (Cb), and V (Cr) image planes into an RGB or grayscale * image. This function uses the accelerated color conversion routines in the * underlying codec but does not execute any of the other steps in the JPEG * decompression process. * * @param handle a handle to a TurboJPEG decompressor or transformer instance * * @param srcPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes * (or just a Y plane, if decoding a grayscale image) that contain a YUV image * to be decoded. These planes can be contiguous or non-contiguous in memory. * The size of each plane should match the value returned by #tjPlaneSizeYUV() * for the given image width, height, strides, and level of chrominance * subsampling. Refer to @ref YUVnotes "YUV Image Format Notes" for more * details. * * @param strides an array of integers, each specifying the number of bytes per * line in the corresponding plane of the YUV source image. Setting the stride * for any plane to 0 is the same as setting it to the plane width (see * @ref YUVnotes "YUV Image Format Notes".) If <tt>strides</tt> is NULL, then * the strides for all planes will be set to their respective plane widths. * You can adjust the strides in order to specify an arbitrary amount of line * padding in each plane or to decode a subregion of a larger YUV planar image. * * @param subsamp the level of chrominance subsampling used in the YUV source * image (see @ref TJSAMP "Chrominance subsampling options".) * * @param dstBuf pointer to an image buffer that will receive the decoded * image. This buffer should normally be <tt>pitch * height</tt> bytes in * size, but the <tt>dstBuf</tt> pointer can also be used to decode into a * specific region of a larger buffer. * * @param width width (in pixels) of the source and destination images * * @param pitch bytes per line in the destination image. Normally, this should * be <tt>width * #tjPixelSize[pixelFormat]</tt> if the destination image is * unpadded, or <tt>#TJPAD(width * #tjPixelSize[pixelFormat])</tt> if each line * of the destination image should be padded to the nearest 32-bit boundary, as * is the case for Windows bitmaps. You can also be clever and use the pitch * parameter to skip lines, etc. Setting this parameter to 0 is the equivalent * of setting it to <tt>width * #tjPixelSize[pixelFormat]</tt>. * * @param height height (in pixels) of the source and destination images * * @param pixelFormat pixel format of the destination image (see @ref TJPF * "Pixel formats".) * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjDecodeYUVPlanes(tjhandle handle, const unsigned char **srcPlanes, const int *strides, int subsamp, unsigned char *dstBuf, int width, int pitch, int height, int pixelFormat, int flags); /** * Create a new TurboJPEG transformer instance. * * @return a handle to the newly-created instance, or NULL if an error * occurred (see #tjGetErrorStr().) */ DLLEXPORT tjhandle DLLCALL tjInitTransform(void); /** * Losslessly transform a JPEG image into another JPEG image. Lossless * transforms work by moving the raw DCT coefficients from one JPEG image * structure to another without altering the values of the coefficients. While * this is typically faster than decompressing the image, transforming it, and * re-compressing it, lossless transforms are not free. Each lossless * transform requires reading and performing Huffman decoding on all of the * coefficients in the source image, regardless of the size of the destination * image. Thus, this function provides a means of generating multiple * transformed images from the same source or applying multiple * transformations simultaneously, in order to eliminate the need to read the * source coefficients multiple times. * * @param handle a handle to a TurboJPEG transformer instance * * @param jpegBuf pointer to a buffer containing the JPEG source image to * transform * * @param jpegSize size of the JPEG source image (in bytes) * * @param n the number of transformed JPEG images to generate * * @param dstBufs pointer to an array of n image buffers. <tt>dstBufs[i]</tt> * will receive a JPEG image that has been transformed using the parameters in * <tt>transforms[i]</tt>. TurboJPEG has the ability to reallocate the JPEG * buffer to accommodate the size of the JPEG image. Thus, you can choose to: * -# pre-allocate the JPEG buffer with an arbitrary size using #tjAlloc() and * let TurboJPEG grow the buffer as needed, * -# set <tt>dstBufs[i]</tt> to NULL to tell TurboJPEG to allocate the buffer * for you, or * -# pre-allocate the buffer to a "worst case" size determined by calling * #tjBufSize() with the transformed or cropped width and height. This should * ensure that the buffer never has to be re-allocated (setting * #TJFLAG_NOREALLOC guarantees this.) * . * If you choose option 1, <tt>dstSizes[i]</tt> should be set to the size of * your pre-allocated buffer. In any case, unless you have set * #TJFLAG_NOREALLOC, you should always check <tt>dstBufs[i]</tt> upon return * from this function, as it may have changed. * * @param dstSizes pointer to an array of n unsigned long variables that will * receive the actual sizes (in bytes) of each transformed JPEG image. If * <tt>dstBufs[i]</tt> points to a pre-allocated buffer, then * <tt>dstSizes[i]</tt> should be set to the size of the buffer. Upon return, * <tt>dstSizes[i]</tt> will contain the size of the JPEG image (in bytes.) * * @param transforms pointer to an array of n #tjtransform structures, each of * which specifies the transform parameters and/or cropping region for the * corresponding transformed output image. * * @param flags the bitwise OR of one or more of the @ref TJFLAG_BOTTOMUP * "flags" * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjTransform(tjhandle handle, const unsigned char *jpegBuf, unsigned long jpegSize, int n, unsigned char **dstBufs, unsigned long *dstSizes, tjtransform *transforms, int flags); /** * Destroy a TurboJPEG compressor, decompressor, or transformer instance. * * @param handle a handle to a TurboJPEG compressor, decompressor or * transformer instance * * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) */ DLLEXPORT int DLLCALL tjDestroy(tjhandle handle); /** * Allocate an image buffer for use with TurboJPEG. You should always use * this function to allocate the JPEG destination buffer(s) for #tjCompress2() * and #tjTransform() unless you are disabling automatic buffer * (re)allocation (by setting #TJFLAG_NOREALLOC.) * * @param bytes the number of bytes to allocate * * @return a pointer to a newly-allocated buffer with the specified number of * bytes. * * @sa tjFree() */ DLLEXPORT unsigned char* DLLCALL tjAlloc(int bytes); /** * Free an image buffer previously allocated by TurboJPEG. You should always * use this function to free JPEG destination buffer(s) that were automatically * (re)allocated by #tjCompress2() or #tjTransform() or that were manually * allocated using #tjAlloc(). * * @param buffer address of the buffer to free * * @sa tjAlloc() */ DLLEXPORT void DLLCALL tjFree(unsigned char *buffer); /** * Returns a descriptive error message explaining why the last command failed. * * @return a descriptive error message explaining why the last command failed. */ DLLEXPORT char* DLLCALL tjGetErrorStr(void); /* Deprecated functions and macros */ #define TJFLAG_FORCEMMX 8 #define TJFLAG_FORCESSE 16 #define TJFLAG_FORCESSE2 32 #define TJFLAG_FORCESSE3 128 /* Backward compatibility functions and macros (nothing to see here) */ #define NUMSUBOPT TJ_NUMSAMP #define TJ_444 TJSAMP_444 #define TJ_422 TJSAMP_422 #define TJ_420 TJSAMP_420 #define TJ_411 TJSAMP_420 #define TJ_GRAYSCALE TJSAMP_GRAY #define TJ_BGR 1 #define TJ_BOTTOMUP TJFLAG_BOTTOMUP #define TJ_FORCEMMX TJFLAG_FORCEMMX #define TJ_FORCESSE TJFLAG_FORCESSE #define TJ_FORCESSE2 TJFLAG_FORCESSE2 #define TJ_ALPHAFIRST 64 #define TJ_FORCESSE3 TJFLAG_FORCESSE3 #define TJ_FASTUPSAMPLE TJFLAG_FASTUPSAMPLE #define TJ_YUV 512 DLLEXPORT unsigned long DLLCALL TJBUFSIZE(int width, int height); DLLEXPORT unsigned long DLLCALL TJBUFSIZEYUV(int width, int height, int jpegSubsamp); DLLEXPORT unsigned long DLLCALL tjBufSizeYUV(int width, int height, int subsamp); DLLEXPORT int DLLCALL tjCompress(tjhandle handle, unsigned char *srcBuf, int width, int pitch, int height, int pixelSize, unsigned char *dstBuf, unsigned long *compressedSize, int jpegSubsamp, int jpegQual, int flags); DLLEXPORT int DLLCALL tjEncodeYUV(tjhandle handle, unsigned char *srcBuf, int width, int pitch, int height, int pixelSize, unsigned char *dstBuf, int subsamp, int flags); DLLEXPORT int DLLCALL tjEncodeYUV2(tjhandle handle, unsigned char *srcBuf, int width, int pitch, int height, int pixelFormat, unsigned char *dstBuf, int subsamp, int flags); DLLEXPORT int DLLCALL tjDecompressHeader(tjhandle handle, unsigned char *jpegBuf, unsigned long jpegSize, int *width, int *height); DLLEXPORT int DLLCALL tjDecompressHeader2(tjhandle handle, unsigned char *jpegBuf, unsigned long jpegSize, int *width, int *height, int *jpegSubsamp); DLLEXPORT int DLLCALL tjDecompress(tjhandle handle, unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, int width, int pitch, int height, int pixelSize, int flags); DLLEXPORT int DLLCALL tjDecompressToYUV(tjhandle handle, unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, int flags); /** * @} */ #ifdef __cplusplus } #endif #endif
{ "pile_set_name": "Github" }
package cli import "unicode" // lexicographicLess compares strings alphabetically considering case. func lexicographicLess(i, j string) bool { iRunes := []rune(i) jRunes := []rune(j) lenShared := len(iRunes) if lenShared > len(jRunes) { lenShared = len(jRunes) } for index := 0; index < lenShared; index++ { ir := iRunes[index] jr := jRunes[index] if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr { return lir < ljr } if ir != jr { return ir < jr } } return i < j }
{ "pile_set_name": "Github" }
/* ** 2017-03-08 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This SQLite extension implements functions that compute SHA3 hashes. ** Two SQL functions are implemented: ** ** sha3(X,SIZE) ** sha3_query(Y,SIZE) ** ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if ** X is NULL. ** ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y ** and returns a hash of their results. ** ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm ** is used. If SIZE is included it must be one of the integers 224, 256, ** 384, or 512, to determine SHA3 hash variant that is computed. */ #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #include <assert.h> #include <string.h> #include <stdarg.h> #if 0 typedef wx_sqlite3_uint64 u64; #endif /****************************************************************************** ** The Hash Engine */ /* ** Macros to determine whether the machine is big or little endian, ** and whether or not that determination is run-time or compile-time. ** ** For best performance, an attempt is made to guess at the byte-order ** using C-preprocessor macros. If that is unsuccessful, or if ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined ** at run-time. */ #ifndef SHA3_BYTEORDER # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ defined(__arm__) # define SHA3_BYTEORDER 1234 # elif defined(sparc) || defined(__ppc__) # define SHA3_BYTEORDER 4321 # else # define SHA3_BYTEORDER 0 # endif #endif /* ** State structure for a SHA3 hash in progress */ typedef struct SHA3Context SHA3Context; struct SHA3Context { union { u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */ unsigned char x[1600]; /* ... or 1600 bytes */ } u; unsigned nRate; /* Bytes of input accepted per Keccak iteration */ unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */ unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */ }; /* ** A single step of the Keccak mixing function for a 1600-bit state */ static void KeccakF1600Step(SHA3Context *p){ int i; u64 b0, b1, b2, b3, b4; u64 c0, c1, c2, c3, c4; u64 d0, d1, d2, d3, d4; static const u64 RC[] = { 0x0000000000000001ULL, 0x0000000000008082ULL, 0x800000000000808aULL, 0x8000000080008000ULL, 0x000000000000808bULL, 0x0000000080000001ULL, 0x8000000080008081ULL, 0x8000000000008009ULL, 0x000000000000008aULL, 0x0000000000000088ULL, 0x0000000080008009ULL, 0x000000008000000aULL, 0x000000008000808bULL, 0x800000000000008bULL, 0x8000000000008089ULL, 0x8000000000008003ULL, 0x8000000000008002ULL, 0x8000000000000080ULL, 0x000000000000800aULL, 0x800000008000000aULL, 0x8000000080008081ULL, 0x8000000000008080ULL, 0x0000000080000001ULL, 0x8000000080008008ULL }; # define a00 (p->u.s[0]) # define a01 (p->u.s[1]) # define a02 (p->u.s[2]) # define a03 (p->u.s[3]) # define a04 (p->u.s[4]) # define a10 (p->u.s[5]) # define a11 (p->u.s[6]) # define a12 (p->u.s[7]) # define a13 (p->u.s[8]) # define a14 (p->u.s[9]) # define a20 (p->u.s[10]) # define a21 (p->u.s[11]) # define a22 (p->u.s[12]) # define a23 (p->u.s[13]) # define a24 (p->u.s[14]) # define a30 (p->u.s[15]) # define a31 (p->u.s[16]) # define a32 (p->u.s[17]) # define a33 (p->u.s[18]) # define a34 (p->u.s[19]) # define a40 (p->u.s[20]) # define a41 (p->u.s[21]) # define a42 (p->u.s[22]) # define a43 (p->u.s[23]) # define a44 (p->u.s[24]) # define ROL64(a,x) ((a<<x)|(a>>(64-x))) for(i=0; i<24; i+=4){ c0 = a00^a10^a20^a30^a40; c1 = a01^a11^a21^a31^a41; c2 = a02^a12^a22^a32^a42; c3 = a03^a13^a23^a33^a43; c4 = a04^a14^a24^a34^a44; d0 = c4^ROL64(c1, 1); d1 = c0^ROL64(c2, 1); d2 = c1^ROL64(c3, 1); d3 = c2^ROL64(c4, 1); d4 = c3^ROL64(c0, 1); b0 = (a00^d0); b1 = ROL64((a11^d1), 44); b2 = ROL64((a22^d2), 43); b3 = ROL64((a33^d3), 21); b4 = ROL64((a44^d4), 14); a00 = b0 ^((~b1)& b2 ); a00 ^= RC[i]; a11 = b1 ^((~b2)& b3 ); a22 = b2 ^((~b3)& b4 ); a33 = b3 ^((~b4)& b0 ); a44 = b4 ^((~b0)& b1 ); b2 = ROL64((a20^d0), 3); b3 = ROL64((a31^d1), 45); b4 = ROL64((a42^d2), 61); b0 = ROL64((a03^d3), 28); b1 = ROL64((a14^d4), 20); a20 = b0 ^((~b1)& b2 ); a31 = b1 ^((~b2)& b3 ); a42 = b2 ^((~b3)& b4 ); a03 = b3 ^((~b4)& b0 ); a14 = b4 ^((~b0)& b1 ); b4 = ROL64((a40^d0), 18); b0 = ROL64((a01^d1), 1); b1 = ROL64((a12^d2), 6); b2 = ROL64((a23^d3), 25); b3 = ROL64((a34^d4), 8); a40 = b0 ^((~b1)& b2 ); a01 = b1 ^((~b2)& b3 ); a12 = b2 ^((~b3)& b4 ); a23 = b3 ^((~b4)& b0 ); a34 = b4 ^((~b0)& b1 ); b1 = ROL64((a10^d0), 36); b2 = ROL64((a21^d1), 10); b3 = ROL64((a32^d2), 15); b4 = ROL64((a43^d3), 56); b0 = ROL64((a04^d4), 27); a10 = b0 ^((~b1)& b2 ); a21 = b1 ^((~b2)& b3 ); a32 = b2 ^((~b3)& b4 ); a43 = b3 ^((~b4)& b0 ); a04 = b4 ^((~b0)& b1 ); b3 = ROL64((a30^d0), 41); b4 = ROL64((a41^d1), 2); b0 = ROL64((a02^d2), 62); b1 = ROL64((a13^d3), 55); b2 = ROL64((a24^d4), 39); a30 = b0 ^((~b1)& b2 ); a41 = b1 ^((~b2)& b3 ); a02 = b2 ^((~b3)& b4 ); a13 = b3 ^((~b4)& b0 ); a24 = b4 ^((~b0)& b1 ); c0 = a00^a20^a40^a10^a30; c1 = a11^a31^a01^a21^a41; c2 = a22^a42^a12^a32^a02; c3 = a33^a03^a23^a43^a13; c4 = a44^a14^a34^a04^a24; d0 = c4^ROL64(c1, 1); d1 = c0^ROL64(c2, 1); d2 = c1^ROL64(c3, 1); d3 = c2^ROL64(c4, 1); d4 = c3^ROL64(c0, 1); b0 = (a00^d0); b1 = ROL64((a31^d1), 44); b2 = ROL64((a12^d2), 43); b3 = ROL64((a43^d3), 21); b4 = ROL64((a24^d4), 14); a00 = b0 ^((~b1)& b2 ); a00 ^= RC[i+1]; a31 = b1 ^((~b2)& b3 ); a12 = b2 ^((~b3)& b4 ); a43 = b3 ^((~b4)& b0 ); a24 = b4 ^((~b0)& b1 ); b2 = ROL64((a40^d0), 3); b3 = ROL64((a21^d1), 45); b4 = ROL64((a02^d2), 61); b0 = ROL64((a33^d3), 28); b1 = ROL64((a14^d4), 20); a40 = b0 ^((~b1)& b2 ); a21 = b1 ^((~b2)& b3 ); a02 = b2 ^((~b3)& b4 ); a33 = b3 ^((~b4)& b0 ); a14 = b4 ^((~b0)& b1 ); b4 = ROL64((a30^d0), 18); b0 = ROL64((a11^d1), 1); b1 = ROL64((a42^d2), 6); b2 = ROL64((a23^d3), 25); b3 = ROL64((a04^d4), 8); a30 = b0 ^((~b1)& b2 ); a11 = b1 ^((~b2)& b3 ); a42 = b2 ^((~b3)& b4 ); a23 = b3 ^((~b4)& b0 ); a04 = b4 ^((~b0)& b1 ); b1 = ROL64((a20^d0), 36); b2 = ROL64((a01^d1), 10); b3 = ROL64((a32^d2), 15); b4 = ROL64((a13^d3), 56); b0 = ROL64((a44^d4), 27); a20 = b0 ^((~b1)& b2 ); a01 = b1 ^((~b2)& b3 ); a32 = b2 ^((~b3)& b4 ); a13 = b3 ^((~b4)& b0 ); a44 = b4 ^((~b0)& b1 ); b3 = ROL64((a10^d0), 41); b4 = ROL64((a41^d1), 2); b0 = ROL64((a22^d2), 62); b1 = ROL64((a03^d3), 55); b2 = ROL64((a34^d4), 39); a10 = b0 ^((~b1)& b2 ); a41 = b1 ^((~b2)& b3 ); a22 = b2 ^((~b3)& b4 ); a03 = b3 ^((~b4)& b0 ); a34 = b4 ^((~b0)& b1 ); c0 = a00^a40^a30^a20^a10; c1 = a31^a21^a11^a01^a41; c2 = a12^a02^a42^a32^a22; c3 = a43^a33^a23^a13^a03; c4 = a24^a14^a04^a44^a34; d0 = c4^ROL64(c1, 1); d1 = c0^ROL64(c2, 1); d2 = c1^ROL64(c3, 1); d3 = c2^ROL64(c4, 1); d4 = c3^ROL64(c0, 1); b0 = (a00^d0); b1 = ROL64((a21^d1), 44); b2 = ROL64((a42^d2), 43); b3 = ROL64((a13^d3), 21); b4 = ROL64((a34^d4), 14); a00 = b0 ^((~b1)& b2 ); a00 ^= RC[i+2]; a21 = b1 ^((~b2)& b3 ); a42 = b2 ^((~b3)& b4 ); a13 = b3 ^((~b4)& b0 ); a34 = b4 ^((~b0)& b1 ); b2 = ROL64((a30^d0), 3); b3 = ROL64((a01^d1), 45); b4 = ROL64((a22^d2), 61); b0 = ROL64((a43^d3), 28); b1 = ROL64((a14^d4), 20); a30 = b0 ^((~b1)& b2 ); a01 = b1 ^((~b2)& b3 ); a22 = b2 ^((~b3)& b4 ); a43 = b3 ^((~b4)& b0 ); a14 = b4 ^((~b0)& b1 ); b4 = ROL64((a10^d0), 18); b0 = ROL64((a31^d1), 1); b1 = ROL64((a02^d2), 6); b2 = ROL64((a23^d3), 25); b3 = ROL64((a44^d4), 8); a10 = b0 ^((~b1)& b2 ); a31 = b1 ^((~b2)& b3 ); a02 = b2 ^((~b3)& b4 ); a23 = b3 ^((~b4)& b0 ); a44 = b4 ^((~b0)& b1 ); b1 = ROL64((a40^d0), 36); b2 = ROL64((a11^d1), 10); b3 = ROL64((a32^d2), 15); b4 = ROL64((a03^d3), 56); b0 = ROL64((a24^d4), 27); a40 = b0 ^((~b1)& b2 ); a11 = b1 ^((~b2)& b3 ); a32 = b2 ^((~b3)& b4 ); a03 = b3 ^((~b4)& b0 ); a24 = b4 ^((~b0)& b1 ); b3 = ROL64((a20^d0), 41); b4 = ROL64((a41^d1), 2); b0 = ROL64((a12^d2), 62); b1 = ROL64((a33^d3), 55); b2 = ROL64((a04^d4), 39); a20 = b0 ^((~b1)& b2 ); a41 = b1 ^((~b2)& b3 ); a12 = b2 ^((~b3)& b4 ); a33 = b3 ^((~b4)& b0 ); a04 = b4 ^((~b0)& b1 ); c0 = a00^a30^a10^a40^a20; c1 = a21^a01^a31^a11^a41; c2 = a42^a22^a02^a32^a12; c3 = a13^a43^a23^a03^a33; c4 = a34^a14^a44^a24^a04; d0 = c4^ROL64(c1, 1); d1 = c0^ROL64(c2, 1); d2 = c1^ROL64(c3, 1); d3 = c2^ROL64(c4, 1); d4 = c3^ROL64(c0, 1); b0 = (a00^d0); b1 = ROL64((a01^d1), 44); b2 = ROL64((a02^d2), 43); b3 = ROL64((a03^d3), 21); b4 = ROL64((a04^d4), 14); a00 = b0 ^((~b1)& b2 ); a00 ^= RC[i+3]; a01 = b1 ^((~b2)& b3 ); a02 = b2 ^((~b3)& b4 ); a03 = b3 ^((~b4)& b0 ); a04 = b4 ^((~b0)& b1 ); b2 = ROL64((a10^d0), 3); b3 = ROL64((a11^d1), 45); b4 = ROL64((a12^d2), 61); b0 = ROL64((a13^d3), 28); b1 = ROL64((a14^d4), 20); a10 = b0 ^((~b1)& b2 ); a11 = b1 ^((~b2)& b3 ); a12 = b2 ^((~b3)& b4 ); a13 = b3 ^((~b4)& b0 ); a14 = b4 ^((~b0)& b1 ); b4 = ROL64((a20^d0), 18); b0 = ROL64((a21^d1), 1); b1 = ROL64((a22^d2), 6); b2 = ROL64((a23^d3), 25); b3 = ROL64((a24^d4), 8); a20 = b0 ^((~b1)& b2 ); a21 = b1 ^((~b2)& b3 ); a22 = b2 ^((~b3)& b4 ); a23 = b3 ^((~b4)& b0 ); a24 = b4 ^((~b0)& b1 ); b1 = ROL64((a30^d0), 36); b2 = ROL64((a31^d1), 10); b3 = ROL64((a32^d2), 15); b4 = ROL64((a33^d3), 56); b0 = ROL64((a34^d4), 27); a30 = b0 ^((~b1)& b2 ); a31 = b1 ^((~b2)& b3 ); a32 = b2 ^((~b3)& b4 ); a33 = b3 ^((~b4)& b0 ); a34 = b4 ^((~b0)& b1 ); b3 = ROL64((a40^d0), 41); b4 = ROL64((a41^d1), 2); b0 = ROL64((a42^d2), 62); b1 = ROL64((a43^d3), 55); b2 = ROL64((a44^d4), 39); a40 = b0 ^((~b1)& b2 ); a41 = b1 ^((~b2)& b3 ); a42 = b2 ^((~b3)& b4 ); a43 = b3 ^((~b4)& b0 ); a44 = b4 ^((~b0)& b1 ); } } /* ** Initialize a new hash. iSize determines the size of the hash ** in bits and should be one of 224, 256, 384, or 512. Or iSize ** can be zero to use the default hash size of 256 bits. */ static void SHA3Init(SHA3Context *p, int iSize){ memset(p, 0, sizeof(*p)); if( iSize>=128 && iSize<=512 ){ p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; }else{ p->nRate = (1600 - 2*256)/8; } #if SHA3_BYTEORDER==1234 /* Known to be little-endian at compile-time. No-op */ #elif SHA3_BYTEORDER==4321 p->ixMask = 7; /* Big-endian */ #else { static unsigned int one = 1; if( 1==*(unsigned char*)&one ){ /* Little endian. No byte swapping. */ p->ixMask = 0; }else{ /* Big endian. Byte swap. */ p->ixMask = 7; } } #endif } /* ** Make consecutive calls to the SHA3Update function to add new content ** to the hash */ static void SHA3Update( SHA3Context *p, const unsigned char *aData, unsigned int nData ){ unsigned int i = 0; #if SHA3_BYTEORDER==1234 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ for(; i+7<nData; i+=8){ p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; p->nLoaded += 8; if( p->nLoaded>=p->nRate ){ KeccakF1600Step(p); p->nLoaded = 0; } } } #endif for(; i<nData; i++){ #if SHA3_BYTEORDER==1234 p->u.x[p->nLoaded] ^= aData[i]; #elif SHA3_BYTEORDER==4321 p->u.x[p->nLoaded^0x07] ^= aData[i]; #else p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; #endif p->nLoaded++; if( p->nLoaded==p->nRate ){ KeccakF1600Step(p); p->nLoaded = 0; } } } /* ** After all content has been added, invoke SHA3Final() to compute ** the final hash. The function returns a pointer to the binary ** hash value. */ static unsigned char *SHA3Final(SHA3Context *p){ unsigned int i; if( p->nLoaded==p->nRate-1 ){ const unsigned char c1 = 0x86; SHA3Update(p, &c1, 1); }else{ const unsigned char c2 = 0x06; const unsigned char c3 = 0x80; SHA3Update(p, &c2, 1); p->nLoaded = p->nRate - 1; SHA3Update(p, &c3, 1); } for(i=0; i<p->nRate; i++){ p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; } return &p->u.x[p->nRate]; } /* End of the hashing logic *****************************************************************************/ /* ** Implementation of the sha3(X,SIZE) function. ** ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default ** size is 256. If X is a BLOB, it is hashed as is. ** For all other non-NULL types of input, X is converted into a UTF-8 string ** and the string is hashed without the trailing 0x00 terminator. The hash ** of a NULL value is NULL. */ static void sha3Func( wx_sqlite3_context *context, int argc, wx_sqlite3_value **argv ){ SHA3Context cx; int eType = wx_sqlite3_value_type(argv[0]); int nByte = wx_sqlite3_value_bytes(argv[0]); int iSize; if( argc==1 ){ iSize = 256; }else{ iSize = wx_sqlite3_value_int(argv[1]); if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ wx_sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " "384 512", -1); return; } } if( eType==SQLITE_NULL ) return; SHA3Init(&cx, iSize); if( eType==SQLITE_BLOB ){ SHA3Update(&cx, wx_sqlite3_value_blob(argv[0]), nByte); }else{ SHA3Update(&cx, wx_sqlite3_value_text(argv[0]), nByte); } wx_sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT); } /* Compute a string using wx_sqlite3_vsnprintf() with a maximum length ** of 50 bytes and add it to the hash. */ static void hash_step_vformat( SHA3Context *p, /* Add content to this context */ const char *zFormat, ... ){ va_list ap; int n; char zBuf[50]; va_start(ap, zFormat); wx_sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap); va_end(ap); n = (int)strlen(zBuf); SHA3Update(p, (unsigned char*)zBuf, n); } /* ** Implementation of the sha3_query(SQL,SIZE) function. ** ** This function compiles and runs the SQL statement(s) given in the ** argument. The results are hashed using a SIZE-bit SHA3. The default ** size is 256. ** ** The format of the byte stream that is hashed is summarized as follows: ** ** S<n>:<sql> ** R ** N ** I<int> ** F<ieee-float> ** B<size>:<bytes> ** T<size>:<text> ** ** <sql> is the original SQL text for each statement run and <n> is ** the size of that text. The SQL text is UTF-8. A single R character ** occurs before the start of each row. N means a NULL value. ** I mean an 8-byte little-endian integer <int>. F is a floating point ** number with an 8-byte little-endian IEEE floating point value <ieee-float>. ** B means blobs of <size> bytes. T means text rendered as <size> ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII ** text integers. ** ** For each SQL statement in the X input, there is one S segment. Each ** S segment is followed by zero or more R segments, one for each row in the ** result set. After each R, there are one or more N, I, F, B, or T segments, ** one for each column in the result set. Segments are concatentated directly ** with no delimiters of any kind. */ static void sha3QueryFunc( wx_sqlite3_context *context, int argc, wx_sqlite3_value **argv ){ wx_sqlite3 *db = wx_sqlite3_context_db_handle(context); const char *zSql = (const char*)wx_sqlite3_value_text(argv[0]); wx_sqlite3_stmt *pStmt = 0; int nCol; /* Number of columns in the result set */ int i; /* Loop counter */ int rc; int n; const char *z; SHA3Context cx; int iSize; if( argc==1 ){ iSize = 256; }else{ iSize = wx_sqlite3_value_int(argv[1]); if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ wx_sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " "384 512", -1); return; } } if( zSql==0 ) return; SHA3Init(&cx, iSize); while( zSql[0] ){ rc = wx_sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); if( rc ){ char *zMsg = wx_sqlite3_mprintf("error SQL statement [%s]: %s", zSql, wx_sqlite3_errmsg(db)); wx_sqlite3_finalize(pStmt); wx_sqlite3_result_error(context, zMsg, -1); wx_sqlite3_free(zMsg); return; } if( !wx_sqlite3_stmt_readonly(pStmt) ){ char *zMsg = wx_sqlite3_mprintf("non-query: [%s]", wx_sqlite3_sql(pStmt)); wx_sqlite3_finalize(pStmt); wx_sqlite3_result_error(context, zMsg, -1); wx_sqlite3_free(zMsg); return; } nCol = wx_sqlite3_column_count(pStmt); z = wx_sqlite3_sql(pStmt); n = (int)strlen(z); hash_step_vformat(&cx,"S%d:",n); SHA3Update(&cx,(unsigned char*)z,n); /* Compute a hash over the result of the query */ while( SQLITE_ROW==wx_sqlite3_step(pStmt) ){ SHA3Update(&cx,(const unsigned char*)"R",1); for(i=0; i<nCol; i++){ switch( wx_sqlite3_column_type(pStmt,i) ){ case SQLITE_NULL: { SHA3Update(&cx, (const unsigned char*)"N",1); break; } case SQLITE_INTEGER: { wx_sqlite3_uint64 u; int j; unsigned char x[9]; wx_sqlite3_int64 v = wx_sqlite3_column_int64(pStmt,i); memcpy(&u, &v, 8); for(j=8; j>=1; j--){ x[j] = u & 0xff; u >>= 8; } x[0] = 'I'; SHA3Update(&cx, x, 9); break; } case SQLITE_FLOAT: { wx_sqlite3_uint64 u; int j; unsigned char x[9]; double r = wx_sqlite3_column_double(pStmt,i); memcpy(&u, &r, 8); for(j=8; j>=1; j--){ x[j] = u & 0xff; u >>= 8; } x[0] = 'F'; SHA3Update(&cx,x,9); break; } case SQLITE_TEXT: { int n2 = wx_sqlite3_column_bytes(pStmt, i); const unsigned char *z2 = wx_sqlite3_column_text(pStmt, i); hash_step_vformat(&cx,"T%d:",n2); SHA3Update(&cx, z2, n2); break; } case SQLITE_BLOB: { int n2 = wx_sqlite3_column_bytes(pStmt, i); const unsigned char *z2 = wx_sqlite3_column_blob(pStmt, i); hash_step_vformat(&cx,"B%d:",n2); SHA3Update(&cx, z2, n2); break; } } } } wx_sqlite3_finalize(pStmt); } wx_sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT); } #ifdef _WIN32 __declspec(dllexport) #endif int wx_sqlite3_shathree_init( wx_sqlite3 *db, char **pzErrMsg, const wx_sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ rc = wx_sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, 0, sha3Func, 0, 0); if( rc==SQLITE_OK ){ rc = wx_sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, 0, sha3Func, 0, 0); } if( rc==SQLITE_OK ){ rc = wx_sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8 | SQLITE_DIRECTONLY, 0, sha3QueryFunc, 0, 0); } if( rc==SQLITE_OK ){ rc = wx_sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8 | SQLITE_DIRECTONLY, 0, sha3QueryFunc, 0, 0); } return rc; }
{ "pile_set_name": "Github" }
''' Created on Dec, 2016 @author: hugo ''' from __future__ import absolute_import import argparse import numpy as np from keras.utils import np_utils from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import ShuffleSplit from autoencoder.testing.classifier import multiclass_classifier, multilabel_classifier from autoencoder.utils.io_utils import load_json, load_pickle def main(): parser = argparse.ArgumentParser() parser.add_argument('train_doc_codes', type=str, help='path to the train doc codes file') parser.add_argument('train_doc_labels', type=str, help='path to the train doc labels file') parser.add_argument('test_doc_codes', type=str, help='path to the test doc codes file') parser.add_argument('test_doc_labels', type=str, help='path to the test doc labels file') parser.add_argument('-nv', '--n_val', type=int, default=1000, help='size of validation set (default 1000)') parser.add_argument('-ne', '--n_epoch', type=int, default=100, help='num of epoches (default 100)') parser.add_argument('-bs', '--batch_size', type=int, default=100, help='batch size (default 100)') parser.add_argument('-cv', '--cross_validation', type=int, help='k-fold cross validation') parser.add_argument('-mlc', '--multilabel_clf', action='store_true', help='multilabel classification flag') args = parser.parse_args() # autoencoder train_doc_codes = load_json(args.train_doc_codes) train_doc_labels = load_json(args.train_doc_labels) test_doc_codes = load_json(args.test_doc_codes) test_doc_labels = load_json(args.test_doc_labels) X_train = np.r_[train_doc_codes.values()] Y_train = [train_doc_labels[i] for i in train_doc_codes] X_test = np.r_[test_doc_codes.values()] Y_test = [test_doc_labels[i] for i in test_doc_codes] # # DBN # X_train = np.array(load_pickle(args.train_doc_codes)) # Y_train = load_pickle(args.train_doc_labels) # X_test = np.array(load_pickle(args.test_doc_codes)) # Y_test = load_pickle(args.test_doc_labels) # import pdb;pdb.set_trace() if args.multilabel_clf: encoder = MultiLabelBinarizer() encoder.fit(Y_train + Y_test) Y_train = encoder.transform(Y_train) Y_test = encoder.transform(Y_test) else: Y = Y_train + Y_test n_train = len(Y_train) n_test = len(Y_test) encoder = LabelEncoder() Y = np_utils.to_categorical(encoder.fit_transform(Y)) Y_train = Y[:n_train] Y_test = Y[-n_test:] seed = 7 np.random.seed(seed) if not args.cross_validation: val_idx = np.random.choice(range(X_train.shape[0]), args.n_val, replace=False) train_idx = list(set(range(X_train.shape[0])) - set(val_idx)) X_new_train = X_train[train_idx] Y_new_train = Y_train[train_idx] X_new_val = X_train[val_idx] Y_new_val = Y_train[val_idx] print 'train: %s, val: %s, test: %s' % (X_new_train.shape[0], X_new_val.shape[0], X_test.shape[0]) if args.multilabel_clf: results = multilabel_classifier(X_new_train, Y_new_train, X_new_val, Y_new_val, \ X_test, Y_test, nb_epoch=args.n_epoch, batch_size=args.batch_size, seed=seed) print 'f1 score on test set: macro_f1: %s, micro_f1: %s' % tuple(results) else: results = multiclass_classifier(X_new_train, Y_new_train, X_new_val, Y_new_val, \ X_test, Y_test, nb_epoch=args.n_epoch, batch_size=args.batch_size, seed=seed) print 'acc on test set: %s' % results else: X = np.concatenate((X_train, X_test), axis=0) Y = np.concatenate((Y_train, Y_test), axis=0) ss = ShuffleSplit(n_splits=int(args.cross_validation), test_size=X_test.shape[0], random_state=seed) results = [] for train_idx, test_idx in ss.split(X): val_idx = np.random.choice(train_idx, args.n_val, replace=False) new_train_idx = list(set(train_idx) - set(val_idx)) X_new_train = X[new_train_idx] Y_new_train = Y[new_train_idx] X_new_val = X[val_idx] Y_new_val = Y[val_idx] if args.multilabel_clf: results.append(multilabel_classifier(X_new_train, Y_new_train, X_new_val, Y_new_val, \ X_test, Y_test, nb_epoch=args.n_epoch, batch_size=args.batch_size, seed=seed)) else: results.append(multiclass_classifier(X_new_train, Y_new_train, X_new_val, Y_new_val, \ X[test_idx], Y[test_idx], nb_epoch=args.n_epoch, batch_size=args.batch_size, seed=seed)) if args.multilabel_clf: macro_f1, micro_f1 = zip(*results) macro_mean = np.mean(macro_f1) macro_std = np.std(macro_f1) micro_mean = np.mean(micro_f1) micro_std = np.std(micro_f1) print 'f1 score on %s-fold cross validation: macro_f1: %s (%s), micro_f1: %s (%s)' \ % (int(args.cross_validation), macro_mean, macro_std, micro_mean, micro_std) else: mean = np.mean(results) std = np.std(results) print 'acc on %s-fold cross validation: %s (%s)' % (int(args.cross_validation), mean, std) import pdb;pdb.set_trace() if __name__ == '__main__': main()
{ "pile_set_name": "Github" }
package com.chibatching.kotprefsample.livedata import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import com.chibatching.kotpref.livedata.asLiveData import com.chibatching.kotprefsample.R import kotlinx.android.synthetic.main.activity_live_data_sample.* class LiveDataSampleActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_live_data_sample) supportActionBar?.setDisplayHomeAsUpEnabled(true) saveButton.setOnClickListener { EditTextData.savedText = editText.text.toString() } EditTextData .asLiveData(EditTextData::savedText) .observe(this, Observer<String> { textView.text = it }) } override fun onSupportNavigateUp(): Boolean { if (super.onSupportNavigateUp()) { return true } finish() return true } }
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); /** * PureEntitiesX: Mob AI Plugin for PMMP * Copyright (C) 2018 RevivalPMMP * * 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 * 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/>. */ namespace revivalpmmp\pureentities\entity; abstract class JumpingEntity extends BaseEntity{ /* * For slimes and Magma Cubes ONLY * Not to be confused for normal entity jumping */ protected function checkTarget(bool $checkSkip = true){ //TODO } public function updateMove($tickDiff){ // TODO $this->jump(); return null; } }
{ "pile_set_name": "Github" }
import React, { Component, PropTypes } from 'react'; import { is, fromJS } from 'immutable'; import { Config } from '../mixin'; import { Router, Route, IndexRoute, browserHistory, Link } from 'react-router'; import { Layout, Menu, Icon } from 'antd'; const SubMenu = Menu.SubMenu; /** * 公共菜单 * * @export * @class Lmenu * @extends {Component} */ export class Lmenu extends Component { constructor(props, context) { super(props, context); //后才能用this获取实例化对象 const openKeys = Config.localItem('OPENKEY') ? [Config.localItem('OPENKEY')] : []; this.state = { openKeys: openKeys }; } onOpenChange = (openKeys) => { const state = this.state; const latestOpenKey = openKeys.find(key => !(state.openKeys.indexOf(key) > -1)); const latestCloseKey = state.openKeys.find(key => !(openKeys.indexOf(key) > -1)); let nextOpenKeys = []; if (latestOpenKey) { nextOpenKeys = this.getAncestorKeys(latestOpenKey).concat(latestOpenKey); } if (latestCloseKey) { nextOpenKeys = this.getAncestorKeys(latestCloseKey); } Config.localItem('OPENKEY', nextOpenKeys); this.setState({ openKeys: nextOpenKeys }); } getAncestorKeys = (key) => { const map = { sub3: ['sub2'], }; return map[key] || []; } render() { const defaultSelectedKey = process.env.NODE_ENV !== 'production' ? [location.pathname.split('/')[location.pathname.split('/').length - 1] || 'home'] : [location.hash.split('/')[location.hash.split('/').length - 1].split('?')[0] || 'home']; return ( <Menu openKeys={this.state.openKeys} onOpenChange={this.onOpenChange} theme="dark" mode={this.props.mode} defaultSelectedKeys={defaultSelectedKey}> <Menu.Item key="home"> <Link to="/home"> <Icon type="area-chart" /> {!this.props.collapsed && <span className="nav-text">实时流量</span>} </Link> </Menu.Item> <SubMenu key="general" title={<span><Icon type="team" /><span className="nav-text">商业分析</span></span>}> <Menu.Item key="button"><Link to="/general/button">用户列表</Link></Menu.Item> <Menu.Item key="allDataView"><Link to="/general/allDataView">数据一览</Link></Menu.Item> </SubMenu> <Menu.Item key="setting"> <Link to="/setting"> <Icon type="star-o" /> {!this.props.collapsed && <span className="nav-text">智能决策</span>} </Link> </Menu.Item> {/*<Menu.Item key="adver">*/} {/*<Link to="/adver">*/} {/*<Icon type="notification" />*/} {/*{!this.props.collapsed && <span className="nav-text">广告管理</span>}*/} {/*</Link>*/} {/*</Menu.Item>*/} <SubMenu key="sub1" title={<span><Icon type="cloud" /><span className="nav-text">商场管理</span></span>} > <Menu.Item key="oneui"><Link to="/ui/monitorSetting">参数设置</Link></Menu.Item> <Menu.Item key="twoui"><Link to="/ui/twoui">商场详情</Link></Menu.Item> </SubMenu> </Menu> ) } }
{ "pile_set_name": "Github" }
package scheduler import ( "fmt" "strings" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/api/genericresource" "github.com/docker/swarmkit/manager/constraint" ) // Filter checks whether the given task can run on the given node. // A filter may only operate type Filter interface { // SetTask returns true when the filter is enabled for a given task // and assigns the task to the filter. It returns false if the filter // isn't applicable to this task. For instance, a constraints filter // would return `false` if the task doesn't contain any constraints. SetTask(*api.Task) bool // Check returns true if the task assigned by SetTask can be scheduled // into the given node. This function should not be called if SetTask // returned false. Check(*NodeInfo) bool // Explain what a failure of this filter means Explain(nodes int) string } // ReadyFilter checks that the node is ready to schedule tasks. type ReadyFilter struct { } // SetTask returns true when the filter is enabled for a given task. func (f *ReadyFilter) SetTask(_ *api.Task) bool { return true } // Check returns true if the task can be scheduled into the given node. func (f *ReadyFilter) Check(n *NodeInfo) bool { return n.Status.State == api.NodeStatus_READY && n.Spec.Availability == api.NodeAvailabilityActive } // Explain returns an explanation of a failure. func (f *ReadyFilter) Explain(nodes int) string { if nodes == 1 { return "1 node not available for new tasks" } return fmt.Sprintf("%d nodes not available for new tasks", nodes) } // ResourceFilter checks that the node has enough resources available to run // the task. type ResourceFilter struct { reservations *api.Resources } // SetTask returns true when the filter is enabled for a given task. func (f *ResourceFilter) SetTask(t *api.Task) bool { r := t.Spec.Resources if r == nil || r.Reservations == nil { return false } res := r.Reservations if res.NanoCPUs == 0 && res.MemoryBytes == 0 && len(res.Generic) == 0 { return false } f.reservations = r.Reservations return true } // Check returns true if the task can be scheduled into the given node. func (f *ResourceFilter) Check(n *NodeInfo) bool { if f.reservations.NanoCPUs > n.AvailableResources.NanoCPUs { return false } if f.reservations.MemoryBytes > n.AvailableResources.MemoryBytes { return false } for _, v := range f.reservations.Generic { enough, err := genericresource.HasEnough(n.AvailableResources.Generic, v) if err != nil || !enough { return false } } return true } // Explain returns an explanation of a failure. func (f *ResourceFilter) Explain(nodes int) string { if nodes == 1 { return "insufficient resources on 1 node" } return fmt.Sprintf("insufficient resources on %d nodes", nodes) } // PluginFilter checks that the node has a specific volume plugin installed type PluginFilter struct { t *api.Task } func referencesVolumePlugin(mount api.Mount) bool { return mount.Type == api.MountTypeVolume && mount.VolumeOptions != nil && mount.VolumeOptions.DriverConfig != nil && mount.VolumeOptions.DriverConfig.Name != "" && mount.VolumeOptions.DriverConfig.Name != "local" } // SetTask returns true when the filter is enabled for a given task. func (f *PluginFilter) SetTask(t *api.Task) bool { c := t.Spec.GetContainer() var volumeTemplates bool if c != nil { for _, mount := range c.Mounts { if referencesVolumePlugin(mount) { volumeTemplates = true break } } } if (c != nil && volumeTemplates) || len(t.Networks) > 0 || t.Spec.LogDriver != nil { f.t = t return true } return false } // Check returns true if the task can be scheduled into the given node. // TODO(amitshukla): investigate storing Plugins as a map so it can be easily probed func (f *PluginFilter) Check(n *NodeInfo) bool { if n.Description == nil || n.Description.Engine == nil { // If the node is not running Engine, plugins are not // supported. return true } // Get list of plugins on the node nodePlugins := n.Description.Engine.Plugins // Check if all volume plugins required by task are installed on node container := f.t.Spec.GetContainer() if container != nil { for _, mount := range container.Mounts { if referencesVolumePlugin(mount) { if _, exists := f.pluginExistsOnNode("Volume", mount.VolumeOptions.DriverConfig.Name, nodePlugins); !exists { return false } } } } // Check if all network plugins required by task are installed on node for _, tn := range f.t.Networks { if tn.Network != nil && tn.Network.DriverState != nil && tn.Network.DriverState.Name != "" { if _, exists := f.pluginExistsOnNode("Network", tn.Network.DriverState.Name, nodePlugins); !exists { return false } } } // It's possible that the LogDriver object does not carry a name, just some // configuration options. In that case, the plugin filter shouldn't fail to // schedule the task if f.t.Spec.LogDriver != nil && f.t.Spec.LogDriver.Name != "none" && f.t.Spec.LogDriver.Name != "" { // If there are no log driver types in the list at all, most likely this is // an older daemon that did not report this information. In this case don't filter if typeFound, exists := f.pluginExistsOnNode("Log", f.t.Spec.LogDriver.Name, nodePlugins); !exists && typeFound { return false } } return true } // pluginExistsOnNode returns true if the (pluginName, pluginType) pair is present in nodePlugins func (f *PluginFilter) pluginExistsOnNode(pluginType string, pluginName string, nodePlugins []api.PluginDescription) (bool, bool) { var typeFound bool for _, np := range nodePlugins { if pluginType != np.Type { continue } typeFound = true if pluginName == np.Name { return true, true } // This does not use the reference package to avoid the // overhead of parsing references as part of the scheduling // loop. This is okay only because plugin names are a very // strict subset of the reference grammar that is always // name:tag. if strings.HasPrefix(np.Name, pluginName) && np.Name[len(pluginName):] == ":latest" { return true, true } } return typeFound, false } // Explain returns an explanation of a failure. func (f *PluginFilter) Explain(nodes int) string { if nodes == 1 { return "missing plugin on 1 node" } return fmt.Sprintf("missing plugin on %d nodes", nodes) } // ConstraintFilter selects only nodes that match certain labels. type ConstraintFilter struct { constraints []constraint.Constraint } // SetTask returns true when the filter is enable for a given task. func (f *ConstraintFilter) SetTask(t *api.Task) bool { if t.Spec.Placement == nil || len(t.Spec.Placement.Constraints) == 0 { return false } constraints, err := constraint.Parse(t.Spec.Placement.Constraints) if err != nil { // constraints have been validated at controlapi // if in any case it finds an error here, treat this task // as constraint filter disabled. return false } f.constraints = constraints return true } // Check returns true if the task's constraint is supported by the given node. func (f *ConstraintFilter) Check(n *NodeInfo) bool { return constraint.NodeMatches(f.constraints, n.Node) } // Explain returns an explanation of a failure. func (f *ConstraintFilter) Explain(nodes int) string { if nodes == 1 { return "scheduling constraints not satisfied on 1 node" } return fmt.Sprintf("scheduling constraints not satisfied on %d nodes", nodes) } // PlatformFilter selects only nodes that run the required platform. type PlatformFilter struct { supportedPlatforms []*api.Platform } // SetTask returns true when the filter is enabled for a given task. func (f *PlatformFilter) SetTask(t *api.Task) bool { placement := t.Spec.Placement if placement != nil { // copy the platform information f.supportedPlatforms = placement.Platforms if len(placement.Platforms) > 0 { return true } } return false } // Check returns true if the task can be scheduled into the given node. func (f *PlatformFilter) Check(n *NodeInfo) bool { // if the supportedPlatforms field is empty, then either it wasn't // provided or there are no constraints if len(f.supportedPlatforms) == 0 { return true } // check if the platform for the node is supported if n.Description != nil { if nodePlatform := n.Description.Platform; nodePlatform != nil { for _, p := range f.supportedPlatforms { if f.platformEqual(*p, *nodePlatform) { return true } } } } return false } func (f *PlatformFilter) platformEqual(imgPlatform, nodePlatform api.Platform) bool { // normalize "x86_64" architectures to "amd64" if imgPlatform.Architecture == "x86_64" { imgPlatform.Architecture = "amd64" } if nodePlatform.Architecture == "x86_64" { nodePlatform.Architecture = "amd64" } // normalize "aarch64" architectures to "arm64" if imgPlatform.Architecture == "aarch64" { imgPlatform.Architecture = "arm64" } if nodePlatform.Architecture == "aarch64" { nodePlatform.Architecture = "arm64" } if (imgPlatform.Architecture == "" || imgPlatform.Architecture == nodePlatform.Architecture) && (imgPlatform.OS == "" || imgPlatform.OS == nodePlatform.OS) { return true } return false } // Explain returns an explanation of a failure. func (f *PlatformFilter) Explain(nodes int) string { if nodes == 1 { return "unsupported platform on 1 node" } return fmt.Sprintf("unsupported platform on %d nodes", nodes) } // HostPortFilter checks that the node has a specific port available. type HostPortFilter struct { t *api.Task } // SetTask returns true when the filter is enabled for a given task. func (f *HostPortFilter) SetTask(t *api.Task) bool { if t.Endpoint != nil { for _, port := range t.Endpoint.Ports { if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 { f.t = t return true } } } return false } // Check returns true if the task can be scheduled into the given node. func (f *HostPortFilter) Check(n *NodeInfo) bool { for _, port := range f.t.Endpoint.Ports { if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 { portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort} if _, ok := n.usedHostPorts[portSpec]; ok { return false } } } return true } // Explain returns an explanation of a failure. func (f *HostPortFilter) Explain(nodes int) string { if nodes == 1 { return "host-mode port already in use on 1 node" } return fmt.Sprintf("host-mode port already in use on %d nodes", nodes) } // MaxReplicasFilter selects only nodes that does not exceed max replicas per node. type MaxReplicasFilter struct { t *api.Task } // SetTask returns true when max replicas per node filter > 0 for a given task. func (f *MaxReplicasFilter) SetTask(t *api.Task) bool { if t.Spec.Placement != nil && t.Spec.Placement.MaxReplicas > 0 { f.t = t return true } return false } // Check returns true if there is less active (assigned or pre-assigned) tasks for this service on current node than set to MaxReplicas limit func (f *MaxReplicasFilter) Check(n *NodeInfo) bool { return uint64(n.ActiveTasksCountByService[f.t.ServiceID]) < f.t.Spec.Placement.MaxReplicas } // Explain returns an explanation of a failure. func (f *MaxReplicasFilter) Explain(nodes int) string { return "max replicas per node limit exceed" }
{ "pile_set_name": "Github" }
#pragma once #include"..\stdafx.h" #include<fstream> #include<string.h> #include<list> #define FILE_LOADED 0x0 #define UNABLE_TO_LOCATE_FILE 0x1 /* Dont confuse it with blam cache Its the cache file which i generate from MapHandler -removed functions and codes that mutate the cache */ struct cache_BLOCK { std::string name; int offset;//offset in the file,if loaded from disk int size; char* data;//actual data if generated at runtime }; class cache_loader { std::string cache_file_loc; //stream readers and writers std::ifstream cache_in; //std::ofstream cache_out; std::list<cache_BLOCK> cache_list; int _last_error; public: //void add_BLOCK(std::string name,int size,char* data); //returns pointer to a BLOCK from the cache file based on the name supplied //no need to call delete,its a pointer maintained by cache_loader cache_BLOCK* get_BLOCK(std::string name); int get_last_error(); cache_loader(std::string file_loc);//open a file for IO ~cache_loader(); };
{ "pile_set_name": "Github" }
<resources> <string name="speak_now">Speak now</string> </resources>
{ "pile_set_name": "Github" }
package containernode import ( "math/rand" "sort" "github.com/onsi/ginkgo/internal/leafnodes" "github.com/onsi/ginkgo/types" ) type subjectOrContainerNode struct { containerNode *ContainerNode subjectNode leafnodes.SubjectNode } func (n subjectOrContainerNode) text() string { if n.containerNode != nil { return n.containerNode.Text() } else { return n.subjectNode.Text() } } type CollatedNodes struct { Containers []*ContainerNode Subject leafnodes.SubjectNode } type ContainerNode struct { text string flag types.FlagType codeLocation types.CodeLocation setupNodes []leafnodes.BasicNode subjectAndContainerNodes []subjectOrContainerNode } func New(text string, flag types.FlagType, codeLocation types.CodeLocation) *ContainerNode { return &ContainerNode{ text: text, flag: flag, codeLocation: codeLocation, } } func (container *ContainerNode) Shuffle(r *rand.Rand) { sort.Sort(container) permutation := r.Perm(len(container.subjectAndContainerNodes)) shuffledNodes := make([]subjectOrContainerNode, len(container.subjectAndContainerNodes)) for i, j := range permutation { shuffledNodes[i] = container.subjectAndContainerNodes[j] } container.subjectAndContainerNodes = shuffledNodes } func (node *ContainerNode) BackPropagateProgrammaticFocus() bool { if node.flag == types.FlagTypePending { return false } shouldUnfocus := false for _, subjectOrContainerNode := range node.subjectAndContainerNodes { if subjectOrContainerNode.containerNode != nil { shouldUnfocus = subjectOrContainerNode.containerNode.BackPropagateProgrammaticFocus() || shouldUnfocus } else { shouldUnfocus = (subjectOrContainerNode.subjectNode.Flag() == types.FlagTypeFocused) || shouldUnfocus } } if shouldUnfocus { if node.flag == types.FlagTypeFocused { node.flag = types.FlagTypeNone } return true } return node.flag == types.FlagTypeFocused } func (node *ContainerNode) Collate() []CollatedNodes { return node.collate([]*ContainerNode{}) } func (node *ContainerNode) collate(enclosingContainers []*ContainerNode) []CollatedNodes { collated := make([]CollatedNodes, 0) containers := make([]*ContainerNode, len(enclosingContainers)) copy(containers, enclosingContainers) containers = append(containers, node) for _, subjectOrContainer := range node.subjectAndContainerNodes { if subjectOrContainer.containerNode != nil { collated = append(collated, subjectOrContainer.containerNode.collate(containers)...) } else { collated = append(collated, CollatedNodes{ Containers: containers, Subject: subjectOrContainer.subjectNode, }) } } return collated } func (node *ContainerNode) PushContainerNode(container *ContainerNode) { node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{containerNode: container}) } func (node *ContainerNode) PushSubjectNode(subject leafnodes.SubjectNode) { node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{subjectNode: subject}) } func (node *ContainerNode) PushSetupNode(setupNode leafnodes.BasicNode) { node.setupNodes = append(node.setupNodes, setupNode) } func (node *ContainerNode) SetupNodesOfType(nodeType types.SpecComponentType) []leafnodes.BasicNode { nodes := []leafnodes.BasicNode{} for _, setupNode := range node.setupNodes { if setupNode.Type() == nodeType { nodes = append(nodes, setupNode) } } return nodes } func (node *ContainerNode) Text() string { return node.text } func (node *ContainerNode) CodeLocation() types.CodeLocation { return node.codeLocation } func (node *ContainerNode) Flag() types.FlagType { return node.flag } //sort.Interface func (node *ContainerNode) Len() int { return len(node.subjectAndContainerNodes) } func (node *ContainerNode) Less(i, j int) bool { return node.subjectAndContainerNodes[i].text() < node.subjectAndContainerNodes[j].text() } func (node *ContainerNode) Swap(i, j int) { node.subjectAndContainerNodes[i], node.subjectAndContainerNodes[j] = node.subjectAndContainerNodes[j], node.subjectAndContainerNodes[i] }
{ "pile_set_name": "Github" }
.brief-link { $image-size: 38px; margin-right: 10px; .image { width: $image-size; height: $image-size; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="320dp" android:layout_height="200dp" android:padding="20dp" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="15dp" android:layout_marginStart="5dp" android:textColor="@android:color/background_dark" android:textSize="18sp" android:text="@string/contact_key_conflict" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/NameTextView" android:layout_margin="10dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/AbortButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginEnd="3dp" android:text="@string/button_abort" /> <Button android:id="@+id/ReplaceButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginStart="3dp" android:text="@string/button_replace" /> </LinearLayout> </LinearLayout>
{ "pile_set_name": "Github" }
00002.jpg 3 00065.jpg 8 00069.jpg 5 00081.jpg 8 00150.jpg 8 00151.jpg 5 00163.jpg 1 00198.jpg 6 00208.jpg 8 00221.jpg 10 00236.jpg 7 00244.jpg 7 00255.jpg 6 00292.jpg 10 00308.jpg 6 00320.jpg 7 00340.jpg 9 00370.jpg 10 00374.jpg 6 00392.jpg 4 00405.jpg 10 00410.jpg 5 00424.jpg 5 00425.jpg 7 00462.jpg 1 00503.jpg 9 00522.jpg 1 00631.jpg 5 00634.jpg 9 00635.jpg 9 00670.jpg 2 00691.jpg 2 00697.jpg 4 00700.jpg 5 00707.jpg 1 00740.jpg 3 00742.jpg 5 00773.jpg 1 00858.jpg 2 00878.jpg 6 00880.jpg 8 00887.jpg 1 00898.jpg 6 00912.jpg 7 00920.jpg 4 00946.jpg 1 01010.jpg 6 01012.jpg 6 01031.jpg 2 01034.jpg 2 01105.jpg 7 01134.jpg 5 01148.jpg 10 01186.jpg 8 01214.jpg 3 01255.jpg 6 01264.jpg 4 01276.jpg 9 01277.jpg 1 01283.jpg 8 01322.jpg 7 01331.jpg 8 01361.jpg 9 01392.jpg 5 01413.jpg 8 01416.jpg 7 01468.jpg 7 01483.jpg 8 01506.jpg 10 01535.jpg 2 01537.jpg 7 01617.jpg 6 01661.jpg 1 01678.jpg 10 01680.jpg 9 01705.jpg 3 01706.jpg 7 01716.jpg 3 01750.jpg 3 01768.jpg 9 01786.jpg 10 01819.jpg 8 01832.jpg 1 01852.jpg 8 01864.jpg 6 01870.jpg 3 01891.jpg 2 01901.jpg 7 01911.jpg 6 01918.jpg 1 01952.jpg 1 01972.jpg 5 02004.jpg 5 02050.jpg 1 02058.jpg 9 02065.jpg 2 02095.jpg 6 02111.jpg 5 02124.jpg 4 02145.jpg 1 02194.jpg 9 02240.jpg 4 02274.jpg 4 02286.jpg 8 02305.jpg 8 02311.jpg 1 02314.jpg 2 02326.jpg 10 02359.jpg 7 02363.jpg 1 02364.jpg 3 02377.jpg 8 02378.jpg 9 02438.jpg 7 02457.jpg 5 02484.jpg 10 02491.jpg 3 02540.jpg 2 02577.jpg 9 02589.jpg 3 02594.jpg 10 02605.jpg 6 02645.jpg 9 02663.jpg 3 02669.jpg 2 02670.jpg 5 02671.jpg 7 02738.jpg 6 02739.jpg 5 02771.jpg 9 02832.jpg 3 02843.jpg 5 02848.jpg 1 02897.jpg 5 02911.jpg 6 02913.jpg 4 02919.jpg 6 02993.jpg 8 03008.jpg 1 03009.jpg 9 03011.jpg 2 03030.jpg 3 03051.jpg 4 03054.jpg 5 03064.jpg 9 03081.jpg 5 03101.jpg 10 03102.jpg 4 03127.jpg 5 03152.jpg 3 03165.jpg 4 03169.jpg 3 03191.jpg 5 03238.jpg 4 03239.jpg 9 03241.jpg 4 03243.jpg 4 03265.jpg 6 03267.jpg 2 03308.jpg 7 03311.jpg 8 03316.jpg 7 03317.jpg 2 03379.jpg 8 03390.jpg 10 03393.jpg 1 03417.jpg 5 03454.jpg 9 03467.jpg 4 03511.jpg 5 03512.jpg 4 03523.jpg 8 03537.jpg 2 03575.jpg 8 03589.jpg 8 03607.jpg 4 03608.jpg 6 03641.jpg 5 03659.jpg 9 03662.jpg 9 03670.jpg 6 03690.jpg 2 03715.jpg 6 03732.jpg 9 03761.jpg 6 03767.jpg 2 03772.jpg 3 03790.jpg 7 03795.jpg 4 03813.jpg 6 03828.jpg 9 03854.jpg 10 03871.jpg 3 03875.jpg 2 03877.jpg 6 03881.jpg 3 03943.jpg 1 03965.jpg 5 03968.jpg 6 04011.jpg 2 04056.jpg 1 04072.jpg 8 04085.jpg 7 04121.jpg 8 04186.jpg 8 04190.jpg 10 04197.jpg 8 04216.jpg 8 04224.jpg 6 04244.jpg 2 04247.jpg 8 04252.jpg 7 04308.jpg 9 04338.jpg 5 04349.jpg 4 04386.jpg 10 04392.jpg 5 04396.jpg 8 04470.jpg 5 04482.jpg 4 04484.jpg 5 04486.jpg 2 04493.jpg 8 04494.jpg 9 04495.jpg 8 04509.jpg 9 04510.jpg 9 04511.jpg 4 04544.jpg 1 04552.jpg 10 04578.jpg 1 04588.jpg 3 04608.jpg 7 04631.jpg 7 04651.jpg 5 04669.jpg 1 04691.jpg 6 04724.jpg 9 04725.jpg 9 04750.jpg 9 04816.jpg 3 04825.jpg 7 04827.jpg 1 04833.jpg 6 04874.jpg 1 04884.jpg 8 04892.jpg 2 04942.jpg 8 05023.jpg 10 05030.jpg 1 05042.jpg 6 05048.jpg 10 05052.jpg 3 05057.jpg 4 05077.jpg 7 05125.jpg 4 05128.jpg 5 05143.jpg 10 05197.jpg 7 05224.jpg 1 05259.jpg 2 05261.jpg 2 05281.jpg 3 05295.jpg 2 05304.jpg 8 05306.jpg 9 05307.jpg 4 05324.jpg 4 05333.jpg 3 05347.jpg 3 05349.jpg 7 05366.jpg 10 05373.jpg 8 05382.jpg 9 05386.jpg 7 05405.jpg 4 05434.jpg 3 05534.jpg 8 05545.jpg 3 05567.jpg 8 05579.jpg 10 05657.jpg 1 05671.jpg 6 05694.jpg 9 05718.jpg 10 05748.jpg 3 05754.jpg 1 05804.jpg 1 05821.jpg 8 05909.jpg 9 05916.jpg 6 05918.jpg 3 05921.jpg 1 05930.jpg 2 05967.jpg 3 05979.jpg 4 06002.jpg 8 06024.jpg 8 06052.jpg 1 06061.jpg 2 06099.jpg 4 06145.jpg 4 06158.jpg 7 06159.jpg 1 06174.jpg 1 06179.jpg 6 06183.jpg 5 06196.jpg 6 06206.jpg 8 06239.jpg 10 06244.jpg 6 06262.jpg 1 06269.jpg 7 06292.jpg 5 06296.jpg 5 06302.jpg 4 06309.jpg 7 06313.jpg 5 06328.jpg 3 06375.jpg 9 06381.jpg 9 06388.jpg 5 06406.jpg 3 06422.jpg 4 06453.jpg 10 06480.jpg 7 06485.jpg 10 06516.jpg 3 06518.jpg 7 06530.jpg 8 06538.jpg 6 06539.jpg 9 06571.jpg 2 06603.jpg 7 06614.jpg 4 06624.jpg 2 06644.jpg 7 06660.jpg 6 06675.jpg 10 06683.jpg 9 06718.jpg 6 06751.jpg 3 06771.jpg 10 06774.jpg 5 06782.jpg 8 06784.jpg 3 06816.jpg 3 06832.jpg 8 06833.jpg 1 06839.jpg 2 06850.jpg 5 06896.jpg 9 06906.jpg 10 06921.jpg 9 06974.jpg 3 07025.jpg 1 07050.jpg 4 07061.jpg 7 07121.jpg 3 07169.jpg 7 07171.jpg 6 07174.jpg 6 07175.jpg 3 07191.jpg 4 07214.jpg 4 07278.jpg 8 07279.jpg 1 07290.jpg 1 07346.jpg 3 07351.jpg 7 07364.jpg 4 07386.jpg 10 07392.jpg 3 07445.jpg 4 07450.jpg 5 07463.jpg 4 07471.jpg 9 07483.jpg 6 07487.jpg 1 07599.jpg 10 07661.jpg 4 07663.jpg 3 07666.jpg 6 07684.jpg 1 07696.jpg 6 07704.jpg 9 07706.jpg 4 07752.jpg 4 07769.jpg 7 07800.jpg 6 07833.jpg 7 07860.jpg 6 07897.jpg 2 07916.jpg 4 07960.jpg 2 07966.jpg 1 08005.jpg 3 08011.jpg 1 08016.jpg 5 08018.jpg 6 08031.jpg 1 08044.jpg 10 08085.jpg 10 08096.jpg 8 08127.jpg 5 08133.jpg 3
{ "pile_set_name": "Github" }
(module SMT-JUMPER_3_1-NC_PASTE_NO-SILK (layer F.Cu) (tedit 596292D3) (attr smd) (fp_text reference >NAME (at 0 -1.524) (layer F.SilkS) (effects (font (size 0.6096 0.6096) (thickness 0.127))) ) (fp_text value >VALUE (at 0 1.524) (layer F.SilkS) (effects (font (size 0.6096 0.6096) (thickness 0.127))) ) (fp_line (start -0.127 0.889) (end -0.127 -0.889) (layer F.Paste) (width 0.508)) (fp_line (start -0.127 0.889) (end 1.397 0.889) (layer F.Paste) (width 0.508)) (fp_line (start -0.127 0.635) (end 1.397 0.635) (layer F.Paste) (width 0.508)) (fp_line (start -0.127 0.127) (end 1.397 0.127) (layer F.Paste) (width 0.508)) (fp_line (start -0.127 -0.381) (end 1.397 -0.381) (layer F.Paste) (width 0.508)) (fp_line (start 1.397 -0.889) (end 1.397 0.889) (layer F.Paste) (width 0.508)) (fp_line (start -0.127 -0.889) (end 1.397 -0.889) (layer F.Paste) (width 0.508)) (pad 1 smd rect (at -0.8128 0) (size 0.635 1.27) (layers F.Cu F.Mask) (solder_mask_margin 0.1016) (solder_paste_margin -25.4)) (pad 2 smd rect (at 0 0) (size 0.635 1.27) (layers F.Cu F.Mask) (solder_mask_margin 0.1016)) (pad 3 smd rect (at 0.8128 0) (size 0.635 1.27) (layers F.Cu F.Mask) (solder_mask_margin 0.1016)) )
{ "pile_set_name": "Github" }
from pretalx.common.signals import EventPluginSignal register_recording_provider = EventPluginSignal() """ This signal is sent out to gather all known recording providers. Receivers should return a subclass of pretalx.agenda.recording.BaseRecordingProvider. As with all event plugin signals, the ``sender`` keyword argument will contain the event. """
{ "pile_set_name": "Github" }
### 0.3.0-8 (2019-01-24) ##### New Features * allow drag and drop columns ([cd25b051](https://github.com/lucasbesen/react-kanban-dnd/commit/cd25b051626284b0f12491a05cf3a982328f35cb)) ##### Bug Fixes * adds package-lock.json to .gitignore ([9112903a](https://github.com/lucasbesen/react-kanban-dnd/commit/9112903aa62726c6ad5579f2707f7c40801c35c5)) ##### Code Style Changes * **readme:** add @GLuchtenberg as contributor ([46e366d6](https://github.com/lucasbesen/react-kanban-dnd/commit/46e366d6cfa0e45469ae681b8c0495305295977d)) #### 0.2.1-7 (2019-01-02) ##### Chores * add contributors ([b62a0200](https://github.com/lucasbesen/react-kanban-dnd/commit/b62a02009efafbfd99161d3445dd5522838be7ad)) ##### Documentation Changes * improved README with contribution info ([38934bbd](https://github.com/lucasbesen/react-kanban-dnd/commit/38934bbd15b7447323a5883f8e73439f1cb285af)) ##### New Features * add script to run docz ([4c92b80e](https://github.com/lucasbesen/react-kanban-dnd/commit/4c92b80ec4e6ec5fa3145059512e4381633c80b6)) * add docz ([e7597f7e](https://github.com/lucasbesen/react-kanban-dnd/commit/e7597f7e73849ce26c6a5fffe96646f9b007062f)) * add codesandbox live demo ([ec7bb6e2](https://github.com/lucasbesen/react-kanban-dnd/commit/ec7bb6e2648acbd73192f0e3b6df9953365d0302)) ##### Bug Fixes * solve strange behavior when repositioning cards ([ccde5803](https://github.com/lucasbesen/react-kanban-dnd/commit/ccde5803f9c1da1c127d8083132ea49a49272e40)) * add .docz on gitignore ([22664341](https://github.com/lucasbesen/react-kanban-dnd/commit/2266434117c3976c6e66bd3ce9d91db5b0c0c4cb)) ##### Refactors * simplify reorder logic ([d71c06e3](https://github.com/lucasbesen/react-kanban-dnd/commit/d71c06e3c773157252400ce1d60bbb6a00f3a221)) ### 0.2.0-6 (2018-10-17) ##### Bug Fixes * fix dependencies version ([444f2ff5](https://github.com/lucasbesen/react-kanban-dnd/commit/444f2ff53caa048c5f5510649d231f004f02c170)) * update dependencies ([44639468](https://github.com/lucasbesen/react-kanban-dnd/commit/44639468ae8c10a43c008c52b01a0ffda2b5f103)) * handle with typescript conversion ([56b93a8c](https://github.com/lucasbesen/react-kanban-dnd/commit/56b93a8cd7e30a94d3fba1891be59446aee096d2)) #### 0.1.5-5 (2018-10-12) ##### Bug Fixes * add idx in dependencie ([60424eb4](https://github.com/lucasbesen/react-kanban-dnd/commit/60424eb44d928b7fad1afa8a605bda81afee6d20)) #### 0.1.4-4 (2018-10-09) #### 0.1.3-3 (2018-10-06) ##### Code Style Changes * fix badge link ([af44f557](https://github.com/lucasbesen/react-kanban-dnd/commit/af44f557e45c1590da218f091f5c53066beacfd0)) * add badges ([fa77b08c](https://github.com/lucasbesen/react-kanban-dnd/commit/fa77b08ce962c17cb1dfdb43e553edd9751843b1)) #### 0.1.2-2 (2018-10-06) ##### Bug Fixes * update package name ([e97f17c2](https://github.com/lucasbesen/react-kanban-dnd/commit/e97f17c2e2f1e120c76fedc02228aea86e4e7b17)) #### 0.1.1-1 (2018-10-04)
{ "pile_set_name": "Github" }
:101E000001C0B1C011248FE592E09EBF8DBF84B7A1 :101E1000882361F0982F9A70923041F081FF02C0C0 :101E200097EF94BF282E80E0B9D0EAC085E08EBD40 :101E300082E08BB988E18AB986E880BD8CE089B9F7 :101E40008EE0ACD0B89A84E026E83FEF44E051E061 :101E50003DBD2CBD48BF08B602FEFDCF98B3952707 :101E600098BBA8955F9902C0815091F790D08134BA :101E700079F48DD0182F96D0123829F480E083D0D1 :101E800080E181D0F3CF83E01138C9F788E0F7CF44 :101E9000823419F484E18ED0F3CF853411F485E0D7 :101EA000FACF853541F473D0C82F71D0D82FCC0F1D :101EB000DD1F78D0E5CF863519F484E07BD0DECF06 :101EC000843699F564D063D0182F61D0D82E012FB5 :101ED00090E6E92EF12C57018FEFA81AB80A57D0D7 :101EE000F701808301507501B1F75CD0F5E4DF1292 :101EF00001C0FFCF50E040E063E0CE0134D07E016E :101F000080E6C82ED12CF601419151916F0161E01C :101F1000C70129D0F2E0EF0EF11C1250A1F750E0FA :101F200040E065E0CE011FD0ABCF843771F42FD0F5 :101F30002ED0F82E2CD036D08E01F80185918F014D :101F400022D0FA94F110F9CF9BCF853731F42AD003 :101F50008EE119D083E917D099CF813509F0A9CF47 :101F600088E01CD0A6CFFC010A0167BFE8951124C8 :101F700007B600FCFDCF667029F0452B19F481E10E :101F800087BFE89508955D9BFECF8CB908955F9B50 :101F9000FECF5C9901C0A8958CB1089598E191BDE0 :101FA00081BD0895F4DF803219F088E0F7DFFFCFBC :101FB00084E1E9CFCF93C82FEADFC150E9F7CF9191 :021FC000F1CF5F :021FFE000008D9 :0400000300001E00DB :00000001FF
{ "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. // +build arm,linux package unix import ( "syscall" "unsafe" ) func Getpagesize() int { return 4096 } func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = int32(nsec / 1e9) tv.Usec = int32(nsec % 1e9 / 1e3) return } func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, 0) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } // Underlying system call writes to newoffset via pointer. // Implemented in assembly to avoid allocation. func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno) func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { newoffset, errno := seek(fd, offset, whence) if errno != 0 { return 0, errno } return newoffset, nil } //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32 //sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32 //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sysnb socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) // 64-bit file system and 32-bit uid calls // (16-bit uid calls are not always supported in newer kernels) //sys Dup2(oldfd int, newfd int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sysnb Getegid() (egid int) = SYS_GETEGID32 //sysnb Geteuid() (euid int) = SYS_GETEUID32 //sysnb Getgid() (gid int) = SYS_GETGID32 //sysnb Getuid() (uid int) = SYS_GETUID32 //sysnb InotifyInit() (fd int, err error) //sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32 //sys Listen(s int, n int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT //sys Setfsgid(gid int) (err error) = SYS_SETFSGID32 //sys Setfsuid(uid int) (err error) = SYS_SETFSUID32 //sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32 //sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32 //sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32 //sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32 //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 // Vsyscalls on amd64. //sysnb Gettimeofday(tv *Timeval) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Pause() (err error) func Time(t *Time_t) (Time_t, error) { var tv Timeval err := Gettimeofday(&tv) if err != nil { return 0, err } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } func Utime(path string, buf *Utimbuf) error { tv := []Timeval{ {Sec: buf.Actime}, {Sec: buf.Modtime}, } return Utimes(path, tv) } //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_ARM_FADVISE64_64, uintptr(fd), uintptr(advice), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } //sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = e } return } func Statfs(path string, buf *Statfs_t) (err error) { pathp, err := BytePtrFromString(path) if err != nil { return err } _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = e } return } func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { page := uintptr(offset / 4096) if offset != int64(page)*4096 { return 0, EINVAL } return mmap2(addr, length, prot, flags, fd, page) } type rlimit32 struct { Cur uint32 Max uint32 } //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT const rlimInf32 = ^uint32(0) const rlimInf64 = ^uint64(0) func Getrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, nil, rlim) if err != ENOSYS { return err } rl := rlimit32{} err = getrlimit(resource, &rl) if err != nil { return } if rl.Cur == rlimInf32 { rlim.Cur = rlimInf64 } else { rlim.Cur = uint64(rl.Cur) } if rl.Max == rlimInf32 { rlim.Max = rlimInf64 } else { rlim.Max = uint64(rl.Max) } return } //sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT func Setrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, rlim, nil) if err != ENOSYS { return err } rl := rlimit32{} if rlim.Cur == rlimInf64 { rl.Cur = rlimInf32 } else if rlim.Cur < uint64(rlimInf32) { rl.Cur = uint32(rlim.Cur) } else { return EINVAL } if rlim.Max == rlimInf64 { rl.Max = rlimInf32 } else if rlim.Max < uint64(rlimInf32) { rl.Max = uint32(rlim.Max) } else { return EINVAL } return setrlimit(resource, &rl) } func (r *PtraceRegs) PC() uint64 { return uint64(r.Uregs[15]) } func (r *PtraceRegs) SetPC(pc uint64) { r.Uregs[15] = uint32(pc) } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) }
{ "pile_set_name": "Github" }
// Copyright 2013 The Chromium 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 org.chromium.chrome.browser.media.cdm; import org.chromium.base.annotations.CalledByNative; /** * A wrapper of the android MediaDrmCredentialManager */ public class MediaDrmCredentialManager { /** * Callback interface for getting notified from credential reset. */ public interface MediaDrmCredentialManagerCallback { /** * This method will be called when credential reset attempt is done. * @param succeeded Whether or not it succeeded. */ @CalledByNative("MediaDrmCredentialManagerCallback") public void onCredentialResetFinished(boolean succeeded); } /** * Attempts to reset the DRM credentials. * @param callback It notifies whether or not it succeeded. */ public static void resetCredentials(MediaDrmCredentialManagerCallback callback) { nativeResetCredentials(callback); } private static native void nativeResetCredentials(MediaDrmCredentialManagerCallback callback); }
{ "pile_set_name": "Github" }
[remap] importer="texture" type="StreamTexture" path.s3tc="res://.import/heightRotated1001.png-cb890e1cb8d75b76dea40e72e968ece6.s3tc.stex" path.etc2="res://.import/heightRotated1001.png-cb890e1cb8d75b76dea40e72e968ece6.etc2.stex" metadata={ "imported_formats": [ "s3tc", "etc2" ], "vram_texture": true } [deps] source_file="res://heightRotated1001.png" dest_files=[ "res://.import/heightRotated1001.png-cb890e1cb8d75b76dea40e72e968ece6.s3tc.stex", "res://.import/heightRotated1001.png-cb890e1cb8d75b76dea40e72e968ece6.etc2.stex" ] [params] compress/mode=2 compress/lossy_quality=0.7 compress/hdr_mode=0 compress/bptc_ldr=0 compress/normal_map=0 flags/repeat=0 flags/filter=false flags/mipmaps=false flags/anisotropic=false flags/srgb=2 process/fix_alpha_border=true process/premult_alpha=false process/HDR_as_SRGB=false process/invert_color=false stream=false size_limit=0 detect_3d=false svg/scale=1.0
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////// // Name: wxluadebugdefs.h // Purpose: definitions for wxLuaDebug module // Author: John Labenski, Francesco Montorsi // Modified by: // Created: 20/5/2006 // Copyright: (c) 2012 John Labenski, Francesco Montorsi // Licence: wxWidgets licence /////////////////////////////////////////////////////////////////////////////// #ifndef __WX_WXLUADEBUGDEFS_H__ #define __WX_WXLUADEBUGDEFS_H__ #include <wx/defs.h> #include "wxlua/wxldefs.h" // ---------------------------------------------------------------------------- // WXDLLIMPEXP macros // ---------------------------------------------------------------------------- #ifdef WXMAKINGDLL_WXLUADEBUG #define WXDLLIMPEXP_WXLUADEBUG WXEXPORT #define WXDLLIMPEXP_DATA_WXLUADEBUG(type) WXEXPORT type #elif defined(WXUSINGDLL) #define WXDLLIMPEXP_WXLUADEBUG WXIMPORT #define WXDLLIMPEXP_DATA_WXLUADEBUG(type) WXIMPORT type #else // not making nor using DLL #define WXDLLIMPEXP_WXLUADEBUG #define WXDLLIMPEXP_DATA_WXLUADEBUG(type) type #endif // Forward declare all wxStEdit classes with this macro #if defined(HAVE_VISIBILITY) || (defined(__WINDOWS__) && defined(__GNUC__)) #define WXDLLIMPEXP_FWD_WXLUADEBUG #else #define WXDLLIMPEXP_FWD_WXLUADEBUG WXDLLIMPEXP_WXLUADEBUG #endif #endif // __WX_WXLUADEBUGDEFS_H__
{ "pile_set_name": "Github" }
/****************************************************************************** * * * License Agreement * * * * Copyright (c) 2005 Altera Corporation, San Jose, California, USA. * * All rights reserved. * * * * 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. * * * * This agreement shall be governed in all respects by the laws of the State * * of California and by the laws of the United States of America. * * * * Altera does not recommend, suggest or require that this reference design * * file be used in conjunction or combination with any other product. * ******************************************************************************/ #include "alt_types.h" /* * This macro is used to load code/data from its load address to its * execution address for a given section. The section name is the input * argument. Note that a leading '.' is assumed in the name. For example * to load the section .onchip_ram, use: * * ALT_LOAD_SECTION_BY_NAME(onchip_ram); * * This requires that the apropriate linker symbols have been generated * for the section in question. This will be the case if you are using the * default linker script. */ #define ALT_LOAD_SECTION_BY_NAME(name) \ { \ extern void _alt_partition_##name##_start; \ extern void _alt_partition_##name##_end; \ extern void _alt_partition_##name##_load_addr; \ \ alt_load_section(&_alt_partition_##name##_load_addr, \ &_alt_partition_##name##_start, \ &_alt_partition_##name##_end); \ } /* * Function used to load an individual section from flash to RAM. * * There is an implicit assumption here that the linker script will ensure * that all sections are word aligned. * */ static void ALT_INLINE alt_load_section (alt_u32* from, alt_u32* to, alt_u32* end) { if (to != from) { while( to != end ) { *to++ = *from++; } } }
{ "pile_set_name": "Github" }
# created by tools/tclZIC.tcl - do not edit if {![info exists TZData(Asia/Shanghai)]} { LoadTimeZoneFile Asia/Shanghai } set TZData(:Asia/Chungking) $TZData(:Asia/Shanghai)
{ "pile_set_name": "Github" }
// Copyright 2011 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. // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris // Socket control messages package unix import ( "runtime" "unsafe" ) // Round the length of a raw sockaddr up to align it properly. func cmsgAlignOf(salen int) int { salign := SizeofPtr switch runtime.GOOS { case "aix": // There is no alignment on AIX. salign = 1 case "darwin", "dragonfly", "solaris", "illumos": // NOTE: It seems like 64-bit Darwin, DragonFly BSD, // illumos, and Solaris kernels still require 32-bit // aligned access to network subsystem. if SizeofPtr == 8 { salign = 4 } case "netbsd", "openbsd": // NetBSD and OpenBSD armv7 require 64-bit alignment. if runtime.GOARCH == "arm" { salign = 8 } } return (salen + salign - 1) & ^(salign - 1) } // CmsgLen returns the value to store in the Len field of the Cmsghdr // structure, taking into account any necessary alignment. func CmsgLen(datalen int) int { return cmsgAlignOf(SizeofCmsghdr) + datalen } // CmsgSpace returns the number of bytes an ancillary element with // payload of the passed data length occupies. func CmsgSpace(datalen int) int { return cmsgAlignOf(SizeofCmsghdr) + cmsgAlignOf(datalen) } func cmsgData(h *Cmsghdr) unsafe.Pointer { return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(SizeofCmsghdr))) } // SocketControlMessage represents a socket control message. type SocketControlMessage struct { Header Cmsghdr Data []byte } // ParseSocketControlMessage parses b as an array of socket control // messages. func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error) { var msgs []SocketControlMessage i := 0 for i+CmsgLen(0) <= len(b) { h, dbuf, err := socketControlMessageHeaderAndData(b[i:]) if err != nil { return nil, err } m := SocketControlMessage{Header: *h, Data: dbuf} msgs = append(msgs, m) i += cmsgAlignOf(int(h.Len)) } return msgs, nil } func socketControlMessageHeaderAndData(b []byte) (*Cmsghdr, []byte, error) { h := (*Cmsghdr)(unsafe.Pointer(&b[0])) if h.Len < SizeofCmsghdr || uint64(h.Len) > uint64(len(b)) { return nil, nil, EINVAL } return h, b[cmsgAlignOf(SizeofCmsghdr):h.Len], nil } // UnixRights encodes a set of open file descriptors into a socket // control message for sending to another process. func UnixRights(fds ...int) []byte { datalen := len(fds) * 4 b := make([]byte, CmsgSpace(datalen)) h := (*Cmsghdr)(unsafe.Pointer(&b[0])) h.Level = SOL_SOCKET h.Type = SCM_RIGHTS h.SetLen(CmsgLen(datalen)) data := cmsgData(h) for _, fd := range fds { *(*int32)(data) = int32(fd) data = unsafe.Pointer(uintptr(data) + 4) } return b } // ParseUnixRights decodes a socket control message that contains an // integer array of open file descriptors from another process. func ParseUnixRights(m *SocketControlMessage) ([]int, error) { if m.Header.Level != SOL_SOCKET { return nil, EINVAL } if m.Header.Type != SCM_RIGHTS { return nil, EINVAL } fds := make([]int, len(m.Data)>>2) for i, j := 0, 0; i < len(m.Data); i += 4 { fds[j] = int(*(*int32)(unsafe.Pointer(&m.Data[i]))) j++ } return fds, nil }
{ "pile_set_name": "Github" }
/** * \file dnn/src/arm_common/elemwise_helper/kimpl/pow.h * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #pragma once #include "src/arm_common/elemwise_helper/kimpl/op_base.h" namespace megdnn { namespace arm_common { // when __fp16 is avaliable POW is very slow, so add there /////////////////////// POW float only //////////////////////////// template <typename src_ctype, typename dst_ctype = src_ctype> struct PowOp : BinaryOpBase<src_ctype, dst_ctype> { using BinaryOpBase<src_ctype, dst_ctype>::BinaryOpBase; constexpr static size_t SIMD_WIDTH = 1; void operator()(const src_ctype& src0, const src_ctype& src1, dst_ctype* dst) const { *dst = operator()(src0, src1); } dst_ctype operator()(const src_ctype& src0, const src_ctype& src1) const { return powf(src0, src1); } }; } // namespace arm_common } // namespace megdnn // vim: syntax=cpp.doxygen
{ "pile_set_name": "Github" }
/****************************************************************************** * Copyright (c) 2011, Duane Merrill. All rights reserved. * Copyright (c) 2011-2018, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 NVIDIA CORPORATION 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. * ******************************************************************************/ /** * \file * Random-access iterator types */ #pragma once #include <iterator> #include "../thread/thread_load.cuh" #include "../thread/thread_store.cuh" #include "../util_namespace.cuh" #if (THRUST_VERSION >= 100700) // This iterator is compatible with Thrust API 1.7 and newer // #include <thrust/iterator/iterator_facade.h> // #include <thrust/iterator/iterator_traits.h> #endif // THRUST_VERSION /// Optional outer namespace(s) CUB_NS_PREFIX /// CUB namespace namespace cub { /** * \addtogroup UtilIterator * @{ */ /** * \brief A random-access input generator for dereferencing a sequence of homogeneous values * * \par Overview * - Read references to a ConstantInputIteratorTiterator always return the supplied constant * of type \p ValueType. * - Can be used with any data type. * - Can be constructed, manipulated, dereferenced, and exchanged within and between host and device * functions. * - Compatible with Thrust API v1.7 or newer. * * \par Snippet * The code snippet below illustrates the use of \p ConstantInputIteratorTto * dereference a sequence of homogeneous doubles. * \par * \code * #include <cub/cub.cuh> // or equivalently <cub/iterator/constant_input_iterator.cuh> * * cub::ConstantInputIterator<double> itr(5.0); * * printf("%f\n", itr[0]); // 5.0 * printf("%f\n", itr[1]); // 5.0 * printf("%f\n", itr[2]); // 5.0 * printf("%f\n", itr[50]); // 5.0 * * \endcode * * \tparam ValueType The value type of this iterator * \tparam OffsetT The difference type of this iterator (Default: \p ptrdiff_t) */ template < typename ValueType, typename OffsetT = ptrdiff_t> class ConstantInputIterator { public: // Required iterator traits typedef ConstantInputIterator self_type; ///< My own type typedef OffsetT difference_type; ///< Type to express the result of subtracting one iterator from another typedef ValueType value_type; ///< The type of the element the iterator can point to typedef ValueType* pointer; ///< The type of a pointer to an element the iterator can point to typedef ValueType reference; ///< The type of a reference to an element the iterator can point to #if (THRUST_VERSION >= 100700) // Use Thrust's iterator categories so we can use these iterators in Thrust 1.7 (or newer) methods typedef typename thrust::detail::iterator_facade_category< thrust::any_system_tag, thrust::random_access_traversal_tag, value_type, reference >::type iterator_category; ///< The iterator category #else typedef std::random_access_iterator_tag iterator_category; ///< The iterator category #endif // THRUST_VERSION private: ValueType val; OffsetT offset; #ifdef _WIN32 OffsetT pad[CUB_MAX(1, (16 / sizeof(OffsetT) - 1))]; // Workaround for win32 parameter-passing bug (ulonglong2 argmin DeviceReduce) #endif public: /// Constructor __host__ __device__ __forceinline__ ConstantInputIterator( ValueType val, ///< Starting value for the iterator instance to report OffsetT offset = 0) ///< Base offset : val(val), offset(offset) {} /// Postfix increment __host__ __device__ __forceinline__ self_type operator++(int) { self_type retval = *this; offset++; return retval; } /// Prefix increment __host__ __device__ __forceinline__ self_type operator++() { offset++; return *this; } /// Indirection __host__ __device__ __forceinline__ reference operator*() const { return val; } /// Addition template <typename Distance> __host__ __device__ __forceinline__ self_type operator+(Distance n) const { self_type retval(val, offset + n); return retval; } /// Addition assignment template <typename Distance> __host__ __device__ __forceinline__ self_type& operator+=(Distance n) { offset += n; return *this; } /// Subtraction template <typename Distance> __host__ __device__ __forceinline__ self_type operator-(Distance n) const { self_type retval(val, offset - n); return retval; } /// Subtraction assignment template <typename Distance> __host__ __device__ __forceinline__ self_type& operator-=(Distance n) { offset -= n; return *this; } /// Distance __host__ __device__ __forceinline__ difference_type operator-(self_type other) const { return offset - other.offset; } /// Array subscript template <typename Distance> __host__ __device__ __forceinline__ reference operator[](Distance /*n*/) const { return val; } /// Structure dereference __host__ __device__ __forceinline__ pointer operator->() { return &val; } /// Equal to __host__ __device__ __forceinline__ bool operator==(const self_type& rhs) { return (offset == rhs.offset) && ((val == rhs.val)); } /// Not equal to __host__ __device__ __forceinline__ bool operator!=(const self_type& rhs) { return (offset != rhs.offset) || (val!= rhs.val); } }; /** @} */ // end group UtilIterator } // CUB namespace CUB_NS_POSTFIX // Optional outer namespace(s)
{ "pile_set_name": "Github" }
<?php class Swift_StreamFilters_StringReplacementFilterFactoryTest extends \PHPUnit\Framework\TestCase { public function testInstancesOfStringReplacementFilterAreCreated() { $factory = $this->createFactory(); $this->assertInstanceOf( 'Swift_StreamFilters_StringReplacementFilter', $factory->createFilter('a', 'b') ); } public function testSameInstancesAreCached() { $factory = $this->createFactory(); $filter1 = $factory->createFilter('a', 'b'); $filter2 = $factory->createFilter('a', 'b'); $this->assertSame($filter1, $filter2, '%s: Instances should be cached'); } public function testDifferingInstancesAreNotCached() { $factory = $this->createFactory(); $filter1 = $factory->createFilter('a', 'b'); $filter2 = $factory->createFilter('a', 'c'); $this->assertNotEquals($filter1, $filter2, '%s: Differing instances should not be cached' ); } private function createFactory() { return new Swift_StreamFilters_StringReplacementFilterFactory(); } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 185342edd797532429f35fbcf982c06c MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
// Copyright 2016 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 bench reads and writes Go benchmarks results files. // // This format is specified at: // https://github.com/golang/proposal/blob/master/design/14313-benchmark-format.md package bench import ( "bufio" "io" "regexp" "strconv" "strings" "time" "unicode" "unicode/utf8" ) // Benchmark records the configuration and results of a single // benchmark run (a single line of a benchmark results file). type Benchmark struct { // Name is the name of the benchmark, without the "Benchmark" // prefix and without the trailing GOMAXPROCS number. Name string // Iterations is the number of times this benchmark executed. Iterations int // Config is the set of configuration pairs for this // Benchmark. These can be specified in both configuration // blocks and in individual benchmark lines. If the benchmark // name is of the form "BenchmarkX-N", the N is stripped out // and stored as "gomaxprocs" here. Config map[string]*Config // Result is the set of (unit, value) metrics for this // benchmark run. Result map[string]float64 } // Config represents a single key/value configuration pair. type Config struct { // Value is the parsed value of this configuration value. Value interface{} // RawValue is the value of this configuration value, exactly // as written in the original benchmark file. RawValue string // InBlock indicates that this configuration value was // specified in a configuration block line. Otherwise, it was // specified in the benchmark line. InBlock bool } var configRe = regexp.MustCompile(`^(\p{Ll}[^\p{Lu}\s\x85\xa0\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}]*):(?:[ \t]+(.*))?$`) // Parse parses a standard Go benchmark results file from r. It // returns a *Benchmark for each benchmark result line in the file. // There may be many result lines for the same benchmark name and // configuration, indicating that the benchmark was run multiple // times. // // In the returned Benchmarks, RawValue is set, but Value is always // nil. Use ParseValues to convert raw values to structured types. func Parse(r io.Reader) ([]*Benchmark, error) { benchmarks := []*Benchmark{} config := make(map[string]*Config) scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Text() if line == "testing: warning: no tests to run" { continue } // Configuration lines. m := configRe.FindStringSubmatch(line) if m != nil { config[m[1]] = &Config{RawValue: m[2], InBlock: true} continue } // Benchmark lines. if strings.HasPrefix(line, "Benchmark") { b := parseBenchmark(line, config) if b != nil { benchmarks = append(benchmarks, b) } } } if err := scanner.Err(); err != nil { return nil, err } return benchmarks, nil } func parseBenchmark(line string, gconfig map[string]*Config) *Benchmark { // TODO: Consider using scanner to avoid the slice allocation. f := strings.Fields(line) if len(f) < 4 { return nil } if f[0] != "Benchmark" { next, _ := utf8.DecodeRuneInString(f[0][len("Benchmark"):]) if !unicode.IsUpper(next) { return nil } } b := &Benchmark{ Config: make(map[string]*Config), Result: make(map[string]float64), } // Copy global config. for k, v := range gconfig { b.Config[k] = v } // Parse name and configuration. name := strings.TrimPrefix(f[0], "Benchmark") if strings.Contains(name, "/") { parts := strings.Split(name, "/") b.Name = parts[0] for _, part := range parts[1:] { if i := strings.Index(part, ":"); i >= 0 { k, v := part[:i], part[i+1:] b.Config[k] = &Config{RawValue: v} } } } else if i := strings.LastIndex(name, "-"); i >= 0 { _, err := strconv.Atoi(name[i+1:]) if err == nil { b.Name = name[:i] b.Config["gomaxprocs"] = &Config{RawValue: name[i+1:]} } else { b.Name = name } } else { b.Name = name } if b.Config["gomaxprocs"] == nil { b.Config["gomaxprocs"] = &Config{RawValue: "1"} } // Parse iterations. n, err := strconv.Atoi(f[1]) if err != nil || n <= 0 { return nil } b.Iterations = n // Parse results. for i := 2; i+2 <= len(f); i += 2 { val, err := strconv.ParseFloat(f[i], 64) if err != nil { continue } b.Result[f[i+1]] = val } return b } // ValueParser is a function that parses a string value into a // structured type or returns an error if the string cannot be parsed. type ValueParser func(string) (interface{}, error) // DefaultValueParsers is the default sequence of value parsers used // by ParseValues if no parsers are specified. var DefaultValueParsers = []ValueParser{ func(s string) (interface{}, error) { return strconv.Atoi(s) }, func(s string) (interface{}, error) { return strconv.ParseFloat(s, 64) }, func(s string) (interface{}, error) { return time.ParseDuration(s) }, } // ParseValues parses the raw configuration values in benchmarks into // structured types using best-effort pattern-based parsing. // // If all of the raw values for a given configuration key can be // parsed by one of the valueParsers, ParseValues sets the parsed // values to the results of that ValueParser. If multiple ValueParsers // can parse all of the raw values, it uses the earliest such parser // in the valueParsers list. // // If valueParsers is nil, it uses DefaultValueParsers. func ParseValues(benchmarks []*Benchmark, valueParsers []ValueParser) { if valueParsers == nil { valueParsers = DefaultValueParsers } // Collect all configuration keys. keys := map[string]bool{} for _, b := range benchmarks { for k := range b.Config { keys[k] = true } } // For each configuration key, try value parsers in priority order. for key := range keys { good := false tryParsers: for _, vp := range valueParsers { // Clear all values. This way we can detect // aliasing and not parse the same value // multiple times. for _, b := range benchmarks { c, ok := b.Config[key] if ok { c.Value = nil } } good = true tryValues: for _, b := range benchmarks { c, ok := b.Config[key] if !ok || c.Value != nil { continue } res, err := vp(c.RawValue) if err != nil { // Parse error. Fail this parser. good = false break tryValues } c.Value = res } if good { // This ValueParser converted all of // the values. break tryParsers } } if !good { // All of the value parsers failed. Fall back // to strings. for _, b := range benchmarks { c, ok := b.Config[key] if ok { c.Value = nil } } for _, b := range benchmarks { c, ok := b.Config[key] if ok && c.Value == nil { c.Value = c.RawValue } } } } }
{ "pile_set_name": "Github" }
#include <wchar.h> wchar_t *wcscat(wchar_t *restrict dest, const wchar_t *restrict src) { wcscpy(dest + wcslen(dest), src); return dest; }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Comment.user_ip' db.add_column(u'blogango_comment', 'user_ip', self.gf('django.db.models.fields.IPAddressField')(max_length=15, null=True), keep_default=False) # Adding field 'Comment.user_agent' db.add_column(u'blogango_comment', 'user_agent', self.gf('django.db.models.fields.CharField')(default='', max_length=200), keep_default=False) def backwards(self, orm): # Deleting field 'Comment.user_ip' db.delete_column(u'blogango_comment', 'user_ip') # Deleting field 'Comment.user_agent' db.delete_column(u'blogango_comment', 'user_agent') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'blogango.blog': { 'Meta': {'object_name': 'Blog'}, 'entries_per_page': ('django.db.models.fields.IntegerField', [], {'default': '10'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'recent_comments': ('django.db.models.fields.IntegerField', [], {'default': '5'}), 'recents': ('django.db.models.fields.IntegerField', [], {'default': '5'}), 'tag_line': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'blogango.blogentry': { 'Meta': {'ordering': "['-created_on']", 'object_name': 'BlogEntry'}, '_text_rendered': ('django.db.models.fields.TextField', [], {}), 'comments_allowed': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(9999, 12, 31, 0, 0)'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_page': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_rte': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'meta_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'meta_keywords': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'summary': ('django.db.models.fields.TextField', [], {}), 'text': ('markupfield.fields.MarkupField', [], {'rendered_field': 'True'}), 'text_markup_type': ('django.db.models.fields.CharField', [], {'default': "'plain'", 'max_length': '30'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'blogango.blogroll': { 'Meta': {'object_name': 'BlogRoll'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'url': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '200'}) }, u'blogango.comment': { 'Meta': {'ordering': "['created_on']", 'object_name': 'Comment'}, 'comment_for': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['blogango.BlogEntry']"}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'email_id': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'is_spam': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'text': ('django.db.models.fields.TextField', [], {}), 'user_agent': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200'}), 'user_ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True'}), 'user_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'user_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}) }, u'blogango.reaction': { 'Meta': {'ordering': "['created_on']", 'object_name': 'Reaction'}, 'comment_for': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['blogango.BlogEntry']"}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'profile_image': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'reaction_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'primary_key': 'True'}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'text': ('django.db.models.fields.TextField', [], {}), 'user_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'user_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'taggit.tag': { 'Meta': {'object_name': 'Tag'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, u'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_tagged_items'", 'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_items'", 'to': u"orm['taggit.Tag']"}) } } complete_apps = ['blogango']
{ "pile_set_name": "Github" }
--- usr/www/all/html/de/fon/foncalls.js +++ usr/www/all/html/de/fon/foncalls.js @@ -3,17 +3,17 @@ <style type="text/css"> <!-- #content {width: 580px; margin: auto;} -#tClient {height: 12px; font-size: 12px; width: 518px; table-layout: fixed} +#tClient {height: 12px; font-size: 11px; width: 522px; table-layout: fixed} #tClient td {padding: 2px; overflow: hidden; height: 24px;} #tClient th {padding: 2px; overflow: hidden;} -#tClient .c1 {text-align: left; width:20px;} -#tClient .c3 {text-align: left; width:<? if lte $var:AbCount 1 `110px` `85px` ?>;} +#tClient .c1 {text-align: left; width:14px;} +#tClient .c3 {text-align: left; width:<? if lte $var:AbCount 1 `102px` `72px` ?>;} #tClient .c4 {text-align: left; width:<? if lte $var:AbCount 1 `100px` `70px` ?>;} -#tClient .c5 {text-align: left; width:75px; <? if lte $var:AbCount 1 `display:none;` ?>} -#tClient .c6 {text-align: right; width:35px;} -#tClient .c7 {text-align: left; width:<? if lte $var:AbCount 1 `136px` `122px` ?>;} -#tClient .c8 {text-align: left; width:<? if lte $var:AbCount 1 `161px` `115px` ?>;} -#tClient .c9 {text-align: center; width: 34px;} +#tClient .c5 {text-align: center; width:68px; <? if lte $var:AbCount 1 `display:none;` ?>} +#tClient .c6 {text-align: center; width:33px;} +#tClient .c7 {text-align: left; width:<? if lte $var:AbCount 1 `110px` `103px` ?>;} +#tClient .c8 {text-align: left; width:<? if lte $var:AbCount 1 `180px` `165px` ?>;} +#tClient .c9 {text-align: center; width: 32px;} #tLegende {margin:auto} #tLegende td {padding: 2px 2px;} #tClient a:link, #tClient a:visited { color: black; } @@ -142,17 +142,17 @@ } function uiNummerDisplay (nr, name) { var buchname = GetBuchName(name); -if (nr=="" && buchname=="") return g_txtUnbekannt; +if (nr=="" && buchname=="") return g_sym0 + g_txtUnbekannt; if ("<? query telcfg:settings/UseClickToDial ?>" == "1") { -if (nr == "") return span(buchname); -if (buchname == "") { -return "<nobr>" + -"<a href=\"javascript:Dial('"+nr+"')\" title=\""+nr+"\">"+nr+"</a></nobr>"; -} -return "<nobr><a href=\"javascript:Dial('"+nr+"')\" title=\""+buchname+"\">"+buchname+"</a></nobr>"; +if (nr == "") return g_sym0 + span(buchname); +if (buchname == "") return "<nobr>" + uiRufnummerInfo (nr) +"<a href=\"javascript:Dial('"+nr+"')\" title=\""+nr+"\">"+nr+"</a></nobr>"; +return "<nobr>" + g_sym0 + "<a href=\"javascript:Dial('"+nr+"')\" title=\""+buchname+"\">"+buchname+"</a></nobr>"; } else { -return span(buchname=="" ? nr:buchname); +return (buchname=="" ? uiRufnummerInfo(nr):g_sym0) + span(buchname=="" ? nr:buchname); +} } +function uiRufnummerInfo (nr) { +return "<a href=\"http://www.dasoertliche.de/Controller?form_name=search_inv&ph=" + encodeURI (nr) + "\" target=\"_blank\" title=\"R&uuml;ckw&auml;rtssuche bei dasoertliche.de nach "+nr+"\"><img src=\"../html/<? echo $var:lang ?>/images/bearbeiten.gif\"></a>"; } function uiRouteDisplay (n, t) { var name;
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <AppKit/NSView.h> @class NSImage, NSMenuItem; @interface AppleBluetoothMenuItemStateView : NSView { float _level; NSMenuItem *_menuItem; NSImage *_image; NSImage *_batteryImage; } @property float level; // @synthesize level=_level; @property(retain) NSImage *batteryImage; // @synthesize batteryImage=_batteryImage; @property(retain) NSImage *image; // @synthesize image=_image; @property(retain) NSMenuItem *menuItem; // @synthesize menuItem=_menuItem; - (void)drawRect:(struct CGRect)arg1; - (id)_foregroundColor; - (id)_lowBatteryColor; - (id)_lowBatteryMaskImage; - (id)_batteryImageForLevel:(float)arg1; - (void)setBatteryLevel:(id)arg1; - (void)dealloc; - (id)initWithMenuItem:(id)arg1 image:(id)arg2 batteryLevel:(id)arg3; @end
{ "pile_set_name": "Github" }
{ "_from": "mongodb@3.1.6", "_id": "mongodb@3.1.6", "_inBundle": false, "_integrity": "sha512-E5QJuXQoMlT7KyCYqNNMfAkhfQD79AT4F8Xd+6x37OX+8BL17GyXyWvfm6wuyx4wnzCCPoCSLeMeUN2S7dU9yw==", "_location": "/mongodb", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, "raw": "mongodb@3.1.6", "name": "mongodb", "escapedName": "mongodb", "rawSpec": "3.1.6", "saveSpec": null, "fetchSpec": "3.1.6" }, "_requiredBy": [ "/mongoose" ], "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.6.tgz", "_shasum": "6054641973b5bf5b5ae1c67dcbcf8fa88280273d", "_spec": "mongodb@3.1.6", "_where": "D:\\git-clone\\node.js\\5-1MongoDB\\MongoDB的CRUD\\node_modules\\mongoose", "author": { "name": "Christian Kvalheim" }, "bugs": { "url": "https://github.com/mongodb/node-mongodb-native/issues" }, "bundleDependencies": false, "dependencies": { "mongodb-core": "3.1.5", "safe-buffer": "^5.1.2" }, "deprecated": false, "description": "The official MongoDB driver for Node.js", "devDependencies": { "bluebird": "3.5.0", "bson": "^1.0.4", "chai": "^4.1.1", "chai-subset": "^1.6.0", "co": "4.6.0", "coveralls": "^2.11.6", "eslint": "^4.5.0", "eslint-plugin-prettier": "^2.2.0", "istanbul": "^0.4.5", "jsdoc": "3.5.5", "lodash.camelcase": "^4.3.0", "mocha-sinon": "^2.1.0", "mongodb-extjson": "^2.1.1", "mongodb-mock-server": "^1.0.0", "mongodb-test-runner": "^1.1.18", "prettier": "~1.12.0", "semver": "^5.5.0", "sinon": "^4.3.0", "sinon-chai": "^3.2.0", "standard-version": "^4.4.0", "worker-farm": "^1.5.0" }, "engines": { "node": ">=4" }, "files": [ "index.js", "lib" ], "homepage": "https://github.com/mongodb/node-mongodb-native", "keywords": [ "mongodb", "driver", "official" ], "license": "Apache-2.0", "main": "index.js", "name": "mongodb", "repository": { "type": "git", "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" }, "scripts": { "bench": "node test/driverBench/", "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional", "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", "lint": "eslint lib test", "release": "standard-version -i HISTORY.md", "test": "npm run lint && mongodb-test-runner -t 60000 test/unit test/functional" }, "version": "3.1.6" }
{ "pile_set_name": "Github" }
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData // package to your project. ////#define Handle_PageResultOfT using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Web; using System.Web.Http; #if Handle_PageResultOfT using System.Web.Http.OData; #endif namespace ZipCodeFinal.Areas.HelpPage { /// <summary> /// Use this class to customize the Help Page. /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation /// or you can provide the samples for the requests/responses. /// </summary> public static class HelpPageConfig { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "ZipCodeFinal.Areas.HelpPage.TextSample.#ctor(System.String)", Justification = "End users may choose to merge this string with existing localized resources.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "bsonspec", Justification = "Part of a URI.")] public static void Register(HttpConfiguration config) { //// Uncomment the following to use the documentation from XML documentation file. //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type //// formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> //{ // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} //}); // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if Handle_PageResultOfT config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. config.SetSampleForMediaType( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new MediaTypeHeaderValue("application/bson")); //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" //// and action named "Put". //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" //// on the controller named "Values" and action named "Get" with parameter "id". //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.SetActualRequestType(typeof(string), "Values", "Get"); //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.SetActualResponseType(typeof(string), "Values", "Post"); } #if Handle_PageResultOfT private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) { if (type.IsGenericType) { Type openGenericType = type.GetGenericTypeDefinition(); if (openGenericType == typeof(PageResult<>)) { // Get the T in PageResult<T> Type[] typeParameters = type.GetGenericArguments(); Debug.Assert(typeParameters.Length == 1); // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor Type itemsType = typeof(List<>).MakeGenericType(typeParameters); object items = sampleGenerator.GetSampleObject(itemsType); // Fill in the other information needed to invoke the PageResult<T> constuctor Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor ConstructorInfo constructor = type.GetConstructor(parameterTypes); return constructor.Invoke(parameters); } } return null; } #endif } }
{ "pile_set_name": "Github" }
// RUN: llvm-mc -triple x86_64-unknown-unknown %s | FileCheck %s .rept 2 .long 1 .endr .rept 3 .rept 2 .long 0 .endr .endr // CHECK: .long 1 // CHECK: .long 1 // CHECK: .long 0 // CHECK: .long 0 // CHECK: .long 0 // CHECK: .long 0 // CHECK: .long 0 // CHECK: .long 0
{ "pile_set_name": "Github" }
#!/usr/bin/env bash for filename in /usr/share/corfu/bin/*; do rm /usr/local/bin/$(basename "$filename") done
{ "pile_set_name": "Github" }
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by HPSocketDLL.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
{ "pile_set_name": "Github" }
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.core.model.script.engine; import java.util.List; import org.openhab.core.thing.binding.ThingActions; public interface IThingActionsProvider { List<ThingActions> get(); }
{ "pile_set_name": "Github" }
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
{ "pile_set_name": "Github" }
// Text overflow // Requires inline-block or block for proper styling .text-overflow() { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
{ "pile_set_name": "Github" }
using Serenity.ComponentModel; using Serenity.Data; using Serenity.Data.Mapping; using Xunit; namespace Serenity.CodeGeneration.Test { public partial class ServerTypingsGeneratorTests { [Fact] public void Reads_NameProperty_FromINameRow() { var generator = CreateGenerator(); var result = generator.Run(); Assert.Contains("SomeModule.WithNameRowInterfaceRow.ts", result.Keys); var code = result["SomeModule.WithNameRowInterfaceRow.ts"]; Assert.Contains("nameProperty = 'SomeName'", code); } [Fact] public void Reads_NameProperty_FromAttribute() { var generator = CreateGenerator(); var result = generator.Run(); Assert.Contains("SomeModule.WithNamePropertyRow.ts", result.Keys); var code = result["SomeModule.WithNamePropertyRow.ts"]; Assert.Contains("nameProperty = 'WithNameProp'", code); } } } namespace ServerTypingsTest.SomeModule.Entities { public class WithNameRowInterfaceRow : Row, INameRow { public string SomeName { get { return Fields.SomeName[this]; } set { Fields.SomeName[this] = value; } } StringField INameRow.NameField => Fields.SomeName; public class RowFields : RowFieldsBase { public StringField SomeName; } public static RowFields Fields = new RowFields().Init(); public WithNameRowInterfaceRow() : base(Fields) { } } public class WithNamePropertyRow : Row { [NameProperty] public string WithNameProp { get { return Fields.WithNameProp[this]; } set { Fields.WithNameProp[this] = value; } } public class RowFields : RowFieldsBase { public StringField WithNameProp; } public static RowFields Fields = new RowFields().Init(); public WithNamePropertyRow() : base(Fields) { } } }
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="properties_63.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
{ "pile_set_name": "Github" }
/* Generated by RuntimeBrowser on iPhone OS 3.0 Image: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ @class EDChartLegendFrame, NSArray, EDChartFrame, EDChartPlot; @interface EDChart : NSObject { EDChartFrame *mChartParentFrame; EDChartLegendFrame *mChartLegendFrame; EDChartFrame *mTitle; struct CGSize { float width; float height; } mSize; EDChartPlot *mPrimaryChartPlot; EDChartPlot *mSecondaryChartPlot; NSArray *mSeriesData; double mMinY; double mMaxY; BOOL mIsDate1904; } - (id)init; - (void)dealloc; - (void)setSize:(struct CGSize { float x1; float x2; })arg1; - (struct CGSize { float x1; float x2; })size; - (void)setChartParentFrame:(id)arg1; - (id)chartParentFrame; - (id)chartPlotFrame; - (void)setChartLegendFrame:(id)arg1; - (id)chartLegendFrame; - (void)setChartTitle:(id)arg1; - (id)title; - (void)setPrimaryChartPlot:(id)arg1; - (id)primaryChartPlot; - (void)setSecondaryChartPlot:(id)arg1; - (id)secondaryChartPlot; - (void)setSeriesData:(id)arg1; - (id)seriesData; - (NSUInteger)seriesCount; - (double)minY; - (double)maxY; - (void)setDate1904:(BOOL)arg1; - (BOOL)isDate1904; @end
{ "pile_set_name": "Github" }
!!! 5 html(lang="en") head !{css} !{js} body h1 Piler Example p View the source :)
{ "pile_set_name": "Github" }
# frozen_string_literal: true class ChangeRoleNameToId < ActiveRecord::Migration[4.2] INDEX = "index_kubernetes_deploy_group_roles_on_project_id" class KubernetesRole < ActiveRecord::Base end class KubernetesDeployGroupRole < ActiveRecord::Base end # change all role names to direct role references or delete the record def up add_column :kubernetes_deploy_group_roles, :kubernetes_role_id, :integer KubernetesDeployGroupRole.find_each do |dgr| if role = KubernetesRole.where(project_id: dgr.project_id, name: dgr.name).first dgr.update_column(:kubernetes_role_id, role.id) else dgr.destroy end end change_column_null :kubernetes_deploy_group_roles, :kubernetes_role_id, false remove_old_index remove_column :kubernetes_deploy_group_roles, :name add_index :kubernetes_deploy_group_roles, [:project_id, :deploy_group_id, :kubernetes_role_id], name: INDEX end def down add_column :kubernetes_deploy_group_roles, :name, :string KubernetesDeployGroupRole.find_each do |dgr| if role = KubernetesRole.where(id: dgr.kubernetes_role_id).first dgr.update_column(:name, role.name) else dgr.destroy end end change_column_null :kubernetes_deploy_group_roles, :name, false remove_old_index remove_column :kubernetes_deploy_group_roles, :kubernetes_role_id add_index :kubernetes_deploy_group_roles, [:project_id, :deploy_group_id, :name], name: INDEX, length: {"name" => 191} end def remove_old_index remove_index :kubernetes_deploy_group_roles, name: INDEX end end
{ "pile_set_name": "Github" }
K 13 svn:mime-type V 24 application/octet-stream END
{ "pile_set_name": "Github" }
#include "license_pbs.h" /* See here for the software license */ #include "lib_ifl.h" #include "test_pbsD_gpuctrl.h" #include <stdlib.h> #include <stdio.h> #include "pbs_error.h" START_TEST(test_pbs_gpumode_err) { char node[1024]; char gpuid[5]; sprintf(node, "napali"); sprintf(gpuid, "1"); fail_unless(pbs_gpumode_err(-1, node, gpuid, 0, NULL) == PBSE_IVALREQ); fail_unless(pbs_gpumode_err(PBS_NET_MAX_CONNECTIONS, node, gpuid, 0, NULL) == PBSE_IVALREQ); fail_unless(pbs_gpumode_err(0, NULL, gpuid, 0, NULL) == PBSE_IVALREQ); fail_unless(pbs_gpumode_err(0, node, NULL, 0, NULL) == PBSE_IVALREQ); fail_unless(pbs_gpumode_err(0, node, gpuid, -1, NULL) == PBSE_IVALREQ); fail_unless(pbs_gpumode_err(0, node, gpuid, 4, NULL) == PBSE_IVALREQ); } END_TEST START_TEST(test_two) { } END_TEST Suite *pbsD_gpuctrl_suite(void) { Suite *s = suite_create("pbsD_gpuctrl_suite methods"); TCase *tc_core = tcase_create("test_pbs_gpumode_err"); tcase_add_test(tc_core, test_pbs_gpumode_err); suite_add_tcase(s, tc_core); tc_core = tcase_create("test_two"); tcase_add_test(tc_core, test_two); suite_add_tcase(s, tc_core); return s; } void rundebug() { } int main(void) { int number_failed = 0; SRunner *sr = NULL; rundebug(); sr = srunner_create(pbsD_gpuctrl_suite()); srunner_set_log(sr, "pbsD_gpuctrl_suite.log"); srunner_run_all(sr, CK_NORMAL); number_failed = srunner_ntests_failed(sr); srunner_free(sr); return number_failed; }
{ "pile_set_name": "Github" }
# -*- mode: cperl; tab-width: 8; indent-tabs-mode: nil; basic-offset: 2 -*- # vim:ts=8:sw=2:et:sta:sts=2 package Module::Metadata; # git description: v1.000025-7-g47ca1b2 # Adapted from Perl-licensed code originally distributed with # Module-Build by Ken Williams # This module provides routines to gather information about # perl modules (assuming this may be expanded in the distant # parrot future to look at other types of modules). sub __clean_eval { eval $_[0] } use strict; use warnings; our $VERSION = '1.000026'; use Carp qw/croak/; use File::Spec; BEGIN { # Try really hard to not depend ony any DynaLoaded module, such as IO::File or Fcntl eval { require Fcntl; Fcntl->import('SEEK_SET'); 1; } or *SEEK_SET = sub { 0 } } use version 0.87; BEGIN { if ($INC{'Log/Contextual.pm'}) { Log::Contextual->import('log_info'); } else { *log_info = sub (&) { warn $_[0]->() }; } } use File::Find qw(find); my $V_NUM_REGEXP = qr{v?[0-9._]+}; # crudely, a v-string or decimal my $PKG_FIRST_WORD_REGEXP = qr{ # the FIRST word in a package name [a-zA-Z_] # the first word CANNOT start with a digit (?: [\w']? # can contain letters, digits, _, or ticks \w # But, NO multi-ticks or trailing ticks )* }x; my $PKG_ADDL_WORD_REGEXP = qr{ # the 2nd+ word in a package name \w # the 2nd+ word CAN start with digits (?: [\w']? # and can contain letters or ticks \w # But, NO multi-ticks or trailing ticks )* }x; my $PKG_NAME_REGEXP = qr{ # match a package name (?: :: )? # a pkg name can start with arisdottle $PKG_FIRST_WORD_REGEXP # a package word (?: (?: :: )+ ### arisdottle (allow one or many times) $PKG_ADDL_WORD_REGEXP ### a package word )* # ^ zero, one or many times (?: :: # allow trailing arisdottle )? }x; my $PKG_REGEXP = qr{ # match a package declaration ^[\s\{;]* # intro chars on a line package # the word 'package' \s+ # whitespace ($PKG_NAME_REGEXP) # a package name \s* # optional whitespace ($V_NUM_REGEXP)? # optional version number \s* # optional whitesapce [;\{] # semicolon line terminator or block start (since 5.16) }x; my $VARNAME_REGEXP = qr{ # match fully-qualified VERSION name ([\$*]) # sigil - $ or * ( ( # optional leading package name (?:::|\')? # possibly starting like just :: (a la $::VERSION) (?:\w+(?:::|\'))* # Foo::Bar:: ... )? VERSION )\b }x; my $VERS_REGEXP = qr{ # match a VERSION definition (?: \(\s*$VARNAME_REGEXP\s*\) # with parens | $VARNAME_REGEXP # without parens ) \s* =[^=~>] # = but not ==, nor =~, nor => }x; sub new_from_file { my $class = shift; my $filename = File::Spec->rel2abs( shift ); return undef unless defined( $filename ) && -f $filename; return $class->_init(undef, $filename, @_); } sub new_from_handle { my $class = shift; my $handle = shift; my $filename = shift; return undef unless defined($handle) && defined($filename); $filename = File::Spec->rel2abs( $filename ); return $class->_init(undef, $filename, @_, handle => $handle); } sub new_from_module { my $class = shift; my $module = shift; my %props = @_; $props{inc} ||= \@INC; my $filename = $class->find_module_by_name( $module, $props{inc} ); return undef unless defined( $filename ) && -f $filename; return $class->_init($module, $filename, %props); } { my $compare_versions = sub { my ($v1, $op, $v2) = @_; $v1 = version->new($v1) unless UNIVERSAL::isa($v1,'version'); my $eval_str = "\$v1 $op \$v2"; my $result = eval $eval_str; log_info { "error comparing versions: '$eval_str' $@" } if $@; return $result; }; my $normalize_version = sub { my ($version) = @_; if ( $version =~ /[=<>!,]/ ) { # logic, not just version # take as is without modification } elsif ( ref $version eq 'version' ) { # version objects $version = $version->is_qv ? $version->normal : $version->stringify; } elsif ( $version =~ /^[^v][^.]*\.[^.]+\./ ) { # no leading v, multiple dots # normalize string tuples without "v": "1.2.3" -> "v1.2.3" $version = "v$version"; } else { # leave alone } return $version; }; # separate out some of the conflict resolution logic my $resolve_module_versions = sub { my $packages = shift; my( $file, $version ); my $err = ''; foreach my $p ( @$packages ) { if ( defined( $p->{version} ) ) { if ( defined( $version ) ) { if ( $compare_versions->( $version, '!=', $p->{version} ) ) { $err .= " $p->{file} ($p->{version})\n"; } else { # same version declared multiple times, ignore } } else { $file = $p->{file}; $version = $p->{version}; } } $file ||= $p->{file} if defined( $p->{file} ); } if ( $err ) { $err = " $file ($version)\n" . $err; } my %result = ( file => $file, version => $version, err => $err ); return \%result; }; sub provides { my $class = shift; croak "provides() requires key/value pairs \n" if @_ % 2; my %args = @_; croak "provides() takes only one of 'dir' or 'files'\n" if $args{dir} && $args{files}; croak "provides() requires a 'version' argument" unless defined $args{version}; croak "provides() does not support version '$args{version}' metadata" unless grep { $args{version} eq $_ } qw/1.4 2/; $args{prefix} = 'lib' unless defined $args{prefix}; my $p; if ( $args{dir} ) { $p = $class->package_versions_from_directory($args{dir}); } else { croak "provides() requires 'files' to be an array reference\n" unless ref $args{files} eq 'ARRAY'; $p = $class->package_versions_from_directory($args{files}); } # Now, fix up files with prefix if ( length $args{prefix} ) { # check in case disabled with q{} $args{prefix} =~ s{/$}{}; for my $v ( values %$p ) { $v->{file} = "$args{prefix}/$v->{file}"; } } return $p } sub package_versions_from_directory { my ( $class, $dir, $files ) = @_; my @files; if ( $files ) { @files = @$files; } else { find( { wanted => sub { push @files, $_ if -f $_ && /\.pm$/; }, no_chdir => 1, }, $dir ); } # First, we enumerate all packages & versions, # separating into primary & alternative candidates my( %prime, %alt ); foreach my $file (@files) { my $mapped_filename = File::Spec::Unix->abs2rel( $file, $dir ); my @path = split( /\//, $mapped_filename ); (my $prime_package = join( '::', @path )) =~ s/\.pm$//; my $pm_info = $class->new_from_file( $file ); foreach my $package ( $pm_info->packages_inside ) { next if $package eq 'main'; # main can appear numerous times, ignore next if $package eq 'DB'; # special debugging package, ignore next if grep /^_/, split( /::/, $package ); # private package, ignore my $version = $pm_info->version( $package ); $prime_package = $package if lc($prime_package) eq lc($package); if ( $package eq $prime_package ) { if ( exists( $prime{$package} ) ) { croak "Unexpected conflict in '$package'; multiple versions found.\n"; } else { $mapped_filename = "$package.pm" if lc("$package.pm") eq lc($mapped_filename); $prime{$package}{file} = $mapped_filename; $prime{$package}{version} = $version if defined( $version ); } } else { push( @{$alt{$package}}, { file => $mapped_filename, version => $version, } ); } } } # Then we iterate over all the packages found above, identifying conflicts # and selecting the "best" candidate for recording the file & version # for each package. foreach my $package ( keys( %alt ) ) { my $result = $resolve_module_versions->( $alt{$package} ); if ( exists( $prime{$package} ) ) { # primary package selected if ( $result->{err} ) { # Use the selected primary package, but there are conflicting # errors among multiple alternative packages that need to be # reported log_info { "Found conflicting versions for package '$package'\n" . " $prime{$package}{file} ($prime{$package}{version})\n" . $result->{err} }; } elsif ( defined( $result->{version} ) ) { # There is a primary package selected, and exactly one # alternative package if ( exists( $prime{$package}{version} ) && defined( $prime{$package}{version} ) ) { # Unless the version of the primary package agrees with the # version of the alternative package, report a conflict if ( $compare_versions->( $prime{$package}{version}, '!=', $result->{version} ) ) { log_info { "Found conflicting versions for package '$package'\n" . " $prime{$package}{file} ($prime{$package}{version})\n" . " $result->{file} ($result->{version})\n" }; } } else { # The prime package selected has no version so, we choose to # use any alternative package that does have a version $prime{$package}{file} = $result->{file}; $prime{$package}{version} = $result->{version}; } } else { # no alt package found with a version, but we have a prime # package so we use it whether it has a version or not } } else { # No primary package was selected, use the best alternative if ( $result->{err} ) { log_info { "Found conflicting versions for package '$package'\n" . $result->{err} }; } # Despite possible conflicting versions, we choose to record # something rather than nothing $prime{$package}{file} = $result->{file}; $prime{$package}{version} = $result->{version} if defined( $result->{version} ); } } # Normalize versions. Can't use exists() here because of bug in YAML::Node. # XXX "bug in YAML::Node" comment seems irrelevant -- dagolden, 2009-05-18 for (grep defined $_->{version}, values %prime) { $_->{version} = $normalize_version->( $_->{version} ); } return \%prime; } } sub _init { my $class = shift; my $module = shift; my $filename = shift; my %props = @_; my $handle = delete $props{handle}; my( %valid_props, @valid_props ); @valid_props = qw( collect_pod inc ); @valid_props{@valid_props} = delete( @props{@valid_props} ); warn "Unknown properties: @{[keys %props]}\n" if scalar( %props ); my %data = ( module => $module, filename => $filename, version => undef, packages => [], versions => {}, pod => {}, pod_headings => [], collect_pod => 0, %valid_props, ); my $self = bless(\%data, $class); if ( not $handle ) { my $filename = $self->{filename}; open $handle, '<', $filename or croak( "Can't open '$filename': $!" ); $self->_handle_bom($handle, $filename); } $self->_parse_fh($handle); unless($self->{module} and length($self->{module})) { my ($v, $d, $f) = File::Spec->splitpath($self->{filename}); if($f =~ /\.pm$/) { $f =~ s/\..+$//; my @candidates = grep /$f$/, @{$self->{packages}}; $self->{module} = shift(@candidates); # punt } else { if(grep /main/, @{$self->{packages}}) { $self->{module} = 'main'; } else { $self->{module} = $self->{packages}[0] || ''; } } } $self->{version} = $self->{versions}{$self->{module}} if defined( $self->{module} ); return $self; } # class method sub _do_find_module { my $class = shift; my $module = shift || croak 'find_module_by_name() requires a package name'; my $dirs = shift || \@INC; my $file = File::Spec->catfile(split( /::/, $module)); foreach my $dir ( @$dirs ) { my $testfile = File::Spec->catfile($dir, $file); return [ File::Spec->rel2abs( $testfile ), $dir ] if -e $testfile and !-d _; # For stuff like ExtUtils::xsubpp $testfile .= '.pm'; return [ File::Spec->rel2abs( $testfile ), $dir ] if -e $testfile; } return; } # class method sub find_module_by_name { my $found = shift()->_do_find_module(@_) or return; return $found->[0]; } # class method sub find_module_dir_by_name { my $found = shift()->_do_find_module(@_) or return; return $found->[1]; } # given a line of perl code, attempt to parse it if it looks like a # $VERSION assignment, returning sigil, full name, & package name sub _parse_version_expression { my $self = shift; my $line = shift; my( $sigil, $variable_name, $package); if ( $line =~ /$VERS_REGEXP/o ) { ( $sigil, $variable_name, $package) = $2 ? ( $1, $2, $3 ) : ( $4, $5, $6 ); if ( $package ) { $package = ($package eq '::') ? 'main' : $package; $package =~ s/::$//; } } return ( $sigil, $variable_name, $package ); } # Look for a UTF-8/UTF-16BE/UTF-16LE BOM at the beginning of the stream. # If there's one, then skip it and set the :encoding layer appropriately. sub _handle_bom { my ($self, $fh, $filename) = @_; my $pos = tell $fh; return unless defined $pos; my $buf = ' ' x 2; my $count = read $fh, $buf, length $buf; return unless defined $count and $count >= 2; my $encoding; if ( $buf eq "\x{FE}\x{FF}" ) { $encoding = 'UTF-16BE'; } elsif ( $buf eq "\x{FF}\x{FE}" ) { $encoding = 'UTF-16LE'; } elsif ( $buf eq "\x{EF}\x{BB}" ) { $buf = ' '; $count = read $fh, $buf, length $buf; if ( defined $count and $count >= 1 and $buf eq "\x{BF}" ) { $encoding = 'UTF-8'; } } if ( defined $encoding ) { if ( "$]" >= 5.008 ) { binmode( $fh, ":encoding($encoding)" ); } } else { seek $fh, $pos, SEEK_SET or croak( sprintf "Can't reset position to the top of '$filename'" ); } return $encoding; } sub _parse_fh { my ($self, $fh) = @_; my( $in_pod, $seen_end, $need_vers ) = ( 0, 0, 0 ); my( @packages, %vers, %pod, @pod ); my $package = 'main'; my $pod_sect = ''; my $pod_data = ''; my $in_end = 0; while (defined( my $line = <$fh> )) { my $line_num = $.; chomp( $line ); # From toke.c : any line that begins by "=X", where X is an alphabetic # character, introduces a POD segment. my $is_cut; if ( $line =~ /^=([a-zA-Z].*)/ ) { my $cmd = $1; # Then it goes back to Perl code for "=cutX" where X is a non-alphabetic # character (which includes the newline, but here we chomped it away). $is_cut = $cmd =~ /^cut(?:[^a-zA-Z]|$)/; $in_pod = !$is_cut; } if ( $in_pod ) { if ( $line =~ /^=head[1-4]\s+(.+)\s*$/ ) { push( @pod, $1 ); if ( $self->{collect_pod} && length( $pod_data ) ) { $pod{$pod_sect} = $pod_data; $pod_data = ''; } $pod_sect = $1; } elsif ( $self->{collect_pod} ) { $pod_data .= "$line\n"; } } elsif ( $is_cut ) { if ( $self->{collect_pod} && length( $pod_data ) ) { $pod{$pod_sect} = $pod_data; $pod_data = ''; } $pod_sect = ''; } else { # Skip after __END__ next if $in_end; # Skip comments in code next if $line =~ /^\s*#/; # Would be nice if we could also check $in_string or something too if ($line eq '__END__') { $in_end++; next; } last if $line eq '__DATA__'; # parse $line to see if it's a $VERSION declaration my( $version_sigil, $version_fullname, $version_package ) = index($line, 'VERSION') >= 1 ? $self->_parse_version_expression( $line ) : (); if ( $line =~ /$PKG_REGEXP/o ) { $package = $1; my $version = $2; push( @packages, $package ) unless grep( $package eq $_, @packages ); $need_vers = defined $version ? 0 : 1; if ( not exists $vers{$package} and defined $version ){ # Upgrade to a version object. my $dwim_version = eval { _dwim_version($version) }; croak "Version '$version' from $self->{filename} does not appear to be valid:\n$line\n\nThe fatal error was: $@\n" unless defined $dwim_version; # "0" is OK! $vers{$package} = $dwim_version; } # VERSION defined with full package spec, i.e. $Module::VERSION } elsif ( $version_fullname && $version_package ) { push( @packages, $version_package ) unless grep( $version_package eq $_, @packages ); $need_vers = 0 if $version_package eq $package; unless ( defined $vers{$version_package} && length $vers{$version_package} ) { $vers{$version_package} = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line ); } # first non-comment line in undeclared package main is VERSION } elsif ( $package eq 'main' && $version_fullname && !exists($vers{main}) ) { $need_vers = 0; my $v = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line ); $vers{$package} = $v; push( @packages, 'main' ); # first non-comment line in undeclared package defines package main } elsif ( $package eq 'main' && !exists($vers{main}) && $line =~ /\w/ ) { $need_vers = 1; $vers{main} = ''; push( @packages, 'main' ); # only keep if this is the first $VERSION seen } elsif ( $version_fullname && $need_vers ) { $need_vers = 0; my $v = $self->_evaluate_version_line( $version_sigil, $version_fullname, $line ); unless ( defined $vers{$package} && length $vers{$package} ) { $vers{$package} = $v; } } } } if ( $self->{collect_pod} && length($pod_data) ) { $pod{$pod_sect} = $pod_data; } $self->{versions} = \%vers; $self->{packages} = \@packages; $self->{pod} = \%pod; $self->{pod_headings} = \@pod; } { my $pn = 0; sub _evaluate_version_line { my $self = shift; my( $sigil, $variable_name, $line ) = @_; # We compile into a local sub because 'use version' would cause # compiletime/runtime issues with local() $pn++; # everybody gets their own package my $eval = qq{ my \$dummy = q# Hide from _packages_inside() #; package Module::Metadata::_version::p${pn}; use version; sub { local $sigil$variable_name; $line; \$$variable_name }; }; $eval = $1 if $eval =~ m{^(.+)}s; local $^W; # Try to get the $VERSION my $vsub = __clean_eval($eval); # some modules say $VERSION <equal sign> $Foo::Bar::VERSION, but Foo::Bar isn't # installed, so we need to hunt in ./lib for it if ( $@ =~ /Can't locate/ && -d 'lib' ) { local @INC = ('lib',@INC); $vsub = __clean_eval($eval); } warn "Error evaling version line '$eval' in $self->{filename}: $@\n" if $@; (ref($vsub) eq 'CODE') or croak "failed to build version sub for $self->{filename}"; my $result = eval { $vsub->() }; # FIXME: $eval is not the right thing to print here croak "Could not get version from $self->{filename} by executing:\n$eval\n\nThe fatal error was: $@\n" if $@; # Upgrade it into a version object my $version = eval { _dwim_version($result) }; # FIXME: $eval is not the right thing to print here croak "Version '$result' from $self->{filename} does not appear to be valid:\n$eval\n\nThe fatal error was: $@\n" unless defined $version; # "0" is OK! return $version; } } # Try to DWIM when things fail the lax version test in obvious ways { my @version_prep = ( # Best case, it just works sub { return shift }, # If we still don't have a version, try stripping any # trailing junk that is prohibited by lax rules sub { my $v = shift; $v =~ s{([0-9])[a-z-].*$}{$1}i; # 1.23-alpha or 1.23b return $v; }, # Activestate apparently creates custom versions like '1.23_45_01', which # cause version.pm to think it's an invalid alpha. So check for that # and strip them sub { my $v = shift; my $num_dots = () = $v =~ m{(\.)}g; my $num_unders = () = $v =~ m{(_)}g; my $leading_v = substr($v,0,1) eq 'v'; if ( ! $leading_v && $num_dots < 2 && $num_unders > 1 ) { $v =~ s{_}{}g; $num_unders = () = $v =~ m{(_)}g; } return $v; }, # Worst case, try numifying it like we would have before version objects sub { my $v = shift; no warnings 'numeric'; return 0 + $v; }, ); sub _dwim_version { my ($result) = shift; return $result if ref($result) eq 'version'; my ($version, $error); for my $f (@version_prep) { $result = $f->($result); $version = eval { version->new($result) }; $error ||= $@ if $@; # capture first failure last if defined $version; } croak $error unless defined $version; return $version; } } ############################################################ # accessors sub name { $_[0]->{module} } sub filename { $_[0]->{filename} } sub packages_inside { @{$_[0]->{packages}} } sub pod_inside { @{$_[0]->{pod_headings}} } sub contains_pod { 0+@{$_[0]->{pod_headings}} } sub version { my $self = shift; my $mod = shift || $self->{module}; my $vers; if ( defined( $mod ) && length( $mod ) && exists( $self->{versions}{$mod} ) ) { return $self->{versions}{$mod}; } else { return undef; } } sub pod { my $self = shift; my $sect = shift; if ( defined( $sect ) && length( $sect ) && exists( $self->{pod}{$sect} ) ) { return $self->{pod}{$sect}; } else { return undef; } } sub is_indexable { my ($self, $package) = @_; my @indexable_packages = grep { $_ ne 'main' } $self->packages_inside; # check for specific package, if provided return !! grep { $_ eq $package } @indexable_packages if $package; # otherwise, check for any indexable packages at all return !! @indexable_packages; } 1; =head1 NAME Module::Metadata - Gather package and POD information from perl module files =head1 SYNOPSIS use Module::Metadata; # information about a .pm file my $info = Module::Metadata->new_from_file( $file ); my $version = $info->version; # CPAN META 'provides' field for .pm files in a directory my $provides = Module::Metadata->provides( dir => 'lib', version => 2 ); =head1 DESCRIPTION This module provides a standard way to gather metadata about a .pm file through (mostly) static analysis and (some) code execution. When determining the version of a module, the C<$VERSION> assignment is C<eval>ed, as is traditional in the CPAN toolchain. =head1 USAGE =head2 Class methods =over 4 =item C<< new_from_file($filename, collect_pod => 1) >> Constructs a C<Module::Metadata> object given the path to a file. Returns undef if the filename does not exist. C<collect_pod> is a optional boolean argument that determines whether POD data is collected and stored for reference. POD data is not collected by default. POD headings are always collected. If the file begins by an UTF-8, UTF-16BE or UTF-16LE byte-order mark, then it is skipped before processing, and the content of the file is also decoded appropriately starting from perl 5.8. =item C<< new_from_handle($handle, $filename, collect_pod => 1) >> This works just like C<new_from_file>, except that a handle can be provided as the first argument. Note that there is no validation to confirm that the handle is a handle or something that can act like one. Passing something that isn't a handle will cause a exception when trying to read from it. The C<filename> argument is mandatory or undef will be returned. You are responsible for setting the decoding layers on C<$handle> if required. =item C<< new_from_module($module, collect_pod => 1, inc => \@dirs) >> Constructs a C<Module::Metadata> object given a module or package name. Returns undef if the module cannot be found. In addition to accepting the C<collect_pod> argument as described above, this method accepts a C<inc> argument which is a reference to an array of directories to search for the module. If none are given, the default is @INC. If the file that contains the module begins by an UTF-8, UTF-16BE or UTF-16LE byte-order mark, then it is skipped before processing, and the content of the file is also decoded appropriately starting from perl 5.8. =item C<< find_module_by_name($module, \@dirs) >> Returns the path to a module given the module or package name. A list of directories can be passed in as an optional parameter, otherwise @INC is searched. Can be called as either an object or a class method. =item C<< find_module_dir_by_name($module, \@dirs) >> Returns the entry in C<@dirs> (or C<@INC> by default) that contains the module C<$module>. A list of directories can be passed in as an optional parameter, otherwise @INC is searched. Can be called as either an object or a class method. =item C<< provides( %options ) >> This is a convenience wrapper around C<package_versions_from_directory> to generate a CPAN META C<provides> data structure. It takes key/value pairs. Valid option keys include: =over =item version B<(required)> Specifies which version of the L<CPAN::Meta::Spec> should be used as the format of the C<provides> output. Currently only '1.4' and '2' are supported (and their format is identical). This may change in the future as the definition of C<provides> changes. The C<version> option is required. If it is omitted or if an unsupported version is given, then C<provides> will throw an error. =item dir Directory to search recursively for F<.pm> files. May not be specified with C<files>. =item files Array reference of files to examine. May not be specified with C<dir>. =item prefix String to prepend to the C<file> field of the resulting output. This defaults to F<lib>, which is the common case for most CPAN distributions with their F<.pm> files in F<lib>. This option ensures the META information has the correct relative path even when the C<dir> or C<files> arguments are absolute or have relative paths from a location other than the distribution root. =back For example, given C<dir> of 'lib' and C<prefix> of 'lib', the return value is a hashref of the form: { 'Package::Name' => { version => '0.123', file => 'lib/Package/Name.pm' }, 'OtherPackage::Name' => ... } =item C<< package_versions_from_directory($dir, \@files?) >> Scans C<$dir> for .pm files (unless C<@files> is given, in which case looks for those files in C<$dir> - and reads each file for packages and versions, returning a hashref of the form: { 'Package::Name' => { version => '0.123', file => 'Package/Name.pm' }, 'OtherPackage::Name' => ... } The C<DB> and C<main> packages are always omitted, as are any "private" packages that have leading underscores in the namespace (e.g. C<Foo::_private>) Note that the file path is relative to C<$dir> if that is specified. This B<must not> be used directly for CPAN META C<provides>. See the C<provides> method instead. =item C<< log_info (internal) >> Used internally to perform logging; imported from Log::Contextual if Log::Contextual has already been loaded, otherwise simply calls warn. =back =head2 Object methods =over 4 =item C<< name() >> Returns the name of the package represented by this module. If there is more than one package, it makes a best guess based on the filename. If it's a script (i.e. not a *.pm) the package name is 'main'. =item C<< version($package) >> Returns the version as defined by the $VERSION variable for the package as returned by the C<name> method if no arguments are given. If given the name of a package it will attempt to return the version of that package if it is specified in the file. =item C<< filename() >> Returns the absolute path to the file. =item C<< packages_inside() >> Returns a list of packages. Note: this is a raw list of packages discovered (or assumed, in the case of C<main>). It is not filtered for C<DB>, C<main> or private packages the way the C<provides> method does. Invalid package names are not returned, for example "Foo:Bar". Strange but valid package names are returned, for example "Foo::Bar::", and are left up to the caller on how to handle. =item C<< pod_inside() >> Returns a list of POD sections. =item C<< contains_pod() >> Returns true if there is any POD in the file. =item C<< pod($section) >> Returns the POD data in the given section. =item C<< is_indexable($package) >> or C<< is_indexable() >> Returns a boolean indicating whether the package (if provided) or any package (otherwise) is eligible for indexing by PAUSE, the Perl Authors Upload Server. Note This only checks for valid C<package> declarations, and does not take any ownership information into account. =back =head1 AUTHOR Original code from Module::Build::ModuleInfo by Ken Williams <kwilliams@cpan.org>, Randy W. Sims <RandyS@ThePierianSpring.org> Released as Module::Metadata by Matt S Trout (mst) <mst@shadowcat.co.uk> with assistance from David Golden (xdg) <dagolden@cpan.org>. =head1 COPYRIGHT & LICENSE Original code Copyright (c) 2001-2011 Ken Williams. Additional code Copyright (c) 2010-2011 Matt Trout and David Golden. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
{ "pile_set_name": "Github" }
/* ----------------------------------------------------------------------- tile.S - Copyright (c) 2011 Tilera Corp. Tilera TILEPro and TILE-Gx Foreign Function Interface 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. ----------------------------------------------------------------------- */ #define LIBFFI_ASM #include <fficonfig.h> #include <ffi.h> /* Number of bytes in a register. */ #define REG_SIZE FFI_SIZEOF_ARG /* Number of bytes in stack linkage area for backtracing. A note about the ABI: on entry to a procedure, sp points to a stack slot where it must spill the return address if it's not a leaf. REG_SIZE bytes beyond that is a slot owned by the caller which contains the sp value that the caller had when it was originally entered (i.e. the caller's frame pointer). */ #define LINKAGE_SIZE (2 * REG_SIZE) /* The first 10 registers are used to pass arguments and return values. */ #define NUM_ARG_REGS 10 #ifdef __tilegx__ #define SW st #define LW ld #define BGZT bgtzt #else #define SW sw #define LW lw #define BGZT bgzt #endif /* void ffi_call_tile (int_reg_t reg_args[NUM_ARG_REGS], const int_reg_t *stack_args, unsigned long stack_args_bytes, void (*fnaddr)(void)); On entry, REG_ARGS contain the outgoing register values, and STACK_ARGS contains STACK_ARG_BYTES of additional values to be passed on the stack. If STACK_ARG_BYTES is zero, then STACK_ARGS is ignored. When the invoked function returns, the values of r0-r9 are blindly stored back into REG_ARGS for the caller to examine. */ .section .text.ffi_call_tile, "ax", @progbits .align 8 .globl ffi_call_tile FFI_HIDDEN(ffi_call_tile) ffi_call_tile: /* Incoming arguments. */ #define REG_ARGS r0 #define INCOMING_STACK_ARGS r1 #define STACK_ARG_BYTES r2 #define ORIG_FNADDR r3 /* Temporary values. */ #define FRAME_SIZE r10 #define TMP r11 #define TMP2 r12 #define OUTGOING_STACK_ARGS r13 #define REG_ADDR_PTR r14 #define RETURN_REG_ADDR r15 #define FNADDR r16 .cfi_startproc { /* Save return address. */ SW sp, lr .cfi_offset lr, 0 /* Prepare to spill incoming r52. */ addi TMP, sp, -REG_SIZE /* Increase frame size to have room to spill r52 and REG_ARGS. The +7 is to round up mod 8. */ addi FRAME_SIZE, STACK_ARG_BYTES, \ REG_SIZE + REG_SIZE + LINKAGE_SIZE + 7 } { /* Round stack frame size to a multiple of 8 to satisfy ABI. */ andi FRAME_SIZE, FRAME_SIZE, -8 /* Compute where to spill REG_ARGS value. */ addi TMP2, sp, -(REG_SIZE * 2) } { /* Spill incoming r52. */ SW TMP, r52 .cfi_offset r52, -REG_SIZE /* Set up our frame pointer. */ move r52, sp .cfi_def_cfa_register r52 /* Push stack frame. */ sub sp, sp, FRAME_SIZE } { /* Prepare to set up stack linkage. */ addi TMP, sp, REG_SIZE /* Prepare to memcpy stack args. */ addi OUTGOING_STACK_ARGS, sp, LINKAGE_SIZE /* Save REG_ARGS which we will need after we call the subroutine. */ SW TMP2, REG_ARGS } { /* Set up linkage info to hold incoming stack pointer. */ SW TMP, r52 } { /* Skip stack args memcpy if we don't have any stack args (common). */ blezt STACK_ARG_BYTES, .Ldone_stack_args_memcpy } .Lmemcpy_stack_args: { /* Load incoming argument from stack_args. */ LW TMP, INCOMING_STACK_ARGS addi INCOMING_STACK_ARGS, INCOMING_STACK_ARGS, REG_SIZE } { /* Store stack argument into outgoing stack argument area. */ SW OUTGOING_STACK_ARGS, TMP addi OUTGOING_STACK_ARGS, OUTGOING_STACK_ARGS, REG_SIZE addi STACK_ARG_BYTES, STACK_ARG_BYTES, -REG_SIZE } { BGZT STACK_ARG_BYTES, .Lmemcpy_stack_args } .Ldone_stack_args_memcpy: { /* Copy aside ORIG_FNADDR so we can overwrite its register. */ move FNADDR, ORIG_FNADDR /* Prepare to load argument registers. */ addi REG_ADDR_PTR, r0, REG_SIZE /* Load outgoing r0. */ LW r0, r0 } /* Load up argument registers from the REG_ARGS array. */ #define LOAD_REG(REG, PTR) \ { \ LW REG, PTR ; \ addi PTR, PTR, REG_SIZE \ } LOAD_REG(r1, REG_ADDR_PTR) LOAD_REG(r2, REG_ADDR_PTR) LOAD_REG(r3, REG_ADDR_PTR) LOAD_REG(r4, REG_ADDR_PTR) LOAD_REG(r5, REG_ADDR_PTR) LOAD_REG(r6, REG_ADDR_PTR) LOAD_REG(r7, REG_ADDR_PTR) LOAD_REG(r8, REG_ADDR_PTR) LOAD_REG(r9, REG_ADDR_PTR) { /* Call the subroutine. */ jalr FNADDR } { /* Restore original lr. */ LW lr, r52 /* Prepare to recover ARGS, which we spilled earlier. */ addi TMP, r52, -(2 * REG_SIZE) } { /* Restore ARGS, so we can fill it in with the return regs r0-r9. */ LW RETURN_REG_ADDR, TMP /* Prepare to restore original r52. */ addi TMP, r52, -REG_SIZE } { /* Pop stack frame. */ move sp, r52 /* Restore original r52. */ LW r52, TMP } #define STORE_REG(REG, PTR) \ { \ SW PTR, REG ; \ addi PTR, PTR, REG_SIZE \ } /* Return all register values by reference. */ STORE_REG(r0, RETURN_REG_ADDR) STORE_REG(r1, RETURN_REG_ADDR) STORE_REG(r2, RETURN_REG_ADDR) STORE_REG(r3, RETURN_REG_ADDR) STORE_REG(r4, RETURN_REG_ADDR) STORE_REG(r5, RETURN_REG_ADDR) STORE_REG(r6, RETURN_REG_ADDR) STORE_REG(r7, RETURN_REG_ADDR) STORE_REG(r8, RETURN_REG_ADDR) STORE_REG(r9, RETURN_REG_ADDR) { jrp lr } .cfi_endproc .size ffi_call_tile, .-ffi_call_tile /* ffi_closure_tile(...) On entry, lr points to the closure plus 8 bytes, and r10 contains the actual return address. This function simply dumps all register parameters into a stack array and passes the closure, the registers array, and the stack arguments to C code that does all of the actual closure processing. */ .section .text.ffi_closure_tile, "ax", @progbits .align 8 .globl ffi_closure_tile FFI_HIDDEN(ffi_closure_tile) .cfi_startproc /* Room to spill all NUM_ARG_REGS incoming registers, plus frame linkage. */ #define CLOSURE_FRAME_SIZE (((NUM_ARG_REGS * REG_SIZE * 2 + LINKAGE_SIZE) + 7) & -8) ffi_closure_tile: { #ifdef __tilegx__ st sp, lr .cfi_offset lr, 0 #else /* Save return address (in r10 due to closure stub wrapper). */ SW sp, r10 .cfi_return_column r10 .cfi_offset r10, 0 #endif /* Compute address for stack frame linkage. */ addli r10, sp, -(CLOSURE_FRAME_SIZE - REG_SIZE) } { /* Save incoming stack pointer in linkage area. */ SW r10, sp .cfi_offset sp, -(CLOSURE_FRAME_SIZE - REG_SIZE) /* Push a new stack frame. */ addli sp, sp, -CLOSURE_FRAME_SIZE .cfi_adjust_cfa_offset CLOSURE_FRAME_SIZE } { /* Create pointer to where to start spilling registers. */ addi r10, sp, LINKAGE_SIZE } /* Spill all the incoming registers. */ STORE_REG(r0, r10) STORE_REG(r1, r10) STORE_REG(r2, r10) STORE_REG(r3, r10) STORE_REG(r4, r10) STORE_REG(r5, r10) STORE_REG(r6, r10) STORE_REG(r7, r10) STORE_REG(r8, r10) { /* Save r9. */ SW r10, r9 #ifdef __tilegx__ /* Pointer to closure is passed in r11. */ move r0, r11 #else /* Compute pointer to the closure object. Because the closure starts with a "jal ffi_closure_tile", we can just take the value of lr (a phony return address pointing into the closure) and subtract 8. */ addi r0, lr, -8 #endif /* Compute a pointer to the register arguments we just spilled. */ addi r1, sp, LINKAGE_SIZE } { /* Compute a pointer to the extra stack arguments (if any). */ addli r2, sp, CLOSURE_FRAME_SIZE + LINKAGE_SIZE /* Call C code to deal with all of the grotty details. */ jal ffi_closure_tile_inner } { addli r10, sp, CLOSURE_FRAME_SIZE } { /* Restore the return address. */ LW lr, r10 /* Compute pointer to registers array. */ addli r10, sp, LINKAGE_SIZE + (NUM_ARG_REGS * REG_SIZE) } /* Return all the register values, which C code may have set. */ LOAD_REG(r0, r10) LOAD_REG(r1, r10) LOAD_REG(r2, r10) LOAD_REG(r3, r10) LOAD_REG(r4, r10) LOAD_REG(r5, r10) LOAD_REG(r6, r10) LOAD_REG(r7, r10) LOAD_REG(r8, r10) LOAD_REG(r9, r10) { /* Pop the frame. */ addli sp, sp, CLOSURE_FRAME_SIZE jrp lr } .cfi_endproc .size ffi_closure_tile, . - ffi_closure_tile /* What follows are code template instructions that get copied to the closure trampoline by ffi_prep_closure_loc. The zeroed operands get replaced by their proper values at runtime. */ .section .text.ffi_template_tramp_tile, "ax", @progbits .align 8 .globl ffi_template_tramp_tile FFI_HIDDEN(ffi_template_tramp_tile) ffi_template_tramp_tile: #ifdef __tilegx__ { moveli r11, 0 /* backpatched to address of containing closure. */ moveli r10, 0 /* backpatched to ffi_closure_tile. */ } /* Note: the following bundle gets generated multiple times depending on the pointer value (esp. useful for -m32 mode). */ { shl16insli r11, r11, 0 ; shl16insli r10, r10, 0 } { info 2+8 /* for backtracer: -> pc in lr, frame size 0 */ ; jr r10 } #else /* 'jal .' yields a PC-relative offset of zero so we can OR in the right offset at runtime. */ { move r10, lr ; jal . /* ffi_closure_tile */ } #endif .size ffi_template_tramp_tile, . - ffi_template_tramp_tile
{ "pile_set_name": "Github" }
// Word Break // 深搜,超时 // 时间复杂度O(2^n),空间复杂度O(n) class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { return dfs(s, dict, 0, 1); } private: static bool dfs(const string &s, unordered_set<string> &dict, size_t start, size_t cur) { if (cur == s.size()) { return dict.find(s.substr(start, cur-start)) != dict.end(); } if (dfs(s, dict, start, cur+1)) return true; // no cut if (dict.find(s.substr(start, cur-start)) != dict.end()) // cut here if (dfs(s, dict, cur+1, cur+1)) return true; return false; } };
{ "pile_set_name": "Github" }
package test type typeForTest []bool
{ "pile_set_name": "Github" }
# vi:filetype= use lib 'lib'; use Test::Nginx::Socket; #repeat_each(10); no_shuffle(); repeat_each(2); plan tests => repeat_each() * 2 * blocks() + 2 * repeat_each() * 3; $ENV{TEST_NGINX_MYSQL_HOST} ||= '127.0.0.1'; $ENV{TEST_NGINX_MYSQL_PORT} ||= 3306; our $http_config = <<'_EOC_'; upstream backend { drizzle_server $TEST_NGINX_MYSQL_HOST:$TEST_NGINX_MYSQL_PORT protocol=mysql dbname=ngx_test user=ngx_test password=ngx_test; } _EOC_ #no_long_string(); run_tests(); #no_diff(); __DATA__ === TEST 1: sanity --- http_config eval: $::http_config --- config location /mysql { drizzle_pass backend; #drizzle_dbname $dbname; drizzle_query 'select * from cats'; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /mysql --- response_headers_like X-Resty-DBD-Module: ngx_drizzle \d+\.\d+\.\d+ Content-Type: application/json --- response_body chomp [["id","name"],[2,null],[3,"bob"]] --- timeout: 15 === TEST 2: keep-alive --- http_config eval: $::http_config --- config location /mysql { drizzle_pass backend; #drizzle_dbname $dbname; drizzle_query 'select * from cats'; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /mysql --- response_body chop [["id","name"],[2,null],[3,"bob"]] === TEST 3: update --- http_config eval: $::http_config --- config location /mysql { drizzle_pass backend; #drizzle_dbname $dbname; drizzle_query "update cats set name='bob' where name='bob'"; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /mysql --- response_body chop {"errcode":0,"errstr":"Rows matched: 1 Changed: 0 Warnings: 0"} === TEST 4: select empty result --- http_config eval: $::http_config --- config location /mysql { drizzle_pass backend; drizzle_query "select * from cats where name='tom'"; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /mysql --- response_body chop [["id","name"]] === TEST 5: update & no module header --- http_config eval: $::http_config --- config location /mysql { if ($arg_name ~ '[^A-Za-z0-9]') { return 400; } drizzle_pass backend; drizzle_module_header off; drizzle_query "update cats set name='$arg_name' where name='$arg_name'"; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /mysql?name=bob --- response_headers X-Resty-DBD-Module: Content-Type: application/json --- response_body chop {"errcode":0,"errstr":"Rows matched: 1 Changed: 0 Warnings: 0"} === TEST 6: invalid SQL --- http_config eval: $::http_config --- config location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query "select '32"; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- response_headers X-Resty-DBD-Module: Content-Type: text/html --- request GET /mysql --- error_code: 500 --- response_body_like: 500 Internal Server Error === TEST 7: single row, single col --- http_config eval: $::http_config --- config location /test { echo_location /mysql "drop table if exists singles"; echo; echo_location /mysql "create table singles (name varchar(15));"; echo; echo_location /mysql "insert into singles values ('marry');"; echo; echo_location /mysql "select * from singles;"; echo; } location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query $query_string; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /test --- response_body {"errcode":0} {"errcode":0} {"errcode":0,"affected_rows":1} [["name"],["marry"]] --- skip_nginx: 2: < 0.7.46 --- timeout: 5 === TEST 8: floating number and insert id --- http_config eval: $::http_config --- config location /test { echo_location /mysql "drop table if exists foo"; echo; echo_location /mysql "create table foo (id serial not null, primary key (id), val real);"; echo; echo_location /mysql "insert into foo (val) values (3.1415926);"; echo; echo_location /mysql "select * from foo;"; echo; } location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query $query_string; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /test --- response_body {"errcode":0} {"errcode":0} {"errcode":0,"insert_id":1,"affected_rows":1} [["id","val"],[1,3.1415926]] --- skip_nginx: 2: < 0.7.46 === TEST 9: text blob field --- http_config eval: $::http_config --- config location /test { echo_location /mysql "drop table if exists foo"; echo; echo_location /mysql "create table foo (id serial, body text);"; echo; echo_location /mysql "insert into foo (body) values ('hello');"; echo; echo_location /mysql "select * from foo;"; echo; } location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query $query_string; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /test --- response_body {"errcode":0} {"errcode":0} {"errcode":0,"insert_id":1,"affected_rows":1} [["id","body"],[1,"hello"]] --- skip_nginx: 2: < 0.7.46 === TEST 10: bool blob field --- http_config eval: $::http_config --- config location /test { echo_location /mysql "drop table if exists foo"; echo; echo_location /mysql "create table foo (id serial, flag bool);"; echo; echo_location /mysql "insert into foo (flag) values (true);"; echo; echo_location /mysql "insert into foo (flag) values (false);"; echo; echo_location /mysql "select * from foo order by id;"; echo; } location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query $query_string; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /test --- response_body {"errcode":0} {"errcode":0} {"errcode":0,"insert_id":1,"affected_rows":1} {"errcode":0,"insert_id":2,"affected_rows":1} [["id","flag"],[1,1],[2,0]] --- skip_nginx: 2: < 0.7.46 --- timeout: 10 === TEST 11: bit field --- http_config eval: $::http_config --- config location /test { echo_location /mysql "drop table if exists foo"; echo; echo_location /mysql "create table foo (id serial, flag bit);"; echo; echo_location /mysql "insert into foo (flag) values (1);"; echo; echo_location /mysql "insert into foo (flag) values (0);"; echo; echo_location /mysql "select * from foo order by id;"; echo; } location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query $query_string; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /test --- response_body {"errcode":0} {"errcode":0} {"errcode":0,"insert_id":1,"affected_rows":1} {"errcode":0,"insert_id":2,"affected_rows":1} [["id","flag"],[1,"\u0001"],[2,"\u0000"]] --- skip_nginx: 2: < 0.7.46 --- timeout: 10 === TEST 12: date type --- http_config eval: $::http_config --- config location /test { echo_location /mysql "drop table if exists foo"; echo; echo_location /mysql "create table foo (id serial, created date);"; echo; echo_location /mysql "insert into foo (created) values ('2007-05-24');"; echo; echo_location /mysql "select * from foo"; echo; } location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query $query_string; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /test --- response_body {"errcode":0} {"errcode":0} {"errcode":0,"insert_id":1,"affected_rows":1} [["id","created"],[1,"2007-05-24"]] === TEST 13: strings need to be escaped --- http_config eval: $::http_config --- config location /test { echo_location /mysql "drop table if exists foo"; echo; echo_location /mysql "create table foo (id serial, body char(25));"; echo; echo_location /mysql "insert into foo (body) values ('a\\r\\nb\\bhello\Z');"; echo; echo_location /mysql "select * from foo"; echo; } location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query $query_string; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /test --- response_body {"errcode":0} {"errcode":0} {"errcode":0,"insert_id":1,"affected_rows":1} [["id","body"],[1,"a\r\nb\bhello\u001a"]] === TEST 14: null values --- http_config eval: $::http_config --- config location /test { echo_location /mysql "drop table if exists foo"; echo; echo_location /mysql "create table foo (id serial, name char(10), age integer);"; echo; echo_location /mysql "insert into foo (name, age) values ('', null);"; echo; echo_location /mysql "insert into foo (name, age) values (null, 0);"; echo; echo_location /mysql "select * from foo order by id"; echo; } location /mysql { drizzle_pass backend; drizzle_module_header off; drizzle_query $query_string; rds_json on; rds_json_format compact; drizzle_buffer_size 1; } --- request GET /test --- response_body {"errcode":0} {"errcode":0} {"errcode":0,"insert_id":1,"affected_rows":1} {"errcode":0,"insert_id":2,"affected_rows":1} [["id","name","age"],[1,"",null],[2,null,0]] --- timeout: 10
{ "pile_set_name": "Github" }
#title: Nutz 该如何发音 #author:zozoh(zozohtnt@gmail.com) ------------------------------------------------------------------------ 问题来自 {*不知名网友} 读作 “纳特Z(Z发重音)” 另外,Nutz 的 Nut 是因为霍金的《果壳中的宇宙》是 zozoh 最喜欢的一本书之一。 Z 是 zozoh 小时,动画片《佐罗》给他很深的印象,尤其是每次转场的中间动画都是 佐罗的剑在黑色的空中 唰唰唰 三下划出锋利的 Z 字,好像三道闪电,酷的要命。 同时 zozoh 本人姓张,所以他很高兴在 Nut 后面 唰唰唰 的来一个 Z
{ "pile_set_name": "Github" }
// Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // Preprocessed version of "boost/mpl/deque.hpp" header // -- DO NOT modify by hand! namespace boost { namespace mpl { template< typename T0 = na, typename T1 = na, typename T2 = na, typename T3 = na , typename T4 = na, typename T5 = na, typename T6 = na, typename T7 = na , typename T8 = na, typename T9 = na, typename T10 = na, typename T11 = na , typename T12 = na, typename T13 = na, typename T14 = na , typename T15 = na, typename T16 = na, typename T17 = na , typename T18 = na, typename T19 = na > struct deque; template< > struct deque< na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na , na, na, na > : vector0< > { typedef vector0< >::type type; }; template< typename T0 > struct deque< T0, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na , na, na, na > : vector1<T0> { typedef typename vector1<T0>::type type; }; template< typename T0, typename T1 > struct deque< T0, T1, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na , na, na, na > : vector2< T0,T1 > { typedef typename vector2< T0,T1 >::type type; }; template< typename T0, typename T1, typename T2 > struct deque< T0, T1, T2, na, na, na, na, na, na, na, na, na, na, na, na, na, na , na, na, na > : vector3< T0,T1,T2 > { typedef typename vector3< T0,T1,T2 >::type type; }; template< typename T0, typename T1, typename T2, typename T3 > struct deque< T0, T1, T2, T3, na, na, na, na, na, na, na, na, na, na, na, na, na , na, na, na > : vector4< T0,T1,T2,T3 > { typedef typename vector4< T0,T1,T2,T3 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 > struct deque< T0, T1, T2, T3, T4, na, na, na, na, na, na, na, na, na, na, na, na , na, na, na > : vector5< T0,T1,T2,T3,T4 > { typedef typename vector5< T0,T1,T2,T3,T4 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5 > struct deque< T0, T1, T2, T3, T4, T5, na, na, na, na, na, na, na, na, na, na, na , na, na, na > : vector6< T0,T1,T2,T3,T4,T5 > { typedef typename vector6< T0,T1,T2,T3,T4,T5 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6 > struct deque< T0, T1, T2, T3, T4, T5, T6, na, na, na, na, na, na, na, na, na, na , na, na, na > : vector7< T0,T1,T2,T3,T4,T5,T6 > { typedef typename vector7< T0,T1,T2,T3,T4,T5,T6 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, na, na, na, na, na, na, na, na, na , na, na, na > : vector8< T0,T1,T2,T3,T4,T5,T6,T7 > { typedef typename vector8< T0,T1,T2,T3,T4,T5,T6,T7 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, na, na, na, na, na, na, na, na , na, na, na > : vector9< T0,T1,T2,T3,T4,T5,T6,T7,T8 > { typedef typename vector9< T0,T1,T2,T3,T4,T5,T6,T7,T8 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, na, na, na, na, na, na, na , na, na, na > : vector10< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9 > { typedef typename vector10< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, na, na, na, na, na, na , na, na, na > : vector11< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10 > { typedef typename vector11< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, na, na, na, na , na, na, na, na > : vector12< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11 > { typedef typename vector12< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11, typename T12 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, na, na, na , na, na, na, na > : vector13< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12 > { typedef typename vector13< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11, typename T12, typename T13 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, na, na , na, na, na, na > : vector14< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13 > { typedef typename vector14< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11, typename T12, typename T13, typename T14 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, na , na, na, na, na > : vector15< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 > { typedef typename vector15< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11, typename T12, typename T13, typename T14 , typename T15 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15, na, na, na, na > : vector16< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15 > { typedef typename vector16< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11, typename T12, typename T13, typename T14 , typename T15, typename T16 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15, T16, na, na, na > : vector17< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15, T16 > { typedef typename vector17< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11, typename T12, typename T13, typename T14 , typename T15, typename T16, typename T17 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15, T16, T17, na, na > : vector18< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15, T16, T17 > { typedef typename vector18< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17 >::type type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11, typename T12, typename T13, typename T14 , typename T15, typename T16, typename T17, typename T18 > struct deque< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15, T16, T17, T18, na > : vector19< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15, T16, T17, T18 > { typedef typename vector19< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18 >::type type; }; /// primary template (not a specialization!) template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 , typename T10, typename T11, typename T12, typename T13, typename T14 , typename T15, typename T16, typename T17, typename T18, typename T19 > struct deque : vector20< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 , T15, T16, T17, T18, T19 > { typedef typename vector20< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19 >::type type; }; }}
{ "pile_set_name": "Github" }
using System.Collections.Generic; namespace AccountGoWeb.Models.Sales { public class Allocate { [System.ComponentModel.DataAnnotations.Required] public int? CustomerId { get; set; } [System.ComponentModel.DataAnnotations.Required] public int? ReceiptId { get; set; } [System.ComponentModel.DataAnnotations.Required] public System.DateTime Date { get; set; } public decimal Amount { get; set; } public decimal RemainingAmountToAllocate { get; set; } public decimal SumAllocatedAmount { get { return ComputeSumToAllocateAmount(); } } public IList<AllocationLine> AllocationLines { get; set; } public Allocate() { AllocationLines = new List<AllocationLine>(); } private decimal ComputeSumToAllocateAmount() { decimal sum = 0; foreach (var line in AllocationLines) { sum += line.AmountToAllocate.GetValueOrDefault(); } return sum; } public bool IsValid() { if (RemainingAmountToAllocate < SumAllocatedAmount) return false; else return true; } } public class AllocationLine { [System.ComponentModel.DataAnnotations.Required] public int? InvoiceId { get; set; } public decimal? Amount { get; set; } public decimal? AllocatedAmount { get; set; } public decimal? AmountToAllocate { get; set; } } }
{ "pile_set_name": "Github" }
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 5, transform = "Integration", sigma = 0.0, exog_count = 20, ar_order = 0);
{ "pile_set_name": "Github" }
unsat
{ "pile_set_name": "Github" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.ML.Probabilistic.Models; using Microsoft.ML.Probabilistic.Distributions; using Microsoft.ML.Probabilistic.Math; using Range = Microsoft.ML.Probabilistic.Models.Range; namespace Microsoft.ML.Probabilistic.Tutorials { [Example("Applications", "Multinomial regression")] public class MultinomialRegression { /// <summary> /// For the multinomial regression model: generate synthetic data, /// infer the model parameters and calculate the RMSE between the true /// and mean inferred coefficients. /// </summary> public void Run() { // This example requires VMP InferenceEngine engine = new InferenceEngine(); if (!(engine.Algorithm is Algorithms.VariationalMessagePassing)) { Console.WriteLine("This example only runs with Variational Message Passing"); return; } int numSamples = 1000; int numFeatures = 6; int numClasses = 4; int countPerSample = 10; var features = new Vector[numSamples]; var counts = new int[numSamples][]; var coefficients = new Vector[numClasses]; var mean = Vector.Zero(numClasses); Rand.Restart(1); for (int i = 0; i < numClasses - 1; i++) { mean[i] = Rand.Normal(); coefficients[i] = Vector.Zero(numFeatures); Rand.Normal(Vector.Zero(numFeatures), PositiveDefiniteMatrix.Identity(numFeatures), coefficients[i]); } mean[numClasses - 1] = 0; coefficients[numClasses - 1] = Vector.Zero(numFeatures); for (int i = 0; i < numSamples; i++) { features[i] = Vector.Zero(numFeatures); Rand.Normal(Vector.Zero(numFeatures), PositiveDefiniteMatrix.Identity(numFeatures), features[i]); var temp = Vector.FromArray(coefficients.Select(o => o.Inner(features[i])).ToArray()); var p = MMath.Softmax(temp + mean); counts[i] = Rand.Multinomial(countPerSample, p); } Rand.Restart(DateTime.Now.Millisecond); VectorGaussian[] bPost; Gaussian[] meanPost; MultinomialRegressionModel(features, counts, out bPost, out meanPost); var bMeans = bPost.Select(o => o.GetMean()).ToArray(); var bVars = bPost.Select(o => o.GetVariance()).ToArray(); double error = 0; Console.WriteLine("Coefficients -------------- "); for (int i = 0; i < numClasses; i++) { error += (bMeans[i] - coefficients[i]).Sum(o => o * o); Console.WriteLine("Class {0} True {1}", i, coefficients[i]); Console.WriteLine("Class {0} Inferred {1}", i, bMeans[i]); } Console.WriteLine("Mean True " + mean); Console.WriteLine("Mean Inferred " + Vector.FromArray(meanPost.Select(o => o.GetMean()).ToArray())); error = System.Math.Sqrt(error / (numClasses * numFeatures)); Console.WriteLine("RMSE is {0}", error); } /// <summary> /// Build and run a multinomial regression model. /// </summary> /// <param name="xObs">An array of vectors of observed inputs. /// The length of the array is the number of samples, and the /// length of the vectors is the number of input features. </param> /// <param name="yObs">An array of array of counts, where the first index is the sample, /// and the second index is the class. </param> /// <param name="bPost">The returned posterior over the coefficients.</param> /// <param name="meanPost">The returned posterior over the means.</param> public void MultinomialRegressionModel( Vector[] xObs, int[][] yObs, out VectorGaussian[] bPost, out Gaussian[] meanPost) { int C = yObs[0].Length; int N = xObs.Length; int K = xObs[0].Count; var c = new Range(C).Named("c"); var n = new Range(N).Named("n"); // model var B = Variable.Array<Vector>(c).Named("coefficients"); B[c] = Variable.VectorGaussianFromMeanAndPrecision( Vector.Zero(K), PositiveDefiniteMatrix.Identity(K)).ForEach(c); var m = Variable.Array<double>(c).Named("mean"); m[c] = Variable.GaussianFromMeanAndPrecision(0, 1).ForEach(c); Variable.ConstrainEqualRandom(B[C - 1], VectorGaussian.PointMass(Vector.Zero(K))); Variable.ConstrainEqualRandom(m[C - 1], Gaussian.PointMass(0)); var x = Variable.Array<Vector>(n); x.ObservedValue = xObs; var yData = Variable.Array(Variable.Array<int>(c), n); yData.ObservedValue = yObs; var trialsCount = Variable.Array<int>(n); trialsCount.ObservedValue = yObs.Select(o => o.Sum()).ToArray(); var g = Variable.Array(Variable.Array<double>(c), n); g[n][c] = Variable.InnerProduct(B[c], x[n]) + m[c]; var p = Variable.Array<Vector>(n); p[n] = Variable.Softmax(g[n]); using (Variable.ForEach(n)) { yData[n] = Variable.Multinomial(trialsCount[n], p[n]); } // inference var ie = new InferenceEngine(); bPost = ie.Infer<VectorGaussian[]>(B); meanPost = ie.Infer<Gaussian[]>(m); } } }
{ "pile_set_name": "Github" }
/* Copyright (c) 2016 Raspberry Pi (Trading) 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: * 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 copyright holder 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 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. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdarg.h> #include <sys/stat.h> #include <errno.h> #include "utils.h" #define OVERLAY_HELP_INDENT 8 int opt_verbose; int opt_dry_run; static STRING_T *allocated_strings; struct overlay_help_state_struct { FILE *fp; long rec_pos; int line_len; int line_pos; int blank_count; int end_of_field; char line_buf[82]; }; static int overlay_help_get_line(OVERLAY_HELP_STATE_T *state); OVERLAY_HELP_STATE_T *overlay_help_open(const char *helpfile) { OVERLAY_HELP_STATE_T *state = NULL; FILE *fp = fopen(helpfile, "r"); if (fp) { state = calloc(1, sizeof(OVERLAY_HELP_STATE_T)); if (!state) fatal_error("Out of memory"); state->fp = fp; state->line_pos = -1; state->rec_pos = -1; } return state; } void overlay_help_close(OVERLAY_HELP_STATE_T *state) { fclose(state->fp); free(state); } int overlay_help_find(OVERLAY_HELP_STATE_T *state, const char *name) { state->line_pos = -1; state->rec_pos = -1; state->blank_count = 0; fseek(state->fp, 0, SEEK_SET); while (overlay_help_find_field(state, "Name")) { const char *overlay = overlay_help_field_data(state); if (overlay && (strcmp(overlay, name) == 0)) { state->rec_pos = (long)ftell(state->fp); return 1; } } return 0; } int overlay_help_find_field(OVERLAY_HELP_STATE_T *state, const char *field) { int field_len = strlen(field); int found = 0; if (state->rec_pos >= 0) fseek(state->fp, state->rec_pos, SEEK_SET); while (!found) { int line_len = overlay_help_get_line(state); if (line_len < 0) break; /* Check for the "<field>:" prefix */ if ((line_len >= (field_len + 1)) && (state->line_buf[field_len] == ':') && (memcmp(state->line_buf, field, field_len) == 0)) { /* Found it If this initial line has no content then skip it */ if (line_len > OVERLAY_HELP_INDENT) state->line_pos = OVERLAY_HELP_INDENT; else state->line_pos = -1; state->end_of_field = 0; found = 1; } else { state->line_pos = -1; } } return found; } const char *overlay_help_field_data(OVERLAY_HELP_STATE_T *state) { int line_len, pos; if (state->end_of_field) return NULL; line_len = state->line_len; if ((state->line_pos < 0) || (state->line_pos >= line_len)) { line_len = overlay_help_get_line(state); /* Fields end at the start of the next field or the end of the record */ if ((line_len < 0) || (state->line_buf[0] != ' ')) { state->end_of_field = 1; return NULL; } if (line_len == 0) return ""; } /* Return field data starting at OVERLAY_HELP_INDENT, if there is any */ pos = line_len; if (pos > OVERLAY_HELP_INDENT) pos = OVERLAY_HELP_INDENT; state->line_pos = -1; return &state->line_buf[pos]; } void overlay_help_print_field(OVERLAY_HELP_STATE_T *state, const char *field, const char *label, int indent, int strip_blanks) { if (!overlay_help_find_field(state, field)) return; while (1) { const char *line = overlay_help_field_data(state); if (!line) break; if (label) { int spaces = indent - strlen(label); if (spaces < 0) spaces = 0; printf("%s%*s%s\n", label, spaces, "", line); label = NULL; } else if (line[0]) { printf("%*s%s\n", indent, "", line); } else if (!strip_blanks) { printf("\n"); } } if (!strip_blanks) printf("\n"); } /* Returns the length of the line, or -1 on end of file or record */ static int overlay_help_get_line(OVERLAY_HELP_STATE_T *state) { int line_len; if (state->line_pos >= 0) return state->line_len; get_next_line: state->line_buf[sizeof(state->line_buf) - 1] = ' '; line_len = -1; if (fgets(state->line_buf, sizeof(state->line_buf), state->fp)) { // Check for overflow // Strip the newline line_len = strlen(state->line_buf); if (line_len && (state->line_buf[line_len - 1] == '\n')) { line_len--; state->line_buf[line_len] = '\0'; } } if (state->rec_pos >= 0) { if (line_len == 0) { state->blank_count++; if (state->blank_count >= 2) return -1; state->line_pos = 0; goto get_next_line; } else if (state->blank_count) { /* Return a single blank line now - the non-empty line will be returned next time */ state->blank_count = 0; return 0; } } state->line_len = line_len; state->line_pos = (line_len >= 0) ? 0 : -1; return line_len; } int run_cmd(const char *fmt, ...) { va_list ap; char *cmd; int ret; va_start(ap, fmt); cmd = vsprintf_dup(fmt, ap); va_end(ap); if (opt_dry_run || opt_verbose) fprintf(stderr, "run_cmd: %s\n", cmd); ret = opt_dry_run ? 0 : system(cmd); free_string(cmd); return ret; } /* Not thread safe */ void free_string(const char *string) { STRING_T *str; if (!string) return; str = (STRING_T *)(string - sizeof(STRING_T)); if (str == allocated_strings) { allocated_strings = str->next; if (allocated_strings == str) allocated_strings = NULL; } str->prev->next = str->next; str->next->prev = str->prev; free(str); } /* Not thread safe */ void free_strings(void) { if (allocated_strings) { STRING_T *str = allocated_strings; do { STRING_T *t = str; str = t->next; free(t); } while (str != allocated_strings); allocated_strings = NULL; } } /* Not thread safe */ char *sprintf_dup(const char *fmt, ...) { va_list ap; char *str; va_start(ap, fmt); str = vsprintf_dup(fmt, ap); va_end(ap); return str; } /* Not thread safe */ char *vsprintf_dup(const char *fmt, va_list ap) { char scratch[512]; int len; STRING_T *str; len = vsnprintf(scratch, sizeof(scratch), fmt, ap) + 1; if (len > sizeof(scratch)) fatal_error("Maximum string length exceeded"); str = malloc(sizeof(STRING_T) + len); if (!str) fatal_error("Out of memory"); memcpy(str->data, scratch, len); if (allocated_strings) { str->next = allocated_strings; str->prev = allocated_strings->prev; str->next->prev = str; str->prev->next = str; } else { str->next = str; str->prev = str; allocated_strings = str; } return str->data; } int dir_exists(const char *dirname) { struct stat finfo; return (stat(dirname, &finfo) == 0) && S_ISDIR(finfo.st_mode); } int file_exists(const char *dirname) { struct stat finfo; return (stat(dirname, &finfo) == 0) && S_ISREG(finfo.st_mode); } void string_vec_init(STRING_VEC_T *vec) { vec->num_strings = 0; vec->max_strings = 0; vec->strings = NULL; } char *string_vec_add(STRING_VEC_T *vec, const char *str, int len) { char *copy; if (vec->num_strings == vec->max_strings) { if (vec->max_strings) vec->max_strings *= 2; else vec->max_strings = 16; vec->strings = realloc(vec->strings, vec->max_strings * sizeof(const char *)); if (!vec->strings) fatal_error("Out of memory"); } if (len) { copy = malloc(len + 1); strncpy(copy, str, len); copy[len] = '\0'; } else copy = strdup(str); if (!copy) fatal_error("Out of memory"); vec->strings[vec->num_strings++] = copy; return copy; } int string_vec_find(STRING_VEC_T *vec, const char *str, int len) { int i; for (i = 0; i < vec->num_strings; i++) { if (len) { if ((strncmp(vec->strings[i], str, len) == 0) && (vec->strings[i][len] == '\0')) return i; } else if (strcmp(vec->strings[i], str) == 0) return i; } return -1; } int string_vec_compare(const void *a, const void *b) { return strcmp(*(const char **)a, *(const char **)b); } void string_vec_sort(STRING_VEC_T *vec) { qsort(vec->strings, vec->num_strings, sizeof(char *), &string_vec_compare); } void string_vec_uninit(STRING_VEC_T *vec) { int i; for (i = 0; i < vec->num_strings; i++) free(vec->strings[i]); free(vec->strings); } int error(const char *fmt, ...) { va_list ap; fprintf(stderr, "* "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); return 1; } void fatal_error(const char *fmt, ...) { va_list ap; fprintf(stderr, "* "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); exit(1); }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2006 The Android Open Source Project * * 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 android.database.sqlite; import android.database.SQLException; /** * A SQLite exception that indicates there was an error with SQL parsing or execution. */ public class SQLiteException extends SQLException { public SQLiteException() { } public SQLiteException(String error) { super(error); } public SQLiteException(String error, Throwable cause) { super(error, cause); } }
{ "pile_set_name": "Github" }
{ "_from": "json-schema-traverse@^0.3.0", "_id": "json-schema-traverse@0.3.1", "_inBundle": false, "_integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=", "_location": "/json-schema-traverse", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "json-schema-traverse@^0.3.0", "name": "json-schema-traverse", "escapedName": "json-schema-traverse", "rawSpec": "^0.3.0", "saveSpec": null, "fetchSpec": "^0.3.0" }, "_requiredBy": [ "/ajv" ], "_resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", "_shasum": "349a6d44c53a51de89b40805c5d5e59b417d3340", "_spec": "json-schema-traverse@^0.3.0", "_where": "/Users/jshore/Documents/Projects/weewikipaint/node_modules/ajv", "author": { "name": "Evgeny Poberezkin" }, "bugs": { "url": "https://github.com/epoberezkin/json-schema-traverse/issues" }, "bundleDependencies": false, "deprecated": false, "description": "Traverse JSON Schema passing each schema object to callback", "devDependencies": { "coveralls": "^2.13.1", "eslint": "^3.19.0", "mocha": "^3.4.2", "nyc": "^11.0.2", "pre-commit": "^1.2.2" }, "homepage": "https://github.com/epoberezkin/json-schema-traverse#readme", "keywords": [ "JSON-Schema", "traverse", "iterate" ], "license": "MIT", "main": "index.js", "name": "json-schema-traverse", "nyc": { "exclude": [ "**/spec/**", "node_modules" ], "reporter": [ "lcov", "text-summary" ] }, "repository": { "type": "git", "url": "git+https://github.com/epoberezkin/json-schema-traverse.git" }, "scripts": { "eslint": "eslint index.js spec", "test": "npm run eslint && nyc npm run test-spec", "test-spec": "mocha spec -R spec" }, "version": "0.3.1" }
{ "pile_set_name": "Github" }
public class JavaClass { public static String foo() { return ":)"; } }
{ "pile_set_name": "Github" }
Spring Boot 学习示例 ========================= ![Spring Boot 2.0](https://img.shields.io/badge/Spring%20Boot-2.0-brightgreen.svg) ![Mysql 5.6](https://img.shields.io/badge/Mysql-5.6-blue.svg) ![JDK 1.8](https://img.shields.io/badge/JDK-1.8-brightgreen.svg) ![Maven](https://img.shields.io/badge/Maven-3.5.0-yellowgreen.svg) ![license](https://img.shields.io/badge/license-MPL--2.0-blue.svg) Spring Boot 使用的各种示例,以最简单、最实用为标准,此开源项目中的每个示例都以最小依赖,最简单为标准,帮助初学者快速掌握 Spring Boot 各组件的使用。 [Spring Boot 中文索引](https://github.com/ityouknow/awesome-spring-boot) &nbsp;| &nbsp; [Spring Cloud学习示例代码](https://github.com/ityouknow/spring-cloud-examples) &nbsp;| &nbsp; [Spring Boot 精品课程](https://github.com/ityouknow/spring-boot-leaning) [English](README_EN.md) &nbsp;| &nbsp; [Github地址](https://github.com/ityouknow/spring-boot-examples) &nbsp;| &nbsp; [码云地址](https://gitee.com/ityouknow/spring-boot-examples) &nbsp;| &nbsp; [Spring Boot 1.0](https://github.com/ityouknow/spring-boot-examples/tree/Spring-Boot-1.0) --- 推荐程序员都关注的一个漫画公众号 ![](http://www.ityouknow.com/assets/images/cartoon.jpg) 关注后,回复:**java** 获取超过 10万 人领取的 Java 知识体系/面试必看资料。 ## Spring Boot 2.0 **[Spring Boot 2.0 最全使用教程](https://github.com/ityouknow/spring-boot-leaning)** **[Favorites-web](https://github.com/cloudfavorites/favorites-web):云收藏(Spring Boot 2.0 实战开源项目)** **示例代码** - [spring-boot-hello](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-hello):Spring Boot 2.0 Hello World 示例 - [spring-boot-banner](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-banner):Spring Boot 定制 Banner 示例 - [spring-boot-docker](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-docker):使用 Docker 部署 Spring Boot 示例 - [dockercompose-springboot-mysql-nginx](https://github.com/ityouknow/spring-boot-examples/tree/master/dockercompose-springboot-mysql-nginx) :Docker Compose + Spring Boot + Nginx + Mysql 示例 - [spring-boot-commandLineRunner](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-commandLineRunner) :Spring Boot 使用 commandLineRunner 实现项目启动时资源初始化示例 - [spring-boot-web-thymeleaf](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-web-thymeleaf) :Spring Boot 使用 thymeleaf 实现布局、验参、增删改查示例 - [spring-boot-memcache-spymemcached](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-memcache-spymemcached) :Spring Boot 使用 spymemcached 集成 memcache 示例 - [spring-boot-webflux](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-webflux) :Spring Boot webflux 示例 - [spring-boot-elasticsearch](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-elasticsearch) :Spring Boot elasticsearch 示例 - [spring-boot-swagger](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-swagger) :Spring Boot swagger2 示例 - [spring-boot-mybatis-plus](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mybatis-plus) :Spring Boot 集成 MyBatis Plus 示例 **参考文章** - [Spring Boot 2(一):【重磅】Spring Boot 2.0权威发布](http://www.ityouknow.com/springboot/2018/03/01/spring-boot-2.0.html) - [Spring Boot 2(二):Spring Boot 2.0尝鲜-动态 Banner](http://www.ityouknow.com/springboot/2018/03/03/spring-boot-banner.html) - [Spring Boot 2(三):Spring Boot 开源软件都有哪些?](http://www.ityouknow.com/springboot/2018/03/05/spring-boot-open-source.html) - [Spring Boot 2(四):使用 Docker 部署 Spring Boot](http://www.ityouknow.com/springboot/2018/03/19/spring-boot-docker.html) - [Spring Boot 2(五):Docker Compose + Spring Boot + Nginx + Mysql 实践](http://www.ityouknow.com/springboot/2018/03/28/dockercompose-springboot-mysql-nginx.html) - [Spring Boot 2(六):使用 Docker 部署 Spring Boot 开源软件云收藏](http://www.ityouknow.com/springboot/2018/04/02/docker-favorites.html) - [Spring Boot 2(七):Spring Boot 如何解决项目启动时初始化资源](http://www.ityouknow.com/springboot/2018/05/03/spring-boot-commandLineRunner.html) - [Spring Boot 2(八):Spring Boot 集成 Memcached](http://www.ityouknow.com/springboot/2018/09/01/spring-boot-memcached.html) - [Spring Boot 2 (九):【重磅】Spring Boot 2.1.0 权威发布](http://www.ityouknow.com/springboot/2018/11/03/spring-boot-2.1.html) - [Spring Boot/Cloud 研发团队介绍](http://www.ityouknow.com/springboot/2019/01/03/spring-pivotal.html) - [Spring Boot 2 (十):Spring Boot 中的响应式编程和 WebFlux 入门](http://www.ityouknow.com/springboot/2019/02/12/spring-boot-webflux.html) ## 下方示例已经全部升级到 2.X **示例代码** - [spring-boot-helloWorld](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-helloWorld):Spring Boot 的 hello World 版本 - [spring-boot-web](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-web):Spring Boot Web 开发综合示例 - [spring-boot-redis](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-redis):Spring Boot 集成 Redis 示例 - [spring-boot-jpa](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-jpa):Spring Boot 使用 Jpa 各种示例 - [spring-boot-mybaits-annotation](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mybatis/spring-boot-mybatis-annotation):注解版本 - [spring-boot-mybaits-xml](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mybatis/spring-boot-mybatis-xml):Xml 配置版本 - [spring-boot-mybatis-xml-mulidatasource](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mybatis/spring-boot-mybatis-xml-mulidatasource):Spring Boot + Mybatis (Xml 版) 多数据源最简解决方案 - [spring-boot-mybatis-annotation-mulidatasource](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mybatis/spring-boot-mybatis-annotation-mulidatasource):Spring Boot + Mybatis(注解版)多数据源最简解决方案 - [spring-boot-thymeleaf](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-thymeleaf):Spring Boot 使用 Thymeleaf 详细示例 - [spring-boot-jpa-thymeleaf-curd](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-jpa-thymeleaf-curd):Spring Boot + Jpa + Thymeleaf 增删改查示例 - [spring-boot-rabbitmq](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-rabbitmq):Spring Boot 和 Rabbitmq 各种消息应用案例 - [spring-boot-scheduler](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-scheduler):Spring Boot 和定时任务案例 - [spring-boot-mail](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mail):Spring Boot 和邮件服务 - [spring-boot-mongodb](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mongodb/spring-boot-mongodb):Spring Boot 和 Mongodb 的使用 - [spring-boot-multi-mongodb](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mongodb/spring-boot-multi-mongodb):Spring Boot 和 Mongodb 多数据源的使用 - [spring-boot-package-war](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-package-war): Spring Boot 打包成 War 包示例 - [spring-boot-shiro](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-shiro):Spring Boot 整合 Shiro Rbac 示例 - [spring-boot-file-upload](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-file-upload):使用 Spring Boot 上传文件示例 - [spring-boot-fastDFS](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-fastDFS):Spring Boot 整合 FastDFS 示例 - [spring-boot-actuator](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-actuator):Spring Boot Actuator 使用示例 - [spring-boot-admin-simple](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-admin-simple):Spring Boot Admin 的使用示例 **参考文章** - [Spring Boot(一):入门篇](http://www.ityouknow.com/springboot/2016/01/06/spring-boot-quick-start.html) - [Spring Boot(二):Web 综合开发](http://www.ityouknow.com/springboot/2016/02/03/spring-boot-web.html) - [Spring Boot(三):Spring Boot 中 Redis 的使用](http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html) - [Spring Boot(四):Thymeleaf 使用详解](http://www.ityouknow.com/springboot/2016/05/01/spring-boot-thymeleaf.html) - [Spring Boot(五):Spring Data Jpa 的使用](http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html) - [Spring Boot(六):如何优雅的使用 Mybatis](http://www.ityouknow.com/springboot/2016/11/06/spring-boot-mybatis.html) - [Spring Boot(七):Spring Boot + Mybatis 多数据源最简解决方案](http://www.ityouknow.com/springboot/2016/11/25/spring-boot-multi-mybatis.html) - [Spring Boot(八):RabbitMQ 详解](http://www.ityouknow.com/springboot/2016/11/30/spring-boot-rabbitMQ.html) - [Spring Boot(九):定时任务](http://www.ityouknow.com/springboot/2016/12/02/spring-boot-scheduler.html) - [Spring Boot(十):邮件服务](http://www.ityouknow.com/springboot/2017/05/06/spring-boot-mail.html) - [Spring Boot(十一):Spring Boot 中 Mongodb 的使用](http://www.ityouknow.com/springboot/2017/05/08/spring-boot-mongodb.html) - [Spring Boot(十二):Spring Boot 如何测试打包部署](http://www.ityouknow.com/springboot/2017/05/09/spring-boot-deploy.html) - [Spring Boot(十三):Spring Boot 小技巧](http://www.ityouknow.com/springboot/2017/06/22/spring-boot-tips.html) - [Spring Boot(十四):Spring Boot 整合 Shiro-登录认证和权限管理](http://www.ityouknow.com/springboot/2017/06/26/spring-boot-shiro.html) - [Spring Boot(十五):Spring Boot + Jpa + Thymeleaf 增删改查示例](http://www.ityouknow.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html) - [Spring Boot(十六):使用 Jenkins 部署 Spring Boot](http://www.ityouknow.com/springboot/2017/11/11/spring-boot-jenkins.html) - [Spring Boot(十七):使用 Spring Boot 上传文件](http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html) - [Spring Boot(十八):使用 Spring Boot 集成 FastDFS](http://www.ityouknow.com/springboot/2018/01/16/spring-boot-fastdfs.html) - [Spring Boot(十九):使用 Spring Boot Actuator 监控应用](http://www.ityouknow.com/springboot/2018/02/06/spring-boot-actuator.html) - [Spring Boot(二十):使用 spring-boot-admin 对 Spring Boot 服务进行监控](http://www.ityouknow.com/springboot/2018/02/11/spring-boot-admin.html) **[Spring Boot 实战:我们的第一款开源项目](http://www.ityouknow.com/springboot/2016/09/26/spring-boot-opensource-favorites.html)** --- > 如果大家想了解关于 Spring Boot 的其它方面应用,也可以以[issues](https://github.com/ityouknow/spring-boot-examples/issues)的形式反馈给我,我后续来完善。 关注公众号:纯洁的微笑,回复"springboot"进群交流 ![](http://www.ityouknow.com/assets/images/keeppuresmile_430.jpg)
{ "pile_set_name": "Github" }
// ***************************************************************************************************************************************** // INPUT BOX by Br3tt aka Falstaff (c)2013-2015 // ***************************************************************************************************************************************** cInputbox = { temp_gr : gdi.CreateImage(1, 1).GetGraphics(), timer_cursor : false, cursor_state : true, doc : new ActiveXObject("htmlfile"), clipboard : null } oInputbox = function (w, h, default_text, empty_text, textcolor, backcolor, bordercolor, backselectioncolor, func, parentObjectName) { this.font = GdiFont(g_fname, g_fsize, g_fstyle); this.w = w; this.h = h; this.textcolor = textcolor; this.backcolor = backcolor; this.bordercolor = bordercolor; this.backselectioncolor = backselectioncolor; this.default_text = default_text; this.text = default_text; this.prev_text = "01234567890123456789"; this.empty_text = empty_text; this.stext = ""; this.prev_text = ""; this.func = func; var gfunc = func; var gfunc_launch_timer = false; var g_parentObjectName = parentObjectName; this.autovalidation = false; // this.edit = false; this.select = false; this.hover = false; this.Cpos = 0; this.Cx = 0; this.offset = 0; this.right_margin = 2; this.drag = false; this.setSize = function (w, h) { this.w = w; this.h = h; }; this.setfont = function (font_name, font_size, font_style) { this.font = GdiFont(font_name, font_size, font_style); //this.font_italic = this.font; }; this.draw = function (gr, x, y) { this.x = x; this.y = y; if (this.edit) { var DT = DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX | DT_CALCRECT; } else { var DT = DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX | DT_CALCRECT | DT_END_ELLIPSIS; } // draw bg gr.SetSmoothingMode(0); if (this.bordercolor) gr.FillSolidRect(x - 2, y + 0, (this.w + 4), this.h - 0, this.bordercolor); gr.FillSolidRect(x - 1, y + 1, (this.w + 2), this.h - 2, this.backcolor); // adjust offset to always see the cursor if (!this.drag && !this.select) { this.Cx = cInputbox.temp_gr.CalcTextWidth(this.text.substr(this.offset, this.Cpos - this.offset), this.font); while (this.Cx >= this.w - this.right_margin) { this.offset++; this.Cx = cInputbox.temp_gr.CalcTextWidth(this.text.substr(this.offset, this.Cpos - this.offset), this.font); } } // draw selection if (this.SelBegin != this.SelEnd) { this.select = true; this.CalcText(); if (this.SelBegin < this.SelEnd) { if (this.SelBegin < this.offset) { var px1 = this.x; } else { var px1 = this.x + this.GetCx(this.SelBegin); } var px1 = this.GetCx(this.SelBegin); var px2 = this.GetCx(this.SelEnd); this.text_selected = this.text.substring(this.SelBegin, this.SelEnd); } else { if (this.SelEnd < this.offset) { var px1 = this.x; } else { var px1 = this.x - this.GetCx(this.SelBegin); } var px2 = this.GetCx(this.SelBegin); var px1 = this.GetCx(this.SelEnd); this.text_selected = this.text.substring(this.SelEnd, this.SelBegin); } if ((this.x + px1 + (px2 - px1)) > this.x + this.w) { gr.FillSolidRect(this.x + px1, this.y + 1, this.w - px1, this.h - 3, this.backselectioncolor); } else { gr.FillSolidRect(this.x + px1, this.y + 1, px2 - px1, this.h - 3, this.backselectioncolor); } } else { this.select = false; this.text_selected = ""; } // draw text if (this.text.length > 0) { gr.GdiDrawText(this.text.substr(this.offset), this.font, this.edit ? this.textcolor : blendColors(this.textcolor, (this.backcolor == 0 ? 0xff000000 : this.backcolor), 0.35), this.x, this.y, this.w, this.h, DT); } else { gr.GdiDrawText(this.empty_text, this.font, blendColors(this.textcolor, (this.backcolor == 0 ? 0xff000000 : this.backcolor), 0.35), this.x, this.y, this.w, this.h, DT); } // draw cursor if (this.edit && !this.select) this.drawcursor(gr); }; this.drawcursor = function (gr) { if (cInputbox.cursor_state) { if (this.Cpos >= this.offset) { this.Cx = this.GetCx(this.Cpos); var x1 = this.x + this.Cx; var x2 = x1; var y1 = this.y + 1; var y2 = this.y + this.h - 2; var lt = 1; gr.DrawLine(x1, y1, x2, y2, lt, this.textcolor); } } } this.repaint = function () { eval(g_parentObjectName + ".repaint()"); } this.CalcText = function () { var arr = cInputbox.temp_gr.GdiDrawText(this.text.substr(this.offset), this.font, 0, 0, 0, 9999999, 9999999, DT_NOPREFIX | DT_CALCRECT).toArray(); this.TLength = arr[4]; this.TWidth = cInputbox.temp_gr.CalcTextWidth(this.text.substr(this.offset), this.font); } this.GetCx = function (pos) { if (pos >= this.offset) { var x = cInputbox.temp_gr.CalcTextWidth(this.text.substr(this.offset, pos - this.offset), this.font); } else { var x = 0; } return x; } this.GetCPos = function (x) { var tx = x - this.x; var pos = 0; for (var i = this.offset; i < this.text.length; i++) { pos += cInputbox.temp_gr.CalcTextWidth(this.text.substr(i, 1), this.font); if (pos >= tx + 3) { break; } } return i; } this.on_focus = function (is_focused) { if (!is_focused && this.edit) { if (this.text.length == 0) { this.text = this.default_text; }; this.edit = false; // clear timer if (cInputbox.timer_cursor) { window.ClearInterval(cInputbox.timer_cursor); cInputbox.timer_cursor = false; cInputbox.cursor_state = true; } this.repaint(); } else if (is_focused && this.edit) { this.resetCursorTimer(); } } this.resetCursorTimer = function () { if (cInputbox.timer_cursor) { window.ClearInterval(cInputbox.timer_cursor); cInputbox.timer_cursor = false; cInputbox.cursor_state = true; } cInputbox.timer_cursor = window.SetInterval(function () { cInputbox.cursor_state = !cInputbox.cursor_state; eval(g_parentObjectName + ".repaint()"); }, 500); } this.check = function (callback, x, y) { this.hover = (x >= this.x - 2 && x <= (this.x + this.w + 1) && y > this.y && y < (this.y + this.h)) ? true : false; switch (callback) { case "down": if (this.hover) { this.dblclk = false; this.drag = true; this.edit = true; this.Cpos = this.GetCPos(x); this.anchor = this.Cpos; this.SelBegin = this.Cpos; this.SelEnd = this.Cpos; this.resetCursorTimer(); } else { this.edit = false; this.select = false; this.SelBegin = 0; this.SelEnd = 0; this.text_selected = ""; if (cInputbox.timer_cursor) { window.ClearInterval(cInputbox.timer_cursor); cInputbox.timer_cursor = false; cInputbox.cursor_state = true; } } this.repaint(); break; case "up": if (!this.dblclk && this.drag) { this.SelEnd = this.GetCPos(x); if (this.select) { if (this.SelBegin > this.SelEnd) { this.sBeginSel = this.SelBegin; this.SelBegin = this.SelEnd; this.SelEnd = this.sBeginSel; } } } else { this.dblclk = false; } this.drag = false; break; case "dblclk": if (this.hover) { this.dblclk = true; this.SelBegin = 0; this.SelEnd = this.text.length; this.text_selected = this.text; this.select = true; this.repaint(); } break; case "move": if (this.drag) { this.CalcText(); var tmp = this.GetCPos(x); var tmp_x = this.GetCx(tmp); if (tmp < this.SelBegin) { if (tmp < this.SelEnd) { if (tmp_x < this.x) { if (this.offset > 0) { this.offset--; this.repaint(); } } } else if (tmp > this.SelEnd) { if (tmp_x + this.x > this.x + this.w) { var len = (this.TWidth > this.w) ? this.TWidth - this.w : 0; if (len > 0) { this.offset++; this.repaint(); } } } this.SelEnd = tmp; } else if (tmp > this.SelBegin) { if (tmp_x + this.x > this.x + this.w) { var len = (this.TWidth > this.w) ? this.TWidth - this.w : 0; if (len > 0) { this.offset++; this.repaint(); } } this.SelEnd = tmp; } this.Cpos = tmp; this.repaint(); } // Set Mouse Cursor Style if (this.hover || this.drag) { window.SetCursor(IDC_IBEAM); } else if (this.ibeam_set) { window.SetCursor(IDC_ARROW); } this.ibeam_set = (this.hover || this.drag); break; case "right": if (this.hover) { this.edit = true; this.resetCursorTimer(); this.repaint(); this.show_context_menu(x, y); } else { this.edit = false; this.select = false; this.SelBegin = 0; this.SelEnd = 0; this.text_selected = ""; if (cInputbox.timer_cursor) { window.ClearInterval(cInputbox.timer_cursor); cInputbox.timer_cursor = false; cInputbox.cursor_state = true; } this.repaint(); } break; }; }; this.show_context_menu = function (x, y) { var idx; var _menu = window.CreatePopupMenu(); cInputbox.clipboard = cInputbox.doc.parentWindow.clipboardData.getData("Text"); _menu.AppendMenuItem(this.select ? MF_STRING : MF_GRAYED | MF_DISABLED, 1, "复制"); _menu.AppendMenuItem(this.select ? MF_STRING : MF_GRAYED | MF_DISABLED, 2, "剪切"); _menu.AppendMenuSeparator(); _menu.AppendMenuItem(cInputbox.clipboard ? MF_STRING : MF_GRAYED | MF_DISABLED, 3, "粘贴"); /*if (utils.IsKeyPressed(VK_SHIFT)) { _menu.AppendMenuSeparator(); _menu.AppendMenuItem(MF_STRING, 20, "属性"); _menu.AppendMenuItem(MF_STRING, 21, "配置..."); }*/ idx = _menu.TrackPopupMenu(x, y); switch (idx) { case 1: if (this.edit && this.select) { cInputbox.doc.parentWindow.clipboardData.setData("Text", this.text_selected); } break; case 2: if (this.edit && this.select) { cInputbox.doc.parentWindow.clipboardData.setData("Text", this.text_selected); var p1 = this.SelBegin; var p2 = this.SelEnd; this.offset = this.offset >= this.text_selected.length ? this.offset - this.text_selected.length : 0; this.select = false; this.text_selected = ""; this.Cpos = this.SelBegin; this.SelEnd = this.SelBegin; this.text = this.text.slice(0, p1) + this.text.slice(p2); this.CalcText(); this.repaint(); this.autovalidation && gfunc(); } break; case 3: if (this.edit && cInputbox.clipboard) { if (this.select) { var p1 = this.SelBegin; var p2 = this.SelEnd; this.select = false; this.text_selected = ""; this.Cpos = this.SelBegin; this.SelEnd = this.SelBegin; if (this.Cpos < this.text.length) { this.text = this.text.slice(0, p1) + cInputbox.clipboard + this.text.slice(p2); } else { this.text = this.text + cInputbox.clipboard; } this.Cpos += cInputbox.clipboard.length; this.CalcText(); this.repaint(); } else { if (this.Cpos > 0) { // cursor pos > 0 this.text = this.text.substring(0, this.Cpos) + cInputbox.clipboard + this.text.substring(this.Cpos, this.text.length); } else { this.text = cInputbox.clipboard + this.text.substring(this.Cpos, this.text.length); } this.Cpos += cInputbox.clipboard.length; this.CalcText(); this.repaint(); } this.autovalidation && gfunc(); }; break; /*case 20: window.ShowProperties(); break; case 21: window.ShowConfigure(); break;*/ } _menu.Dispose(); } this.on_key_down = function (vkey) { this.resetCursorTimer(); var kmask = GetKeyboardMask(); this.on_key(vkey, kmask); }; this.on_key = function (vkey, mask) { if (mask == KMask.none) { switch (vkey) { case VK_SHIFT: break; case VK_BACK: //save text before update this.stext = this.text; if (this.edit) { if (this.select) { if (this.text_selected.length == this.text.length) { this.text = ""; this.Cpos = 0; } else { if (this.SelBegin > 0) { this.text = this.text.substring(0, this.SelBegin) + this.text.substring(this.SelEnd, this.text.length); this.Cpos = this.SelBegin; } else { this.text = this.text.substring(this.SelEnd, this.text.length); this.Cpos = this.SelBegin; } } } else { if (this.Cpos > 0) { this.text = this.text.substr(0, this.Cpos - 1) + this.text.substr(this.Cpos, this.text.length - this.Cpos); if (this.offset > 0) { this.offset--; } this.Cpos--; this.repaint(); } } } this.CalcText(); this.offset = this.offset >= this.text_selected.length ? this.offset - this.text_selected.length : 0; this.text_selected = ""; this.SelBegin = this.Cpos; this.SelEnd = this.SelBegin; this.select = false; this.repaint(); break; case VK_DELETE: //save text before update this.stext = this.text; if (this.edit) { if (this.select) { if (this.text_selected.length == this.text.length) { this.text = ""; this.Cpos = 0; } else { if (this.SelBegin > 0) { this.text = this.text.substring(0, this.SelBegin) + this.text.substring(this.SelEnd, this.text.length); this.Cpos = this.SelBegin; } else { this.text = this.text.substring(this.SelEnd, this.text.length); this.Cpos = this.SelBegin; } } } else { if (this.Cpos < this.text.length) { this.text = this.text.substr(0, this.Cpos) + this.text.substr(this.Cpos + 1, this.text.length - this.Cpos - 1); this.repaint(); } } } this.CalcText(); this.offset = this.offset >= this.text_selected.length ? this.offset - this.text_selected.length : 0; this.text_selected = ""; this.SelBegin = this.Cpos; this.SelEnd = this.SelBegin; this.select = false; this.repaint(); break; case VK_RETURN: if (this.edit && this.text.length >= 0) { try{this.func();}catch(e){eval(this.func);}; } else {} break; case VK_ESCAPE: if (this.edit) { this.edit = false; this.text_selected = ""; this.select = false; this.repaint(); } break; case VK_END: if (this.edit) { this.Cpos = this.text.length; this.SelBegin = 0; this.SelEnd = 0; this.select = false; this.repaint(); } break; case VK_HOME: if (this.edit) { this.Cpos = 0; this.SelBegin = 0; this.SelEnd = 0; this.select = false; this.offset = 0; this.repaint(); } break; case VK_LEFT: if (this.edit) { if (this.offset > 0) { if (this.Cpos <= this.offset) { this.offset--; this.Cpos--; } else { this.Cpos--; } } else { if (this.Cpos > 0) this.Cpos--; } this.SelBegin = this.Cpos; this.SelEnd = this.Cpos; this.select = false; this.repaint(); } break; case VK_RIGHT: if (this.edit) { if (this.Cpos < this.text.length) this.Cpos++; this.SelBegin = this.Cpos; this.SelEnd = this.Cpos; this.select = false; this.repaint(); } break; } if (this.edit) this.repaint(); } else { switch (mask) { case KMask.shift: if (vkey == VK_HOME) { // SHIFT + HOME if (this.edit) { if (!this.select) { this.anchor = this.Cpos; this.select = true; if (this.Cpos > 0) { this.SelEnd = this.Cpos; this.SelBegin = 0; this.select = true; this.Cpos = 0; } } else { if (this.Cpos > 0) { if (this.anchor < this.Cpos) { this.SelBegin = 0; this.SelEnd = this.anchor; } else if (this.anchor > this.Cpos) { this.SelBegin = 0; } this.Cpos = 0; } } if (this.offset > 0) { this.offset = 0; } this.repaint(); } }; if (vkey == VK_END) { // SHIFT + END if (this.edit) { if (!this.select) { this.anchor = this.Cpos; if (this.Cpos < this.text.length) { this.SelBegin = this.Cpos; this.SelEnd = this.text.length; this.Cpos = this.text.length; this.select = true; } } else { if (this.Cpos < this.text.length) { if (this.anchor < this.Cpos) { this.SelEnd = this.text.length; } else if (this.anchor > this.Cpos) { this.SelBegin = this.anchor; this.SelEnd = this.text.length; } this.Cpos = this.text.length; } } this.Cx = cInputbox.temp_gr.CalcTextWidth(this.text.substr(this.offset, this.Cpos - this.offset), this.font); while (this.Cx >= this.w - this.right_margin) { this.offset++; this.Cx = cInputbox.temp_gr.CalcTextWidth(this.text.substr(this.offset, this.Cpos - this.offset), this.font); } this.repaint(); } }; if (vkey == VK_LEFT) { // SHIFT + KEY LEFT if (this.edit) { if (!this.select) { this.anchor = this.Cpos; this.select = true; if (this.Cpos > 0) { this.SelEnd = this.Cpos; this.SelBegin = this.Cpos - 1; this.select = true; this.Cpos--; } } else { if (this.Cpos > 0) { if (this.anchor < this.Cpos) { this.SelEnd--; } else if (this.anchor > this.Cpos) { this.SelBegin--; } this.Cpos--; } } if (this.offset > 0) { var tmp = this.Cpos; var tmp_x = this.GetCx(tmp); if (tmp < this.offset) { this.offset--; } } this.repaint(); } }; if (vkey == VK_RIGHT) { // SHIFT + KEY RIGHT if (this.edit) { if (!this.select) { this.anchor = this.Cpos; if (this.Cpos < this.text.length) { this.SelBegin = this.Cpos; this.Cpos++; this.SelEnd = this.Cpos; this.select = true; } } else { if (this.Cpos < this.text.length) { if (this.anchor < this.Cpos) { this.SelEnd++; } else if (this.anchor > this.Cpos) { this.SelBegin++; } this.Cpos++; } } // handle scroll text on cursor selection var tmp_x = this.GetCx(this.Cpos); if (tmp_x > (this.w - this.right_margin)) { this.offset++; } this.repaint(); } }; break; case KMask.ctrl: if (vkey == 65) { // CTRL+A if (this.edit && this.text.length > 0) { this.SelBegin = 0; this.SelEnd = this.text.length; this.text_selected = this.text; this.select = true; this.repaint(); } }; if (vkey == 67) { // CTRL+C if (this.edit && this.select) { cInputbox.doc.parentWindow.clipboardData.setData("Text", this.text_selected); } }; if (vkey == 88) { // CTRL+X if (this.edit && this.select) { //save text avant MAJ this.stext = this.text; // cInputbox.doc.parentWindow.clipboardData.setData("Text", this.text_selected); var p1 = this.SelBegin; var p2 = this.SelEnd; this.select = false; this.text_selected = ""; this.Cpos = this.SelBegin; this.SelEnd = this.SelBegin; this.text = this.text.slice(0, p1) + this.text.slice(p2); this.CalcText(); this.repaint(); } }; if (vkey == 90) { // CTRL+Z (annulation saisie) if (this.edit) { this.text = this.stext; this.repaint(); } }; if (vkey == 86) { // CTRL+V cInputbox.clipboard = cInputbox.doc.parentWindow.clipboardData.getData("Text"); if (this.edit && cInputbox.clipboard) { //save text avant MAJ this.stext = this.text; // if (this.select) { var p1 = this.SelBegin; var p2 = this.SelEnd; this.select = false; this.text_selected = ""; this.Cpos = this.SelBegin; this.SelEnd = this.SelBegin; if (this.Cpos < this.text.length) { this.text = this.text.slice(0, p1) + cInputbox.clipboard + this.text.slice(p2); } else { this.text = this.text + cInputbox.clipboard; } this.Cpos += cInputbox.clipboard.length; this.CalcText(); this.repaint(); } else { if (this.Cpos > 0) { // cursor pos > 0 this.text = this.text.substring(0, this.Cpos) + cInputbox.clipboard + this.text.substring(this.Cpos, this.text.length); } else { this.text = cInputbox.clipboard + this.text.substring(this.Cpos, this.text.length); } this.Cpos += cInputbox.clipboard.length; this.CalcText(); this.repaint(); } }; }; break; } } // autosearch: has text changed after on_key or on_char ? if (this.autovalidation) { if (this.text != this.prev_text) { // launch timer to process the search gfunc_launch_timer && window.ClearTimeout(gfunc_launch_timer); gfunc_launch_timer = window.SetTimeout(function () { gfunc(); gfunc_launch_timer && window.ClearTimeout(gfunc_launch_timer); gfunc_launch_timer = false; }, 500); this.prev_text = this.text; } } } this.on_char = function (code, mask) { if (code == 1 && this.edit && mask == KMask.ctrl) { this.Spos = 0; this.Cpos = this.text.length; this.select = true; this.repaint(); } if (code > 31 && this.edit) { //save text before update this.stext = this.text; if (this.select) { var p1 = this.SelBegin; var p2 = this.SelEnd; this.text_selected = ""; this.Cpos = this.SelBegin; this.SelEnd = this.SelBegin; } else { var p1 = this.Cpos; var p2 = (this.text.length - this.Cpos) * -1; } if (this.Cpos < this.text.length) { this.text = this.text.slice(0, p1) + String.fromCharCode(code) + this.text.slice(p2); } else { this.text = this.text + String.fromCharCode(code); } this.Cpos++; if (this.select) { this.CalcText(); if (this.TWidth <= (this.w)) { this.offset = 0; } else { if (this.Cpos - this.offset < 0) { this.offset = this.offset > 0 ? this.Cpos - 1 : 0; } } this.select = false; } this.repaint(); } // autosearch: has text changed after on_key or on_char ? if (this.autovalidation) { if (this.text != this.prev_text) { // launch timer to process the search gfunc_launch_timer && window.ClearTimeout(gfunc_launch_timer); gfunc_launch_timer = window.SetTimeout(function () { gfunc(); gfunc_launch_timer && window.ClearTimeout(gfunc_launch_timer); gfunc_launch_timer = false; }, 500); this.prev_text = this.text; } } }; };
{ "pile_set_name": "Github" }
# frozen_string_literal: true module Spree module Promo Environment = ActiveSupport::Deprecation::DeprecatedConstantProxy.new( 'Spree::Promo::Environment', 'Spree::Core::Environment::Promotions', Spree::Deprecation ) end end
{ "pile_set_name": "Github" }
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/aec3/moving_average.h" #include "test/gtest.h" namespace webrtc { TEST(MovingAverage, Average) { constexpr size_t num_elem = 4; constexpr size_t mem_len = 3; constexpr float e = 1e-6f; aec3::MovingAverage ma(num_elem, mem_len); std::array<float, num_elem> data1 = {1, 2, 3, 4}; std::array<float, num_elem> data2 = {5, 1, 9, 7}; std::array<float, num_elem> data3 = {3, 3, 5, 6}; std::array<float, num_elem> data4 = {8, 4, 2, 1}; std::array<float, num_elem> output; ma.Average(data1, output); EXPECT_NEAR(output[0], data1[0] / 3.0f, e); EXPECT_NEAR(output[1], data1[1] / 3.0f, e); EXPECT_NEAR(output[2], data1[2] / 3.0f, e); EXPECT_NEAR(output[3], data1[3] / 3.0f, e); ma.Average(data2, output); EXPECT_NEAR(output[0], (data1[0] + data2[0]) / 3.0f, e); EXPECT_NEAR(output[1], (data1[1] + data2[1]) / 3.0f, e); EXPECT_NEAR(output[2], (data1[2] + data2[2]) / 3.0f, e); EXPECT_NEAR(output[3], (data1[3] + data2[3]) / 3.0f, e); ma.Average(data3, output); EXPECT_NEAR(output[0], (data1[0] + data2[0] + data3[0]) / 3.0f, e); EXPECT_NEAR(output[1], (data1[1] + data2[1] + data3[1]) / 3.0f, e); EXPECT_NEAR(output[2], (data1[2] + data2[2] + data3[2]) / 3.0f, e); EXPECT_NEAR(output[3], (data1[3] + data2[3] + data3[3]) / 3.0f, e); ma.Average(data4, output); EXPECT_NEAR(output[0], (data2[0] + data3[0] + data4[0]) / 3.0f, e); EXPECT_NEAR(output[1], (data2[1] + data3[1] + data4[1]) / 3.0f, e); EXPECT_NEAR(output[2], (data2[2] + data3[2] + data4[2]) / 3.0f, e); EXPECT_NEAR(output[3], (data2[3] + data3[3] + data4[3]) / 3.0f, e); } TEST(MovingAverage, PassThrough) { constexpr size_t num_elem = 4; constexpr size_t mem_len = 1; constexpr float e = 1e-6f; aec3::MovingAverage ma(num_elem, mem_len); std::array<float, num_elem> data1 = {1, 2, 3, 4}; std::array<float, num_elem> data2 = {5, 1, 9, 7}; std::array<float, num_elem> data3 = {3, 3, 5, 6}; std::array<float, num_elem> data4 = {8, 4, 2, 1}; std::array<float, num_elem> output; ma.Average(data1, output); EXPECT_NEAR(output[0], data1[0], e); EXPECT_NEAR(output[1], data1[1], e); EXPECT_NEAR(output[2], data1[2], e); EXPECT_NEAR(output[3], data1[3], e); ma.Average(data2, output); EXPECT_NEAR(output[0], data2[0], e); EXPECT_NEAR(output[1], data2[1], e); EXPECT_NEAR(output[2], data2[2], e); EXPECT_NEAR(output[3], data2[3], e); ma.Average(data3, output); EXPECT_NEAR(output[0], data3[0], e); EXPECT_NEAR(output[1], data3[1], e); EXPECT_NEAR(output[2], data3[2], e); EXPECT_NEAR(output[3], data3[3], e); ma.Average(data4, output); EXPECT_NEAR(output[0], data4[0], e); EXPECT_NEAR(output[1], data4[1], e); EXPECT_NEAR(output[2], data4[2], e); EXPECT_NEAR(output[3], data4[3], e); } } // namespace webrtc
{ "pile_set_name": "Github" }
# Copyright 2016, 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. # [START datastore_admin_client_create] from google.cloud.datastore_admin_v1.gapic import datastore_admin_client def client_create(): """Creates a new Datastore admin client.""" client = datastore_admin_client.DatastoreAdminClient() print("Admin client created\n") return client # [END datastore_admin_client_create] # [START datastore_admin_entities_export] def export_entities(project_id, output_url_prefix): """ Exports a copy of all or a subset of entities from Datastore to another storage system, such as Cloud Storage. """ # project_id = "project-id" # output_url_prefix = "gs://bucket-name" client = datastore_admin_client.DatastoreAdminClient() op = client.export_entities(project_id, output_url_prefix) response = op.result(timeout=200) print("Entities were exported\n") return response # [END datastore_admin_entities_export] # [START datastore_admin_entities_import] def import_entities(project_id, input_url): """Imports entities into Datastore.""" # project_id := "project-id" # input_url := "gs://bucket-name/overall-export-metadata-file" client = datastore_admin_client.DatastoreAdminClient() op = client.import_entities(project_id, input_url) response = op.result(timeout=200) print("Entities were imported\n") return response # [END datastore_admin_entities_import] # [START datastore_admin_index_get] def get_index(project_id, index_id): """Gets an index.""" # project_id := "my-project-id" # index_id := "my-index" client = datastore_admin_client.DatastoreAdminClient() index = client.get_index(project_id, index_id) print("Got index: %v\n", index.index_id) return index # [END datastore_admin_index_get] # [START datastore_admin_index_list] def list_indexes(project_id): """Lists the indexes.""" # project_id := "my-project-id" client = datastore_admin_client.DatastoreAdminClient() indexes = [] for index in client.list_indexes(project_id): indexes.append(index) print("Got index: %v\n", index.index_id) print("Got list of indexes\n") return indexes # [END datastore_admin_index_list]
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <SolutionDir Condition=" '$(SolutionDir)' == '' ">$(ProjectDir)..\</SolutionDir> <TargetFrameworks>net45;netstandard2.0</TargetFrameworks> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <Description>Extensions for BruTile that require the full .Net Framework</Description> <PackageTags>tiling gis osm geo file ado.net</PackageTags> <RootNamespace>BruTile.Cache</RootNamespace> </PropertyGroup> <Import Project="$(SolutionDir)BruTile.Common.props" /> <ItemGroup> <ProjectReference Include="..\BruTile\BruTile.csproj" /> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
export enum DropEffect { none = "none", link = "link", copy = "copy", move = "move", } /** * Helper functions for drag and drop */ export class DragUtils { /** * Call this in the draghover callback to allow/disallow dropping */ public static allowDrop(event: DragEvent, allowed: boolean, effect: DropEffect = DropEffect.move) { if (!allowed) { return; } event.dataTransfer!.dropEffect = effect; event.stopPropagation(); event.preventDefault(); } }
{ "pile_set_name": "Github" }
/*- * Copyright (c) 1990, 1993, 1994 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Margo Seltzer. * * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)hash_page.c 8.7 (Berkeley) 8/16/94"; #endif /* LIBC_SCCS and not lint */ /* * PACKAGE: hashing * * DESCRIPTION: * Page manipulation for hashing package. * * ROUTINES: * * External * __get_page * __add_ovflpage * Internal * overflow_page * open_temp */ #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifdef DEBUG #include <assert.h> #endif #include <db.h> #include "hash.h" #include "page.h" #include "extern.h" static u_int32_t *fetch_bitmap __P((HTAB *, int)); static u_int32_t first_free __P((u_int32_t)); static int open_temp __P((HTAB *)); static u_int16_t overflow_page __P((HTAB *)); static void putpair __P((char *, const DBT *, const DBT *)); static void squeeze_key __P((u_int16_t *, const DBT *, const DBT *)); static int ugly_split __P((HTAB *, u_int32_t, BUFHEAD *, BUFHEAD *, int, int)); #define PAGE_INIT(P) { \ ((u_int16_t *)(P))[0] = 0; \ ((u_int16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(u_int16_t); \ ((u_int16_t *)(P))[2] = hashp->BSIZE; \ } /* * This is called AFTER we have verified that there is room on the page for * the pair (PAIRFITS has returned true) so we go right ahead and start moving * stuff on. */ static void putpair(p, key, val) char *p; const DBT *key, *val; { register u_int16_t *bp, n, off; bp = (u_int16_t *)p; /* Enter the key first. */ n = bp[0]; off = OFFSET(bp) - key->size; memmove(p + off, key->data, key->size); bp[++n] = off; /* Now the data. */ off -= val->size; memmove(p + off, val->data, val->size); bp[++n] = off; /* Adjust page info. */ bp[0] = n; bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t)); bp[n + 2] = off; } /* * Returns: * 0 OK * -1 error */ extern int __delpair(hashp, bufp, ndx) HTAB *hashp; BUFHEAD *bufp; register int ndx; { register u_int16_t *bp, newoff; register int n; u_int16_t pairlen; bp = (u_int16_t *)bufp->page; n = bp[0]; if (bp[ndx + 1] < REAL_KEY) return (__big_delete(hashp, bufp)); if (ndx != 1) newoff = bp[ndx - 1]; else newoff = hashp->BSIZE; pairlen = newoff - bp[ndx + 1]; if (ndx != (n - 1)) { /* Hard Case -- need to shuffle keys */ register int i; register char *src = bufp->page + (int)OFFSET(bp); register char *dst = src + (int)pairlen; memmove(dst, src, bp[ndx + 1] - OFFSET(bp)); /* Now adjust the pointers */ for (i = ndx + 2; i <= n; i += 2) { if (bp[i + 1] == OVFLPAGE) { bp[i - 2] = bp[i]; bp[i - 1] = bp[i + 1]; } else { bp[i - 2] = bp[i] + pairlen; bp[i - 1] = bp[i + 1] + pairlen; } } } /* Finally adjust the page data */ bp[n] = OFFSET(bp) + pairlen; bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(u_int16_t); bp[0] = n - 2; hashp->NKEYS--; bufp->flags |= BUF_MOD; return (0); } /* * Returns: * 0 ==> OK * -1 ==> Error */ extern int __split_page(hashp, obucket, nbucket) HTAB *hashp; u_int32_t obucket, nbucket; { register BUFHEAD *new_bufp, *old_bufp; register u_int16_t *ino; register char *np; DBT key, val; int n, ndx, retval; u_int16_t copyto, diff, off, moved; char *op; copyto = (u_int16_t)hashp->BSIZE; off = (u_int16_t)hashp->BSIZE; old_bufp = __get_buf(hashp, obucket, NULL, 0); if (old_bufp == NULL) return (-1); new_bufp = __get_buf(hashp, nbucket, NULL, 0); if (new_bufp == NULL) return (-1); old_bufp->flags |= (BUF_MOD | BUF_PIN); new_bufp->flags |= (BUF_MOD | BUF_PIN); ino = (u_int16_t *)(op = old_bufp->page); np = new_bufp->page; moved = 0; for (n = 1, ndx = 1; n < ino[0]; n += 2) { if (ino[n + 1] < REAL_KEY) { retval = ugly_split(hashp, obucket, old_bufp, new_bufp, (int)copyto, (int)moved); old_bufp->flags &= ~BUF_PIN; new_bufp->flags &= ~BUF_PIN; return (retval); } key.data = (u_char *)op + ino[n]; key.size = off - ino[n]; if (__call_hash(hashp, key.data, key.size) == obucket) { /* Don't switch page */ diff = copyto - off; if (diff) { copyto = ino[n + 1] + diff; memmove(op + copyto, op + ino[n + 1], off - ino[n + 1]); ino[ndx] = copyto + ino[n] - ino[n + 1]; ino[ndx + 1] = copyto; } else copyto = ino[n + 1]; ndx += 2; } else { /* Switch page */ val.data = (u_char *)op + ino[n + 1]; val.size = ino[n] - ino[n + 1]; putpair(np, &key, &val); moved += 2; } off = ino[n + 1]; } /* Now clean up the page */ ino[0] -= moved; FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3); OFFSET(ino) = copyto; #ifdef DEBUG3 (void)fprintf(stderr, "split %d/%d\n", ((u_int16_t *)np)[0] / 2, ((u_int16_t *)op)[0] / 2); #endif /* unpin both pages */ old_bufp->flags &= ~BUF_PIN; new_bufp->flags &= ~BUF_PIN; return (0); } /* * Called when we encounter an overflow or big key/data page during split * handling. This is special cased since we have to begin checking whether * the key/data pairs fit on their respective pages and because we may need * overflow pages for both the old and new pages. * * The first page might be a page with regular key/data pairs in which case * we have a regular overflow condition and just need to go on to the next * page or it might be a big key/data pair in which case we need to fix the * big key/data pair. * * Returns: * 0 ==> success * -1 ==> failure */ static int ugly_split(hashp, obucket, old_bufp, new_bufp, copyto, moved) HTAB *hashp; u_int32_t obucket; /* Same as __split_page. */ BUFHEAD *old_bufp, *new_bufp; int copyto; /* First byte on page which contains key/data values. */ int moved; /* Number of pairs moved to new page. */ { register BUFHEAD *bufp; /* Buffer header for ino */ register u_int16_t *ino; /* Page keys come off of */ register u_int16_t *np; /* New page */ register u_int16_t *op; /* Page keys go on to if they aren't moving */ BUFHEAD *last_bfp; /* Last buf header OVFL needing to be freed */ DBT key, val; SPLIT_RETURN ret; u_int16_t n, off, ov_addr, scopyto; char *cino; /* Character value of ino */ bufp = old_bufp; ino = (u_int16_t *)old_bufp->page; np = (u_int16_t *)new_bufp->page; op = (u_int16_t *)old_bufp->page; last_bfp = NULL; scopyto = (u_int16_t)copyto; /* ANSI */ n = ino[0] - 1; while (n < ino[0]) { if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) { if (__big_split(hashp, old_bufp, new_bufp, bufp, bufp->addr, obucket, &ret)) return (-1); old_bufp = ret.oldp; if (!old_bufp) return (-1); op = (u_int16_t *)old_bufp->page; new_bufp = ret.newp; if (!new_bufp) return (-1); np = (u_int16_t *)new_bufp->page; bufp = ret.nextp; if (!bufp) return (0); cino = (char *)bufp->page; ino = (u_int16_t *)cino; last_bfp = ret.nextp; } else if (ino[n + 1] == OVFLPAGE) { ov_addr = ino[n]; /* * Fix up the old page -- the extra 2 are the fields * which contained the overflow information. */ ino[0] -= (moved + 2); FREESPACE(ino) = scopyto - sizeof(u_int16_t) * (ino[0] + 3); OFFSET(ino) = scopyto; bufp = __get_buf(hashp, ov_addr, bufp, 0); if (!bufp) return (-1); ino = (u_int16_t *)bufp->page; n = 1; scopyto = hashp->BSIZE; moved = 0; if (last_bfp) __free_ovflpage(hashp, last_bfp); last_bfp = bufp; } /* Move regular sized pairs of there are any */ off = hashp->BSIZE; for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) { cino = (char *)ino; key.data = (u_char *)cino + ino[n]; key.size = off - ino[n]; val.data = (u_char *)cino + ino[n + 1]; val.size = ino[n] - ino[n + 1]; off = ino[n + 1]; if (__call_hash(hashp, key.data, key.size) == obucket) { /* Keep on old page */ if (PAIRFITS(op, (&key), (&val))) putpair((char *)op, &key, &val); else { old_bufp = __add_ovflpage(hashp, old_bufp); if (!old_bufp) return (-1); op = (u_int16_t *)old_bufp->page; putpair((char *)op, &key, &val); } old_bufp->flags |= BUF_MOD; } else { /* Move to new page */ if (PAIRFITS(np, (&key), (&val))) putpair((char *)np, &key, &val); else { new_bufp = __add_ovflpage(hashp, new_bufp); if (!new_bufp) return (-1); np = (u_int16_t *)new_bufp->page; putpair((char *)np, &key, &val); } new_bufp->flags |= BUF_MOD; } } } if (last_bfp) __free_ovflpage(hashp, last_bfp); return (0); } /* * Add the given pair to the page * * Returns: * 0 ==> OK * 1 ==> failure */ extern int __addel(hashp, bufp, key, val) HTAB *hashp; BUFHEAD *bufp; const DBT *key, *val; { register u_int16_t *bp, *sop; int do_expand; bp = (u_int16_t *)bufp->page; do_expand = 0; while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY)) /* Exception case */ if (bp[2] == FULL_KEY_DATA && bp[0] == 2) /* This is the last page of a big key/data pair and we need to add another page */ break; else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) { bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); if (!bufp) return (-1); bp = (u_int16_t *)bufp->page; } else /* Try to squeeze key on this page */ if (FREESPACE(bp) > PAIRSIZE(key, val)) { squeeze_key(bp, key, val); return (0); } else { bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); if (!bufp) return (-1); bp = (u_int16_t *)bufp->page; } if (PAIRFITS(bp, key, val)) putpair(bufp->page, key, val); else { do_expand = 1; bufp = __add_ovflpage(hashp, bufp); if (!bufp) return (-1); sop = (u_int16_t *)bufp->page; if (PAIRFITS(sop, key, val)) putpair((char *)sop, key, val); else if (__big_insert(hashp, bufp, key, val)) return (-1); } bufp->flags |= BUF_MOD; /* * If the average number of keys per bucket exceeds the fill factor, * expand the table. */ hashp->NKEYS++; if (do_expand || (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR)) return (__expand_table(hashp)); return (0); } /* * * Returns: * pointer on success * NULL on error */ extern BUFHEAD * __add_ovflpage(hashp, bufp) HTAB *hashp; BUFHEAD *bufp; { register u_int16_t *sp; u_int16_t ndx, ovfl_num; #ifdef DEBUG1 int tmp1, tmp2; #endif sp = (u_int16_t *)bufp->page; /* Check if we are dynamically determining the fill factor */ if (hashp->FFACTOR == DEF_FFACTOR) { hashp->FFACTOR = sp[0] >> 1; if (hashp->FFACTOR < MIN_FFACTOR) hashp->FFACTOR = MIN_FFACTOR; } bufp->flags |= BUF_MOD; ovfl_num = overflow_page(hashp); #ifdef DEBUG1 tmp1 = bufp->addr; tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0; #endif if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1))) return (NULL); bufp->ovfl->flags |= BUF_MOD; #ifdef DEBUG1 (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n", tmp1, tmp2, bufp->ovfl->addr); #endif ndx = sp[0]; /* * Since a pair is allocated on a page only if there's room to add * an overflow page, we know that the OVFL information will fit on * the page. */ sp[ndx + 4] = OFFSET(sp); sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE; sp[ndx + 1] = ovfl_num; sp[ndx + 2] = OVFLPAGE; sp[0] = ndx + 2; #ifdef HASH_STATISTICS hash_overflows++; #endif return (bufp->ovfl); } /* * Returns: * 0 indicates SUCCESS * -1 indicates FAILURE */ extern int __get_page(hashp, p, bucket, is_bucket, is_disk, is_bitmap) HTAB *hashp; char *p; u_int32_t bucket; int is_bucket, is_disk, is_bitmap; { register int fd, page, size; int rsize; u_int16_t *bp; fd = hashp->fp; size = hashp->BSIZE; if ((fd == -1) || !is_disk) { PAGE_INIT(p); return (0); } if (is_bucket) page = BUCKET_TO_PAGE(bucket); else page = OADDR_TO_PAGE(bucket); if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) || ((rsize = read(fd, p, size)) == -1)) return (-1); bp = (u_int16_t *)p; if (!rsize) bp[0] = 0; /* We hit the EOF, so initialize a new page */ else if (rsize != size) { errno = EFTYPE; return (-1); } if (!is_bitmap && !bp[0]) { PAGE_INIT(p); } else if (hashp->LORDER != BYTE_ORDER) { register int i, max; if (is_bitmap) { max = hashp->BSIZE >> 2; /* divide by 4 */ for (i = 0; i < max; i++) M_32_SWAP(((int *)p)[i]); } else { M_16_SWAP(bp[0]); max = bp[0] + 2; for (i = 1; i <= max; i++) M_16_SWAP(bp[i]); } } return (0); } /* * Write page p to disk * * Returns: * 0 ==> OK * -1 ==>failure */ extern int __put_page(hashp, p, bucket, is_bucket, is_bitmap) HTAB *hashp; char *p; u_int32_t bucket; int is_bucket, is_bitmap; { register int fd, page, size; int wsize; size = hashp->BSIZE; if ((hashp->fp == -1) && open_temp(hashp)) return (-1); fd = hashp->fp; if (hashp->LORDER != BYTE_ORDER) { register int i; register int max; if (is_bitmap) { max = hashp->BSIZE >> 2; /* divide by 4 */ for (i = 0; i < max; i++) M_32_SWAP(((int *)p)[i]); } else { max = ((u_int16_t *)p)[0] + 2; for (i = 0; i <= max; i++) M_16_SWAP(((u_int16_t *)p)[i]); } } if (is_bucket) page = BUCKET_TO_PAGE(bucket); else page = OADDR_TO_PAGE(bucket); if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) || ((wsize = write(fd, p, size)) == -1)) /* Errno is set */ return (-1); if (wsize != size) { errno = EFTYPE; return (-1); } return (0); } #define BYTE_MASK ((1 << INT_BYTE_SHIFT) -1) /* * Initialize a new bitmap page. Bitmap pages are left in memory * once they are read in. */ extern int __ibitmap(hashp, pnum, nbits, ndx) HTAB *hashp; int pnum, nbits, ndx; { u_int32_t *ip; int clearbytes, clearints; if ((ip = (u_int32_t *)malloc(hashp->BSIZE)) == NULL) return (1); hashp->nmaps++; clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1; clearbytes = clearints << INT_TO_BYTE; (void)memset((char *)ip, 0, clearbytes); (void)memset(((char *)ip) + clearbytes, 0xFF, hashp->BSIZE - clearbytes); ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK); SETBIT(ip, 0); hashp->BITMAPS[ndx] = (u_int16_t)pnum; hashp->mapp[ndx] = ip; return (0); } static u_int32_t first_free(map) u_int32_t map; { register u_int32_t i, mask; mask = 0x1; for (i = 0; i < BITS_PER_MAP; i++) { if (!(mask & map)) return (i); mask = mask << 1; } return (i); } static u_int16_t overflow_page(hashp) HTAB *hashp; { register u_int32_t *freep; register int max_free, offset, splitnum; u_int16_t addr; int bit, first_page, free_bit, free_page, i, in_use_bits, j; #ifdef DEBUG2 int tmp1, tmp2; #endif splitnum = hashp->OVFL_POINT; max_free = hashp->SPARES[splitnum]; free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT); free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1); /* Look through all the free maps to find the first free block */ first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT); for ( i = first_page; i <= free_page; i++ ) { if (!(freep = (u_int32_t *)hashp->mapp[i]) && !(freep = fetch_bitmap(hashp, i))) return (0); if (i == free_page) in_use_bits = free_bit; else in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1; if (i == first_page) { bit = hashp->LAST_FREED & ((hashp->BSIZE << BYTE_SHIFT) - 1); j = bit / BITS_PER_MAP; bit = bit & ~(BITS_PER_MAP - 1); } else { bit = 0; j = 0; } for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP) if (freep[j] != ALL_SET) goto found; } /* No Free Page Found */ hashp->LAST_FREED = hashp->SPARES[splitnum]; hashp->SPARES[splitnum]++; offset = hashp->SPARES[splitnum] - (splitnum ? hashp->SPARES[splitnum - 1] : 0); #define OVMSG "HASH: Out of overflow pages. Increase page size\n" if (offset > SPLITMASK) { if (++splitnum >= NCACHED) { (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1); return (0); } hashp->OVFL_POINT = splitnum; hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1]; hashp->SPARES[splitnum-1]--; offset = 1; } /* Check if we need to allocate a new bitmap page */ if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) { free_page++; if (free_page >= NCACHED) { (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1); return (0); } /* * This is tricky. The 1 indicates that you want the new page * allocated with 1 clear bit. Actually, you are going to * allocate 2 pages from this map. The first is going to be * the map page, the second is the overflow page we were * looking for. The init_bitmap routine automatically, sets * the first bit of itself to indicate that the bitmap itself * is in use. We would explicitly set the second bit, but * don't have to if we tell init_bitmap not to leave it clear * in the first place. */ if (__ibitmap(hashp, (int)OADDR_OF(splitnum, offset), 1, free_page)) return (0); hashp->SPARES[splitnum]++; #ifdef DEBUG2 free_bit = 2; #endif offset++; if (offset > SPLITMASK) { if (++splitnum >= NCACHED) { (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1); return (0); } hashp->OVFL_POINT = splitnum; hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1]; hashp->SPARES[splitnum-1]--; offset = 0; } } else { /* * Free_bit addresses the last used bit. Bump it to address * the first available bit. */ free_bit++; SETBIT(freep, free_bit); } /* Calculate address of the new overflow page */ addr = OADDR_OF(splitnum, offset); #ifdef DEBUG2 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n", addr, free_bit, free_page); #endif return (addr); found: bit = bit + first_free(freep[j]); SETBIT(freep, bit); #ifdef DEBUG2 tmp1 = bit; tmp2 = i; #endif /* * Bits are addressed starting with 0, but overflow pages are addressed * beginning at 1. Bit is a bit addressnumber, so we need to increment * it to convert it to a page number. */ bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT)); if (bit >= hashp->LAST_FREED) hashp->LAST_FREED = bit - 1; /* Calculate the split number for this page */ for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++); offset = (i ? bit - hashp->SPARES[i - 1] : bit); if (offset >= SPLITMASK) return (0); /* Out of overflow pages */ addr = OADDR_OF(i, offset); #ifdef DEBUG2 (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n", addr, tmp1, tmp2); #endif /* Allocate and return the overflow page */ return (addr); } /* * Mark this overflow page as free. */ extern void __free_ovflpage(hashp, obufp) HTAB *hashp; BUFHEAD *obufp; { register u_int16_t addr; u_int32_t *freep; int bit_address, free_page, free_bit; u_int16_t ndx; addr = obufp->addr; #ifdef DEBUG1 (void)fprintf(stderr, "Freeing %d\n", addr); #endif ndx = (((u_int16_t)addr) >> SPLITSHIFT); bit_address = (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1; if (bit_address < hashp->LAST_FREED) hashp->LAST_FREED = bit_address; free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT)); free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1); if (!(freep = hashp->mapp[free_page])) freep = fetch_bitmap(hashp, free_page); #ifdef DEBUG /* * This had better never happen. It means we tried to read a bitmap * that has already had overflow pages allocated off it, and we * failed to read it from the file. */ if (!freep) assert(0); #endif CLRBIT(freep, free_bit); #ifdef DEBUG2 (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n", obufp->addr, free_bit, free_page); #endif __reclaim_buf(hashp, obufp); } /* * Returns: * 0 success * -1 failure */ static int open_temp(hashp) HTAB *hashp; { sigset_t set, oset; static char namestr[] = "_hashXXXXXX"; /* Block signals; make sure file goes away at process exit. */ (void)sigfillset(&set); (void)sigprocmask(SIG_BLOCK, &set, &oset); if ((hashp->fp = mkstemp(namestr)) != -1) { (void)unlink(namestr); (void)fcntl(hashp->fp, F_SETFD, 1); } (void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL); return (hashp->fp != -1 ? 0 : -1); } /* * We have to know that the key will fit, but the last entry on the page is * an overflow pair, so we need to shift things. */ static void squeeze_key(sp, key, val) u_int16_t *sp; const DBT *key, *val; { register char *p; u_int16_t free_space, n, off, pageno; p = (char *)sp; n = sp[0]; free_space = FREESPACE(sp); off = OFFSET(sp); pageno = sp[n - 1]; off -= key->size; sp[n - 1] = off; memmove(p + off, key->data, key->size); off -= val->size; sp[n] = off; memmove(p + off, val->data, val->size); sp[0] = n + 2; sp[n + 1] = pageno; sp[n + 2] = OVFLPAGE; FREESPACE(sp) = free_space - PAIRSIZE(key, val); OFFSET(sp) = off; } static u_int32_t * fetch_bitmap(hashp, ndx) HTAB *hashp; int ndx; { if (ndx >= hashp->nmaps) return (NULL); if ((hashp->mapp[ndx] = (u_int32_t *)malloc(hashp->BSIZE)) == NULL) return (NULL); if (__get_page(hashp, (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) { free(hashp->mapp[ndx]); return (NULL); } return (hashp->mapp[ndx]); } #ifdef DEBUG4 int print_chain(addr) int addr; { BUFHEAD *bufp; short *bp, oaddr; (void)fprintf(stderr, "%d ", addr); bufp = __get_buf(hashp, addr, NULL, 0); bp = (short *)bufp->page; while (bp[0] && ((bp[bp[0]] == OVFLPAGE) || ((bp[0] > 2) && bp[2] < REAL_KEY))) { oaddr = bp[bp[0] - 1]; (void)fprintf(stderr, "%d ", (int)oaddr); bufp = __get_buf(hashp, (int)oaddr, bufp, 0); bp = (short *)bufp->page; } (void)fprintf(stderr, "\n"); } #endif
{ "pile_set_name": "Github" }
/* esp_scsi.h: Defines and structures for the ESP drier. * * Copyright (C) 2007 David S. Miller (davem@davemloft.net) */ #ifndef _ESP_SCSI_H #define _ESP_SCSI_H /* Access Description Offset */ #define ESP_TCLOW 0x00UL /* rw Low bits transfer count 0x00 */ #define ESP_TCMED 0x01UL /* rw Mid bits transfer count 0x04 */ #define ESP_FDATA 0x02UL /* rw FIFO data bits 0x08 */ #define ESP_CMD 0x03UL /* rw SCSI command bits 0x0c */ #define ESP_STATUS 0x04UL /* ro ESP status register 0x10 */ #define ESP_BUSID ESP_STATUS /* wo BusID for sel/resel 0x10 */ #define ESP_INTRPT 0x05UL /* ro Kind of interrupt 0x14 */ #define ESP_TIMEO ESP_INTRPT /* wo Timeout for sel/resel 0x14 */ #define ESP_SSTEP 0x06UL /* ro Sequence step register 0x18 */ #define ESP_STP ESP_SSTEP /* wo Transfer period/sync 0x18 */ #define ESP_FFLAGS 0x07UL /* ro Bits current FIFO info 0x1c */ #define ESP_SOFF ESP_FFLAGS /* wo Sync offset 0x1c */ #define ESP_CFG1 0x08UL /* rw First cfg register 0x20 */ #define ESP_CFACT 0x09UL /* wo Clock conv factor 0x24 */ #define ESP_STATUS2 ESP_CFACT /* ro HME status2 register 0x24 */ #define ESP_CTEST 0x0aUL /* wo Chip test register 0x28 */ #define ESP_CFG2 0x0bUL /* rw Second cfg register 0x2c */ #define ESP_CFG3 0x0cUL /* rw Third cfg register 0x30 */ #define ESP_TCHI 0x0eUL /* rw High bits transf count 0x38 */ #define ESP_UID ESP_TCHI /* ro Unique ID code 0x38 */ #define FAS_RLO ESP_TCHI /* rw HME extended counter 0x38 */ #define ESP_FGRND 0x0fUL /* rw Data base for fifo 0x3c */ #define FAS_RHI ESP_FGRND /* rw HME extended counter 0x3c */ #define SBUS_ESP_REG_SIZE 0x40UL /* Bitfield meanings for the above registers. */ /* ESP config reg 1, read-write, found on all ESP chips */ #define ESP_CONFIG1_ID 0x07 /* My BUS ID bits */ #define ESP_CONFIG1_CHTEST 0x08 /* Enable ESP chip tests */ #define ESP_CONFIG1_PENABLE 0x10 /* Enable parity checks */ #define ESP_CONFIG1_PARTEST 0x20 /* Parity test mode enabled? */ #define ESP_CONFIG1_SRRDISAB 0x40 /* Disable SCSI reset reports */ #define ESP_CONFIG1_SLCABLE 0x80 /* Enable slow cable mode */ /* ESP config reg 2, read-write, found only on esp100a+esp200+esp236 chips */ #define ESP_CONFIG2_DMAPARITY 0x01 /* enable DMA Parity (200,236) */ #define ESP_CONFIG2_REGPARITY 0x02 /* enable reg Parity (200,236) */ #define ESP_CONFIG2_BADPARITY 0x04 /* Bad parity target abort */ #define ESP_CONFIG2_SCSI2ENAB 0x08 /* Enable SCSI-2 features (tgtmode) */ #define ESP_CONFIG2_HI 0x10 /* High Impedance DREQ ??? */ #define ESP_CONFIG2_HMEFENAB 0x10 /* HME features enable */ #define ESP_CONFIG2_BCM 0x20 /* Enable byte-ctrl (236) */ #define ESP_CONFIG2_DISPINT 0x20 /* Disable pause irq (hme) */ #define ESP_CONFIG2_FENAB 0x40 /* Enable features (fas100,216) */ #define ESP_CONFIG2_SPL 0x40 /* Enable status-phase latch (236) */ #define ESP_CONFIG2_MKDONE 0x40 /* HME magic feature */ #define ESP_CONFIG2_HME32 0x80 /* HME 32 extended */ #define ESP_CONFIG2_MAGIC 0xe0 /* Invalid bits... */ /* ESP config register 3 read-write, found only esp236+fas236+fas100a+hme chips */ #define ESP_CONFIG3_FCLOCK 0x01 /* FAST SCSI clock rate (esp100a/hme) */ #define ESP_CONFIG3_TEM 0x01 /* Enable thresh-8 mode (esp/fas236) */ #define ESP_CONFIG3_FAST 0x02 /* Enable FAST SCSI (esp100a/hme) */ #define ESP_CONFIG3_ADMA 0x02 /* Enable alternate-dma (esp/fas236) */ #define ESP_CONFIG3_TENB 0x04 /* group2 SCSI2 support (esp100a/hme) */ #define ESP_CONFIG3_SRB 0x04 /* Save residual byte (esp/fas236) */ #define ESP_CONFIG3_TMS 0x08 /* Three-byte msg's ok (esp100a/hme) */ #define ESP_CONFIG3_FCLK 0x08 /* Fast SCSI clock rate (esp/fas236) */ #define ESP_CONFIG3_IDMSG 0x10 /* ID message checking (esp100a/hme) */ #define ESP_CONFIG3_FSCSI 0x10 /* Enable FAST SCSI (esp/fas236) */ #define ESP_CONFIG3_GTM 0x20 /* group2 SCSI2 support (esp/fas236) */ #define ESP_CONFIG3_IDBIT3 0x20 /* Bit 3 of HME SCSI-ID (hme) */ #define ESP_CONFIG3_TBMS 0x40 /* Three-byte msg's ok (esp/fas236) */ #define ESP_CONFIG3_EWIDE 0x40 /* Enable Wide-SCSI (hme) */ #define ESP_CONFIG3_IMS 0x80 /* ID msg chk'ng (esp/fas236) */ #define ESP_CONFIG3_OBPUSH 0x80 /* Push odd-byte to dma (hme) */ /* ESP command register read-write */ /* Group 1 commands: These may be sent at any point in time to the ESP * chip. None of them can generate interrupts 'cept * the "SCSI bus reset" command if you have not disabled * SCSI reset interrupts in the config1 ESP register. */ #define ESP_CMD_NULL 0x00 /* Null command, ie. a nop */ #define ESP_CMD_FLUSH 0x01 /* FIFO Flush */ #define ESP_CMD_RC 0x02 /* Chip reset */ #define ESP_CMD_RS 0x03 /* SCSI bus reset */ /* Group 2 commands: ESP must be an initiator and connected to a target * for these commands to work. */ #define ESP_CMD_TI 0x10 /* Transfer Information */ #define ESP_CMD_ICCSEQ 0x11 /* Initiator cmd complete sequence */ #define ESP_CMD_MOK 0x12 /* Message okie-dokie */ #define ESP_CMD_TPAD 0x18 /* Transfer Pad */ #define ESP_CMD_SATN 0x1a /* Set ATN */ #define ESP_CMD_RATN 0x1b /* De-assert ATN */ /* Group 3 commands: ESP must be in the MSGOUT or MSGIN state and be connected * to a target as the initiator for these commands to work. */ #define ESP_CMD_SMSG 0x20 /* Send message */ #define ESP_CMD_SSTAT 0x21 /* Send status */ #define ESP_CMD_SDATA 0x22 /* Send data */ #define ESP_CMD_DSEQ 0x23 /* Discontinue Sequence */ #define ESP_CMD_TSEQ 0x24 /* Terminate Sequence */ #define ESP_CMD_TCCSEQ 0x25 /* Target cmd cmplt sequence */ #define ESP_CMD_DCNCT 0x27 /* Disconnect */ #define ESP_CMD_RMSG 0x28 /* Receive Message */ #define ESP_CMD_RCMD 0x29 /* Receive Command */ #define ESP_CMD_RDATA 0x2a /* Receive Data */ #define ESP_CMD_RCSEQ 0x2b /* Receive cmd sequence */ /* Group 4 commands: The ESP must be in the disconnected state and must * not be connected to any targets as initiator for * these commands to work. */ #define ESP_CMD_RSEL 0x40 /* Reselect */ #define ESP_CMD_SEL 0x41 /* Select w/o ATN */ #define ESP_CMD_SELA 0x42 /* Select w/ATN */ #define ESP_CMD_SELAS 0x43 /* Select w/ATN & STOP */ #define ESP_CMD_ESEL 0x44 /* Enable selection */ #define ESP_CMD_DSEL 0x45 /* Disable selections */ #define ESP_CMD_SA3 0x46 /* Select w/ATN3 */ #define ESP_CMD_RSEL3 0x47 /* Reselect3 */ /* This bit enables the ESP's DMA on the SBus */ #define ESP_CMD_DMA 0x80 /* Do DMA? */ /* ESP status register read-only */ #define ESP_STAT_PIO 0x01 /* IO phase bit */ #define ESP_STAT_PCD 0x02 /* CD phase bit */ #define ESP_STAT_PMSG 0x04 /* MSG phase bit */ #define ESP_STAT_PMASK 0x07 /* Mask of phase bits */ #define ESP_STAT_TDONE 0x08 /* Transfer Completed */ #define ESP_STAT_TCNT 0x10 /* Transfer Counter Is Zero */ #define ESP_STAT_PERR 0x20 /* Parity error */ #define ESP_STAT_SPAM 0x40 /* Real bad error */ /* This indicates the 'interrupt pending' condition on esp236, it is a reserved * bit on other revs of the ESP. */ #define ESP_STAT_INTR 0x80 /* Interrupt */ /* The status register can be masked with ESP_STAT_PMASK and compared * with the following values to determine the current phase the ESP * (at least thinks it) is in. For our purposes we also add our own * software 'done' bit for our phase management engine. */ #define ESP_DOP (0) /* Data Out */ #define ESP_DIP (ESP_STAT_PIO) /* Data In */ #define ESP_CMDP (ESP_STAT_PCD) /* Command */ #define ESP_STATP (ESP_STAT_PCD|ESP_STAT_PIO) /* Status */ #define ESP_MOP (ESP_STAT_PMSG|ESP_STAT_PCD) /* Message Out */ #define ESP_MIP (ESP_STAT_PMSG|ESP_STAT_PCD|ESP_STAT_PIO) /* Message In */ /* HME only: status 2 register */ #define ESP_STAT2_SCHBIT 0x01 /* Upper bits 3-7 of sstep enabled */ #define ESP_STAT2_FFLAGS 0x02 /* The fifo flags are now latched */ #define ESP_STAT2_XCNT 0x04 /* The transfer counter is latched */ #define ESP_STAT2_CREGA 0x08 /* The command reg is active now */ #define ESP_STAT2_WIDE 0x10 /* Interface on this adapter is wide */ #define ESP_STAT2_F1BYTE 0x20 /* There is one byte at top of fifo */ #define ESP_STAT2_FMSB 0x40 /* Next byte in fifo is most significant */ #define ESP_STAT2_FEMPTY 0x80 /* FIFO is empty */ /* ESP interrupt register read-only */ #define ESP_INTR_S 0x01 /* Select w/o ATN */ #define ESP_INTR_SATN 0x02 /* Select w/ATN */ #define ESP_INTR_RSEL 0x04 /* Reselected */ #define ESP_INTR_FDONE 0x08 /* Function done */ #define ESP_INTR_BSERV 0x10 /* Bus service */ #define ESP_INTR_DC 0x20 /* Disconnect */ #define ESP_INTR_IC 0x40 /* Illegal command given */ #define ESP_INTR_SR 0x80 /* SCSI bus reset detected */ /* ESP sequence step register read-only */ #define ESP_STEP_VBITS 0x07 /* Valid bits */ #define ESP_STEP_ASEL 0x00 /* Selection&Arbitrate cmplt */ #define ESP_STEP_SID 0x01 /* One msg byte sent */ #define ESP_STEP_NCMD 0x02 /* Was not in command phase */ #define ESP_STEP_PPC 0x03 /* Early phase chg caused cmnd * bytes to be lost */ #define ESP_STEP_FINI4 0x04 /* Command was sent ok */ /* Ho hum, some ESP's set the step register to this as well... */ #define ESP_STEP_FINI5 0x05 #define ESP_STEP_FINI6 0x06 #define ESP_STEP_FINI7 0x07 /* ESP chip-test register read-write */ #define ESP_TEST_TARG 0x01 /* Target test mode */ #define ESP_TEST_INI 0x02 /* Initiator test mode */ #define ESP_TEST_TS 0x04 /* Tristate test mode */ /* ESP unique ID register read-only, found on fas236+fas100a only */ #define ESP_UID_F100A 0x00 /* ESP FAS100A */ #define ESP_UID_F236 0x02 /* ESP FAS236 */ #define ESP_UID_REV 0x07 /* ESP revision */ #define ESP_UID_FAM 0xf8 /* ESP family */ /* ESP fifo flags register read-only */ /* Note that the following implies a 16 byte FIFO on the ESP. */ #define ESP_FF_FBYTES 0x1f /* Num bytes in FIFO */ #define ESP_FF_ONOTZERO 0x20 /* offset ctr not zero (esp100) */ #define ESP_FF_SSTEP 0xe0 /* Sequence step */ /* ESP clock conversion factor register write-only */ #define ESP_CCF_F0 0x00 /* 35.01MHz - 40MHz */ #define ESP_CCF_NEVER 0x01 /* Set it to this and die */ #define ESP_CCF_F2 0x02 /* 10MHz */ #define ESP_CCF_F3 0x03 /* 10.01MHz - 15MHz */ #define ESP_CCF_F4 0x04 /* 15.01MHz - 20MHz */ #define ESP_CCF_F5 0x05 /* 20.01MHz - 25MHz */ #define ESP_CCF_F6 0x06 /* 25.01MHz - 30MHz */ #define ESP_CCF_F7 0x07 /* 30.01MHz - 35MHz */ /* HME only... */ #define ESP_BUSID_RESELID 0x10 #define ESP_BUSID_CTR32BIT 0x40 #define ESP_BUS_TIMEOUT 250 /* In milli-seconds */ #define ESP_TIMEO_CONST 8192 #define ESP_NEG_DEFP(mhz, cfact) \ ((ESP_BUS_TIMEOUT * ((mhz) / 1000)) / (8192 * (cfact))) #define ESP_HZ_TO_CYCLE(hertz) ((1000000000) / ((hertz) / 1000)) #define ESP_TICK(ccf, cycle) ((7682 * (ccf) * (cycle) / 1000)) /* For slow to medium speed input clock rates we shoot for 5mb/s, but for high * input clock rates we try to do 10mb/s although I don't think a transfer can * even run that fast with an ESP even with DMA2 scatter gather pipelining. */ #define SYNC_DEFP_SLOW 0x32 /* 5mb/s */ #define SYNC_DEFP_FAST 0x19 /* 10mb/s */ struct esp_cmd_priv { union { dma_addr_t dma_addr; int num_sg; } u; int cur_residue; struct scatterlist *cur_sg; int tot_residue; }; #define ESP_CMD_PRIV(CMD) ((struct esp_cmd_priv *)(&(CMD)->SCp)) enum esp_rev { ESP100 = 0x00, /* NCR53C90 - very broken */ ESP100A = 0x01, /* NCR53C90A */ ESP236 = 0x02, FAS236 = 0x03, FAS100A = 0x04, FAST = 0x05, FASHME = 0x06, }; struct esp_cmd_entry { struct list_head list; struct scsi_cmnd *cmd; unsigned int saved_cur_residue; struct scatterlist *saved_cur_sg; unsigned int saved_tot_residue; u8 flags; #define ESP_CMD_FLAG_WRITE 0x01 /* DMA is a write */ #define ESP_CMD_FLAG_ABORT 0x02 /* being aborted */ #define ESP_CMD_FLAG_AUTOSENSE 0x04 /* Doing automatic REQUEST_SENSE */ u8 tag[2]; u8 status; u8 message; unsigned char *sense_ptr; unsigned char *saved_sense_ptr; dma_addr_t sense_dma; struct completion *eh_done; }; /* XXX make this configurable somehow XXX */ #define ESP_DEFAULT_TAGS 16 #define ESP_MAX_TARGET 16 #define ESP_MAX_LUN 8 #define ESP_MAX_TAG 256 struct esp_lun_data { struct esp_cmd_entry *non_tagged_cmd; int num_tagged; int hold; struct esp_cmd_entry *tagged_cmds[ESP_MAX_TAG]; }; struct esp_target_data { /* These are the ESP_STP, ESP_SOFF, and ESP_CFG3 register values which * match the currently negotiated settings for this target. The SCSI * protocol values are maintained in spi_{offset,period,wide}(starget). */ u8 esp_period; u8 esp_offset; u8 esp_config3; u8 flags; #define ESP_TGT_WIDE 0x01 #define ESP_TGT_DISCONNECT 0x02 #define ESP_TGT_NEGO_WIDE 0x04 #define ESP_TGT_NEGO_SYNC 0x08 #define ESP_TGT_CHECK_NEGO 0x40 #define ESP_TGT_BROKEN 0x80 /* When ESP_TGT_CHECK_NEGO is set, on the next scsi command to this * device we will try to negotiate the following parameters. */ u8 nego_goal_period; u8 nego_goal_offset; u8 nego_goal_width; u8 nego_goal_tags; struct scsi_target *starget; }; struct esp_event_ent { u8 type; #define ESP_EVENT_TYPE_EVENT 0x01 #define ESP_EVENT_TYPE_CMD 0x02 u8 val; u8 sreg; u8 seqreg; u8 sreg2; u8 ireg; u8 select_state; u8 event; u8 __pad; }; struct esp; struct esp_driver_ops { /* Read and write the ESP 8-bit registers. On some * applications of the ESP chip the registers are at 4-byte * instead of 1-byte intervals. */ void (*esp_write8)(struct esp *esp, u8 val, unsigned long reg); u8 (*esp_read8)(struct esp *esp, unsigned long reg); /* Map and unmap DMA memory. Eventually the driver will be * converted to the generic DMA API as soon as SBUS is able to * cope with that. At such time we can remove this. */ dma_addr_t (*map_single)(struct esp *esp, void *buf, size_t sz, int dir); int (*map_sg)(struct esp *esp, struct scatterlist *sg, int num_sg, int dir); void (*unmap_single)(struct esp *esp, dma_addr_t addr, size_t sz, int dir); void (*unmap_sg)(struct esp *esp, struct scatterlist *sg, int num_sg, int dir); /* Return non-zero if there is an IRQ pending. Usually this * status bit lives in the DMA controller sitting in front of * the ESP. This has to be accurate or else the ESP interrupt * handler will not run. */ int (*irq_pending)(struct esp *esp); /* Return the maximum allowable size of a DMA transfer for a * given buffer. */ u32 (*dma_length_limit)(struct esp *esp, u32 dma_addr, u32 dma_len); /* Reset the DMA engine entirely. On return, ESP interrupts * should be enabled. Often the interrupt enabling is * controlled in the DMA engine. */ void (*reset_dma)(struct esp *esp); /* Drain any pending DMA in the DMA engine after a transfer. * This is for writes to memory. */ void (*dma_drain)(struct esp *esp); /* Invalidate the DMA engine after a DMA transfer. */ void (*dma_invalidate)(struct esp *esp); /* Setup an ESP command that will use a DMA transfer. * The 'esp_count' specifies what transfer length should be * programmed into the ESP transfer counter registers, whereas * the 'dma_count' is the length that should be programmed into * the DMA controller. Usually they are the same. If 'write' * is non-zero, this transfer is a write into memory. 'cmd' * holds the ESP command that should be issued by calling * scsi_esp_cmd() at the appropriate time while programming * the DMA hardware. */ void (*send_dma_cmd)(struct esp *esp, u32 dma_addr, u32 esp_count, u32 dma_count, int write, u8 cmd); /* Return non-zero if the DMA engine is reporting an error * currently. */ int (*dma_error)(struct esp *esp); }; #define ESP_MAX_MSG_SZ 8 #define ESP_EVENT_LOG_SZ 32 #define ESP_QUICKIRQ_LIMIT 100 #define ESP_RESELECT_TAG_LIMIT 2500 struct esp { void __iomem *regs; void __iomem *dma_regs; const struct esp_driver_ops *ops; struct Scsi_Host *host; void *dev; struct esp_cmd_entry *active_cmd; struct list_head queued_cmds; struct list_head active_cmds; u8 *command_block; dma_addr_t command_block_dma; unsigned int data_dma_len; /* The following are used to determine the cause of an IRQ. Upon every * IRQ entry we synchronize these with the hardware registers. */ u8 sreg; u8 seqreg; u8 sreg2; u8 ireg; u32 prev_hme_dmacsr; u8 prev_soff; u8 prev_stp; u8 prev_cfg3; u8 __pad; struct list_head esp_cmd_pool; struct esp_target_data target[ESP_MAX_TARGET]; int fifo_cnt; u8 fifo[16]; struct esp_event_ent esp_event_log[ESP_EVENT_LOG_SZ]; int esp_event_cur; u8 msg_out[ESP_MAX_MSG_SZ]; int msg_out_len; u8 msg_in[ESP_MAX_MSG_SZ]; int msg_in_len; u8 bursts; u8 config1; u8 config2; u8 scsi_id; u32 scsi_id_mask; enum esp_rev rev; u32 flags; #define ESP_FLAG_DIFFERENTIAL 0x00000001 #define ESP_FLAG_RESETTING 0x00000002 #define ESP_FLAG_DOING_SLOWCMD 0x00000004 #define ESP_FLAG_WIDE_CAPABLE 0x00000008 #define ESP_FLAG_QUICKIRQ_CHECK 0x00000010 #define ESP_FLAG_DISABLE_SYNC 0x00000020 u8 select_state; #define ESP_SELECT_NONE 0x00 /* Not selecting */ #define ESP_SELECT_BASIC 0x01 /* Select w/o MSGOUT phase */ #define ESP_SELECT_MSGOUT 0x02 /* Select with MSGOUT */ /* When we are not selecting, we are expecting an event. */ u8 event; #define ESP_EVENT_NONE 0x00 #define ESP_EVENT_CMD_START 0x01 #define ESP_EVENT_CMD_DONE 0x02 #define ESP_EVENT_DATA_IN 0x03 #define ESP_EVENT_DATA_OUT 0x04 #define ESP_EVENT_DATA_DONE 0x05 #define ESP_EVENT_MSGIN 0x06 #define ESP_EVENT_MSGIN_MORE 0x07 #define ESP_EVENT_MSGIN_DONE 0x08 #define ESP_EVENT_MSGOUT 0x09 #define ESP_EVENT_MSGOUT_DONE 0x0a #define ESP_EVENT_STATUS 0x0b #define ESP_EVENT_FREE_BUS 0x0c #define ESP_EVENT_CHECK_PHASE 0x0d #define ESP_EVENT_RESET 0x10 /* Probed in esp_get_clock_params() */ u32 cfact; u32 cfreq; u32 ccycle; u32 ctick; u32 neg_defp; u32 sync_defp; /* Computed in esp_reset_esp() */ u32 max_period; u32 min_period; u32 radelay; /* Slow command state. */ u8 *cmd_bytes_ptr; int cmd_bytes_left; struct completion *eh_reset; void *dma; int dmarev; }; /* A front-end driver for the ESP chip should do the following in * it's device probe routine: * 1) Allocate the host and private area using scsi_host_alloc() * with size 'sizeof(struct esp)'. The first argument to * scsi_host_alloc() should be &scsi_esp_template. * 2) Set host->max_id as appropriate. * 3) Set esp->host to the scsi_host itself, and esp->dev * to the device object pointer. * 4) Hook up esp->ops to the front-end implementation. * 5) If the ESP chip supports wide transfers, set ESP_FLAG_WIDE_CAPABLE * in esp->flags. * 6) Map the DMA and ESP chip registers. * 7) DMA map the ESP command block, store the DMA address * in esp->command_block_dma. * 8) Register the scsi_esp_intr() interrupt handler. * 9) Probe for and provide the following chip properties: * esp->scsi_id (assign to esp->host->this_id too) * esp->scsi_id_mask * If ESP bus is differential, set ESP_FLAG_DIFFERENTIAL * esp->cfreq * DMA burst bit mask in esp->bursts, if necessary * 10) Perform any actions necessary before the ESP device can * be programmed for the first time. On some configs, for * example, the DMA engine has to be reset before ESP can * be programmed. * 11) If necessary, call dev_set_drvdata() as needed. * 12) Call scsi_esp_register() with prepared 'esp' structure * and a device pointer if possible. * 13) Check scsi_esp_register() return value, release all resources * if an error was returned. */ extern struct scsi_host_template scsi_esp_template; extern int scsi_esp_register(struct esp *, struct device *); extern void scsi_esp_unregister(struct esp *); extern irqreturn_t scsi_esp_intr(int, void *); extern void scsi_esp_cmd(struct esp *, u8); #endif /* !(_ESP_SCSI_H) */
{ "pile_set_name": "Github" }
package com.daviancorp.android.ui.general; /* * Copyright (C) 2013 The Android Open Source Project * * 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. */ //import android.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.widget.LinearLayout; import com.daviancorp.android.mh4udatabase.R; import com.daviancorp.android.ui.general.SlidingTabLayout; class SlidingTabStrip extends LinearLayout { private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0; private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26; private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 3; private static final int DEFAULT_SELECTED_INDICATOR_COLOR = R.color.accent_color; private final int mBottomBorderThickness; private final Paint mBottomBorderPaint; private final int mSelectedIndicatorThickness; private final Paint mSelectedIndicatorPaint; private final int mDefaultBottomBorderColor; private int mSelectedPosition; private float mSelectionOffset; private SlidingTabLayout.TabColorizer mCustomTabColorizer; private final SimpleTabColorizer mDefaultTabColorizer; SlidingTabStrip(Context context) { this(context, null); } SlidingTabStrip(Context context, AttributeSet attrs) { super(context, attrs); setWillNotDraw(false); final float density = getResources().getDisplayMetrics().density; TypedValue outValue = new TypedValue(); //context.getTheme().resolveAttribute(R.attr.colorForeground, outValue, true); final int themeForegroundColor = outValue.data; mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA); mDefaultTabColorizer = new SimpleTabColorizer(); mDefaultTabColorizer.setIndicatorColors(getResources().getColor(DEFAULT_SELECTED_INDICATOR_COLOR)); mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density); mBottomBorderPaint = new Paint(); mBottomBorderPaint.setColor(mDefaultBottomBorderColor); mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density); mSelectedIndicatorPaint = new Paint(); } void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) { mCustomTabColorizer = customTabColorizer; invalidate(); } void setSelectedIndicatorColors(int... colors) { // Make sure that the custom colorizer is removed mCustomTabColorizer = null; mDefaultTabColorizer.setIndicatorColors(colors); invalidate(); } void onViewPagerPageChanged(int position, float positionOffset) { mSelectedPosition = position; mSelectionOffset = positionOffset; invalidate(); } @Override protected void onDraw(Canvas canvas) { final int height = getHeight(); final int childCount = getChildCount(); final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null ? mCustomTabColorizer : mDefaultTabColorizer; // Thick colored underline below the current selection if (childCount > 0) { View selectedTitle = getChildAt(mSelectedPosition); int left = selectedTitle.getLeft(); int right = selectedTitle.getRight(); int color = tabColorizer.getIndicatorColor(mSelectedPosition); if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) { int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1); if (color != nextColor) { color = blendColors(nextColor, color, mSelectionOffset); } // Draw the selection partway between the tabs View nextTitle = getChildAt(mSelectedPosition + 1); left = (int) (mSelectionOffset * nextTitle.getLeft() + (1.0f - mSelectionOffset) * left); right = (int) (mSelectionOffset * nextTitle.getRight() + (1.0f - mSelectionOffset) * right); } mSelectedIndicatorPaint.setColor(color); canvas.drawRect(left, height - mSelectedIndicatorThickness, right, height, mSelectedIndicatorPaint); } // Thin underline along the entire bottom edge canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint); } /** * Set the alpha value of the {@code color} to be the given {@code alpha} value. */ private static int setColorAlpha(int color, byte alpha) { return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color)); } /** * Blend {@code color1} and {@code color2} using the given ratio. * * @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend, * 0.0 will return {@code color2}. */ private static int blendColors(int color1, int color2, float ratio) { final float inverseRation = 1f - ratio; float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation); float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation); float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation); return Color.rgb((int) r, (int) g, (int) b); } private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer { private int[] mIndicatorColors; @Override public final int getIndicatorColor(int position) { return mIndicatorColors[position % mIndicatorColors.length]; } void setIndicatorColors(int... colors) { mIndicatorColors = colors; } } }
{ "pile_set_name": "Github" }
--- layout: index title: usedefaultprefix --- "usedefaultprefix" is a [boolean](../types/boolean.html) attribute. If set to true, the object's [prefix](prefix.html) is ignored if set, and a default prefix is used instead - for English games, "a" or "an" is used.
{ "pile_set_name": "Github" }
{ "name": "abp-web-resources", "version": "2.1.2", "description": "ASP.NET Boilerplate web resources", "main": "Abp/Framework/scripts/abp.js", "dependencies": {}, "devDependencies": { "del": "^2.2.0", "gulp": "^3.9.0", "gulp-shell": "^0.5.2", "xml2js": "^0.4.16" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/aspnetboilerplate/bower-abp-resources.git" }, "keywords": [ "asp.net", "boilerplate", "web", "resources" ], "author": "Halil İbrahim Kalkan", "license": "MIT", "bugs": { "url": "https://github.com/aspnetboilerplate/bower-abp-resources/issues" }, "homepage": "http://www.aspnetboilerplate.com/" }
{ "pile_set_name": "Github" }
package com.dotmarketing.portlets.rules.parameter.comparison; import com.dotcms.util.HttpRequestDataUtil; /** * @author Geoff M. Granum */ public class NetmaskComparison extends Comparison<String> { public NetmaskComparison() { super("netmask"); } @Override public boolean perform(String ipAddress, String netmask) { return HttpRequestDataUtil.isIpMatchingNetmask(ipAddress, netmask); } }
{ "pile_set_name": "Github" }
//===-- PowerPCTargetInfo.cpp - PowerPC Target Implementation -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PPC.h" #include "llvm/Module.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; Target llvm::ThePPC32Target, llvm::ThePPC64Target; extern "C" void LLVMInitializePowerPCTargetInfo() { RegisterTarget<Triple::ppc, /*HasJIT=*/true> X(ThePPC32Target, "ppc32", "PowerPC 32"); RegisterTarget<Triple::ppc64, /*HasJIT=*/true> Y(ThePPC64Target, "ppc64", "PowerPC 64"); }
{ "pile_set_name": "Github" }
# LZ4 - Fast LZ compression algorithm # Copyright (C) 2011-2014, Yann Collet. # BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) prefix=@PREFIX@ libdir=@LIBDIR@ includedir=@INCLUDEDIR@ Name: lz4 Description: fast lossless compression algorithm library URL: http://code.google.com/p/lz4/ Version: @VERSION@ Libs: -L@LIBDIR@ -llz4 Cflags: -I@INCLUDEDIR@
{ "pile_set_name": "Github" }
/* Copyright (C) 2013-2019 Expedia 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 com.hotels.styx.proxy.backends.file; /** * FileMonitor watches a file and notifies when it changes. */ public interface FileMonitor { FileMonitor DISABLED = x -> { }; void start(Listener listener); /** * A Listener to receive file change notifications. */ interface Listener { void fileChanged(); } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010 Francisco Jerez. * All Rights Reserved. * * 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 (including the * next paragraph) 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 COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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 "nv04.h" #include "fbmem.h" #include <subdev/bios.h> #include <subdev/bios/init.h> static void nv10_devinit_meminit(struct nvkm_devinit *init) { struct nvkm_subdev *subdev = &init->subdev; struct nvkm_device *device = subdev->device; static const int mem_width[] = { 0x10, 0x00, 0x20 }; int mem_width_count; uint32_t patt = 0xdeadbeef; struct io_mapping *fb; int i, j, k; if (device->card_type >= NV_11 && device->chipset >= 0x17) mem_width_count = 3; else mem_width_count = 2; /* Map the framebuffer aperture */ fb = fbmem_init(device); if (!fb) { nvkm_error(subdev, "failed to map fb\n"); return; } nvkm_wr32(device, NV10_PFB_REFCTRL, NV10_PFB_REFCTRL_VALID_1); /* Probe memory bus width */ for (i = 0; i < mem_width_count; i++) { nvkm_mask(device, NV04_PFB_CFG0, 0x30, mem_width[i]); for (j = 0; j < 4; j++) { for (k = 0; k < 4; k++) fbmem_poke(fb, 0x1c, 0); fbmem_poke(fb, 0x1c, patt); fbmem_poke(fb, 0x3c, 0); if (fbmem_peek(fb, 0x1c) == patt) goto mem_width_found; } } mem_width_found: patt <<= 1; /* Probe amount of installed memory */ for (i = 0; i < 4; i++) { int off = nvkm_rd32(device, 0x10020c) - 0x100000; fbmem_poke(fb, off, patt); fbmem_poke(fb, 0, 0); fbmem_peek(fb, 0); fbmem_peek(fb, 0); fbmem_peek(fb, 0); fbmem_peek(fb, 0); if (fbmem_peek(fb, off) == patt) goto amount_found; } /* IC missing - disable the upper half memory space. */ nvkm_mask(device, NV04_PFB_CFG0, 0x1000, 0); amount_found: fbmem_fini(fb); } static const struct nvkm_devinit_func nv10_devinit = { .dtor = nv04_devinit_dtor, .preinit = nv04_devinit_preinit, .post = nv04_devinit_post, .meminit = nv10_devinit_meminit, .pll_set = nv04_devinit_pll_set, }; int nv10_devinit_new(struct nvkm_device *device, int index, struct nvkm_devinit **pinit) { return nv04_devinit_new_(&nv10_devinit, device, index, pinit); }
{ "pile_set_name": "Github" }
LBL_CreateProjectStep=Name and Location datasourcePanelVisual.projectLocationLabel.text=Project &Location: datasourcePanelVisual.projectNameLabel.text=Project &Name: datasourcePanelVisual.createdFolderLabel.text=Project &Folder: datasourcePanelVisual.browseButton.actionCommand=BROWSE datasourcePanelVisual.browseButton.text=Br&owse...
{ "pile_set_name": "Github" }
package main import ( "fmt" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/kava-labs/kava/app" ) /* NOTE TO FUTURE IMPLEMENTERS This monkey patches the sdk `keys` command, therefore needs to be reviewed on any sdk updates. The patch adds support for using kava's legacy bip44 coin type to the cli. Coin types are used to create a bip44 derivation path, which is used as a mapping from mnemonic to private key. In cosmos-sdk v0.38.3, all private keys are stored without reference to the mnemonic or bip44 derivation path, except ledger keys. Ledger keys are just references to a private key on a ledger device. They contain the bip44 derivation path. To patch the cli, we only need to modify: - when new ledger references are created - anything to do with converting a mnemonic to a private key. These only happen in `kvcli keys add` cmd. For private key generation, use a --legacy-hd-path flag to enable old coin type. The current cosmos ledger app (v1.5.3) only supports the legacy coin type. So we only need to ensure ledger reference creation doesn't use the new coin type. Signing txs: - with local keys - the stored the priv key is used to sign, mnemonics or bip44 paths not involved - with ledger - the stored bip44 path is used to instruct the ledger which key to sign with */ const flagLegacyHDPath = "legacy-hd-path" const flagHDPath = "hd-path" // this is copied from keys add cmd because it's not exported // getModifiedKeysCmd returns the standard cosmos-sdk/client/keys cmd but modified to support new and old bip44 coin types supported by kava. func getModifiedKeysCmd() *cobra.Command { keysCmd := keys.Commands() for _, c := range keysCmd.Commands() { if c.Name() == "add" { monkeyPatchCmdKeysAdd(c) break } } return keysCmd } // monkeyPatchCmdKeysAdd modifies the `keys add` command to use the old bip44 coin type when a flag is passed. func monkeyPatchCmdKeysAdd(keysAddCmd *cobra.Command) { // add flag keysAddCmd.Flags().Bool(flagLegacyHDPath, false, fmt.Sprintf("Use the old bip44 coin type (%d) to derive addresses from mnemonics.", sdk.CoinType)) // replace description keysAddCmd.Long = fmt.Sprintf(`Derive a new private key and encrypt to disk. Optionally specify a BIP39 mnemonic, a BIP39 passphrase to further secure the mnemonic, and BIP44 account/index numbers to derive a specific key. The key will be stored under the given name and encrypted with the given password. NOTE: This cli defaults to Kava's BIP44 coin type %d. Use the --%s flag to use the old one (%d). The flag --recover allows one to recover a key from a seed passphrase. If run with --dry-run, a key would be generated (or recovered) but not stored to the local keystore. Use the --pubkey flag to add arbitrary public keys to the keystore for constructing multisig transactions. You can add a multisig key by passing the list of key names you want the public key to be composed of to the --multisig flag and the minimum number of signatures required through --multisig-threshold. The keys are sorted by address, unless the flag --nosort is set. `, app.Bip44CoinType, flagLegacyHDPath, sdk.CoinType) // replace the run function with a wrapped version that sets the old coin type in the global config oldRun := keysAddCmd.RunE keysAddCmd.RunE = func(cmd *cobra.Command, args []string) error { if !viper.GetBool(flagLegacyHDPath) && viper.GetBool(flags.FlagUseLedger) { return fmt.Errorf("cosmos ledger app only supports legacy bip44 coin type, must use --%s flag when adding ledger key", flagLegacyHDPath) } if viper.GetBool(flagLegacyHDPath) && viper.IsSet(flagHDPath) { return fmt.Errorf("cannot use a custom hd path (--%s) and legacy bip44 coin type (--%s) at the same time", flagHDPath, flagLegacyHDPath) } if viper.GetBool(flagLegacyHDPath) { preExistingCoinType := sdk.GetConfig().GetCoinType() sdk.GetConfig().SetCoinType(sdk.CoinType) // set old coin type err := oldRun(cmd, args) sdk.GetConfig().SetCoinType(preExistingCoinType) // revert to pre-existing coin type return err } return oldRun(cmd, args) } }
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Routing\Generator; use Symfony\Component\Routing\Exception\InvalidParameterException; use Symfony\Component\Routing\Exception\MissingMandatoryParametersException; use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Component\Routing\RequestContextAwareInterface; /** * UrlGeneratorInterface is the interface that all URL generator classes must implement. * * The constants in this interface define the different types of resource references that * are declared in RFC 3986: http://tools.ietf.org/html/rfc3986 * We are using the term "URL" instead of "URI" as this is more common in web applications * and we do not need to distinguish them as the difference is mostly semantical and * less technical. Generating URIs, i.e. representation-independent resource identifiers, * is also possible. * * @author Fabien Potencier <fabien@symfony.com> * @author Tobias Schultze <http://tobion.de> */ interface UrlGeneratorInterface extends RequestContextAwareInterface { /** * Generates an absolute URL, e.g. "http://example.com/dir/file". */ const ABSOLUTE_URL = 0; /** * Generates an absolute path, e.g. "/dir/file". */ const ABSOLUTE_PATH = 1; /** * Generates a relative path based on the current request path, e.g. "../parent-file". * * @see UrlGenerator::getRelativePath() */ const RELATIVE_PATH = 2; /** * Generates a network path, e.g. "//example.com/dir/file". * Such reference reuses the current scheme but specifies the host. */ const NETWORK_PATH = 3; /** * Generates a URL or path for a specific route based on the given parameters. * * Parameters that reference placeholders in the route pattern will substitute them in the * path or host. Extra params are added as query string to the URL. * * When the passed reference type cannot be generated for the route because it requires a different * host or scheme than the current one, the method will return a more comprehensive reference * that includes the required params. For example, when you call this method with $referenceType = ABSOLUTE_PATH * but the route requires the https scheme whereas the current scheme is http, it will instead return an * ABSOLUTE_URL with the https scheme and the current host. This makes sure the generated URL matches * the route in any case. * * If there is no route with the given name, the generator must throw the RouteNotFoundException. * * The special parameter _fragment will be used as the document fragment suffixed to the final URL. * * @param string $name The name of the route * @param mixed[] $parameters An array of parameters * @param int $referenceType The type of reference to be generated (one of the constants) * * @return string The generated URL * * @throws RouteNotFoundException If the named route doesn't exist * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route * @throws InvalidParameterException When a parameter value for a placeholder is not correct because * it does not match the requirement */ public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH); }
{ "pile_set_name": "Github" }
/* * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #ifndef AWT_OBJECT_H #define AWT_OBJECT_H #include "awt.h" #include "awt_Toolkit.h" #include "java_awt_Event.h" #include "java_awt_AWTEvent.h" #include "sun_awt_windows_WObjectPeer.h" /************************************************************************ * AwtObject class */ class AwtObject { public: class ExecuteArgs { public: UINT cmdId; LPARAM param1; LPARAM param2; LPARAM param3; LPARAM param4; }; /* sun.awt.windows.WObjectPeer field and method ids */ static jfieldID pDataID; static jfieldID destroyedID; static jfieldID targetID; static jmethodID getPeerForTargetMID; static jclass wObjectPeerClass; static jfieldID createErrorID; AwtObject(); virtual ~AwtObject(); // Frees all the resources used by this object and then sends a message to TT to delete it. // After this method has been called, this object must not be used in any way. virtual void Dispose(); // Static method to be called from JNI methods to dispose AwtObject // specified by jobject static void _Dispose(jobject self); // Static method to be called from JNI methods to dispose AwtObject // specified by pData static void _Dispose(PDATA pData); INLINE CriticalSection& GetLock() { return m_Lock; } // Return the associated AWT peer or target object. INLINE jobject GetPeer(JNIEnv *env) { return m_peerObject; } INLINE jobject GetTarget(JNIEnv *env) { jobject peer = GetPeer(env); if (peer != NULL) { return env->GetObjectField(peer, AwtObject::targetID); } else { return NULL; } } INLINE jobject GetTargetAsGlobalRef(JNIEnv *env) { jobject localRef = GetTarget(env); if (localRef == NULL) { return NULL; } jobject globalRef = env->NewGlobalRef(localRef); env->DeleteLocalRef(localRef); return globalRef; } // Return the peer associated with some target static jobject GetPeerForTarget(JNIEnv *env, jobject target); // Java callback routines // Invoke a callback on the java peer object asynchronously void DoCallback(const char* methodName, const char* methodSig, ...); // Allocate and initialize a new event, and post it to the peer's // target object. No response is expected from the target. void SendEvent(jobject event); INLINE void EnableCallbacks(BOOL e) { m_callbacksEnabled = e; } // Execute any code associated with a command ID -- only classes with // DoCommand() defined should associate their instances with cmdIDs. virtual void DoCommand(void) { DASSERT(FALSE); } // execute given code on Windows message-pump thread static LRESULT WinThreadExec(jobject peerObject, UINT cmdId, LPARAM param1 = 0L, LPARAM param2 = 0L, LPARAM param3 = 0L, LPARAM param4 = 0L); // callback function to execute code on Windows message-pump thread virtual LRESULT WinThreadExecProc(AwtObject::ExecuteArgs * args); // overridden in AwtComponent to return FALSE if any messages // are being processed by this component virtual BOOL CanBeDeleted() { return TRUE; } protected: jobject m_peerObject; BOOL m_callbacksEnabled; private: CriticalSection m_Lock; }; #endif // AWT_OBJECT_H
{ "pile_set_name": "Github" }
/* Copyright 2019 The Vitess 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. */ // This file contains useful data structures for RPCs in Vitess. syntax = "proto3"; package query; // CallerID is passed along RPCs to identify the originating client // for a request. It is not meant to be secure, but only // informational. The client can put whatever info they want in these // fields, and they will be trusted by the servers. The fields will // just be used for logging purposes, and to easily find a client. // VtGate propagates it to VtTablet, and VtTablet may use this // information for monitoring purposes, to display on dashboards, or // for blacklisting purposes. message CallerID { // principal is the effective user identifier. It is usually filled in // with whoever made the request to the appserver, if the request // came from an automated job or another system component. // If the request comes directly from the Internet, or if the Vitess client // takes action on its own accord, it is okay for this field to be absent. string principal = 1; // component describes the running process of the effective caller. // It can for instance be the hostname:port of the servlet initiating the // database call, or the container engine ID used by the servlet. string component = 2; // subcomponent describes a component inisde the immediate caller which // is responsible for generating is request. Suggested values are a // servlet name or an API endpoint name. string subcomponent = 3; } // Code represents canonical error codes. The names, numbers and comments // must match the ones defined by grpc: // https://godoc.org/google.golang.org/grpc/codes. enum Code { // OK is returned on success. OK = 0; // CANCELED indicates the operation was cancelled (typically by the caller). CANCELED = 1; // UNKNOWN error. An example of where this error may be returned is // if a Status value received from another address space belongs to // an error-space that is not known in this address space. Also // errors raised by APIs that do not return enough error information // may be converted to this error. UNKNOWN = 2; // INVALID_ARGUMENT indicates client specified an invalid argument. // Note that this differs from FAILED_PRECONDITION. It indicates arguments // that are problematic regardless of the state of the system // (e.g., a malformed file name). INVALID_ARGUMENT = 3; // DEADLINE_EXCEEDED means operation expired before completion. // For operations that change the state of the system, this error may be // returned even if the operation has completed successfully. For // example, a successful response from a server could have been delayed // long enough for the deadline to expire. DEADLINE_EXCEEDED = 4; // NOT_FOUND means some requested entity (e.g., file or directory) was // not found. NOT_FOUND = 5; // ALREADY_EXISTS means an attempt to create an entity failed because one // already exists. ALREADY_EXISTS = 6; // PERMISSION_DENIED indicates the caller does not have permission to // execute the specified operation. It must not be used for rejections // caused by exhausting some resource (use RESOURCE_EXHAUSTED // instead for those errors). It must not be // used if the caller cannot be identified (use Unauthenticated // instead for those errors). PERMISSION_DENIED = 7; // UNAUTHENTICATED indicates the request does not have valid // authentication credentials for the operation. UNAUTHENTICATED = 16; // RESOURCE_EXHAUSTED indicates some resource has been exhausted, perhaps // a per-user quota, or perhaps the entire file system is out of space. RESOURCE_EXHAUSTED = 8; // FAILED_PRECONDITION indicates operation was rejected because the // system is not in a state required for the operation's execution. // For example, directory to be deleted may be non-empty, an rmdir // operation is applied to a non-directory, etc. // // A litmus test that may help a service implementor in deciding // between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: // (a) Use UNAVAILABLE if the client can retry just the failing call. // (b) Use ABORTED if the client should retry at a higher-level // (e.g., restarting a read-modify-write sequence). // (c) Use FAILED_PRECONDITION if the client should not retry until // the system state has been explicitly fixed. E.g., if an "rmdir" // fails because the directory is non-empty, FAILED_PRECONDITION // should be returned since the client should not retry unless // they have first fixed up the directory by deleting files from it. // (d) Use FAILED_PRECONDITION if the client performs conditional // REST Get/Update/Delete on a resource and the resource on the // server does not match the condition. E.g., conflicting // read-modify-write on the same resource. FAILED_PRECONDITION = 9; // ABORTED indicates the operation was aborted, typically due to a // concurrency issue like sequencer check failures, transaction aborts, // etc. // // See litmus test above for deciding between FAILED_PRECONDITION, // ABORTED, and UNAVAILABLE. ABORTED = 10; // OUT_OF_RANGE means operation was attempted past the valid range. // E.g., seeking or reading past end of file. // // Unlike INVALID_ARGUMENT, this error indicates a problem that may // be fixed if the system state changes. For example, a 32-bit file // system will generate INVALID_ARGUMENT if asked to read at an // offset that is not in the range [0,2^32-1], but it will generate // OUT_OF_RANGE if asked to read from an offset past the current // file size. // // There is a fair bit of overlap between FAILED_PRECONDITION and // OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific // error) when it applies so that callers who are iterating through // a space can easily look for an OUT_OF_RANGE error to detect when // they are done. OUT_OF_RANGE = 11; // UNIMPLEMENTED indicates operation is not implemented or not // supported/enabled in this service. UNIMPLEMENTED = 12; // INTERNAL errors. Means some invariants expected by underlying // system has been broken. If you see one of these errors, // something is very broken. INTERNAL = 13; // UNAVAILABLE indicates the service is currently unavailable. // This is a most likely a transient condition and may be corrected // by retrying with a backoff. // // See litmus test above for deciding between FAILED_PRECONDITION, // ABORTED, and UNAVAILABLE. UNAVAILABLE = 14; // DATA_LOSS indicates unrecoverable data loss or corruption. DATA_LOSS = 15; } // LegacyErrorCode is the enum values for Errors. This type is deprecated. // Use Code instead. Background: In the initial design, we thought // that we may end up with a different list of canonical error codes // than the ones defined by grpc. In hindsight, we realize that // the grpc error codes are fairly generic and mostly sufficient. // In order to avoid confusion, this type will be deprecated in // favor of the new Code that matches exactly what grpc defines. // Some names below have a _LEGACY suffix. This is to prevent // name collisions with Code. enum LegacyErrorCode { // SUCCESS_LEGACY is returned from a successful call. SUCCESS_LEGACY = 0; // CANCELLED_LEGACY means that the context was cancelled (and noticed in the app layer, // as opposed to the RPC layer). CANCELLED_LEGACY = 1; // UNKNOWN_ERROR_LEGACY includes: // 1. MySQL error codes that we don't explicitly handle. // 2. MySQL response that wasn't as expected. For example, we might expect a MySQL // timestamp to be returned in a particular way, but it wasn't. // 3. Anything else that doesn't fall into a different bucket. UNKNOWN_ERROR_LEGACY = 2; // BAD_INPUT_LEGACY is returned when an end-user either sends SQL that couldn't be parsed correctly, // or tries a query that isn't supported by Vitess. BAD_INPUT_LEGACY = 3; // DEADLINE_EXCEEDED_LEGACY is returned when an action is taking longer than a given timeout. DEADLINE_EXCEEDED_LEGACY = 4; // INTEGRITY_ERROR_LEGACY is returned on integrity error from MySQL, usually due to // duplicate primary keys. INTEGRITY_ERROR_LEGACY = 5; // PERMISSION_DENIED_LEGACY errors are returned when a user requests access to something // that they don't have permissions for. PERMISSION_DENIED_LEGACY = 6; // RESOURCE_EXHAUSTED_LEGACY is returned when a query exceeds its quota in some dimension // and can't be completed due to that. Queries that return RESOURCE_EXHAUSTED // should not be retried, as it could be detrimental to the server's health. // Examples of errors that will cause the RESOURCE_EXHAUSTED code: // 1. TxPoolFull: this is retried server-side, and is only returned as an error // if the server-side retries failed. // 2. Query is killed due to it taking too long. RESOURCE_EXHAUSTED_LEGACY = 7; // QUERY_NOT_SERVED_LEGACY means that a query could not be served right now. // Client can interpret it as: "the tablet that you sent this query to cannot // serve the query right now, try a different tablet or try again later." // This could be due to various reasons: QueryService is not serving, should // not be serving, wrong shard, wrong tablet type, blacklisted table, etc. // Clients that receive this error should usually retry the query, but after taking // the appropriate steps to make sure that the query will get sent to the correct // tablet. QUERY_NOT_SERVED_LEGACY = 8; // NOT_IN_TX_LEGACY means that we're not currently in a transaction, but we should be. NOT_IN_TX_LEGACY = 9; // INTERNAL_ERROR_LEGACY means some invariants expected by underlying // system has been broken. If you see one of these errors, // something is very broken. INTERNAL_ERROR_LEGACY = 10; // TRANSIENT_ERROR_LEGACY is used for when there is some error that we expect we can // recover from automatically - often due to a resource limit temporarily being // reached. Retrying this error, with an exponential backoff, should succeed. // Clients should be able to successfully retry the query on the same backends. // Examples of things that can trigger this error: // 1. Query has been throttled // 2. VtGate could have request backlog TRANSIENT_ERROR_LEGACY = 11; // UNAUTHENTICATED_LEGACY errors are returned when a user requests access to something, // and we're unable to verify the user's authentication. UNAUTHENTICATED_LEGACY = 12; } // RPCError is an application-level error structure returned by // VtTablet (and passed along by VtGate if appropriate). // We use this so the clients don't have to parse the error messages, // but instead can depend on the value of the code. message RPCError { LegacyErrorCode legacy_code = 1; string message = 2; Code code = 3; }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2015 Sebastian Daschner, sebastian-daschner.com * * 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/LICENSE2.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.sebastian_daschner.jaxrs_analyzer.analysis.classes.testclasses.resource.response; import com.sebastian_daschner.jaxrs_analyzer.model.elements.HttpResponse; import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class TestClass59 { ConfigurationManager configurationManager; @javax.ws.rs.GET public Response method(final String name) { ConfigurationManager.Configuration configuration = this.configurationManager.getConfiguration(name); if (configuration == null) return Response.noContent().build(); return Response.ok(configuration).build(); } public static Set<HttpResponse> getResult() { final HttpResponse responseFound = new HttpResponse(); responseFound.getStatuses().add(200); responseFound.getEntityTypes().add("Lcom/sebastian_daschner/jaxrs_analyzer/analysis/classes/testclasses/resource/response/TestClass59$ConfigurationManager$Configuration;"); final HttpResponse responseNotFound = new HttpResponse(); responseNotFound.getStatuses().add(204); return new HashSet<>(Arrays.asList(responseFound, responseNotFound)); } private interface ConfigurationManager { Configuration getConfiguration(String name); class Configuration { } } }
{ "pile_set_name": "Github" }
{ "status_code": 200, "data": { "User": { "Path": "/", "UserName": "devbot", "UserId": "AIDAZL6XWCR2OXOEADG5A", "Arn": "arn:aws:iam::644160558196:user/devbot", "CreateDate": { "__class__": "datetime", "year": 2020, "month": 4, "day": 2, "hour": 10, "minute": 36, "second": 22, "microsecond": 0 }, "PermissionsBoundary": { "PermissionsBoundaryType": "Policy", "PermissionsBoundaryArn": "arn:aws:iam::644160558196:policy/BlackListIamList" } }, "ResponseMetadata": {} } }
{ "pile_set_name": "Github" }
/* Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved. * Portions Copyright © 1997-1999 Vita Nuova Limited * Portions Copyright © 2000-2007 Vita Nuova Holdings Limited * (www.vitanuova.com) * Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others * * Modified for the Akaros operating system: * Copyright (c) 2013-2014 The Regents of the University of California * Copyright (c) 2013-2015 Google Inc. * * 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 <slab.h> #include <kmalloc.h> #include <kref.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <error.h> #include <cpio.h> #include <pmap.h> #include <smp.h> #include <net/ip.h> /* * Generous estimate of number of fields, including terminal NULL pointer */ static int ncmdfield(char *p, int n) { int white, nwhite; char *ep; int nf; if (p == NULL) return 1; nf = 0; ep = p + n; white = 1; /* first text will start field */ while (p < ep) { /* UTF is irrelevant */ nwhite = (strchr(" \t\r\n", *p++ & 0xFF) != 0); if (white && !nwhite) /* beginning of field */ nf++; white = nwhite; } return nf + 1; /* +1 for NULL */ } /* * parse a command written to a device */ struct cmdbuf *parsecmd(char *p, size_t n) { ERRSTACK(1); struct cmdbuf *volatile cb; int nf; char *sp; nf = ncmdfield(p, n); /* allocate Cmdbuf plus string pointers plus copy of string including \0 */ sp = kzmalloc(sizeof(*cb) + nf * sizeof(char *) + n + 1, 0); cb = (struct cmdbuf *)sp; cb->f = (char **)(&cb[1]); cb->buf = (char *)(&cb->f[nf]); if (current != NULL && waserror()) { kfree(cb); nexterror(); } memmove(cb->buf, p, n); if (current != NULL) poperror(); /* dump new line and null terminate */ if (n > 0 && cb->buf[n - 1] == '\n') n--; cb->buf[n] = '\0'; cb->nf = tokenize(cb->buf, cb->f, nf - 1); cb->f[cb->nf] = NULL; return cb; } /* * Reconstruct original message, for error diagnostic */ void cmderror(struct cmdbuf *cb, char *s) { int i; char *p, *e; p = get_cur_genbuf(); e = p + GENBUF_SZ - 10; p = seprintf(p, e, "%s \"", s); for (i = 0; i < cb->nf; i++) { if (i > 0) p = seprintf(p, e, " "); p = seprintf(p, e, "%s", cb->f[i]); } seprintf(p, e, "\""); error(EFAIL, "%s", get_cur_genbuf()); } void debugcmd(struct cmdbuf *cb) { printk("cb %p, nr %d\n", cb, cb->nf); for (int i = 0; i < cb->nf; i++) { printk("%d: %s\n", i, cb->f[i]); } } /* * Look up entry in table */ struct cmdtab *lookupcmd(struct cmdbuf *cb, struct cmdtab *ctab, int nctab) { int i; struct cmdtab *ct; if (cb->nf == 0) error(EFAIL, "empty control message"); for (ct = ctab, i = 0; i < nctab; i++, ct++) { if (strcmp(ct->cmd, "*") != 0) /* wildcard always matches */ if (strcmp(ct->cmd, cb->f[0]) != 0) continue; if (ct->narg != 0 && ct->narg != cb->nf) cmderror(cb, "wrong number of args"); return ct; } cmderror(cb, "unknown control message"); return NULL; }
{ "pile_set_name": "Github" }
![Google Cloud Datastore API](http://www.google.com/images/icons/product/search-32.gif) # Unoffical Google Cloud Datastore API Samples for .NET ## API Description Accesses the schemaless NoSQL database to provide fully managed, robust, scalable storage for your application. [Offical Documentation](https://cloud.google.com/datastore/) ## Sample Description These samples show how to access the [Google Cloud Datastore API](https://cloud.google.com/datastore/) with the Offical [Google .Net client library](https://github.com/google/google-api-dotnet-client) Tutorials to go along with some of these samples can be found on [www.daimto.com](http://www.daimto.com/) # Developer Documentation * [Google API client Library for .NET - Get Started](https://developers.google.com/api-client-library/dotnet/get_started) * [Supported APIs](https://developers.google.com/api-client-library/dotnet/apis/) ## Installation Check API version README for information on how to install it and use these samples. ## Contributing These samples have been programmatically generated. Changes must be made in the T4 template files. Changes made in the samples themselves will be over written the next time the project is generated. Generated date: 2017-10-08 See [Contributing](CONTRIBUTING.md) ## License Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/) 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.
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Depends on csslint.js from https://github.com/stubbornella/csslint // declare global: CSSLint (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.registerHelper("lint", "css", function(text, options) { var found = []; if (!window.CSSLint) { if (window.console) { window.console.error("Error: window.CSSLint not defined, CodeMirror CSS linting cannot run."); } return found; } var results = CSSLint.verify(text, options), messages = results.messages, message = null; for ( var i = 0; i < messages.length; i++) { message = messages[i]; var startLine = message.line -1, endLine = message.line -1, startCol = message.col -1, endCol = message.col; found.push({ from: CodeMirror.Pos(startLine, startCol), to: CodeMirror.Pos(endLine, endCol), message: message.message, severity : message.type }); } return found; }); });
{ "pile_set_name": "Github" }
@import "configs"; .x-colorpicker-demo { position: absolute; left: $padding-width; top: ($padding-height + $line-height) / 2 - ($font-size - 2) / 4; width: $font-size - 2px; height: $font-size - 2px; + .x-textbox { padding-left: $padding-width * 2 + $font-size - 6px; } }
{ "pile_set_name": "Github" }
# Compression | Recipe | Crates | Categories | |--------|--------|------------| | [Decompress a tarball][ex-tar-decompress] | [![flate2-badge]][flate2] [![tar-badge]][tar] | [![cat-compression-badge]][cat-compression] | | [Compress a directory into a tarball][ex-tar-compress] | [![flate2-badge]][flate2] [![tar-badge]][tar] | [![cat-compression-badge]][cat-compression] | | [Decompress a tarball while removing a prefix from the paths][ex-tar-strip-prefix] | [![flate2-badge]][flate2] [![tar-badge]][tar] | [![cat-compression-badge]][cat-compression] | [ex-tar-decompress]: compression/tar.html#decompress-a-tarball [ex-tar-compress]: compression/tar.html#compress-a-directory-into-tarball [ex-tar-strip-prefix]: compression/tar.html#decompress-a-tarball-while-removing-a-prefix-from-the-paths {{#include links.md}}
{ "pile_set_name": "Github" }
package t1722 sealed trait Top trait C { private object P extends Top } /* $ scala -e 'new AnyRef with C' error: error while loading Top, class file '/private/tmp/bobobo/./Top.class' is broken (error reading Scala signature of /private/tmp/bobobo/./Top.class: malformed Scala signature of Top at 185; reference value P of trait C refers to nonexisting symbol.) one error found Martin: I think this has to do with children property. */
{ "pile_set_name": "Github" }
# Change Symbology of a Graphic 1. Run the sample, then turn on the drawing toolbar 2. Pick the rectangle drawing tool and draw a graphic (a rectangle) 3. Add this Add-In to a toolbar in ArcMap and click the button 4. The graphic, which was originally yellow, will now change color to green (it will actually be added back to the screen as a green graphic element) Note that Element is an Abstract class in the Carto Namespace. Its Object model diagram is under Carto Map Elements, and not under Carto Map and Page layout. Author: Sami E. [Documentation on IGraphicsContainer] (http://resources.arcgis.com/en/help/arcobjects-net/componenthelp/index.html#//0012000005p0000000) ## Features *Uses IGraphicsContainer *Uses IRgbColor *Uses ISimpleMarkerSymbol *Uses ISimpleRenderer *Uses ISymbol *Uses IGeoFeatureLayer
{ "pile_set_name": "Github" }