text
stringlengths
2
100k
meta
dict
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. 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, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing 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 MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR 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. # from boto.exception import JSONResponseError class LimitExceededException(JSONResponseError): pass class ResourceInUseException(JSONResponseError): pass class AccessDeniedException(JSONResponseError): pass class ResourceNotFoundException(JSONResponseError): pass class InternalServiceException(JSONResponseError): pass class ValidationException(JSONResponseError): pass class IncompatibleVersionException(JSONResponseError): pass
{ "pile_set_name": "Github" }
ID %Mix LLK LLK0 ----------------------------------------------------------------- 0 0.214766 157575 177169 1 0.214767 157576 177170 2 0.0994769 90260.4 91166.7 3 0.234567 -4703.97 -5204.97
{ "pile_set_name": "Github" }
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util.refresh import android.annotation.TargetApi import android.app.AlarmManager import android.app.PendingIntent import android.app.job.JobScheduler import android.content.Context import android.content.Intent import android.os.Build import android.os.SystemClock import android.support.v4.util.ArrayMap import org.mariotaku.kpreferences.KPreferences import de.vanita5.twittnuker.annotation.AutoRefreshType import de.vanita5.twittnuker.constant.refreshIntervalKey import de.vanita5.twittnuker.service.JobTaskService.Companion.JOB_IDS_REFRESH import de.vanita5.twittnuker.service.LegacyTaskService import de.vanita5.twittnuker.util.TaskServiceRunner.Companion.ACTION_REFRESH_FILTERS_SUBSCRIPTIONS import de.vanita5.twittnuker.util.TaskServiceRunner.Companion.ACTION_REFRESH_LAUNCH_PRESENTATIONS import java.util.concurrent.TimeUnit class LegacyAutoRefreshController( context: Context, kPreferences: KPreferences ) : AutoRefreshController(context, kPreferences) { private val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager private val pendingIntents: ArrayMap<String, PendingIntent> = ArrayMap() init { AutoRefreshType.ALL.forEach { type -> val action = LegacyTaskService.getRefreshAction(type) ?: return@forEach val intent = Intent(context, LegacyTaskService::class.java) intent.action = action pendingIntents[type] = PendingIntent.getService(context, 0, intent, 0) } } override fun appStarted() { rescheduleAll() rescheduleFiltersSubscriptionsRefresh() rescheduleLaunchPresentationsRefresh() } override fun rescheduleAll() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { removeAllJobs(context, JOB_IDS_REFRESH) } super.rescheduleAll() } override fun unschedule(type: String) { val pendingIntent = pendingIntents[type] ?: return alarmManager.cancel(pendingIntent) } override fun schedule(type: String) { val pendingIntent = pendingIntents[type] ?: return val interval = TimeUnit.MINUTES.toMillis(kPreferences[refreshIntervalKey]) if (interval > 0) { val triggerAt = SystemClock.elapsedRealtime() + interval alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, interval, pendingIntent) } } private fun rescheduleFiltersSubscriptionsRefresh() { val interval = TimeUnit.HOURS.toMillis(4) val triggerAt = SystemClock.elapsedRealtime() + interval val intent = Intent(context, LegacyTaskService::class.java) intent.action = ACTION_REFRESH_FILTERS_SUBSCRIPTIONS alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, interval, PendingIntent.getService(context, 0, intent, 0)) } private fun rescheduleLaunchPresentationsRefresh() { val interval = TimeUnit.HOURS.toMillis(6) val triggerAt = SystemClock.elapsedRealtime() + interval val intent = Intent(context, LegacyTaskService::class.java) intent.action = ACTION_REFRESH_LAUNCH_PRESENTATIONS alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, interval, PendingIntent.getService(context, 0, intent, 0)) } companion object { @TargetApi(Build.VERSION_CODES.LOLLIPOP) fun removeAllJobs(context: Context, jobIds: IntArray) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return val jobService = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler jobIds.forEach { id -> jobService.cancel(id) } } } }
{ "pile_set_name": "Github" }
**This airport has been automatically generated** We have no information about 47MN[*] airport other than its name, ICAO and location (US). This airport will have to be done from scratch, which includes adding runways, taxiways, parking locations, boundaries... Good luck if you decide to do this airport!
{ "pile_set_name": "Github" }
/* jep - Java Embedded Python Copyright (c) 2019 JEP AUTHORS. This file is licensed under the the zlib/libpng License. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "Jep.h" static jmethodID order = 0; jobject java_nio_LongBuffer_order(JNIEnv* env, jobject this) { jobject result = NULL; Py_BEGIN_ALLOW_THREADS if (JNI_METHOD(order, env, JLONGBUFFER_TYPE, "order", "()Ljava/nio/ByteOrder;")) { result = (*env)->CallObjectMethod(env, this, order); } Py_END_ALLOW_THREADS return result; }
{ "pile_set_name": "Github" }
{ "format_version": "1.13.0", "minecraft:biome": { "description": { "identifier": "redwood_taiga_hills_mutated" }, "components": { "minecraft:climate": { "downfall": 0.8, "snow_accumulation": [ 0.0, 0.125 ], "temperature": 0.3 }, "minecraft:overworld_height": { "noise_params": [ 0.55, 0.5 ] }, "minecraft:surface_parameters": { "sea_floor_depth": 7, "sea_floor_material": "minecraft:gravel", "foundation_material": "minecraft:stone", "mid_material": "minecraft:dirt", "top_material": "minecraft:grass", "sea_material": "minecraft:water" }, "minecraft:surface_material_adjustments": { "adjustments": [ { "materials": { "top_material": { "name": "minecraft:dirt", "states": { "dirt_type": "coarse" } } }, "noise_frequency_scale": 0.0625, "noise_range": [ 0.212, 1.0 ] }, { "materials": { "top_material": "minecraft:podzol" }, "noise_frequency_scale": 0.0625, "noise_range": [ -0.115, 0.212 ] } ] }, "animal": {}, "forest": {}, "hills": {}, "mega": {}, "monster": {}, "mutated": {}, "taiga": {}, // "overworld" tag cannot be present in order to match legacy behavior, but is // required for correct world generation -- hence: overworld_generation "overworld_generation": {} } } }
{ "pile_set_name": "Github" }
/* * Driver for Alauda-based card readers * * Current development and maintenance by: * (c) 2005 Daniel Drake <[email protected]> * * The 'Alauda' is a chip manufacturered by RATOC for OEM use. * * Alauda implements a vendor-specific command set to access two media reader * ports (XD, SmartMedia). This driver converts SCSI commands to the commands * which are accepted by these devices. * * The driver was developed through reverse-engineering, with the help of the * sddr09 driver which has many similarities, and with some help from the * (very old) vendor-supplied GPL sma03 driver. * * For protocol info, see http://alauda.sourceforge.net * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/module.h> #include <scsi/scsi.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include "usb.h" #include "transport.h" #include "protocol.h" #include "debug.h" MODULE_DESCRIPTION("Driver for Alauda-based card readers"); MODULE_AUTHOR("Daniel Drake <[email protected]>"); MODULE_LICENSE("GPL"); /* * Status bytes */ #define ALAUDA_STATUS_ERROR 0x01 #define ALAUDA_STATUS_READY 0x40 /* * Control opcodes (for request field) */ #define ALAUDA_GET_XD_MEDIA_STATUS 0x08 #define ALAUDA_GET_SM_MEDIA_STATUS 0x98 #define ALAUDA_ACK_XD_MEDIA_CHANGE 0x0a #define ALAUDA_ACK_SM_MEDIA_CHANGE 0x9a #define ALAUDA_GET_XD_MEDIA_SIG 0x86 #define ALAUDA_GET_SM_MEDIA_SIG 0x96 /* * Bulk command identity (byte 0) */ #define ALAUDA_BULK_CMD 0x40 /* * Bulk opcodes (byte 1) */ #define ALAUDA_BULK_GET_REDU_DATA 0x85 #define ALAUDA_BULK_READ_BLOCK 0x94 #define ALAUDA_BULK_ERASE_BLOCK 0xa3 #define ALAUDA_BULK_WRITE_BLOCK 0xb4 #define ALAUDA_BULK_GET_STATUS2 0xb7 #define ALAUDA_BULK_RESET_MEDIA 0xe0 /* * Port to operate on (byte 8) */ #define ALAUDA_PORT_XD 0x00 #define ALAUDA_PORT_SM 0x01 /* * LBA and PBA are unsigned ints. Special values. */ #define UNDEF 0xffff #define SPARE 0xfffe #define UNUSABLE 0xfffd struct alauda_media_info { unsigned long capacity; /* total media size in bytes */ unsigned int pagesize; /* page size in bytes */ unsigned int blocksize; /* number of pages per block */ unsigned int uzonesize; /* number of usable blocks per zone */ unsigned int zonesize; /* number of blocks per zone */ unsigned int blockmask; /* mask to get page from address */ unsigned char pageshift; unsigned char blockshift; unsigned char zoneshift; u16 **lba_to_pba; /* logical to physical block map */ u16 **pba_to_lba; /* physical to logical block map */ }; struct alauda_info { struct alauda_media_info port[2]; int wr_ep; /* endpoint to write data out of */ unsigned char sense_key; unsigned long sense_asc; /* additional sense code */ unsigned long sense_ascq; /* additional sense code qualifier */ }; #define short_pack(lsb,msb) ( ((u16)(lsb)) | ( ((u16)(msb))<<8 ) ) #define LSB_of(s) ((s)&0xFF) #define MSB_of(s) ((s)>>8) #define MEDIA_PORT(us) us->srb->device->lun #define MEDIA_INFO(us) ((struct alauda_info *)us->extra)->port[MEDIA_PORT(us)] #define PBA_LO(pba) ((pba & 0xF) << 5) #define PBA_HI(pba) (pba >> 3) #define PBA_ZONE(pba) (pba >> 11) static int init_alauda(struct us_data *us); /* * The table of devices */ #define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \ vendorName, productName, useProtocol, useTransport, \ initFunction, flags) \ { USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \ .driver_info = (flags)|(USB_US_TYPE_STOR<<24) } struct usb_device_id alauda_usb_ids[] = { # include "unusual_alauda.h" { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, alauda_usb_ids); #undef UNUSUAL_DEV /* * The flags table */ #define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \ vendor_name, product_name, use_protocol, use_transport, \ init_function, Flags) \ { \ .vendorName = vendor_name, \ .productName = product_name, \ .useProtocol = use_protocol, \ .useTransport = use_transport, \ .initFunction = init_function, \ } static struct us_unusual_dev alauda_unusual_dev_list[] = { # include "unusual_alauda.h" { } /* Terminating entry */ }; #undef UNUSUAL_DEV /* * Media handling */ struct alauda_card_info { unsigned char id; /* id byte */ unsigned char chipshift; /* 1<<cs bytes total capacity */ unsigned char pageshift; /* 1<<ps bytes in a page */ unsigned char blockshift; /* 1<<bs pages per block */ unsigned char zoneshift; /* 1<<zs blocks per zone */ }; static struct alauda_card_info alauda_card_ids[] = { /* NAND flash */ { 0x6e, 20, 8, 4, 8}, /* 1 MB */ { 0xe8, 20, 8, 4, 8}, /* 1 MB */ { 0xec, 20, 8, 4, 8}, /* 1 MB */ { 0x64, 21, 8, 4, 9}, /* 2 MB */ { 0xea, 21, 8, 4, 9}, /* 2 MB */ { 0x6b, 22, 9, 4, 9}, /* 4 MB */ { 0xe3, 22, 9, 4, 9}, /* 4 MB */ { 0xe5, 22, 9, 4, 9}, /* 4 MB */ { 0xe6, 23, 9, 4, 10}, /* 8 MB */ { 0x73, 24, 9, 5, 10}, /* 16 MB */ { 0x75, 25, 9, 5, 10}, /* 32 MB */ { 0x76, 26, 9, 5, 10}, /* 64 MB */ { 0x79, 27, 9, 5, 10}, /* 128 MB */ { 0x71, 28, 9, 5, 10}, /* 256 MB */ /* MASK ROM */ { 0x5d, 21, 9, 4, 8}, /* 2 MB */ { 0xd5, 22, 9, 4, 9}, /* 4 MB */ { 0xd6, 23, 9, 4, 10}, /* 8 MB */ { 0x57, 24, 9, 4, 11}, /* 16 MB */ { 0x58, 25, 9, 4, 12}, /* 32 MB */ { 0,} }; static struct alauda_card_info *alauda_card_find_id(unsigned char id) { int i; for (i = 0; alauda_card_ids[i].id != 0; i++) if (alauda_card_ids[i].id == id) return &(alauda_card_ids[i]); return NULL; } /* * ECC computation. */ static unsigned char parity[256]; static unsigned char ecc2[256]; static void nand_init_ecc(void) { int i, j, a; parity[0] = 0; for (i = 1; i < 256; i++) parity[i] = (parity[i&(i-1)] ^ 1); for (i = 0; i < 256; i++) { a = 0; for (j = 0; j < 8; j++) { if (i & (1<<j)) { if ((j & 1) == 0) a ^= 0x04; if ((j & 2) == 0) a ^= 0x10; if ((j & 4) == 0) a ^= 0x40; } } ecc2[i] = ~(a ^ (a<<1) ^ (parity[i] ? 0xa8 : 0)); } } /* compute 3-byte ecc on 256 bytes */ static void nand_compute_ecc(unsigned char *data, unsigned char *ecc) { int i, j, a; unsigned char par, bit, bits[8]; par = 0; for (j = 0; j < 8; j++) bits[j] = 0; /* collect 16 checksum bits */ for (i = 0; i < 256; i++) { par ^= data[i]; bit = parity[data[i]]; for (j = 0; j < 8; j++) if ((i & (1<<j)) == 0) bits[j] ^= bit; } /* put 4+4+4 = 12 bits in the ecc */ a = (bits[3] << 6) + (bits[2] << 4) + (bits[1] << 2) + bits[0]; ecc[0] = ~(a ^ (a<<1) ^ (parity[par] ? 0xaa : 0)); a = (bits[7] << 6) + (bits[6] << 4) + (bits[5] << 2) + bits[4]; ecc[1] = ~(a ^ (a<<1) ^ (parity[par] ? 0xaa : 0)); ecc[2] = ecc2[par]; } static int nand_compare_ecc(unsigned char *data, unsigned char *ecc) { return (data[0] == ecc[0] && data[1] == ecc[1] && data[2] == ecc[2]); } static void nand_store_ecc(unsigned char *data, unsigned char *ecc) { memcpy(data, ecc, 3); } /* * Alauda driver */ /* * Forget our PBA <---> LBA mappings for a particular port */ static void alauda_free_maps (struct alauda_media_info *media_info) { unsigned int shift = media_info->zoneshift + media_info->blockshift + media_info->pageshift; unsigned int num_zones = media_info->capacity >> shift; unsigned int i; if (media_info->lba_to_pba != NULL) for (i = 0; i < num_zones; i++) { kfree(media_info->lba_to_pba[i]); media_info->lba_to_pba[i] = NULL; } if (media_info->pba_to_lba != NULL) for (i = 0; i < num_zones; i++) { kfree(media_info->pba_to_lba[i]); media_info->pba_to_lba[i] = NULL; } } /* * Returns 2 bytes of status data * The first byte describes media status, and second byte describes door status */ static int alauda_get_media_status(struct us_data *us, unsigned char *data) { int rc; unsigned char command; if (MEDIA_PORT(us) == ALAUDA_PORT_XD) command = ALAUDA_GET_XD_MEDIA_STATUS; else command = ALAUDA_GET_SM_MEDIA_STATUS; rc = usb_stor_ctrl_transfer(us, us->recv_ctrl_pipe, command, 0xc0, 0, 1, data, 2); US_DEBUGP("alauda_get_media_status: Media status %02X %02X\n", data[0], data[1]); return rc; } /* * Clears the "media was changed" bit so that we know when it changes again * in the future. */ static int alauda_ack_media(struct us_data *us) { unsigned char command; if (MEDIA_PORT(us) == ALAUDA_PORT_XD) command = ALAUDA_ACK_XD_MEDIA_CHANGE; else command = ALAUDA_ACK_SM_MEDIA_CHANGE; return usb_stor_ctrl_transfer(us, us->send_ctrl_pipe, command, 0x40, 0, 1, NULL, 0); } /* * Retrieves a 4-byte media signature, which indicates manufacturer, capacity, * and some other details. */ static int alauda_get_media_signature(struct us_data *us, unsigned char *data) { unsigned char command; if (MEDIA_PORT(us) == ALAUDA_PORT_XD) command = ALAUDA_GET_XD_MEDIA_SIG; else command = ALAUDA_GET_SM_MEDIA_SIG; return usb_stor_ctrl_transfer(us, us->recv_ctrl_pipe, command, 0xc0, 0, 0, data, 4); } /* * Resets the media status (but not the whole device?) */ static int alauda_reset_media(struct us_data *us) { unsigned char *command = us->iobuf; memset(command, 0, 9); command[0] = ALAUDA_BULK_CMD; command[1] = ALAUDA_BULK_RESET_MEDIA; command[8] = MEDIA_PORT(us); return usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); } /* * Examines the media and deduces capacity, etc. */ static int alauda_init_media(struct us_data *us) { unsigned char *data = us->iobuf; int ready = 0; struct alauda_card_info *media_info; unsigned int num_zones; while (ready == 0) { msleep(20); if (alauda_get_media_status(us, data) != USB_STOR_XFER_GOOD) return USB_STOR_TRANSPORT_ERROR; if (data[0] & 0x10) ready = 1; } US_DEBUGP("alauda_init_media: We are ready for action!\n"); if (alauda_ack_media(us) != USB_STOR_XFER_GOOD) return USB_STOR_TRANSPORT_ERROR; msleep(10); if (alauda_get_media_status(us, data) != USB_STOR_XFER_GOOD) return USB_STOR_TRANSPORT_ERROR; if (data[0] != 0x14) { US_DEBUGP("alauda_init_media: Media not ready after ack\n"); return USB_STOR_TRANSPORT_ERROR; } if (alauda_get_media_signature(us, data) != USB_STOR_XFER_GOOD) return USB_STOR_TRANSPORT_ERROR; US_DEBUGP("alauda_init_media: Media signature: %02X %02X %02X %02X\n", data[0], data[1], data[2], data[3]); media_info = alauda_card_find_id(data[1]); if (media_info == NULL) { printk(KERN_WARNING "alauda_init_media: Unrecognised media signature: " "%02X %02X %02X %02X\n", data[0], data[1], data[2], data[3]); return USB_STOR_TRANSPORT_ERROR; } MEDIA_INFO(us).capacity = 1 << media_info->chipshift; US_DEBUGP("Found media with capacity: %ldMB\n", MEDIA_INFO(us).capacity >> 20); MEDIA_INFO(us).pageshift = media_info->pageshift; MEDIA_INFO(us).blockshift = media_info->blockshift; MEDIA_INFO(us).zoneshift = media_info->zoneshift; MEDIA_INFO(us).pagesize = 1 << media_info->pageshift; MEDIA_INFO(us).blocksize = 1 << media_info->blockshift; MEDIA_INFO(us).zonesize = 1 << media_info->zoneshift; MEDIA_INFO(us).uzonesize = ((1 << media_info->zoneshift) / 128) * 125; MEDIA_INFO(us).blockmask = MEDIA_INFO(us).blocksize - 1; num_zones = MEDIA_INFO(us).capacity >> (MEDIA_INFO(us).zoneshift + MEDIA_INFO(us).blockshift + MEDIA_INFO(us).pageshift); MEDIA_INFO(us).pba_to_lba = kcalloc(num_zones, sizeof(u16*), GFP_NOIO); MEDIA_INFO(us).lba_to_pba = kcalloc(num_zones, sizeof(u16*), GFP_NOIO); if (alauda_reset_media(us) != USB_STOR_XFER_GOOD) return USB_STOR_TRANSPORT_ERROR; return USB_STOR_TRANSPORT_GOOD; } /* * Examines the media status and does the right thing when the media has gone, * appeared, or changed. */ static int alauda_check_media(struct us_data *us) { struct alauda_info *info = (struct alauda_info *) us->extra; unsigned char status[2]; int rc; rc = alauda_get_media_status(us, status); /* Check for no media or door open */ if ((status[0] & 0x80) || ((status[0] & 0x1F) == 0x10) || ((status[1] & 0x01) == 0)) { US_DEBUGP("alauda_check_media: No media, or door open\n"); alauda_free_maps(&MEDIA_INFO(us)); info->sense_key = 0x02; info->sense_asc = 0x3A; info->sense_ascq = 0x00; return USB_STOR_TRANSPORT_FAILED; } /* Check for media change */ if (status[0] & 0x08) { US_DEBUGP("alauda_check_media: Media change detected\n"); alauda_free_maps(&MEDIA_INFO(us)); alauda_init_media(us); info->sense_key = UNIT_ATTENTION; info->sense_asc = 0x28; info->sense_ascq = 0x00; return USB_STOR_TRANSPORT_FAILED; } return USB_STOR_TRANSPORT_GOOD; } /* * Checks the status from the 2nd status register * Returns 3 bytes of status data, only the first is known */ static int alauda_check_status2(struct us_data *us) { int rc; unsigned char command[] = { ALAUDA_BULK_CMD, ALAUDA_BULK_GET_STATUS2, 0, 0, 0, 0, 3, 0, MEDIA_PORT(us) }; unsigned char data[3]; rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); if (rc != USB_STOR_XFER_GOOD) return rc; rc = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, data, 3, NULL); if (rc != USB_STOR_XFER_GOOD) return rc; US_DEBUGP("alauda_check_status2: %02X %02X %02X\n", data[0], data[1], data[2]); if (data[0] & ALAUDA_STATUS_ERROR) return USB_STOR_XFER_ERROR; return USB_STOR_XFER_GOOD; } /* * Gets the redundancy data for the first page of a PBA * Returns 16 bytes. */ static int alauda_get_redu_data(struct us_data *us, u16 pba, unsigned char *data) { int rc; unsigned char command[] = { ALAUDA_BULK_CMD, ALAUDA_BULK_GET_REDU_DATA, PBA_HI(pba), PBA_ZONE(pba), 0, PBA_LO(pba), 0, 0, MEDIA_PORT(us) }; rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); if (rc != USB_STOR_XFER_GOOD) return rc; return usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, data, 16, NULL); } /* * Finds the first unused PBA in a zone * Returns the absolute PBA of an unused PBA, or 0 if none found. */ static u16 alauda_find_unused_pba(struct alauda_media_info *info, unsigned int zone) { u16 *pba_to_lba = info->pba_to_lba[zone]; unsigned int i; for (i = 0; i < info->zonesize; i++) if (pba_to_lba[i] == UNDEF) return (zone << info->zoneshift) + i; return 0; } /* * Reads the redundancy data for all PBA's in a zone * Produces lba <--> pba mappings */ static int alauda_read_map(struct us_data *us, unsigned int zone) { unsigned char *data = us->iobuf; int result; int i, j; unsigned int zonesize = MEDIA_INFO(us).zonesize; unsigned int uzonesize = MEDIA_INFO(us).uzonesize; unsigned int lba_offset, lba_real, blocknum; unsigned int zone_base_lba = zone * uzonesize; unsigned int zone_base_pba = zone * zonesize; u16 *lba_to_pba = kcalloc(zonesize, sizeof(u16), GFP_NOIO); u16 *pba_to_lba = kcalloc(zonesize, sizeof(u16), GFP_NOIO); if (lba_to_pba == NULL || pba_to_lba == NULL) { result = USB_STOR_TRANSPORT_ERROR; goto error; } US_DEBUGP("alauda_read_map: Mapping blocks for zone %d\n", zone); /* 1024 PBA's per zone */ for (i = 0; i < zonesize; i++) lba_to_pba[i] = pba_to_lba[i] = UNDEF; for (i = 0; i < zonesize; i++) { blocknum = zone_base_pba + i; result = alauda_get_redu_data(us, blocknum, data); if (result != USB_STOR_XFER_GOOD) { result = USB_STOR_TRANSPORT_ERROR; goto error; } /* special PBAs have control field 0^16 */ for (j = 0; j < 16; j++) if (data[j] != 0) goto nonz; pba_to_lba[i] = UNUSABLE; US_DEBUGP("alauda_read_map: PBA %d has no logical mapping\n", blocknum); continue; nonz: /* unwritten PBAs have control field FF^16 */ for (j = 0; j < 16; j++) if (data[j] != 0xff) goto nonff; continue; nonff: /* normal PBAs start with six FFs */ if (j < 6) { US_DEBUGP("alauda_read_map: PBA %d has no logical mapping: " "reserved area = %02X%02X%02X%02X " "data status %02X block status %02X\n", blocknum, data[0], data[1], data[2], data[3], data[4], data[5]); pba_to_lba[i] = UNUSABLE; continue; } if ((data[6] >> 4) != 0x01) { US_DEBUGP("alauda_read_map: PBA %d has invalid address " "field %02X%02X/%02X%02X\n", blocknum, data[6], data[7], data[11], data[12]); pba_to_lba[i] = UNUSABLE; continue; } /* check even parity */ if (parity[data[6] ^ data[7]]) { printk(KERN_WARNING "alauda_read_map: Bad parity in LBA for block %d" " (%02X %02X)\n", i, data[6], data[7]); pba_to_lba[i] = UNUSABLE; continue; } lba_offset = short_pack(data[7], data[6]); lba_offset = (lba_offset & 0x07FF) >> 1; lba_real = lba_offset + zone_base_lba; /* * Every 1024 physical blocks ("zone"), the LBA numbers * go back to zero, but are within a higher block of LBA's. * Also, there is a maximum of 1000 LBA's per zone. * In other words, in PBA 1024-2047 you will find LBA 0-999 * which are really LBA 1000-1999. This allows for 24 bad * or special physical blocks per zone. */ if (lba_offset >= uzonesize) { printk(KERN_WARNING "alauda_read_map: Bad low LBA %d for block %d\n", lba_real, blocknum); continue; } if (lba_to_pba[lba_offset] != UNDEF) { printk(KERN_WARNING "alauda_read_map: " "LBA %d seen for PBA %d and %d\n", lba_real, lba_to_pba[lba_offset], blocknum); continue; } pba_to_lba[i] = lba_real; lba_to_pba[lba_offset] = blocknum; continue; } MEDIA_INFO(us).lba_to_pba[zone] = lba_to_pba; MEDIA_INFO(us).pba_to_lba[zone] = pba_to_lba; result = 0; goto out; error: kfree(lba_to_pba); kfree(pba_to_lba); out: return result; } /* * Checks to see whether we have already mapped a certain zone * If we haven't, the map is generated */ static void alauda_ensure_map_for_zone(struct us_data *us, unsigned int zone) { if (MEDIA_INFO(us).lba_to_pba[zone] == NULL || MEDIA_INFO(us).pba_to_lba[zone] == NULL) alauda_read_map(us, zone); } /* * Erases an entire block */ static int alauda_erase_block(struct us_data *us, u16 pba) { int rc; unsigned char command[] = { ALAUDA_BULK_CMD, ALAUDA_BULK_ERASE_BLOCK, PBA_HI(pba), PBA_ZONE(pba), 0, PBA_LO(pba), 0x02, 0, MEDIA_PORT(us) }; unsigned char buf[2]; US_DEBUGP("alauda_erase_block: Erasing PBA %d\n", pba); rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); if (rc != USB_STOR_XFER_GOOD) return rc; rc = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, buf, 2, NULL); if (rc != USB_STOR_XFER_GOOD) return rc; US_DEBUGP("alauda_erase_block: Erase result: %02X %02X\n", buf[0], buf[1]); return rc; } /* * Reads data from a certain offset page inside a PBA, including interleaved * redundancy data. Returns (pagesize+64)*pages bytes in data. */ static int alauda_read_block_raw(struct us_data *us, u16 pba, unsigned int page, unsigned int pages, unsigned char *data) { int rc; unsigned char command[] = { ALAUDA_BULK_CMD, ALAUDA_BULK_READ_BLOCK, PBA_HI(pba), PBA_ZONE(pba), 0, PBA_LO(pba) + page, pages, 0, MEDIA_PORT(us) }; US_DEBUGP("alauda_read_block: pba %d page %d count %d\n", pba, page, pages); rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); if (rc != USB_STOR_XFER_GOOD) return rc; return usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, data, (MEDIA_INFO(us).pagesize + 64) * pages, NULL); } /* * Reads data from a certain offset page inside a PBA, excluding redundancy * data. Returns pagesize*pages bytes in data. Note that data must be big enough * to hold (pagesize+64)*pages bytes of data, but you can ignore those 'extra' * trailing bytes outside this function. */ static int alauda_read_block(struct us_data *us, u16 pba, unsigned int page, unsigned int pages, unsigned char *data) { int i, rc; unsigned int pagesize = MEDIA_INFO(us).pagesize; rc = alauda_read_block_raw(us, pba, page, pages, data); if (rc != USB_STOR_XFER_GOOD) return rc; /* Cut out the redundancy data */ for (i = 0; i < pages; i++) { int dest_offset = i * pagesize; int src_offset = i * (pagesize + 64); memmove(data + dest_offset, data + src_offset, pagesize); } return rc; } /* * Writes an entire block of data and checks status after write. * Redundancy data must be already included in data. Data should be * (pagesize+64)*blocksize bytes in length. */ static int alauda_write_block(struct us_data *us, u16 pba, unsigned char *data) { int rc; struct alauda_info *info = (struct alauda_info *) us->extra; unsigned char command[] = { ALAUDA_BULK_CMD, ALAUDA_BULK_WRITE_BLOCK, PBA_HI(pba), PBA_ZONE(pba), 0, PBA_LO(pba), 32, 0, MEDIA_PORT(us) }; US_DEBUGP("alauda_write_block: pba %d\n", pba); rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); if (rc != USB_STOR_XFER_GOOD) return rc; rc = usb_stor_bulk_transfer_buf(us, info->wr_ep, data, (MEDIA_INFO(us).pagesize + 64) * MEDIA_INFO(us).blocksize, NULL); if (rc != USB_STOR_XFER_GOOD) return rc; return alauda_check_status2(us); } /* * Write some data to a specific LBA. */ static int alauda_write_lba(struct us_data *us, u16 lba, unsigned int page, unsigned int pages, unsigned char *ptr, unsigned char *blockbuffer) { u16 pba, lbap, new_pba; unsigned char *bptr, *cptr, *xptr; unsigned char ecc[3]; int i, result; unsigned int uzonesize = MEDIA_INFO(us).uzonesize; unsigned int zonesize = MEDIA_INFO(us).zonesize; unsigned int pagesize = MEDIA_INFO(us).pagesize; unsigned int blocksize = MEDIA_INFO(us).blocksize; unsigned int lba_offset = lba % uzonesize; unsigned int new_pba_offset; unsigned int zone = lba / uzonesize; alauda_ensure_map_for_zone(us, zone); pba = MEDIA_INFO(us).lba_to_pba[zone][lba_offset]; if (pba == 1) { /* Maybe it is impossible to write to PBA 1. Fake success, but don't do anything. */ printk(KERN_WARNING "alauda_write_lba: avoid writing to pba 1\n"); return USB_STOR_TRANSPORT_GOOD; } new_pba = alauda_find_unused_pba(&MEDIA_INFO(us), zone); if (!new_pba) { printk(KERN_WARNING "alauda_write_lba: Out of unused blocks\n"); return USB_STOR_TRANSPORT_ERROR; } /* read old contents */ if (pba != UNDEF) { result = alauda_read_block_raw(us, pba, 0, blocksize, blockbuffer); if (result != USB_STOR_XFER_GOOD) return result; } else { memset(blockbuffer, 0, blocksize * (pagesize + 64)); } lbap = (lba_offset << 1) | 0x1000; if (parity[MSB_of(lbap) ^ LSB_of(lbap)]) lbap ^= 1; /* check old contents and fill lba */ for (i = 0; i < blocksize; i++) { bptr = blockbuffer + (i * (pagesize + 64)); cptr = bptr + pagesize; nand_compute_ecc(bptr, ecc); if (!nand_compare_ecc(cptr+13, ecc)) { US_DEBUGP("Warning: bad ecc in page %d- of pba %d\n", i, pba); nand_store_ecc(cptr+13, ecc); } nand_compute_ecc(bptr + (pagesize / 2), ecc); if (!nand_compare_ecc(cptr+8, ecc)) { US_DEBUGP("Warning: bad ecc in page %d+ of pba %d\n", i, pba); nand_store_ecc(cptr+8, ecc); } cptr[6] = cptr[11] = MSB_of(lbap); cptr[7] = cptr[12] = LSB_of(lbap); } /* copy in new stuff and compute ECC */ xptr = ptr; for (i = page; i < page+pages; i++) { bptr = blockbuffer + (i * (pagesize + 64)); cptr = bptr + pagesize; memcpy(bptr, xptr, pagesize); xptr += pagesize; nand_compute_ecc(bptr, ecc); nand_store_ecc(cptr+13, ecc); nand_compute_ecc(bptr + (pagesize / 2), ecc); nand_store_ecc(cptr+8, ecc); } result = alauda_write_block(us, new_pba, blockbuffer); if (result != USB_STOR_XFER_GOOD) return result; new_pba_offset = new_pba - (zone * zonesize); MEDIA_INFO(us).pba_to_lba[zone][new_pba_offset] = lba; MEDIA_INFO(us).lba_to_pba[zone][lba_offset] = new_pba; US_DEBUGP("alauda_write_lba: Remapped LBA %d to PBA %d\n", lba, new_pba); if (pba != UNDEF) { unsigned int pba_offset = pba - (zone * zonesize); result = alauda_erase_block(us, pba); if (result != USB_STOR_XFER_GOOD) return result; MEDIA_INFO(us).pba_to_lba[zone][pba_offset] = UNDEF; } return USB_STOR_TRANSPORT_GOOD; } /* * Read data from a specific sector address */ static int alauda_read_data(struct us_data *us, unsigned long address, unsigned int sectors) { unsigned char *buffer; u16 lba, max_lba; unsigned int page, len, offset; unsigned int blockshift = MEDIA_INFO(us).blockshift; unsigned int pageshift = MEDIA_INFO(us).pageshift; unsigned int blocksize = MEDIA_INFO(us).blocksize; unsigned int pagesize = MEDIA_INFO(us).pagesize; unsigned int uzonesize = MEDIA_INFO(us).uzonesize; struct scatterlist *sg; int result; /* * Since we only read in one block at a time, we have to create * a bounce buffer and move the data a piece at a time between the * bounce buffer and the actual transfer buffer. * We make this buffer big enough to hold temporary redundancy data, * which we use when reading the data blocks. */ len = min(sectors, blocksize) * (pagesize + 64); buffer = kmalloc(len, GFP_NOIO); if (buffer == NULL) { printk(KERN_WARNING "alauda_read_data: Out of memory\n"); return USB_STOR_TRANSPORT_ERROR; } /* Figure out the initial LBA and page */ lba = address >> blockshift; page = (address & MEDIA_INFO(us).blockmask); max_lba = MEDIA_INFO(us).capacity >> (blockshift + pageshift); result = USB_STOR_TRANSPORT_GOOD; offset = 0; sg = NULL; while (sectors > 0) { unsigned int zone = lba / uzonesize; /* integer division */ unsigned int lba_offset = lba - (zone * uzonesize); unsigned int pages; u16 pba; alauda_ensure_map_for_zone(us, zone); /* Not overflowing capacity? */ if (lba >= max_lba) { US_DEBUGP("Error: Requested lba %u exceeds " "maximum %u\n", lba, max_lba); result = USB_STOR_TRANSPORT_ERROR; break; } /* Find number of pages we can read in this block */ pages = min(sectors, blocksize - page); len = pages << pageshift; /* Find where this lba lives on disk */ pba = MEDIA_INFO(us).lba_to_pba[zone][lba_offset]; if (pba == UNDEF) { /* this lba was never written */ US_DEBUGP("Read %d zero pages (LBA %d) page %d\n", pages, lba, page); /* This is not really an error. It just means that the block has never been written. Instead of returning USB_STOR_TRANSPORT_ERROR it is better to return all zero data. */ memset(buffer, 0, len); } else { US_DEBUGP("Read %d pages, from PBA %d" " (LBA %d) page %d\n", pages, pba, lba, page); result = alauda_read_block(us, pba, page, pages, buffer); if (result != USB_STOR_TRANSPORT_GOOD) break; } /* Store the data in the transfer buffer */ usb_stor_access_xfer_buf(buffer, len, us->srb, &sg, &offset, TO_XFER_BUF); page = 0; lba++; sectors -= pages; } kfree(buffer); return result; } /* * Write data to a specific sector address */ static int alauda_write_data(struct us_data *us, unsigned long address, unsigned int sectors) { unsigned char *buffer, *blockbuffer; unsigned int page, len, offset; unsigned int blockshift = MEDIA_INFO(us).blockshift; unsigned int pageshift = MEDIA_INFO(us).pageshift; unsigned int blocksize = MEDIA_INFO(us).blocksize; unsigned int pagesize = MEDIA_INFO(us).pagesize; struct scatterlist *sg; u16 lba, max_lba; int result; /* * Since we don't write the user data directly to the device, * we have to create a bounce buffer and move the data a piece * at a time between the bounce buffer and the actual transfer buffer. */ len = min(sectors, blocksize) * pagesize; buffer = kmalloc(len, GFP_NOIO); if (buffer == NULL) { printk(KERN_WARNING "alauda_write_data: Out of memory\n"); return USB_STOR_TRANSPORT_ERROR; } /* * We also need a temporary block buffer, where we read in the old data, * overwrite parts with the new data, and manipulate the redundancy data */ blockbuffer = kmalloc((pagesize + 64) * blocksize, GFP_NOIO); if (blockbuffer == NULL) { printk(KERN_WARNING "alauda_write_data: Out of memory\n"); kfree(buffer); return USB_STOR_TRANSPORT_ERROR; } /* Figure out the initial LBA and page */ lba = address >> blockshift; page = (address & MEDIA_INFO(us).blockmask); max_lba = MEDIA_INFO(us).capacity >> (pageshift + blockshift); result = USB_STOR_TRANSPORT_GOOD; offset = 0; sg = NULL; while (sectors > 0) { /* Write as many sectors as possible in this block */ unsigned int pages = min(sectors, blocksize - page); len = pages << pageshift; /* Not overflowing capacity? */ if (lba >= max_lba) { US_DEBUGP("alauda_write_data: Requested lba %u exceeds " "maximum %u\n", lba, max_lba); result = USB_STOR_TRANSPORT_ERROR; break; } /* Get the data from the transfer buffer */ usb_stor_access_xfer_buf(buffer, len, us->srb, &sg, &offset, FROM_XFER_BUF); result = alauda_write_lba(us, lba, page, pages, buffer, blockbuffer); if (result != USB_STOR_TRANSPORT_GOOD) break; page = 0; lba++; sectors -= pages; } kfree(buffer); kfree(blockbuffer); return result; } /* * Our interface with the rest of the world */ static void alauda_info_destructor(void *extra) { struct alauda_info *info = (struct alauda_info *) extra; int port; if (!info) return; for (port = 0; port < 2; port++) { struct alauda_media_info *media_info = &info->port[port]; alauda_free_maps(media_info); kfree(media_info->lba_to_pba); kfree(media_info->pba_to_lba); } } /* * Initialize alauda_info struct and find the data-write endpoint */ static int init_alauda(struct us_data *us) { struct alauda_info *info; struct usb_host_interface *altsetting = us->pusb_intf->cur_altsetting; nand_init_ecc(); us->extra = kzalloc(sizeof(struct alauda_info), GFP_NOIO); if (!us->extra) { US_DEBUGP("init_alauda: Gah! Can't allocate storage for" "alauda info struct!\n"); return USB_STOR_TRANSPORT_ERROR; } info = (struct alauda_info *) us->extra; us->extra_destructor = alauda_info_destructor; info->wr_ep = usb_sndbulkpipe(us->pusb_dev, altsetting->endpoint[0].desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); return USB_STOR_TRANSPORT_GOOD; } static int alauda_transport(struct scsi_cmnd *srb, struct us_data *us) { int rc; struct alauda_info *info = (struct alauda_info *) us->extra; unsigned char *ptr = us->iobuf; static unsigned char inquiry_response[36] = { 0x00, 0x80, 0x00, 0x01, 0x1F, 0x00, 0x00, 0x00 }; if (srb->cmnd[0] == INQUIRY) { US_DEBUGP("alauda_transport: INQUIRY. " "Returning bogus response.\n"); memcpy(ptr, inquiry_response, sizeof(inquiry_response)); fill_inquiry_response(us, ptr, 36); return USB_STOR_TRANSPORT_GOOD; } if (srb->cmnd[0] == TEST_UNIT_READY) { US_DEBUGP("alauda_transport: TEST_UNIT_READY.\n"); return alauda_check_media(us); } if (srb->cmnd[0] == READ_CAPACITY) { unsigned int num_zones; unsigned long capacity; rc = alauda_check_media(us); if (rc != USB_STOR_TRANSPORT_GOOD) return rc; num_zones = MEDIA_INFO(us).capacity >> (MEDIA_INFO(us).zoneshift + MEDIA_INFO(us).blockshift + MEDIA_INFO(us).pageshift); capacity = num_zones * MEDIA_INFO(us).uzonesize * MEDIA_INFO(us).blocksize; /* Report capacity and page size */ ((__be32 *) ptr)[0] = cpu_to_be32(capacity - 1); ((__be32 *) ptr)[1] = cpu_to_be32(512); usb_stor_set_xfer_buf(ptr, 8, srb); return USB_STOR_TRANSPORT_GOOD; } if (srb->cmnd[0] == READ_10) { unsigned int page, pages; rc = alauda_check_media(us); if (rc != USB_STOR_TRANSPORT_GOOD) return rc; page = short_pack(srb->cmnd[3], srb->cmnd[2]); page <<= 16; page |= short_pack(srb->cmnd[5], srb->cmnd[4]); pages = short_pack(srb->cmnd[8], srb->cmnd[7]); US_DEBUGP("alauda_transport: READ_10: page %d pagect %d\n", page, pages); return alauda_read_data(us, page, pages); } if (srb->cmnd[0] == WRITE_10) { unsigned int page, pages; rc = alauda_check_media(us); if (rc != USB_STOR_TRANSPORT_GOOD) return rc; page = short_pack(srb->cmnd[3], srb->cmnd[2]); page <<= 16; page |= short_pack(srb->cmnd[5], srb->cmnd[4]); pages = short_pack(srb->cmnd[8], srb->cmnd[7]); US_DEBUGP("alauda_transport: WRITE_10: page %d pagect %d\n", page, pages); return alauda_write_data(us, page, pages); } if (srb->cmnd[0] == REQUEST_SENSE) { US_DEBUGP("alauda_transport: REQUEST_SENSE.\n"); memset(ptr, 0, 18); ptr[0] = 0xF0; ptr[2] = info->sense_key; ptr[7] = 11; ptr[12] = info->sense_asc; ptr[13] = info->sense_ascq; usb_stor_set_xfer_buf(ptr, 18, srb); return USB_STOR_TRANSPORT_GOOD; } if (srb->cmnd[0] == ALLOW_MEDIUM_REMOVAL) { /* sure. whatever. not like we can stop the user from popping the media out of the device (no locking doors, etc) */ return USB_STOR_TRANSPORT_GOOD; } US_DEBUGP("alauda_transport: Gah! Unknown command: %d (0x%x)\n", srb->cmnd[0], srb->cmnd[0]); info->sense_key = 0x05; info->sense_asc = 0x20; info->sense_ascq = 0x00; return USB_STOR_TRANSPORT_FAILED; } static int alauda_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct us_data *us; int result; result = usb_stor_probe1(&us, intf, id, (id - alauda_usb_ids) + alauda_unusual_dev_list); if (result) return result; us->transport_name = "Alauda Control/Bulk"; us->transport = alauda_transport; us->transport_reset = usb_stor_Bulk_reset; us->max_lun = 1; result = usb_stor_probe2(us); return result; } static struct usb_driver alauda_driver = { .name = "ums-alauda", .probe = alauda_probe, .disconnect = usb_stor_disconnect, .suspend = usb_stor_suspend, .resume = usb_stor_resume, .reset_resume = usb_stor_reset_resume, .pre_reset = usb_stor_pre_reset, .post_reset = usb_stor_post_reset, .id_table = alauda_usb_ids, .soft_unbind = 1, }; static int __init alauda_init(void) { return usb_register(&alauda_driver); } static void __exit alauda_exit(void) { usb_deregister(&alauda_driver); } module_init(alauda_init); module_exit(alauda_exit);
{ "pile_set_name": "Github" }
<?php namespace AmpProject\Optimizer\Exception; use OutOfBoundsException; /** * Exception thrown when an invalid configuration key was provided. * * @package ampproject/optimizer */ final class InvalidConfigurationKey extends OutOfBoundsException implements AmpOptimizerException { /** * Instantiate an InvalidConfigurationKey exception for an invalid key. * * @param string $key Key that was invalid. * @return self */ public static function fromKey($key) { $message = "The provided configuration key '{$key}' is not valid."; return new self($message); } /** * Instantiate an InvalidConfigurationKey exception for an invalid transformer configuration key. * * @param string $transformer Transformer class or identifier. * @param string $key Key that was invalid. * @return self */ public static function fromTransformerKey($transformer, $key) { $parts = explode('\\', $transformer); $transformer = array_pop($parts); $message = "The provided configuration key '{$key}' is not valid for the transformer '{$transformer}'."; return new self($message); } }
{ "pile_set_name": "Github" }
{ "created_at": "2015-02-27T22:28:43.971214", "description": "A meteor smart package for the bootstrap bootboxjs plugin", "fork": false, "full_name": "TimHeckel/meteor-bootboxjs", "language": "JavaScript", "updated_at": "2015-03-10T07:01:59.041825" }
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* ftstroke.h */ /* */ /* FreeType path stroker (specification). */ /* */ /* Copyright 2002-2018 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef FTSTROKE_H_ #define FTSTROKE_H_ #include <ft2build.h> #include FT_OUTLINE_H #include FT_GLYPH_H FT_BEGIN_HEADER /************************************************************************ * * @section: * glyph_stroker * * @title: * Glyph Stroker * * @abstract: * Generating bordered and stroked glyphs. * * @description: * This component generates stroked outlines of a given vectorial * glyph. It also allows you to retrieve the `outside' and/or the * `inside' borders of the stroke. * * This can be useful to generate `bordered' glyph, i.e., glyphs * displayed with a coloured (and anti-aliased) border around their * shape. * * @order: * FT_Stroker * * FT_Stroker_LineJoin * FT_Stroker_LineCap * FT_StrokerBorder * * FT_Outline_GetInsideBorder * FT_Outline_GetOutsideBorder * * FT_Glyph_Stroke * FT_Glyph_StrokeBorder * * FT_Stroker_New * FT_Stroker_Set * FT_Stroker_Rewind * FT_Stroker_ParseOutline * FT_Stroker_Done * * FT_Stroker_BeginSubPath * FT_Stroker_EndSubPath * * FT_Stroker_LineTo * FT_Stroker_ConicTo * FT_Stroker_CubicTo * * FT_Stroker_GetBorderCounts * FT_Stroker_ExportBorder * FT_Stroker_GetCounts * FT_Stroker_Export * */ /************************************************************** * * @type: * FT_Stroker * * @description: * Opaque handle to a path stroker object. */ typedef struct FT_StrokerRec_* FT_Stroker; /************************************************************** * * @enum: * FT_Stroker_LineJoin * * @description: * These values determine how two joining lines are rendered * in a stroker. * * @values: * FT_STROKER_LINEJOIN_ROUND :: * Used to render rounded line joins. Circular arcs are used * to join two lines smoothly. * * FT_STROKER_LINEJOIN_BEVEL :: * Used to render beveled line joins. The outer corner of * the joined lines is filled by enclosing the triangular * region of the corner with a straight line between the * outer corners of each stroke. * * FT_STROKER_LINEJOIN_MITER_FIXED :: * Used to render mitered line joins, with fixed bevels if the * miter limit is exceeded. The outer edges of the strokes * for the two segments are extended until they meet at an * angle. If the segments meet at too sharp an angle (such * that the miter would extend from the intersection of the * segments a distance greater than the product of the miter * limit value and the border radius), then a bevel join (see * above) is used instead. This prevents long spikes being * created. FT_STROKER_LINEJOIN_MITER_FIXED generates a miter * line join as used in PostScript and PDF. * * FT_STROKER_LINEJOIN_MITER_VARIABLE :: * FT_STROKER_LINEJOIN_MITER :: * Used to render mitered line joins, with variable bevels if * the miter limit is exceeded. The intersection of the * strokes is clipped at a line perpendicular to the bisector * of the angle between the strokes, at the distance from the * intersection of the segments equal to the product of the * miter limit value and the border radius. This prevents * long spikes being created. * FT_STROKER_LINEJOIN_MITER_VARIABLE generates a mitered line * join as used in XPS. FT_STROKER_LINEJOIN_MITER is an alias * for FT_STROKER_LINEJOIN_MITER_VARIABLE, retained for * backward compatibility. */ typedef enum FT_Stroker_LineJoin_ { FT_STROKER_LINEJOIN_ROUND = 0, FT_STROKER_LINEJOIN_BEVEL = 1, FT_STROKER_LINEJOIN_MITER_VARIABLE = 2, FT_STROKER_LINEJOIN_MITER = FT_STROKER_LINEJOIN_MITER_VARIABLE, FT_STROKER_LINEJOIN_MITER_FIXED = 3 } FT_Stroker_LineJoin; /************************************************************** * * @enum: * FT_Stroker_LineCap * * @description: * These values determine how the end of opened sub-paths are * rendered in a stroke. * * @values: * FT_STROKER_LINECAP_BUTT :: * The end of lines is rendered as a full stop on the last * point itself. * * FT_STROKER_LINECAP_ROUND :: * The end of lines is rendered as a half-circle around the * last point. * * FT_STROKER_LINECAP_SQUARE :: * The end of lines is rendered as a square around the * last point. */ typedef enum FT_Stroker_LineCap_ { FT_STROKER_LINECAP_BUTT = 0, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINECAP_SQUARE } FT_Stroker_LineCap; /************************************************************** * * @enum: * FT_StrokerBorder * * @description: * These values are used to select a given stroke border * in @FT_Stroker_GetBorderCounts and @FT_Stroker_ExportBorder. * * @values: * FT_STROKER_BORDER_LEFT :: * Select the left border, relative to the drawing direction. * * FT_STROKER_BORDER_RIGHT :: * Select the right border, relative to the drawing direction. * * @note: * Applications are generally interested in the `inside' and `outside' * borders. However, there is no direct mapping between these and the * `left' and `right' ones, since this really depends on the glyph's * drawing orientation, which varies between font formats. * * You can however use @FT_Outline_GetInsideBorder and * @FT_Outline_GetOutsideBorder to get these. */ typedef enum FT_StrokerBorder_ { FT_STROKER_BORDER_LEFT = 0, FT_STROKER_BORDER_RIGHT } FT_StrokerBorder; /************************************************************** * * @function: * FT_Outline_GetInsideBorder * * @description: * Retrieve the @FT_StrokerBorder value corresponding to the * `inside' borders of a given outline. * * @input: * outline :: * The source outline handle. * * @return: * The border index. @FT_STROKER_BORDER_RIGHT for empty or invalid * outlines. */ FT_EXPORT( FT_StrokerBorder ) FT_Outline_GetInsideBorder( FT_Outline* outline ); /************************************************************** * * @function: * FT_Outline_GetOutsideBorder * * @description: * Retrieve the @FT_StrokerBorder value corresponding to the * `outside' borders of a given outline. * * @input: * outline :: * The source outline handle. * * @return: * The border index. @FT_STROKER_BORDER_LEFT for empty or invalid * outlines. */ FT_EXPORT( FT_StrokerBorder ) FT_Outline_GetOutsideBorder( FT_Outline* outline ); /************************************************************** * * @function: * FT_Stroker_New * * @description: * Create a new stroker object. * * @input: * library :: * FreeType library handle. * * @output: * astroker :: * A new stroker object handle. NULL in case of error. * * @return: * FreeType error code. 0~means success. */ FT_EXPORT( FT_Error ) FT_Stroker_New( FT_Library library, FT_Stroker *astroker ); /************************************************************** * * @function: * FT_Stroker_Set * * @description: * Reset a stroker object's attributes. * * @input: * stroker :: * The target stroker handle. * * radius :: * The border radius. * * line_cap :: * The line cap style. * * line_join :: * The line join style. * * miter_limit :: * The miter limit for the FT_STROKER_LINEJOIN_MITER_FIXED and * FT_STROKER_LINEJOIN_MITER_VARIABLE line join styles, * expressed as 16.16 fixed-point value. * * @note: * The radius is expressed in the same units as the outline * coordinates. * * This function calls @FT_Stroker_Rewind automatically. */ FT_EXPORT( void ) FT_Stroker_Set( FT_Stroker stroker, FT_Fixed radius, FT_Stroker_LineCap line_cap, FT_Stroker_LineJoin line_join, FT_Fixed miter_limit ); /************************************************************** * * @function: * FT_Stroker_Rewind * * @description: * Reset a stroker object without changing its attributes. * You should call this function before beginning a new * series of calls to @FT_Stroker_BeginSubPath or * @FT_Stroker_EndSubPath. * * @input: * stroker :: * The target stroker handle. */ FT_EXPORT( void ) FT_Stroker_Rewind( FT_Stroker stroker ); /************************************************************** * * @function: * FT_Stroker_ParseOutline * * @description: * A convenience function used to parse a whole outline with * the stroker. The resulting outline(s) can be retrieved * later by functions like @FT_Stroker_GetCounts and @FT_Stroker_Export. * * @input: * stroker :: * The target stroker handle. * * outline :: * The source outline. * * opened :: * A boolean. If~1, the outline is treated as an open path instead * of a closed one. * * @return: * FreeType error code. 0~means success. * * @note: * If `opened' is~0 (the default), the outline is treated as a closed * path, and the stroker generates two distinct `border' outlines. * * If `opened' is~1, the outline is processed as an open path, and the * stroker generates a single `stroke' outline. * * This function calls @FT_Stroker_Rewind automatically. */ FT_EXPORT( FT_Error ) FT_Stroker_ParseOutline( FT_Stroker stroker, FT_Outline* outline, FT_Bool opened ); /************************************************************** * * @function: * FT_Stroker_BeginSubPath * * @description: * Start a new sub-path in the stroker. * * @input: * stroker :: * The target stroker handle. * * to :: * A pointer to the start vector. * * open :: * A boolean. If~1, the sub-path is treated as an open one. * * @return: * FreeType error code. 0~means success. * * @note: * This function is useful when you need to stroke a path that is * not stored as an @FT_Outline object. */ FT_EXPORT( FT_Error ) FT_Stroker_BeginSubPath( FT_Stroker stroker, FT_Vector* to, FT_Bool open ); /************************************************************** * * @function: * FT_Stroker_EndSubPath * * @description: * Close the current sub-path in the stroker. * * @input: * stroker :: * The target stroker handle. * * @return: * FreeType error code. 0~means success. * * @note: * You should call this function after @FT_Stroker_BeginSubPath. * If the subpath was not `opened', this function `draws' a * single line segment to the start position when needed. */ FT_EXPORT( FT_Error ) FT_Stroker_EndSubPath( FT_Stroker stroker ); /************************************************************** * * @function: * FT_Stroker_LineTo * * @description: * `Draw' a single line segment in the stroker's current sub-path, * from the last position. * * @input: * stroker :: * The target stroker handle. * * to :: * A pointer to the destination point. * * @return: * FreeType error code. 0~means success. * * @note: * You should call this function between @FT_Stroker_BeginSubPath and * @FT_Stroker_EndSubPath. */ FT_EXPORT( FT_Error ) FT_Stroker_LineTo( FT_Stroker stroker, FT_Vector* to ); /************************************************************** * * @function: * FT_Stroker_ConicTo * * @description: * `Draw' a single quadratic Bezier in the stroker's current sub-path, * from the last position. * * @input: * stroker :: * The target stroker handle. * * control :: * A pointer to a Bezier control point. * * to :: * A pointer to the destination point. * * @return: * FreeType error code. 0~means success. * * @note: * You should call this function between @FT_Stroker_BeginSubPath and * @FT_Stroker_EndSubPath. */ FT_EXPORT( FT_Error ) FT_Stroker_ConicTo( FT_Stroker stroker, FT_Vector* control, FT_Vector* to ); /************************************************************** * * @function: * FT_Stroker_CubicTo * * @description: * `Draw' a single cubic Bezier in the stroker's current sub-path, * from the last position. * * @input: * stroker :: * The target stroker handle. * * control1 :: * A pointer to the first Bezier control point. * * control2 :: * A pointer to second Bezier control point. * * to :: * A pointer to the destination point. * * @return: * FreeType error code. 0~means success. * * @note: * You should call this function between @FT_Stroker_BeginSubPath and * @FT_Stroker_EndSubPath. */ FT_EXPORT( FT_Error ) FT_Stroker_CubicTo( FT_Stroker stroker, FT_Vector* control1, FT_Vector* control2, FT_Vector* to ); /************************************************************** * * @function: * FT_Stroker_GetBorderCounts * * @description: * Call this function once you have finished parsing your paths * with the stroker. It returns the number of points and * contours necessary to export one of the `border' or `stroke' * outlines generated by the stroker. * * @input: * stroker :: * The target stroker handle. * * border :: * The border index. * * @output: * anum_points :: * The number of points. * * anum_contours :: * The number of contours. * * @return: * FreeType error code. 0~means success. * * @note: * When an outline, or a sub-path, is `closed', the stroker generates * two independent `border' outlines, named `left' and `right'. * * When the outline, or a sub-path, is `opened', the stroker merges * the `border' outlines with caps. The `left' border receives all * points, while the `right' border becomes empty. * * Use the function @FT_Stroker_GetCounts instead if you want to * retrieve the counts associated to both borders. */ FT_EXPORT( FT_Error ) FT_Stroker_GetBorderCounts( FT_Stroker stroker, FT_StrokerBorder border, FT_UInt *anum_points, FT_UInt *anum_contours ); /************************************************************** * * @function: * FT_Stroker_ExportBorder * * @description: * Call this function after @FT_Stroker_GetBorderCounts to * export the corresponding border to your own @FT_Outline * structure. * * Note that this function appends the border points and * contours to your outline, but does not try to resize its * arrays. * * @input: * stroker :: * The target stroker handle. * * border :: * The border index. * * outline :: * The target outline handle. * * @note: * Always call this function after @FT_Stroker_GetBorderCounts to * get sure that there is enough room in your @FT_Outline object to * receive all new data. * * When an outline, or a sub-path, is `closed', the stroker generates * two independent `border' outlines, named `left' and `right'. * * When the outline, or a sub-path, is `opened', the stroker merges * the `border' outlines with caps. The `left' border receives all * points, while the `right' border becomes empty. * * Use the function @FT_Stroker_Export instead if you want to * retrieve all borders at once. */ FT_EXPORT( void ) FT_Stroker_ExportBorder( FT_Stroker stroker, FT_StrokerBorder border, FT_Outline* outline ); /************************************************************** * * @function: * FT_Stroker_GetCounts * * @description: * Call this function once you have finished parsing your paths * with the stroker. It returns the number of points and * contours necessary to export all points/borders from the stroked * outline/path. * * @input: * stroker :: * The target stroker handle. * * @output: * anum_points :: * The number of points. * * anum_contours :: * The number of contours. * * @return: * FreeType error code. 0~means success. */ FT_EXPORT( FT_Error ) FT_Stroker_GetCounts( FT_Stroker stroker, FT_UInt *anum_points, FT_UInt *anum_contours ); /************************************************************** * * @function: * FT_Stroker_Export * * @description: * Call this function after @FT_Stroker_GetBorderCounts to * export all borders to your own @FT_Outline structure. * * Note that this function appends the border points and * contours to your outline, but does not try to resize its * arrays. * * @input: * stroker :: * The target stroker handle. * * outline :: * The target outline handle. */ FT_EXPORT( void ) FT_Stroker_Export( FT_Stroker stroker, FT_Outline* outline ); /************************************************************** * * @function: * FT_Stroker_Done * * @description: * Destroy a stroker object. * * @input: * stroker :: * A stroker handle. Can be NULL. */ FT_EXPORT( void ) FT_Stroker_Done( FT_Stroker stroker ); /************************************************************** * * @function: * FT_Glyph_Stroke * * @description: * Stroke a given outline glyph object with a given stroker. * * @inout: * pglyph :: * Source glyph handle on input, new glyph handle on output. * * @input: * stroker :: * A stroker handle. * * destroy :: * A Boolean. If~1, the source glyph object is destroyed * on success. * * @return: * FreeType error code. 0~means success. * * @note: * The source glyph is untouched in case of error. * * Adding stroke may yield a significantly wider and taller glyph * depending on how large of a radius was used to stroke the glyph. You * may need to manually adjust horizontal and vertical advance amounts * to account for this added size. */ FT_EXPORT( FT_Error ) FT_Glyph_Stroke( FT_Glyph *pglyph, FT_Stroker stroker, FT_Bool destroy ); /************************************************************** * * @function: * FT_Glyph_StrokeBorder * * @description: * Stroke a given outline glyph object with a given stroker, but * only return either its inside or outside border. * * @inout: * pglyph :: * Source glyph handle on input, new glyph handle on output. * * @input: * stroker :: * A stroker handle. * * inside :: * A Boolean. If~1, return the inside border, otherwise * the outside border. * * destroy :: * A Boolean. If~1, the source glyph object is destroyed * on success. * * @return: * FreeType error code. 0~means success. * * @note: * The source glyph is untouched in case of error. * * Adding stroke may yield a significantly wider and taller glyph * depending on how large of a radius was used to stroke the glyph. You * may need to manually adjust horizontal and vertical advance amounts * to account for this added size. */ FT_EXPORT( FT_Error ) FT_Glyph_StrokeBorder( FT_Glyph *pglyph, FT_Stroker stroker, FT_Bool inside, FT_Bool destroy ); /* */ FT_END_HEADER #endif /* FTSTROKE_H_ */ /* END */ /* Local Variables: */ /* coding: utf-8 */ /* End: */
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: ml/param/ParamMap.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: ml/param/ParamMap.js</h1> <section> <article> <pre class="prettyprint source linenums"><code>/* * Copyright 2016 IBM Corp. * * 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. */ module.exports = function(kernelP) { return (function() { var Utils = require('../../utils.js'); var gKernelP = kernelP; /** * A param to value map. * @classdesc * Creates an empty param map. * @class * @memberof module:eclairjs/ml/param */ function ParamMap() { Utils.handleConstructor(this, arguments, gKernelP); } /** * Puts a list of param pairs (overwrites if the input params exists). * @param {...module:eclairjs/ml/param.ParamPair | module:eclairjs/ml/param.Param} paramPairs * @param {object} value * @returns {module:eclairjs/ml/param.ParamMap} */ ParamMap.prototype.put = function() { var args = { target: this, method: 'put', args: Utils.wrapArguments(arguments), returnType: ParamMap }; return Utils.generate(args); }; /** * Optionally returns the value associated with a param. * @param {module:eclairjs/ml/param.Param} param * @returns {object} */ ParamMap.prototype.get = function(param) { var args = { target: this, method: 'get', args: Utils.wrapArguments(arguments), returnType: Object }; return Utils.generate(args); }; /** * Returns the value associated with a param or a default value. * @param {module:eclairjs/ml/param.Param} param * @param {object} default * @returns {object} */ ParamMap.prototype.getOrElse = function() { var args = { target: this, method: 'getOrElse', args: Utils.wrapArguments(arguments), returnType: Object }; return Utils.generate(args); }; /** * Gets the value of the input param or its default value if it does not exist. * Raises a NoSuchElementException if there is no value associated with the input param. * @param {module:eclairjs/ml/param.Param} param * @returns {object} */ ParamMap.prototype.apply = function(param) { var args = { target: this, method: 'apply', args: Utils.wrapArguments(arguments), returnType: Object }; return Utils.generate(args); }; /** * Checks whether a parameter is explicitly specified. * @param {module:eclairjs/ml/param.Param} param * @returns {Promise.&lt;boolean>} */ ParamMap.prototype.contains = function(param) { var args = { target: this, method: 'contains', args: Utils.wrapArguments(arguments), returnType: Boolean }; return Utils.generate(args); }; /** * Removes a key from this map and returns its value associated previously as an option. * @param {module:eclairjs/ml/param.Param} param * @returns {object} */ ParamMap.prototype.remove = function(param) { var args = { target: this, method: 'remove', args: Utils.wrapArguments(arguments), returnType: Object }; return Utils.generate(args); }; /** * Filters this param map for the given parent. * @param {module:eclairjs/ml/param.Params} parent * @returns {module:eclairjs/ml/param.ParamMap} */ ParamMap.prototype.filter = function(parent) { var args = { target: this, method: 'filter', args: Utils.wrapArguments(arguments), returnType: ParamMap }; return Utils.generate(args); }; /** * Creates a copy of this param map. * @returns {module:eclairjs/ml/param.ParamMap} */ ParamMap.prototype.copy = function() { var args = { target: this, method: 'copy', args: Utils.wrapArguments(arguments), returnType: ParamMap }; return Utils.generate(args); }; /** * @returns {Promise.&lt;string>} */ ParamMap.prototype.toString = function() { var args = { target: this, method: 'toString', args: Utils.wrapArguments(arguments), returnType: String }; return Utils.generate(args); }; /** * Converts this param map to a array of param pairs. * @returns {module:eclairjs/ml/param.ParamMap[]} */ ParamMap.prototype.toArray = function () { var args = { target: this, method: 'toArray', args: Utils.wrapArguments(arguments), returnType: [ParamMap] }; return Utils.generate(args); }; /** * Number of param pairs in this map. * @returns {Promise.&lt;number>} */ ParamMap.prototype.size = function() { var args = { target: this, method: 'size', args: Utils.wrapArguments(arguments), returnType: Number }; return Utils.generate(args); }; /** * Returns a new param map that contains parameters in this map and the given map, * where the latter overwrites this if there exist conflicts. * @param {module:eclairjs/ml/param.ParamMap} other * @returns {module:eclairjs/ml/param.ParamMap} */ ParamMap.prototype.$plus$plus = function (other) { var args = { target: this, method: '$plus$plus', args: Utils.wrapArguments(arguments), returnType: ParamMap }; return Utils.generate(args); }; // // static methods // /** * Returns an empty param map. * @returns {module:eclairjs/ml/param.ParamMap} */ ParamMap.empty = function() { var args = { target: ParamMap, method: 'empty', kernelP: gKernelP, static: true, args: Utils.wrapArguments(arguments), returnType: ParamMap }; return Utils.generate(args); }; /** * Constructs a param map by specifying its entries. * @param {...module:eclairjs/ml/param.ParamPair} paramPairs * @returns {module:eclairjs/ml/param.ParamMap} */ ParamMap.apply = function(paramPairs) { var args = { target: ParamMap, method: 'apply', kernelP: gKernelP, static: true, args: Utils.wrapArguments(arguments), returnType: ParamMap }; return Utils.generate(args); }; ParamMap.moduleLocation = '/ml/param/ParamMap'; return ParamMap; })(); };</code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-eclairjs.html">eclairjs</a></li><li><a href="module-eclairjs_ml.html">eclairjs/ml</a></li><li><a href="module-eclairjs_ml_classification.html">eclairjs/ml/classification</a></li><li><a href="module-eclairjs_ml_clustering.html">eclairjs/ml/clustering</a></li><li><a href="module-eclairjs_ml_evaluation.html">eclairjs/ml/evaluation</a></li><li><a href="module-eclairjs_ml_feature.html">eclairjs/ml/feature</a></li><li><a href="module-eclairjs_ml_param.html">eclairjs/ml/param</a></li><li><a href="module-eclairjs_ml_recommendation.html">eclairjs/ml/recommendation</a></li><li><a href="module-eclairjs_ml_regression.html">eclairjs/ml/regression</a></li><li><a href="module-eclairjs_ml_tuning.html">eclairjs/ml/tuning</a></li><li><a href="module-eclairjs_mllib.html">eclairjs/mllib</a></li><li><a href="module-eclairjs_mllib_classification.html">eclairjs/mllib/classification</a></li><li><a href="module-eclairjs_mllib_clustering.html">eclairjs/mllib/clustering</a></li><li><a href="module-eclairjs_mllib_evaluation.html">eclairjs/mllib/evaluation</a></li><li><a href="module-eclairjs_mllib_feature.html">eclairjs/mllib/feature</a></li><li><a href="module-eclairjs_mllib_fpm.html">eclairjs/mllib/fpm</a></li><li><a href="module-eclairjs_mllib_linalg.html">eclairjs/mllib/linalg</a></li><li><a href="module-eclairjs_mllib_linalg_distributed.html">eclairjs/mllib/linalg/distributed</a></li><li><a href="module-eclairjs_mllib_optimization.html">eclairjs/mllib/optimization</a></li><li><a href="module-eclairjs_mllib_random.html">eclairjs/mllib/random</a></li><li><a href="module-eclairjs_mllib_recommendation.html">eclairjs/mllib/recommendation</a></li><li><a href="module-eclairjs_mllib_regression.html">eclairjs/mllib/regression</a></li><li><a href="module-eclairjs_mllib_tree.html">eclairjs/mllib/tree</a></li><li><a href="module-eclairjs_mllib_tree_configuration.html">eclairjs/mllib/tree/configuration</a></li><li><a href="module-eclairjs_mllib_tree_loss.html">eclairjs/mllib/tree/loss</a></li><li><a href="module-eclairjs_mllib_tree_model.html">eclairjs/mllib/tree/model</a></li><li><a href="module-eclairjs_mllib_util.html">eclairjs/mllib/util</a></li><li><a href="module-eclairjs_rdd.html">eclairjs/rdd</a></li><li><a href="module-eclairjs_sql.html">eclairjs/sql</a></li><li><a href="module-eclairjs_sql_streaming.html">eclairjs/sql/streaming</a></li><li><a href="module-eclairjs_sql_types.html">eclairjs/sql/types</a></li><li><a href="module-eclairjs_storage.html">eclairjs/storage</a></li><li><a href="module-eclairjs_streaming.html">eclairjs/streaming</a></li><li><a href="module-eclairjs_streaming_dstream.html">eclairjs/streaming/dstream</a></li><li><a href="module-eclairjs_streaming_kafka.html">eclairjs/streaming/kafka</a></li><li><a href="module-eclairjs_streaming_twitter.html">eclairjs/streaming/twitter</a></li></ul><h3>Classes</h3><ul><li><a href="-_resolveRows.html">_resolveRows</a></li><li><a href="InputDStream.html">InputDStream</a></li><li><a href="IsotonicRegressionModel.html">IsotonicRegressionModel</a></li><li><a href="MLReader.html">MLReader</a></li><li><a href="MLWriter.html">MLWriter</a></li><li><a href="module-eclairjs.Accumulable.html">Accumulable</a></li><li><a href="module-eclairjs.AccumulableParam.html">AccumulableParam</a></li><li><a href="module-eclairjs.Accumulator.html">Accumulator</a></li><li><a href="module-eclairjs.FloatAccumulatorParam.html">FloatAccumulatorParam</a></li><li><a href="module-eclairjs.IntAccumulatorParam.html">IntAccumulatorParam</a></li><li><a href="module-eclairjs.List.html">List</a></li><li><a href="module-eclairjs.SparkConf.html">SparkConf</a></li><li><a href="module-eclairjs.SparkContext.html">SparkContext</a></li><li><a href="module-eclairjs.Tuple.html">Tuple</a></li><li><a href="module-eclairjs.Tuple2.html">Tuple2</a></li><li><a href="module-eclairjs.Tuple3.html">Tuple3</a></li><li><a href="module-eclairjs.Tuple4.html">Tuple4</a></li><li><a href="module-eclairjs_ml.Estimator.html">Estimator</a></li><li><a href="module-eclairjs_ml.Model.html">Model</a></li><li><a href="module-eclairjs_ml.Pipeline.html">Pipeline</a></li><li><a href="module-eclairjs_ml.PipelineModel.html">PipelineModel</a></li><li><a href="module-eclairjs_ml.PipelineStage.html">PipelineStage</a></li><li><a href="module-eclairjs_ml.PredictionModel.html">PredictionModel</a></li><li><a href="module-eclairjs_ml.Predictor.html">Predictor</a></li><li><a href="module-eclairjs_ml.Transformer.html">Transformer</a></li><li><a href="module-eclairjs_ml.UnaryTransformer.html">UnaryTransformer</a></li><li><a href="module-eclairjs_ml_attribute.NumericAttribute.html">NumericAttribute</a></li><li><a href="module-eclairjs_ml_classification.ClassificationModel.html">ClassificationModel</a></li><li><a href="module-eclairjs_ml_classification.Classifier.html">Classifier</a></li><li><a href="module-eclairjs_ml_classification.DecisionTreeClassifier.html">DecisionTreeClassifier</a></li><li><a href="module-eclairjs_ml_classification.GBTClassifier.html">GBTClassifier</a></li><li><a href="module-eclairjs_ml_classification.LogisticRegression.html">LogisticRegression</a></li><li><a href="module-eclairjs_ml_classification.LogisticRegressionModel.html">LogisticRegressionModel</a></li><li><a href="module-eclairjs_ml_classification.LogisticRegressionSummary.html">LogisticRegressionSummary</a></li><li><a href="module-eclairjs_ml_classification.LogisticRegressionTrainingSummary.html">LogisticRegressionTrainingSummary</a></li><li><a href="module-eclairjs_ml_classification.MultilayerPerceptronClassificationModel.html">MultilayerPerceptronClassificationModel</a></li><li><a href="module-eclairjs_ml_classification.NaiveBayes.html">NaiveBayes</a></li><li><a href="module-eclairjs_ml_classification.NaiveBayesModel.html">NaiveBayesModel</a></li><li><a href="module-eclairjs_ml_classification.OneVsRestModel.html">OneVsRestModel</a></li><li><a href="module-eclairjs_ml_classification.ProbabilisticClassificationModel.html">ProbabilisticClassificationModel</a></li><li><a href="module-eclairjs_ml_classification.ProbabilisticClassifier.html">ProbabilisticClassifier</a></li><li><a href="module-eclairjs_ml_classification.RandomForestClassificationModel.html">RandomForestClassificationModel</a></li><li><a href="module-eclairjs_ml_classification.RandomForestClassifier.html">RandomForestClassifier</a></li><li><a href="module-eclairjs_ml_clustering.BisectingKMeans.html">BisectingKMeans</a></li><li><a href="module-eclairjs_ml_clustering.BisectingKMeansModel.html">BisectingKMeansModel</a></li><li><a href="module-eclairjs_ml_clustering.GaussianMixture.html">GaussianMixture</a></li><li><a href="module-eclairjs_ml_clustering.GaussianMixtureModel.html">GaussianMixtureModel</a></li><li><a href="module-eclairjs_ml_clustering.GaussianMixtureSummary.html">GaussianMixtureSummary</a></li><li><a href="module-eclairjs_ml_clustering.KMeans.html">KMeans</a></li><li><a href="module-eclairjs_ml_clustering.KMeansModel.html">KMeansModel</a></li><li><a href="module-eclairjs_ml_clustering.LDA.html">LDA</a></li><li><a href="module-eclairjs_ml_clustering.LDAModel.html">LDAModel</a></li><li><a href="module-eclairjs_ml_evaluation.MulticlassClassificationEvaluator.html">MulticlassClassificationEvaluator</a></li><li><a href="module-eclairjs_ml_evaluation.RegressionEvaluator.html">RegressionEvaluator</a></li><li><a href="module-eclairjs_ml_feature.ChiSqSelectorModel.html">ChiSqSelectorModel</a></li><li><a href="module-eclairjs_ml_feature.ElementwiseProduct.html">ElementwiseProduct</a></li><li><a href="module-eclairjs_ml_feature.IDFModel.html">IDFModel</a></li><li><a href="module-eclairjs_ml_feature.IndexToString.html">IndexToString</a></li><li><a href="module-eclairjs_ml_feature.MinMaxScaler.html">MinMaxScaler</a></li><li><a href="module-eclairjs_ml_feature.MinMaxScalerModel.html">MinMaxScalerModel</a></li><li><a href="module-eclairjs_ml_feature.NGram.html">NGram</a></li><li><a href="module-eclairjs_ml_feature.Normalizer.html">Normalizer</a></li><li><a href="module-eclairjs_ml_feature.OneHotEncoder.html">OneHotEncoder</a></li><li><a href="module-eclairjs_ml_feature.PCA.html">PCA</a></li><li><a href="module-eclairjs_ml_feature.PCAModel.html">PCAModel</a></li><li><a href="module-eclairjs_ml_feature.PolynomialExpansion.html">PolynomialExpansion</a></li><li><a href="module-eclairjs_ml_feature.QuantileDiscretizer.html">QuantileDiscretizer</a></li><li><a href="module-eclairjs_ml_feature.RFormulaModel.html">RFormulaModel</a></li><li><a href="module-eclairjs_ml_feature.StandardScalerModel.html">StandardScalerModel</a></li><li><a href="module-eclairjs_ml_feature.StringIndexer.html">StringIndexer</a></li><li><a href="module-eclairjs_ml_feature.StringIndexerModel.html">StringIndexerModel</a></li><li><a href="module-eclairjs_ml_feature.VectorIndexer.html">VectorIndexer</a></li><li><a href="module-eclairjs_ml_feature.VectorIndexerModel.html">VectorIndexerModel</a></li><li><a href="module-eclairjs_ml_feature.Word2VecModel.html">Word2VecModel</a></li><li><a href="module-eclairjs_ml_param.BooleanParam.html">BooleanParam</a></li><li><a href="module-eclairjs_ml_param.DoubleParam.html">DoubleParam</a></li><li><a href="module-eclairjs_ml_param.IntParam.html">IntParam</a></li><li><a href="module-eclairjs_ml_param.Param.html">Param</a></li><li><a href="module-eclairjs_ml_param.ParamMap.html">ParamMap</a></li><li><a href="module-eclairjs_ml_param.ParamPair.html">ParamPair</a></li><li><a href="module-eclairjs_ml_recommendation.ALSModel.html">ALSModel</a></li><li><a href="module-eclairjs_ml_regression.AFTSurvivalRegressionModel.html">AFTSurvivalRegressionModel</a></li><li><a href="module-eclairjs_ml_regression.DecisionTreeRegressionModel.html">DecisionTreeRegressionModel</a></li><li><a href="module-eclairjs_ml_regression.DecisionTreeRegressor.html">DecisionTreeRegressor</a></li><li><a href="module-eclairjs_ml_regression.GBTRegressionModel.html">GBTRegressionModel</a></li><li><a href="module-eclairjs_ml_regression.GBTRegressor.html">GBTRegressor</a></li><li><a href="module-eclairjs_ml_regression.GeneralizedLinearRegression.html">GeneralizedLinearRegression</a></li><li><a href="module-eclairjs_ml_regression.GeneralizedLinearRegressionModel.html">GeneralizedLinearRegressionModel</a></li><li><a href="module-eclairjs_ml_regression.GeneralizedLinearRegressionSummary.html">GeneralizedLinearRegressionSummary</a></li><li><a href="module-eclairjs_ml_regression.GeneralizedLinearRegressionTrainingSummary.html">GeneralizedLinearRegressionTrainingSummary</a></li><li><a href="module-eclairjs_ml_regression.LinearRegression.html">LinearRegression</a></li><li><a href="module-eclairjs_ml_regression.LinearRegressionModel.html">LinearRegressionModel</a></li><li><a href="module-eclairjs_ml_regression.LinearRegressionSummary.html">LinearRegressionSummary</a></li><li><a href="module-eclairjs_ml_regression.LinearRegressionTrainingSummary.html">LinearRegressionTrainingSummary</a></li><li><a href="module-eclairjs_ml_regression.RandomForestRegressionModel.html">RandomForestRegressionModel</a></li><li><a href="module-eclairjs_ml_regression.RandomForestRegressor.html">RandomForestRegressor</a></li><li><a href="module-eclairjs_ml_regression.RegressionModel.html">RegressionModel</a></li><li><a href="module-eclairjs_ml_tuning.CrossValidatorModel.html">CrossValidatorModel</a></li><li><a href="module-eclairjs_ml_tuning.ParamGridBuilder.html">ParamGridBuilder</a></li><li><a href="module-eclairjs_ml_tuning.TrainValidationSplit.html">TrainValidationSplit</a></li><li><a href="module-eclairjs_ml_tuning.TrainValidationSplitModel.html">TrainValidationSplitModel</a></li><li><a href="module-eclairjs_ml_util.MLReadable.html">MLReadable</a></li><li><a href="module-eclairjs_ml_util.MLWritable.html">MLWritable</a></li><li><a href="module-eclairjs_mllib.MLUtils.html">MLUtils</a></li><li><a href="module-eclairjs_mllib_classification.LogisticRegressionModel.html">LogisticRegressionModel</a></li><li><a href="module-eclairjs_mllib_classification.LogisticRegressionWithLBFGS.html">LogisticRegressionWithLBFGS</a></li><li><a href="module-eclairjs_mllib_classification.LogisticRegressionWithSGD.html">LogisticRegressionWithSGD</a></li><li><a href="module-eclairjs_mllib_classification.NaiveBayes.html">NaiveBayes</a></li><li><a href="module-eclairjs_mllib_classification.NaiveBayesModel.html">NaiveBayesModel</a></li><li><a href="module-eclairjs_mllib_classification.SVMModel.html">SVMModel</a></li><li><a href="module-eclairjs_mllib_classification.SVMWithSGD.html">SVMWithSGD</a></li><li><a href="module-eclairjs_mllib_clustering.BisectingKMeans.html">BisectingKMeans</a></li><li><a href="module-eclairjs_mllib_clustering.BisectingKMeansModel.html">BisectingKMeansModel</a></li><li><a href="module-eclairjs_mllib_clustering.KMeans.html">KMeans</a></li><li><a href="module-eclairjs_mllib_clustering.KMeansModel.html">KMeansModel</a></li><li><a href="module-eclairjs_mllib_clustering.LDA.html">LDA</a></li><li><a href="module-eclairjs_mllib_clustering.LDAModel.html">LDAModel</a></li><li><a href="module-eclairjs_mllib_clustering.PowerIterationClustering.html">PowerIterationClustering</a></li><li><a href="module-eclairjs_mllib_clustering.PowerIterationClusteringModel.html">PowerIterationClusteringModel</a></li><li><a href="module-eclairjs_mllib_evaluation.BinaryClassificationMetrics.html">BinaryClassificationMetrics</a></li><li><a href="module-eclairjs_mllib_evaluation.MulticlassMetrics.html">MulticlassMetrics</a></li><li><a href="module-eclairjs_mllib_evaluation.RankingMetrics.html">RankingMetrics</a></li><li><a href="module-eclairjs_mllib_evaluation.RegressionMetrics.html">RegressionMetrics</a></li><li><a href="module-eclairjs_mllib_feature.Word2Vec.html">Word2Vec</a></li><li><a href="module-eclairjs_mllib_feature.Word2VecModel.html">Word2VecModel</a></li><li><a href="module-eclairjs_mllib_fpm.AssociationRules.html">AssociationRules</a></li><li><a href="module-eclairjs_mllib_fpm.FPGrowth.html">FPGrowth</a></li><li><a href="module-eclairjs_mllib_fpm.FPGrowthModel.html">FPGrowthModel</a></li><li><a href="module-eclairjs_mllib_fpm.PrefixSpan.html">PrefixSpan</a></li><li><a href="module-eclairjs_mllib_fpm.PrefixSpanModel.html">PrefixSpanModel</a></li><li><a href="module-eclairjs_mllib_linalg.DenseVector.html">DenseVector</a></li><li><a href="module-eclairjs_mllib_linalg.Matrix.html">Matrix</a></li><li><a href="module-eclairjs_mllib_linalg.SingularValueDecomposition.html">SingularValueDecomposition</a></li><li><a href="module-eclairjs_mllib_linalg.Vector.html">Vector</a></li><li><a href="module-eclairjs_mllib_linalg.Vectors.html">Vectors</a></li><li><a href="module-eclairjs_mllib_linalg_distributed.RowMatrix.html">RowMatrix</a></li><li><a href="module-eclairjs_mllib_optimization.LBFGS.html">LBFGS</a></li><li><a href="module-eclairjs_mllib_optimization.LogisticGradient.html">LogisticGradient</a></li><li><a href="module-eclairjs_mllib_optimization.SquaredL2Updater.html">SquaredL2Updater</a></li><li><a href="module-eclairjs_mllib_random.RandomRDDs.html">RandomRDDs</a></li><li><a href="module-eclairjs_mllib_recommendation.ALS.html">ALS</a></li><li><a href="module-eclairjs_mllib_recommendation.MatrixFactorizationModel.html">MatrixFactorizationModel</a></li><li><a href="module-eclairjs_mllib_recommendation.Rating.html">Rating</a></li><li><a href="module-eclairjs_mllib_regression.LabeledPoint.html">LabeledPoint</a></li><li><a href="module-eclairjs_mllib_regression.LinearRegressionModel.html">LinearRegressionModel</a></li><li><a href="module-eclairjs_mllib_regression.LinearRegressionWithSGD.html">LinearRegressionWithSGD</a></li><li><a href="module-eclairjs_mllib_tree.DecisionTree.html">DecisionTree</a></li><li><a href="module-eclairjs_mllib_tree.GradientBoostedTrees.html">GradientBoostedTrees</a></li><li><a href="module-eclairjs_mllib_tree.RandomForest.html">RandomForest</a></li><li><a href="module-eclairjs_mllib_tree_configuration.BoostingStrategy.html">BoostingStrategy</a></li><li><a href="module-eclairjs_mllib_tree_configuration.Strategy.html">Strategy</a></li><li><a href="module-eclairjs_mllib_tree_loss.Loss.html">Loss</a></li><li><a href="module-eclairjs_mllib_tree_model.DecisionTreeModel.html">DecisionTreeModel</a></li><li><a href="module-eclairjs_mllib_tree_model.GradientBoostedTreesModel.html">GradientBoostedTreesModel</a></li><li><a href="module-eclairjs_mllib_tree_model.RandomForestModel.html">RandomForestModel</a></li><li><a href="module-eclairjs_rdd.FloatRDD.html">FloatRDD</a></li><li><a href="module-eclairjs_rdd.PairRDD.html">PairRDD</a></li><li><a href="module-eclairjs_rdd.RDD.html">RDD</a></li><li><a href="module-eclairjs_sql.Column.html">Column</a></li><li><a href="module-eclairjs_sql.DataFrame.html">DataFrame</a></li><li><a href="module-eclairjs_sql.DataFrameNaFunctions.html">DataFrameNaFunctions</a></li><li><a href="module-eclairjs_sql.DataFrameReader.html">DataFrameReader</a></li><li><a href="module-eclairjs_sql.DataFrameStatFunctions.html">DataFrameStatFunctions</a></li><li><a href="module-eclairjs_sql.DataFrameWriter.html">DataFrameWriter</a></li><li><a href="module-eclairjs_sql.Encoder.html">Encoder</a></li><li><a href="module-eclairjs_sql.Encoders.html">Encoders</a></li><li><a href="module-eclairjs_sql.functions.html">functions</a></li><li><a href="module-eclairjs_sql.GroupedData.html">GroupedData</a></li><li><a href="module-eclairjs_sql.RelationalGroupedDataset.html">RelationalGroupedDataset</a></li><li><a href="module-eclairjs_sql.Row.html">Row</a></li><li><a href="module-eclairjs_sql.RowFactory.html">RowFactory</a></li><li><a href="module-eclairjs_sql.SparkSession.html">SparkSession</a></li><li><a href="module-eclairjs_sql.SQLContext.html">SQLContext</a></li><li><a href="module-eclairjs_sql.SQLContextQueryExecution.html">SQLContextQueryExecution</a></li><li><a href="module-eclairjs_sql.SqlDate.html">SqlDate</a></li><li><a href="module-eclairjs_sql.SqlTimestamp.html">SqlTimestamp</a></li><li><a href="module-eclairjs_sql_streaming.DataStreamReader.html">DataStreamReader</a></li><li><a href="module-eclairjs_sql_streaming.DataStreamWriter.html">DataStreamWriter</a></li><li><a href="module-eclairjs_sql_streaming.SinkStatus.html">SinkStatus</a></li><li><a href="module-eclairjs_sql_streaming.SourceStatus.html">SourceStatus</a></li><li><a href="module-eclairjs_sql_streaming.StreamingQuery.html">StreamingQuery</a></li><li><a href="module-eclairjs_sql_streaming.StreamingQueryInfo.html">StreamingQueryInfo</a></li><li><a href="module-eclairjs_sql_streaming.StreamingQueryListener.html">StreamingQueryListener</a></li><li><a href="module-eclairjs_sql_streaming.StreamingQueryManager.html">StreamingQueryManager</a></li><li><a href="module-eclairjs_sql_types.DataTypes.html">DataTypes</a></li><li><a href="module-eclairjs_sql_types.Metadata.html">Metadata</a></li><li><a href="module-eclairjs_sql_types.StructField.html">StructField</a></li><li><a href="module-eclairjs_sql_types.StructType.html">StructType</a></li><li><a href="module-eclairjs_storage.StorageLevel.html">StorageLevel</a></li><li><a href="module-eclairjs_streaming.Duration.html">Duration</a></li><li><a href="module-eclairjs_streaming.StreamingContext.html">StreamingContext</a></li><li><a href="module-eclairjs_streaming_dstream.DStream.html">DStream</a></li><li><a href="module-eclairjs_streaming_dstream.PairDStream.html">PairDStream</a></li><li><a href="module-eclairjs_streaming_kafka.KafkaUtils.html">KafkaUtils</a></li><li><a href="module-eclairjs_streaming_twitter.TwitterAuthorization.html">TwitterAuthorization</a></li><li><a href="module-eclairjs_streaming_twitter.TwitterUtils.html">TwitterUtils</a></li><li><a href="ReceiverInputDStream.html">ReceiverInputDStream</a></li></ul><h3>Global</h3><ul><li><a href="global.html#handleArguments">handleArguments</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.0-dev</a> on Thu Oct 27 2016 11:28:59 GMT-0400 (EDT) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html>
{ "pile_set_name": "Github" }
# Node Classification on Citation Networks This example shows how to use modules defined in `dgl.nn.pytorch.conv` to do node classification on citation network datasets. ## Datasets - Cora - Citeseer - Pubmed ## Models - GCN: [Semi-Supervised Classification with Graph Convolutional Networks](https://arxiv.org/pdf/1609.02907) - GAT: [Graph Attention Networks](https://arxiv.org/abs/1710.10903) - GraphSAGE [Inductive Representation Learning on Large Graphs](https://cs.stanford.edu/people/jure/pubs/graphsage-nips17.pdf) - APPNP: [Predict then Propagate: Graph Neural Networks meet Personalized PageRank](https://arxiv.org/pdf/1810.05997) - GIN: [How Powerful are Graph Neural Networks?](https://arxiv.org/abs/1810.00826) - TAGCN: [Topology Adaptive Graph Convolutional Networks](https://arxiv.org/abs/1710.10370) - SGC: [Simplifying Graph Convolutional Networks](https://arxiv.org/abs/1902.07153) - AGNN: [Attention-based Graph Neural Network for Semi-supervised Learning](https://arxiv.org/pdf/1803.03735.pdf) - ChebNet: [Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering](https://arxiv.org/abs/1606.09375) ## Usage ``` python run.py [--gpu GPU] --model MODEL_NAME --dataset DATASET_NAME [--self-loop] ``` The hyperparameters might not be the optimal, you could specify them manually in `conf.py`.
{ "pile_set_name": "Github" }
post_install() { cd mingw64 local _prefix=$(pwd -W) cd - local _it for _it in theano-cache theano-nose ; do sed -e "s|/mingw64|${_prefix}|g" \ -i ${_prefix}/bin/${_it}-script.py done } post_upgrade() { post_install }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: d3cb8a3ac104423469cd5cdf24c8f4eb NativeFormatImporter: externalObjects: {} mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
/* Interface for high-level plugins in GCC - Parts common between GCC, ICI and high-level plugins. Copyright (C) 2009-2013 Free Software Foundation, Inc. Contributed by INRIA. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef HIGHLEV_PLUGIN_COMMON_H #define HIGHLEV_PLUGIN_COMMON_H /* Return codes for invoke_plugin_callbacks / call_plugin_event . */ #define PLUGEVT_SUCCESS 0 #define PLUGEVT_NO_EVENTS 1 #define PLUGEVT_NO_SUCH_EVENT 2 #define PLUGEVT_NO_CALLBACK 3 #endif /* HIGHLEV_PLUGIN_COMMON_H */
{ "pile_set_name": "Github" }
from ops.data import OpsClass, OpsField, DszObject, DszCommandObject, cmd_definitions import dsz if ('copy' not in cmd_definitions): dszcopy = OpsClass('copyresults', {'destination': OpsField('destination', dsz.TYPE_STRING), 'source': OpsField('source', dsz.TYPE_STRING)}, DszObject) copycommand = OpsClass('copy', {'copyresults': dszcopy}, DszCommandObject) cmd_definitions['copy'] = copycommand
{ "pile_set_name": "Github" }
// Copyright (c) 2019 E.S.R.Labs. All rights reserved. // // NOTICE: All information contained herein is, and remains // the property of E.S.R.Labs and its suppliers, if any. // The intellectual and technical concepts contained herein are // proprietary to E.S.R.Labs and its suppliers and may be covered // by German and Foreign Patents, patents in process, and are protected // by trade secret or copyright law. // Dissemination of this information or reproduction of this material // is strictly forbidden unless prior written permission is obtained // from E.S.R.Labs. use crate::parse; use anyhow::{anyhow, Result}; use crossbeam_channel as cc; use encoding_rs_io::*; use indexer_base::{ chunks::{ChunkFactory, ChunkResults}, config::IndexingConfig, progress::*, utils, utils::restore_line, }; use parse::detect_timestamp_in_string; use std::{ cell::RefCell, fs, io::{BufRead, BufReader, BufWriter, Read, Write}, path::PathBuf, time::Instant, }; pub async fn create_index_and_mapping( config: IndexingConfig, source_file_size: u64, parse_timestamps: bool, update_channel: cc::Sender<ChunkResults>, shutdown_receiver: Option<cc::Receiver<()>>, ) -> Result<()> { let initial_line_nr = match utils::next_line_nr(&config.out_path) { Ok(nr) => nr, Err(e) => { let c = format!( "could not determine last line number of {:?} ({})", config.out_path, e ); let _ = update_channel.send(Err(Notification { severity: Severity::ERROR, content: c.clone(), line: None, })); return Err(anyhow!(c)); } }; let (out_file, current_out_file_size) = utils::get_out_file_and_size(config.append, &config.out_path)?; let in_file = match fs::File::open(&config.in_file) { Ok(file) => file, Err(e) => { warn!("could not open {:?}", config.in_file); let _ = update_channel.try_send(Err(Notification { severity: Severity::WARNING, content: format!("could not open file ({})", e), line: None, })); return Err(anyhow!("could not open file ({})", e)); } }; let mut decode_builder = DecodeReaderBytesBuilder::new(); decode_builder .utf8_passthru(true) .strip_bom(true) .bom_override(true) .bom_sniffing(true); let decode_buffer_inst = RefCell::new(vec![0; 8 * (1 << 10)]); let mut decode_buffer = decode_buffer_inst.borrow_mut(); let read_from = decode_builder.build_with_buffer(in_file, &mut *decode_buffer)?; index_file( read_from, &config.tag, out_file, current_out_file_size, config.chunk_size, source_file_size, initial_line_nr, parse_timestamps, update_channel, shutdown_receiver, ) } #[allow(clippy::too_many_arguments)] pub fn index_file<T: Read>( read_from: T, tag: &str, out_file: fs::File, current_out_file_size: usize, chunk_size: usize, source_file_size: u64, initial_line_nr: usize, timestamps: bool, update_channel: cc::Sender<ChunkResults>, shutdown_receiver: Option<cc::Receiver<()>>, ) -> Result<()> { let start = Instant::now(); let mut chunk_count = 0usize; let mut last_byte_index = 0usize; let mut chunk_factory = ChunkFactory::new(chunk_size, current_out_file_size); let mut reader = BufReader::new(read_from); let mut line_nr = initial_line_nr; let mut buf_writer = BufWriter::with_capacity(10 * 1024 * 1024, &out_file); let mut buf = vec![]; let mut stopped = false; let mut progress_reporter = ProgressReporter::new(source_file_size, update_channel.clone()); while let Ok(len) = reader.read_until(b'\n', &mut buf) { if stopped { info!("we where stopped in indexer",); break; }; let s = unsafe { std::str::from_utf8_unchecked(&buf) }; let trimmed_line = s.trim_matches(utils::is_newline); let trimmed_len = trimmed_line.len(); let had_newline = trimmed_len != len; if len == 0 { // no more content break; }; let ts = if timestamps { match detect_timestamp_in_string(trimmed_line, None) { Ok((time, _, _)) => Some(time), Err(_) => Some(0), } } else { None }; let additional_bytes: usize = utils::write_tagged_line(tag, &mut buf_writer, trimmed_line, line_nr, had_newline, ts)?; line_nr += 1; match chunk_factory.add_bytes(line_nr, additional_bytes) { Some(chunk) => { stopped = utils::check_if_stop_was_requested(shutdown_receiver.as_ref(), "indexer"); chunk_count += 1; last_byte_index = chunk.b.1; update_channel.send(Ok(IndexingProgress::GotItem { item: chunk }))?; buf_writer.flush()?; false } None => false, }; progress_reporter.make_progress(len); buf = vec![]; } if stopped { debug!("sending IndexingProgress::Stopped"); update_channel.send(Ok(IndexingProgress::Stopped))?; Ok(()) } else { buf_writer.flush()?; if let Some(chunk) = chunk_factory.create_last_chunk(line_nr, chunk_count == 0) { last_byte_index = chunk.b.1; trace!("index: add last chunk {:?}", chunk); update_channel.send(Ok(IndexingProgress::GotItem { item: chunk }))?; chunk_count += 1; } if chunk_count > 0 { let last_expected_byte_index = out_file.metadata().map(|md| md.len() as usize)?; if last_expected_byte_index != last_byte_index { return Err(anyhow!( "error in computation! last byte in chunks is {} but should be {}", last_byte_index, last_expected_byte_index )); } } info!( "done, created {} chunks in {} ms, sending Finished", chunk_count, start.elapsed().as_millis() ); update_channel.send(Ok(IndexingProgress::Finished))?; Ok(()) } } pub fn restore_original_from_indexed_file(indexed_file: &PathBuf, out: &PathBuf) -> Result<()> { let f = fs::File::open(&indexed_file)?; let reader = &mut std::io::BufReader::new(f); let out_file = std::fs::File::create(out)?; trace!("created out_file: {:?}", &out_file); let mut out_writer = BufWriter::new(out_file); let lines_iter = &mut reader.lines(); for line_res in lines_iter { let line = line_res?; out_writer.write_fmt(format_args!("{}\n", restore_line(&line)))?; } Ok(()) }
{ "pile_set_name": "Github" }
// go run mksyscall.go -l32 -openbsd -arm -tags openbsd,arm syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build openbsd,arm package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0) rtable = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { _, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return }
{ "pile_set_name": "Github" }
[Unit] Description=MinIO Documentation=https://docs.min.io Wants=network-online.target After=network-online.target AssertFileIsExecutable=/usr/local/bin/minio [Service] WorkingDirectory=/usr/local User=minio-user Group=minio-user EnvironmentFile=-/etc/default/minio ExecStartPre=/bin/bash -c "if [ -z \"${MINIO_VOLUMES}\" ]; then echo \"Variable MINIO_VOLUMES not set in /etc/default/minio\"; exit 1; fi" ExecStartPre=/bin/bash -c "if [ -z \"${MINIO_ACCESS_KEY}\" ]; then echo \"Variable MINIO_ACCESS_KEY not set in /etc/default/minio\"; exit 1; fi" ExecStartPre=/bin/bash -c "if [ -z \"${MINIO_SECRET_KEY}\" ]; then echo \"Variable MINIO_SECRET_KEY not set in /etc/default/minio\"; exit 1; fi" ExecStart=/usr/local/bin/minio server $MINIO_OPTS $MINIO_VOLUMES # Let systemd restart this service always Restart=always # Specifies the maximum file descriptor number that can be opened by this process LimitNOFILE=65536 # Disable timeout logic and wait until process is stopped TimeoutStopSec=infinity SendSIGKILL=no [Install] WantedBy=multi-user.target # Built for ${project.name}-${project.version} (${project.name})
{ "pile_set_name": "Github" }
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2017 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdio.h> #include "zend.h" #ifdef HAVE_STDARG_H # include <stdarg.h> #endif #if ZEND_BROKEN_SPRINTF int zend_sprintf(char *buffer, const char *format, ...) { va_list args; va_start(args, format); vsprintf(buffer, format, args); va_end(args); return strlen(buffer); } #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
{ "pile_set_name": "Github" }
# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:et:sw=4:ts=4:sts=4 PortSystem 1.0 PortGroup qt4 1.0 PortGroup cmake 1.0 name TOra version 2.1.3 revision 6 license GPL-2 description GUI tool for Oracle, PostgreSQL, and MySQL long_description Database developer/DBA frontend for various DB servers. maintainers nomaintainer categories aqua databases platforms macosx homepage http://torasql.com/ master_sites sourceforge:tora distname tora-${version} checksums md5 ea4a75a9daeaf58492413e3f7fe40293 \ sha1 d33ea3bafb09c5382ef4e0cb0e8ca4ed848a9155 \ rmd160 084d90c94184939e24ac94109ff7940a33bed1d7 depends_lib port:qscintilla-qt4 patchfiles patch-cmake-modules-FindOracle.cmake.diff \ patch-osx_tools-Info.plist.in.diff \ patch-cmake-modules-FindQScintilla.cmake.diff \ patch-src-toextract.h \ patch-src-toextract.cpp \ patch-src-toreport.cpp configure.pre_args -DCMAKE_INSTALL_PREFIX=${prefix}/tmprelease/ # -Dmacports_prefix is there due to the patch for the Info.plist file configure.args-append -DUSE_PCH=0 \ -Dmacports_prefix=${prefix} \ -DWANT_BUNDLE=1 \ -DWANT_BUNDLE_STANDALONE=0 \ -DWANT_RPM=0 \ -DWANT_INTERNAL_QSCINTILLA=0 \ -DENABLE_DB2=0 \ -DENABLE_ORACLE=0 \ ${qt_cmake_defines} . # # Postgresql - it should follow qt4-mac variants for this DB variant psql83 conflicts psql84 psql90 psql91 \ description {Enable Postgre SQL Driver version 8.3} {} variant psql84 conflicts psql83 psql90 psql91 \ description {Enable Postgre SQL Driver version 8.4} {} variant psql90 conflicts psql83 psql84 psql91 \ description {Enable Postgre SQL Driver version 9.0} {} variant psql91 conflicts psql83 psql84 psql90 \ description {Enable Postgre SQL Driver version 9.1} {} set psql_version "" if {[variant_isset psql83]} { set psql_version "83" } elseif {[variant_isset psql84]} { set psql_version "84" } elseif {[variant_isset psql90]} { set psql_version "90" } elseif {[variant_isset psql91]} { set psql_version "91" } if {${psql_version} != ""} { depends_lib-append port:postgresql${psql_version} lunshift header_path ${prefix}/include/postgresql${psql_version} lunshift library_path ${prefix}/lib/postgresql${psql_version} configure.pre_args-append -DENABLE_PGSQL=1 \ -DPOSTGRESQL_PATH_INCLUDES=${prefix}/include/postgresql${psql_version} \ -DPOSTGRESQL_PATH_LIB=${prefix}/lib/postgresql${psql_version} } else { configure.pre_args-append -DENABLE_PGSQL=0 } # # Oracle variant oracle description {Enable support for Oracle} { depends_lib-append port:oracle-instantclient configure.args-delete -DENABLE_ORACLE=0 configure.args-append -DENABLE_ORACLE=1 \ -DORACLE_PATH_INCLUDES=${prefix}/lib/oracle/sdk/include \ -DORACLE_PATH_LIB=${prefix}/lib/oracle \ } default_variants +oracle # # Debug variant debug description {provide a debug build in case of difficulties} { configure.pre_args-append -DWANT_DEBUG=1 } destroot { file copy ${worksrcpath}/src/${name}.app ${destroot}${applications_dir} }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson * * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 _DEFER_INTERNAL_H_ #define _DEFER_INTERNAL_H_ #ifdef __cplusplus extern "C" { #endif #include "event2/event-config.h" #include <sys/queue.h> struct deferred_cb; typedef void (*deferred_cb_fn)(struct deferred_cb *, void *); /** A deferred_cb is a callback that can be scheduled to run as part of * an event_base's event_loop, rather than running immediately. */ struct deferred_cb { /** Links to the adjacent active (pending) deferred_cb objects. */ TAILQ_ENTRY (deferred_cb) cb_next; /** True iff this deferred_cb is pending in an event_base. */ unsigned queued : 1; /** The function to execute when the callback runs. */ deferred_cb_fn cb; /** The function's second argument. */ void *arg; }; /** A deferred_cb_queue is a list of deferred_cb that we can add to and run. */ struct deferred_cb_queue { /** Lock used to protect the queue. */ void *lock; /** How many entries are in the queue? */ int active_count; /** Function called when adding to the queue from another thread. */ void (*notify_fn)(struct deferred_cb_queue *, void *); void *notify_arg; /** Deferred callback management: a list of deferred callbacks to * run active the active events. */ TAILQ_HEAD (deferred_cb_list, deferred_cb) deferred_cb_list; }; /** Initialize an empty, non-pending deferred_cb. @param deferred The deferred_cb structure to initialize. @param cb The function to run when the deferred_cb executes. @param arg The function's second argument. */ void event_deferred_cb_init(struct deferred_cb *, deferred_cb_fn, void *); /** Cancel a deferred_cb if it is currently scheduled in an event_base. */ void event_deferred_cb_cancel(struct deferred_cb_queue *, struct deferred_cb *); /** Activate a deferred_cb if it is not currently scheduled in an event_base. */ void event_deferred_cb_schedule(struct deferred_cb_queue *, struct deferred_cb *); #define LOCK_DEFERRED_QUEUE(q) \ EVLOCK_LOCK((q)->lock, 0) #define UNLOCK_DEFERRED_QUEUE(q) \ EVLOCK_UNLOCK((q)->lock, 0) #ifdef __cplusplus } #endif void event_deferred_cb_queue_init(struct deferred_cb_queue *); struct deferred_cb_queue *event_base_get_deferred_cb_queue(struct event_base *); #endif /* _EVENT_INTERNAL_H_ */
{ "pile_set_name": "Github" }
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { getProxyServingType, getSourceUrl, parseQueryString, parseUrlDeprecated, } from '../url'; import {getRandomString64} from './cid-impl'; import {isArray} from '../types'; import {map} from '../utils/object'; import {registerServiceBuilderForDoc} from '../service'; /** @private @const {!Array<string>} */ const filteredLinkRels = ['prefetch', 'preload', 'preconnect', 'dns-prefetch']; /** * Properties: * - sourceUrl: the source url of an amp document. * - canonicalUrl: The doc's canonical. * - pageViewId: Id for this page view. Low entropy but should be unique * - pageViewId64: Id for this page view. High entropy but should be unique * for concurrent page views of a user(). * - linkRels: A map object of link tag's rel (key) and corresponding * hrefs (value). rel could be 'canonical', 'icon', etc. * - viewport: The global doc's viewport. * - replaceParams: A map object of extra query string parameter names (key) * to corresponding values, used for custom analytics. * Null if not applicable. * * @typedef {{ * sourceUrl: string, * canonicalUrl: string, * pageViewId: string, * pageViewId64: !Promise<string>, * linkRels: !Object<string, string|!Array<string>>, * viewport: ?string, * replaceParams: ?Object<string, string|!Array<string>> * }} */ export let DocumentInfoDef; /** * @param {!Node|!./ampdoc-impl.AmpDoc} nodeOrDoc * @return {*} TODO(#23582): Specify return type */ export function installDocumentInfoServiceForDoc(nodeOrDoc) { return registerServiceBuilderForDoc(nodeOrDoc, 'documentInfo', DocInfo); } export class DocInfo { /** * @param {!./ampdoc-impl.AmpDoc} ampdoc */ constructor(ampdoc) { /** @private @const */ this.ampdoc_ = ampdoc; /** @private {?DocumentInfoDef} */ this.info_ = null; /** @private {?Promise<string>} */ this.pageViewId64_ = null; } /** @return {!DocumentInfoDef} */ get() { if (this.info_) { return this.info_; } const ampdoc = this.ampdoc_; const url = ampdoc.getUrl(); const sourceUrl = getSourceUrl(url); const rootNode = ampdoc.getRootNode(); let canonicalUrl = rootNode && rootNode.AMP && rootNode.AMP.canonicalUrl; if (!canonicalUrl) { const canonicalTag = rootNode.querySelector('link[rel=canonical]'); canonicalUrl = canonicalTag ? parseUrlDeprecated(canonicalTag.href).href : sourceUrl; } const pageViewId = getPageViewId(ampdoc.win); const linkRels = getLinkRels(ampdoc.win.document); const viewport = getViewport(ampdoc.win.document); const replaceParams = getReplaceParams(ampdoc); return (this.info_ = { /** @return {string} */ get sourceUrl() { return getSourceUrl(ampdoc.getUrl()); }, canonicalUrl, pageViewId, get pageViewId64() { // Must be calculated async since getRandomString64() can load the // amp-crypto-polyfill on some browsers, and extensions service // may not be registered yet. if (!this.pageViewId64_) { this.pageViewId64_ = getRandomString64(ampdoc.win); } return this.pageViewId64_; }, linkRels, viewport, replaceParams, }); } } /** * Returns a relatively low entropy random string. * This should be called once per window and then cached for subsequent * access to the same value to be persistent per page. * @param {!Window} win * @return {string} */ function getPageViewId(win) { return String(Math.floor(win.Math.random() * 10000)); } /** * Returns a map object of link tag relations in document head. * Key is the link rel, value is a list of corresponding hrefs. * @param {!Document} doc * @return {!JsonObject<string, string|!Array<string>>} */ function getLinkRels(doc) { const linkRels = map(); if (doc.head) { const links = doc.head.querySelectorAll('link[rel]'); for (let i = 0; i < links.length; i++) { const link = links[i]; const {href} = link; const rels = link.getAttribute('rel'); if (!rels || !href) { continue; } rels.split(/\s+/).forEach((rel) => { if (filteredLinkRels.indexOf(rel) != -1) { return; } let value = linkRels[rel]; if (value) { // Change to array if more than one href for the same rel if (!isArray(value)) { value = linkRels[rel] = [value]; } value.push(href); } else { linkRels[rel] = href; } }); } } return linkRels; } /** * Returns the viewport of the document. Note that this is the viewport of the * host document for AmpDocShadow instances. * @param {!Document} doc * @return {?string} */ function getViewport(doc) { const viewportEl = doc.head.querySelector('meta[name="viewport"]'); return viewportEl ? viewportEl.getAttribute('content') : null; } /** * Attempts to retrieve extra parameters from the "amp_r" query param, * returning null if invalid. * @param {!./ampdoc-impl.AmpDoc} ampdoc * @return {?JsonObject<string, string|!Array<string>>} */ function getReplaceParams(ampdoc) { // The "amp_r" parameter is only supported for ads. if ( !ampdoc.isSingleDoc() || getProxyServingType(ampdoc.win.location.href) != 'a' ) { return null; } const url = parseUrlDeprecated(ampdoc.win.location.href); const replaceRaw = parseQueryString(url.search)['amp_r']; if (replaceRaw === undefined) { // Differentiate the case between empty replace params and invalid result return null; } return parseQueryString(replaceRaw); }
{ "pile_set_name": "Github" }
/** \page org_mitk_views_volumevisualization The Volume Visualization Plugin \imageMacro{volume_visualization.svg,"Icon of the Volume Visualization Plugin",2.00} \tableofcontents \section QVV_Overview Overview The <b> Volume Visualization Plugin </b> is a basic tool for volume rendering of three dimensional medical images. MITK provides generic transfer function presets for medical CT and MRT data. These functions that map the gray-value to color and opacity can be interactively edited. Additionally, there are controls to quickly generate commonly used transfer function shapes like the threshold and bell curve to help identify a range of grey-values. \imageMacro{QmitkVolumeVisualization_Overview.png,"",16.00} \section QVV_EnableVRPage Volume Rendering \subsection QVV_LoadingImage Select an image and enable volume rendering \imageMacro{QmitkVolumeVisualization_Checkboxen.png,"",8.21} Select an image on top of the view and click on the checkbox left of 'Volumerendering'. Please be patient, while the image is prepared for rendering, which can take up to a half minute. \note Volume Visualization imposes following restrictions on images: <ul> <li> It has to be a 3D scalar image, that means e.g. a CT or MRT image. <li> 3D+t images are supported for rendering, but the histograms are not computed. <li> Also be aware that volume visualization requires a huge amount of memory. Very large images may not work unless you use the 64bit version. </ul> \subsection QVV_LODGPU Dropdown menus for the rendering and blend modes Two dropdown menus are located right next to the 'Volumerendering' checkbox. They allow you to select a rendering mode (Default, RayCast, GPU) and the blend mode (Composite, Max, Min, Avg, Add). Any rendering mode requires a lot of computing resources including processor, memory and often also graphics card. The 'Default' selection usually finds the best 'rendering' mode for the available hardware. Alternatively, it is possible to manually specify the selections 'RayCast' and 'GPU'. The 'RayCast' selection is based on CPU computation and therefore typically slow, but allows to render without hardware acceleration. The 'GPU' selection uses computing resources on the graphics card to accelerate volume rendering. It requires a powerful graphics card and OpenGL hardware support for shaders but achieves much higher frame rates than software-rendering. Blend modes define how the volume voxels, intersected by the rendering rays, are pooled. The 'Composite' mode specifies standard volume rendering, for which each voxel contributes equally with opacity and color. Other 'blend' modes simply visualize the voxel of the maximum / minimum intensity and average / add the intensities along the rendering ray. \section QVV_PresetPage Applying premade presets \subsection QVV_Preset Internal presets There are some internal presets given that can be used with normal CT data (given in Houndsfield units). A large set of medical data has been tested with those presets, but they may not suit some special cases. Click on the 'Preset' tab for using internal or custom presets. \imageMacro{QmitkVolumeVisualization_InternalPresets.png,"",8.30} <ul> <li> 'CT Generic' is the default transfer function that is first applied. <li> 'CT Black&White' does not use any colors for the volume visualization as it may be distracting on some data. <li> 'CT Cardiac' is well-suited for CT images containing the heart. <li> 'CT Bone' emphasizes bones and shows other areas more transparent. <li> 'CT Bone (Gradient)' is like 'CT Bone' but shows only the surface from other organs by using the gradient. <li> 'MR Generic' is the default transfer function that can be used on MRT data (which is not normalized like CT data). <li> 'CT Thorax small' is useful if only a proportion of the thorax is selected to emphasize details. <li> 'CT Thorax large' is useful if a large proportion or the entire thorax is selected to emphasize details. </ul> \subsection QVV_CustomPreset Saving and loading custom presets After creating or editing a transfer function (see \ref QVV_Editing or \ref QVV_ThresholdBell), the custom transfer function can be stored and later retrieved on the filesystem. Click 'Save' (respectively 'Load') button below the preset selection to save (load) the threshold-, color- and gradient function combined in a single .xml file. \section QVV_ThresholdBell Interactively create transfer functions Besides the possibility to directly edit the transfer functions (\ref QVV_Editing), the plugin provides two commonly known shapes to quickly generate transfer functions with a few clicks. Both generators have two parameters that can be modified by first clicking on the cross and then moving the mouse up/down and left/right. The first parameter 'center' (controlled by horizontal movement of the mouse) specifies the gray value where the center of the shape will be located. The second parameter 'width' (controlled by vertical movement of the mouse) specifies the width (or steepness) of the shape. \subsection Threshold Click on the 'Threshold' tab to activate the threshold function generator. \imageMacro{QmitkVolumeVisualization_Threshold.png,"",8.21} A threshold shape begins with zero and raises to one across the 'center' parameter. Lower widths result in steeper threshold functions. \subsection Bell Click on the 'Bell' tab to activate the bell-shaped threshold function generator. \imageMacro{QmitkVolumeVisualization_Bell.png,"",8.23} A threshold shape begins with zero and raises to one at the 'center' parameter and then lowers again to zero. The 'width' parameter corresponds to the width of the bell. \section QVV_Editing Customize transfer functions in detail \subsection QVV_Navigate Choosing gray value interval to edit \imageMacro{QmitkVolumeVisualization_Slider.png,"",8.23} To navigate across the gray value range or to zoom in some ranges use the 'range'-slider. All three function editors have in common following: <ul> <li> By left-clicking a new point is added. <li> By right-clicking a point is deleted. <li> By left-clicking and holding, an exisiting point can be dragged. <li> By pressing arrow keys, the currently selected point is moved. <li> By pressing the 'DELETE' key, the currently selected point is deleted. <li> Between points the transferfunctions are linear interpolated. </ul> There are three transfer functions to customize: \subsection QVV_GO Grayvalue -> Opacity \imageMacro{QmitkVolumeVisualization_Opacity.png,"Gray values will be mapped to opacity.",8.04} An opacity of 0 means total transparent, an opacity of 1 means total opaque. The opacity editor allows changing the opacity for all gray values independently. You can alter the position of control points using your mouse. You can add control points by left-clicking on the graph. To remove a control point again you can right-click on the respective point. \subsection QVV_GC Grayvalue -> Color \imageMacro{QmitkVolumeVisualization_Color.png,"Gray values will be mapped to color.",8.81} The color transfer function editor also allows you to change its color by double-clicking a point. You can add color control points by left-clicking on the color bar. To remove a control point again right-click on the respective point. \subsection QVV_GGO Grayvalue and Gradient -> Opacity \imageMacro{QmitkVolumeVisualization_Gradient.png,"",8.85} The gradient editor allows you to change the gradient influence for all gray values independently. You can move the existing control points using your mouse. Additionally, you can add control points by left-clicking on the graph. To remove a control point again, right-click on the respective point. */
{ "pile_set_name": "Github" }
<?php /** * @package jelix * @subpackage db * @author Laurent Jouanneau * @copyright 2010-2018 Laurent Jouanneau * * @link http://www.jelix.org * @licence http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file */ /** * */ abstract class jDbTable { /** * @var string the name of the table */ protected $name; /** * @var jDbSchema the schema which holds the table */ protected $schema; /** * @var jDbColumn[]. null means "columns are not loaded" */ protected $columns = null; /** * @var jDbPrimaryKey the primary key. null means "primary key is not loaded". false means : no primary key */ protected $primaryKey = null; /** * @var jDbUniqueKey[] list unique keys. null means "unique key are not loaded" */ protected $uniqueKeys = null; /** * @var jDbIndex[] list of indexes. null means "indexes are not loaded" */ protected $indexes = null; /** * @var jDbReference[] list of references. null means "references are not loaded" */ protected $references = null; /** * @param string $name the table name * @param jDbSchema $schema */ function __construct($name, $schema) { $this->name = $name; $this->schema = $schema; } public function getName() { return $this->name; } /** * * @return jDbColumn[] */ public function getColumns() { if ($this->columns === null) { $this->_loadTableDefinition(); } return $this->columns; } /** * @param string $name * @param bool $forChange * @return jDbColumn|null */ public function getColumn($name, $forChange = false) { if ($this->columns === null) { $this->_loadTableDefinition(); } if (isset($this->columns[$name])) { if ($forChange) { return clone $this->columns[$name]; } return $this->columns[$name]; } return null; } public function addColumn(jDbColumn $column) { if ($this->columns === null) { $this->_loadTableDefinition(); } if (isset($this->columns[$column->name])) { if ($this->columns[$column->name]->isEqualTo($column)) { return; } $this->_alterColumn($this->columns[$column->name], $column); $this->columns[$column->name] = $column; return; } $this->_addColumn($column); $this->columns[$column->name] = $column; } public function alterColumn(jDbColumn $column, $oldName = '') { $oldColumn = $this->getColumn(($oldName?:$column->name)); if (!$oldColumn) { $this->addColumn($column); return; } if (!$column->nativeType) { $type = $this->schema->getConn()->tools()->getTypeInfo($column->type); $column->nativeType = $type[0]; } if ($oldColumn->isEqualTo($column)) { return; } // FIXME : if rename, modify indexes and table constraints that have this column $this->_alterColumn($oldColumn, $column); if ($oldName) { unset($this->columns[$oldName]); } $this->columns[$column->name] = $column; } public function dropColumn($name) { if ($this->columns === null) { $this->_loadTableDefinition(); } if (!isset($this->columns[$name])) { return; } $this->_dropColumn($this->columns[$name]); // FIXME : remove/modify indexes and table constraints that have this column unset($this->columns[$name]); } /** * @return jDbPrimaryKey|false false if there is no primary key */ public function getPrimaryKey() { if ($this->primaryKey === null) $this->_loadTableDefinition(); return $this->primaryKey; } public function setPrimaryKey(jDbPrimaryKey $key) { $pk = $this->getPrimaryKey(); if ($pk == $key) { return; } if ($pk !== false) { $this->_replaceConstraint($pk, $key); } else { $this->_createConstraint($key); } $this->primaryKey = $key; } public function dropPrimaryKey() { $pk = $this->getPrimaryKey(); if ($pk !== false) { $this->_dropConstraint($pk); $this->primaryKey = false; } } /** * @return jDbIndex[] */ public function getIndexes() { if ($this->indexes === null) $this->_loadTableDefinition(); return $this->indexes; } /** * @return jDbIndex|null */ public function getIndex($name) { if ($this->indexes === null) $this->_loadTableDefinition(); if (isset($this->indexes[$name])) return $this->indexes[$name]; return null; } public function addIndex(jDbIndex $index) { $this->alterIndex($index); } public function alterIndex(jDbIndex $index) { if (trim($index->name) == '') { throw new Exception("Index should have name"); } $idx = $this->getIndex($index->name); if ($idx) { $this->_dropIndex($idx); } $this->_createIndex($index); $this->indexes[$index->name] = $index; } public function dropIndex($indexName) { $idx = $this->getIndex($indexName); if ($idx) { $this->_dropIndex($idx); unset($this->indexes[$indexName]); } } /** * @return jDbUniqueKey[] */ public function getUniqueKeys() { if ($this->uniqueKeys === null) $this->_loadTableDefinition(); return $this->uniqueKeys; } /** * @return jDbUniqueKey|null */ public function getUniqueKey($name) { if ($this->uniqueKeys === null) { $this->_loadTableDefinition(); } if (isset($this->uniqueKeys[$name])) { return $this->uniqueKeys[$name]; } return null; } public function addUniqueKey(jDbUniqueKey $key) { if (trim($key->name) == '') { $key->name = $this->name.'_'.implode('_', $key->columns).'_unique'; } $this->alterUniqueKey($key); } public function alterUniqueKey(jDbUniqueKey $key) { $idx = $this->getUniqueKey($key->name); if ($idx) { $this->_replaceConstraint($idx, $key); unset($this->uniqueKeys[$idx->name]); } else { $this->_createConstraint($key); } $this->uniqueKeys[$key->name] = $key; } public function dropUniqueKey($indexName) { $idx = $this->getUniqueKey($indexName); if ($idx) { $this->_dropConstraint($idx); unset($this->uniqueKeys[$idx->name]); } } /** * @return jDbReference[] */ public function getReferences() { if ($this->references === null) $this->_loadTableDefinition(); return $this->references; } /** * @return jDbReference|null */ public function getReference($refName) { if ($this->references === null) $this->_loadTableDefinition(); if (isset($this->references[$refName])) return $this->references[$refName]; return null; } public function addReference(jDbReference $reference) { if (trim($reference->name) == '') { $reference->name = $this->name.'_'.implode('_', $reference->columns).'_fkey'; } $this->alterReference($reference); } public function alterReference(jDbReference $reference) { $ref = $this->getReference($reference->name); if ($ref) { $this->_replaceConstraint($ref, $reference); unset($this->references[$ref->name]); } else { $this->_createConstraint($reference); } $this->references[$reference->name] = $reference; } public function dropReference($refName) { $ref = $this->getReference($refName); if ($ref) { $this->_dropConstraint($ref); unset($this->references[$ref->name]); } } protected function _loadTableDefinition() { $this->_loadColumns(); $this->_loadIndexesAndKeys(); $this->_loadReferences(); } abstract protected function _loadColumns(); abstract protected function _alterColumn(jDbColumn $old, jDbColumn $new); abstract protected function _addColumn(jDbColumn $new); protected function _dropColumn(jDbColumn $col) { $conn = $this->schema->getConn(); $sql = 'ALTER TABLE '.$conn->encloseName($this->name). ' DROP COLUMN '.$conn->encloseName($col->name); $conn->exec($sql); } abstract protected function _loadIndexesAndKeys(); abstract protected function _loadReferences(); abstract protected function _createIndex(jDbIndex $index); abstract protected function _dropIndex(jDbIndex $index); abstract protected function _createConstraint(jDbConstraint $constraint); abstract protected function _dropConstraint(jDbConstraint $constraint); protected function _replaceConstraint(jDbConstraint $oldConstraint, jDbConstraint $newConstraint) { $this->_dropConstraint($oldConstraint); $this->_createConstraint($newConstraint); } }
{ "pile_set_name": "Github" }
package com.googlecode.objectify.impl.translate; import com.googlecode.objectify.annotation.Translate; import com.googlecode.objectify.impl.Path; /** * <p>Translator factory which lets users define a custom translator for a field.</p> * * @author Jeff Schnitzer <[email protected]> */ public class TranslateTranslatorFactory implements TranslatorFactory<Object, Object> { boolean earlyOnly; /** * @param earlyOnly determines whether this instance ignores @Translate annotations with early=false */ public TranslateTranslatorFactory(boolean earlyOnly) { this.earlyOnly = earlyOnly; } @Override public Translator<Object, Object> create(TypeKey<Object> tk, CreateContext ctx, Path path) { final Translate translateAnno = tk.getAnnotation(Translate.class); if (translateAnno == null) return null; if (earlyOnly && !translateAnno.early()) return null; @SuppressWarnings("unchecked") TranslatorFactory<Object, Object> transFact = (TranslatorFactory<Object, Object>)ctx.getFactory().construct(translateAnno.value()); Translator<Object, Object> trans = transFact.create(tk, ctx, path); if (trans == null) { path.throwIllegalState("TranslatorFactory " + transFact + " was unable to produce a Translator for " + tk.getType()); return null; // never gets here } else { return trans; } } }
{ "pile_set_name": "Github" }
<?php /** * The MenuItemsController * * @copyright Copyright (c) 2010 Carl Sutton ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Menus.Controller * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author Carl Sutton <[email protected]> */ /** * The MenuItemsController * * @package Infinitas.Menus.Controller */ class MenuItemsController extends MenusAppController { /** * List all menu items * * @return void */ public function admin_index() { $this->Paginator->settings = array( 'contain' => array( 'Menu', 'Group' ) ); $menuItems = $this->Paginator->paginate( null, array_merge(array($this->modelClass . '.parent_id !=' => 0), $this->Filter->filter) ); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'menu_id' => array(null => __d('menus', 'All')) + $this->{$this->modelClass}->Menu->find('list'), 'group_id' => array(null => __d('menus', 'Public')) + $this->{$this->modelClass}->Group->find('list'), 'active' => (array)Configure::read('CORE.active_options') ); $this->set(compact('menuItems', 'filterOptions')); } /** * Add menu items * * @return void */ public function admin_add() { parent::admin_add(); if (isset($this->request->params['named']['parent_id'])) { $this->request->data[$this->modelClass]['parent_id'] = $this->request->params['named']['parent_id']; } $menus = $this->{$this->modelClass}->Menu->find('list'); if (empty($menus)) { $this->notice(__d('menus', 'Please add a menu before adding items'), array( 'level' => 'notice', 'redirect' => array( 'controller' => 'menus' ) )); } $groups = array(0 => __d('menus', 'Public')) + $this->{$this->modelClass}->Group->find('list'); if (!empty($this->request->data[$this->modelClass]['parent_id'])) { $parents = array(0 => __d('menus', 'Root')) + $this->{$this->modelClass}->generateTreeList(array( $this->modelClass . '.parent_id !=' => 0, $this->modelClass . '.menu_id' => reset(array_keys($menus)) )); } $plugins = $this->{$this->modelClass}->getPlugins(); $this->set(compact('menus', 'groups', 'parents', 'plugins')); } /** * Edit menu items * * @param string $id the id of the menu item * * @return void */ public function admin_edit($id = null) { parent::admin_edit($id); $menus = $this->{$this->modelClass}->Menu->find('list'); $groups = array(0 => __d('menus', 'Public')) + $this->{$this->modelClass}->Group->find('list'); $parents = $this->{$this->modelClass}->getParents($this->request->data[$this->modelClass]['menu_id']); $plugins = $this->{$this->modelClass}->getPlugins(); $controllers = $this->{$this->modelClass}->getControllers($this->request->data[$this->modelClass]['plugin']); $actions = $this->{$this->modelClass}->getActions($this->request->data[$this->modelClass]['plugin'], $this->request->data[$this->modelClass]['controller']); $this->set(compact('menus', 'groups', 'parents', 'plugins', 'controllers', 'actions')); } /** * Get parent menus * * Used for the ajax getting of parent menus items to populate the ajax * dropdown menus when building and editing menu items. * * @return void */ public function admin_getParents() { if (empty($this->request->data[$this->modelClass]['menu_id'])) { return false; } $this->set('json', $this->{$this->modelClass}->getParents($this->request->data[$this->modelClass]['menu_id'])); } }
{ "pile_set_name": "Github" }
public class Solution2 { // 状态压缩 public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length; if (m == 0) { return 0; } int n = obstacleGrid[0].length; // 默认都是 0 int[] dp = new int[n]; // 这一句很关键,题目当中说了,网格中间有障碍物,所以初值可以这样设置 // 审题很关键 dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (obstacleGrid[i][j] == 1) { dp[j] = 0; } else if (j > 0) { dp[j] += dp[j - 1]; } } } // System.out.println(Arrays.toString(dp)); return dp[n - 1]; } public static void main(String[] args) { int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; Solution2 solution2 = new Solution2(); int res = solution2.uniquePathsWithObstacles(obstacleGrid); System.out.println(res); } }
{ "pile_set_name": "Github" }
using GameObjects; using GameObjects.Influences; using System; using System.Runtime.Serialization;namespace GameObjects.Influences.InfluenceKindPack { [DataContract]public class InfluenceKind2240 : InfluenceKind { private float rate = 0f; private int type = 0; public override void ApplyInfluenceKind(Faction faction) { switch (this.type) { case 0: faction.OffenceRateOfBubing += this.rate; break; case 1: faction.OffenceRateOfNubing += this.rate; break; case 2: faction.OffenceRateOfQibing += this.rate; break; case 3: faction.OffenceRateOfShuijun += this.rate; break; case 4: faction.OffenceRateOfQixie += this.rate; break; } } public override void InitializeParameter(string parameter) { try { this.type = int.Parse(parameter); } catch { } } public override void InitializeParameter2(string parameter) { try { this.rate = float.Parse(parameter); } catch { } } public override void PurifyInfluenceKind(Faction faction) { switch (this.type) { case 0: faction.OffenceRateOfBubing -= this.rate; break; case 1: faction.OffenceRateOfNubing -= this.rate; break; case 2: faction.OffenceRateOfQibing -= this.rate; break; case 3: faction.OffenceRateOfShuijun -= this.rate; break; case 4: faction.OffenceRateOfQixie -= this.rate; break; } } } }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- """Tests for the Data Retriever""" import os import random import subprocess import pytest import requests import retriever as rt from retriever.lib.cleanup import correct_invalid_value from retriever.lib.engine import Engine from retriever.lib.engine_tools import getmd5 from retriever.lib.engine_tools import json2csv from retriever.lib.engine_tools import xml2csv_test from retriever.lib.table import TabularDataset from retriever.lib.templates import BasicTextTemplate try: from retriever.lib.engine_tools import geojson2csv except ModuleNotFoundError: pass from retriever.lib.engine_tools import sqlite2csv from retriever.lib.engine_tools import sort_file from retriever.lib.engine_tools import sort_csv from retriever.lib.engine_tools import create_file from retriever.lib.engine_tools import file_2list from retriever.lib.datapackage import clean_input, is_empty from retriever.lib.defaults import HOME_DIR, RETRIEVER_DATASETS, RETRIEVER_REPOSITORY, KAGGLE_TOKEN_PATH # Create simple engine fixture test_engine = Engine() test_engine.table = TabularDataset(**{"name": "test"}) test_engine.script = BasicTextTemplate( **{"tables": test_engine.table, "name": "test"}) test_engine.opts = {'database_name': '{db}_abc'} geojson2csv_dataset = [ ("simple_geojson2csv", "lake_county.geojson", "http://data-lakecountyil.opendata.arcgis.com/datasets/cd63911cc52841f38b289aeeeff0f300_1.geojson", 'fid,zip,colorectal,lung_bronc,breast_can,prostate_c,urinary_sy,all_cancer,shape_length,shape_area,geometry') ] sqlite2csv_dataset = [ ("simple_sqlite2csv", "portal_project.sqlite", "https://ndownloader.figshare.com/files/11188550", "plots", ['plot_id,plot_type']) ] json2csv_datasets = [ # test_name, json_data, header_values, row_key, expected ("simple_json", ["""{"User": "Alex", "Country": "US", "Age": "25"}"""], ['User','Country','Age'], None, ['user,country,age', 'Alex,US,25']), ("nested_json", ["""{"prizes":[{"year":"2019","category":"chemistry","laureates":[{"id":"976","firstname":"John","surname":"Goodenough","motivation":"text shorted","share":"3"}]}]}"""], ["id", "firstname", "surname", "motivation", "share"], 'prizes', ['id,firstname,surname,motivation,share', '976,John,Goodenough,text shorted,3']), ("null_data_json", ["""[{"User":"Alex","id":"US1","Age":"25","kt":"2.0","qt":"1.00"},{"User":"Tom","id":"US2","Age":"20","kt":"0.0","qt":"1.0"},{"User":"Dan","id":"44","Age":"2","kt":"0","qt":"1"},{"User":"Kim","id":"654","Age":"","kt":"","qt":""}]"""], ["User", "id", "Age", "kt", "qt"], None, ['User,id,Age,kt,qt', 'Alex,US1,25,2.0,1.00', 'Tom,US2,20,0.0,1.0', 'Dan,44,2,0,1', 'Kim,654,,,']) ] xml2csv_dataset = [ ("simple_xml", ["""<root><row><User>Alex</User><Country>US</Country><Age>25</Age></row><row><User>Ben</User><Country>US</Country><Age>24</Age></row></root>"""], ["User", "Country", "Age"], 1, ['User,Country,Age', 'Alex,US,25', 'Ben,US,24']) ] # Main paths HOMEDIR = os.path.expanduser('~') file_location = os.path.dirname(os.path.realpath(__file__)) retriever_root_dir = os.path.abspath(os.path.join(file_location, os.pardir)) # Setup paths for the raw data files used raw_dir_files = os.path.normpath(os.path.join(retriever_root_dir, 'raw_data/{file_name}')) # file: sample_zip.csv achive_zip = raw_dir_files.format(file_name='sample_zip.zip') # file: test/sample_tar.csv achive_tar = raw_dir_files.format(file_name='sample_tar.tar') achive_tar_gz = raw_dir_files.format(file_name='sample_tar.tar.gz') achive_gz = raw_dir_files.format(file_name='sample.gz') # Setup urls for downloading raw data from the test/raw_data directory achive_url = """file://{loc}/raw_data/""" \ .format(loc=file_location) + '{file_path}' zip_url = os.path.normpath(achive_url.format(file_path='sample_zip.zip')) tar_url = os.path.normpath(achive_url.format(file_path='sample_tar.tar')) tar_gz_url = os.path.normpath(achive_url.format(file_path='sample_tar.tar.gz')) gz_url = os.path.normpath(achive_url.format(file_path='sample.gz')) kaggle_datasets = [ # test_name, data_source, dataset_identifier, dataset_name, repath, expected ("kaggle_competition", "competition", "titanic", "titanic", ["gender_submission.csv", "test.csv", "train.csv"]), ("kaggle_unknown", "dataset", "uciml/iris", "iris", ['Iris.csv', 'database.sqlite']), ("kaggle_dataset", "competition", "non_existent_dataset", "non_existent_dataset", []), ] def setup_module(): """"Automatically sets up the environment before the module runs. Make sure you are in the main local retriever directory. """ os.chdir(retriever_root_dir) subprocess.call(['cp', '-r', 'test/raw_data', retriever_root_dir]) def teardown_module(): """Automatically clean up after the module. Make sure you are in the main local retriever directory after these tests. """ os.chdir(retriever_root_dir) subprocess.call(['rm', '-r', 'raw_data']) subprocess.call(['rm', '-r', test_engine.format_data_dir()]) def setup_functions(): """Set up function. Tests can use the function to clean up before running. Not automatically run. """ teardown_module() setup_module() def test_auto_get_columns(): """Basic test of getting column labels from header.""" test_engine.table.delimiter = "," columns, _ = test_engine.table.auto_get_columns( ['a', 'b', 'c', 'd']) assert columns == [['a', None], ['b', None], ['c', None], ['d', None]] def test_auto_get_datatypes(): """Test the length detected by auto_get_datatype. The function adds 100 to the auto detected length of column """ test_engine.auto_get_datatypes(None, [["ö", 'bb', 'Löve']], [['a', None], ['b', None], ['c', None]]) length = test_engine.table.columns # encoded char "?" will return 2 in length assert [length[0][1][1], length[1][1][1], length[2][1][1]] == \ [2, 2, 5] def test_auto_get_columns_extra_whitespace(): """Test getting column labels from header with extra whitespace.""" test_engine.table.delimiter = "," columns, _ = test_engine.table.auto_get_columns( ['a', 'b', 'c', 'd ']) assert columns == [['a', None], ['b', None], ['c', None], ['d', None]] def test_auto_get_columns_cleanup(): """Test of automatically cleaning up column labels from header.""" test_engine.table.delimiter = "," columns, _ = test_engine.table.auto_get_columns([ 'a)', 'a\nd', 'b.b', 'c/c', 'd___d', 'group']) assert columns == [['a', None], ['ad', None], ['b_b', None], ['c_c', None], ['d_d', None], ['grp', None]] def test_auto_get_delimiter_comma(): """Test if commas are properly detected as delimiter.""" test_engine.auto_get_delimiter("a,b,c;,d") assert test_engine.table.delimiter == "," def test_auto_get_delimiter_tab(): """Test if commas are properly detected as delimiter.""" test_engine.auto_get_delimiter("a\tb\tc\td,") assert test_engine.table.delimiter == "\t" def test_auto_get_delimiter_semicolon(): """Test if semicolons are properly detected as delimiter.""" test_engine.auto_get_delimiter("a;b;c;,d") assert test_engine.table.delimiter == ";" def test_correct_invalid_value_string(): assert \ correct_invalid_value('NA', {'missingValues': ['NA', '-999']}) is None def test_correct_invalid_value_number(): assert \ correct_invalid_value(-999, {'missingValues': ['NA', '-999']}) is None def test_correct_invalid_value_exception(): assert correct_invalid_value(-999, {}) == -999 def test_create_db_statement(): """Test creating the create database SQL statement.""" assert test_engine.create_db_statement() == 'CREATE DATABASE test_abc' def test_database_name(): """Test creating database name.""" assert test_engine.database_name() == 'test_abc' def test_datasets(): """Check if datasets lookup includes a known value""" datasets = rt.datasets(keywords=['mammals']) dataset_names = [dataset.name for dataset in datasets['offline']] dataset_names.extend(datasets['online']) assert 'mammal-masses' in dataset_names def test_datasets_keywords(): """Check if datasets lookup on keyword includes a known value""" datasets = rt.datasets(keywords=['mammals']) dataset_names = [dataset.name for dataset in datasets['offline']] dataset_names.extend(datasets['online']) assert 'mammal-masses' in dataset_names def test_datasets_licenses(): """Check if datasets lookup on license includes a known value""" datasets = rt.datasets(licenses=['CC0-1.0']) dataset_names = [dataset.name for dataset in datasets['offline']] dataset_names.extend(datasets['online']) assert 'amniote-life-hist' in dataset_names def test_dataset_names(): """Check if dataset names lookup includes a known value""" datasets = rt.dataset_names() dataset_names = datasets['offline'] dataset_names.extend(datasets['online']) assert 'mammal-masses' in dataset_names def test_dataset_names_upstream(): """Check if upstream datasets include a known value""" datasets = rt.get_dataset_names_upstream() assert 'portal' in datasets license_datasets = rt.get_dataset_names_upstream(licenses=['CC0-1.0']) assert 'bird-size' in license_datasets keyword_datasets = rt.get_dataset_names_upstream(keywords=['plants']) assert 'biodiversity-response' in keyword_datasets def test_drop_statement(): """Test the creation of drop statements.""" assert test_engine.drop_statement( 'TABLE', 'tablename') == "DROP TABLE IF EXISTS tablename" @pytest.mark.parametrize("test_name, data_source, dataset_identifier, repath, expected", kaggle_datasets) def test_download_kaggle_dataset(test_name, data_source, dataset_identifier, repath, expected): """Test the downloading of dataset from kaggle.""" setup_functions() files = test_engine.download_from_kaggle( data_source=data_source, dataset_name=dataset_identifier, archive_dir=raw_dir_files, archive_full_path=os.path.join(raw_dir_files, repath) ) kaggle_token = os.path.isfile(KAGGLE_TOKEN_PATH) kaggle_username = os.getenv('KAGGLE_USERNAME', "").strip() kaggle_key = os.getenv('KAGGLE_KEY', "").strip() if kaggle_token or (kaggle_username and kaggle_key): assert files == expected else: assert files == None def test_download_archive_gz_known(): """Download and extract known files from a gzipped file to the .retriever/data dir""" setup_functions() files = test_engine.download_files_from_archive( url=gz_url, file_names=['test/sample_tar.csv'], archive_type='gz') r_path = os.path.normpath( os.path.join(HOMEDIR, '.retriever/raw_data/test/test/sample_tar.csv')) assert r_path == test_engine.find_file('test/sample_tar.csv') assert ['sample_tar.csv'] <= files def test_download_archive_gz_unknown(): """Download and extract unknown files from a gzipped file to the .retriever/data dir""" setup_functions() files = test_engine.download_files_from_archive(url=gz_url, archive_type='gz') r_path = os.path.normpath( os.path.join(HOMEDIR, '.retriever/raw_data/test/test/sample_tar.csv')) assert r_path == test_engine.find_file('test/sample_tar.csv') assert ['sample_tar.csv'] <= files def test_download_archive_targz_known(): """Download and extract known files from a targzipped file to the .retriever/data dir""" setup_functions() files = test_engine.download_files_from_archive(url=tar_gz_url, file_names=['test/sample_tar.csv'], archive_type='tar.gz') r_path = os.path.normpath( os.path.join(HOMEDIR, '.retriever/raw_data/test/test/sample_tar.csv')) assert r_path == test_engine.find_file('test/sample_tar.csv') assert ['sample_tar.csv'] <= files def test_download_archive_targz_unknown(): """Download and extract unknown files from a targzipped file to the .retriever/data dir""" setup_functions() files = test_engine.download_files_from_archive(url=tar_gz_url, archive_type='tar.gz') r_path = os.path.normpath( os.path.join(HOMEDIR, '.retriever/raw_data/test/test/sample_tar.csv')) assert r_path == test_engine.find_file('test/sample_tar.csv') assert ['sample_tar.csv'] <= files def test_download_archive_tar_known(): """Download and extract known files from a tarred file to the .retriever/data dir""" setup_functions() files = test_engine.download_files_from_archive( url=tar_url, file_names=['test/sample_tar.csv'], archive_type='tar') r_path = os.path.normpath( os.path.join(HOMEDIR, '.retriever/raw_data/test/test/sample_tar.csv')) assert r_path == test_engine.find_file('test/sample_tar.csv') assert ['sample_tar.csv'] <= files def test_download_archive_tar_unknown(): """Download and extract unknown files from a tarred file to the .retriever/data dir""" setup_functions() files = test_engine.download_files_from_archive(url=tar_url, archive_type='tar') r_path = os.path.normpath( os.path.join(HOMEDIR, '.retriever/raw_data/test/test/sample_tar.csv')) assert r_path == test_engine.find_file('test/sample_tar.csv') assert ['sample_tar.csv'] <= files def test_download_archive_zip_known(): """Download and extract known files from a zipped file to the .retriever/data dir""" setup_functions() files = test_engine.download_files_from_archive(url=zip_url, file_names=['sample_zip.csv'], archive_type='zip') r_path = os.path.normpath( os.path.join(HOMEDIR, '.retriever/raw_data/test/sample_zip.csv')) assert r_path == test_engine.find_file('sample_zip.csv') assert ['sample_zip.csv'] <= files def test_download_archive_zip_unkown(): """Download and extract unknown files from a zipped file to the .retriever/data dir""" setup_functions() files = test_engine.download_files_from_archive(url=zip_url, archive_type='zip') r_path = os.path.normpath( os.path.join(HOMEDIR, '.retriever/raw_data/test/sample_zip.csv')) assert r_path == test_engine.find_file('sample_zip.csv') assert ['sample_zip.csv'] <= files def test_extract_known_tar(): """Test extraction of known tarred filename""" setup_functions() archivedir_write_path = raw_dir_files.format(file_name="") expected = test_engine.extract_tar(achive_tar, archivedir_write_path, archive_type="tar", file_name='test/sample_tar.csv') assert ['test/sample_tar.csv'] == expected assert os.path.exists( raw_dir_files.format(file_name='test/sample_tar.csv')) def test_extract_unknown_tar(): """Test extraction of unknown tarred filename""" setup_functions() archivedir_write_path = raw_dir_files.format(file_name="") expected = test_engine.extract_tar(achive_tar, archivedir_write_path, archive_type='tar', file_name=None) assert ['test/sample_tar.csv'] == expected assert os.path.exists( raw_dir_files.format(file_name='test/sample_tar.csv')) def test_extract_known_zip(): """Test extraction of known zipped filename""" setup_functions() zip_known = raw_dir_files.format(file_name='zip_known') expected = test_engine.extract_zip(achive_zip, archivedir_write_path=zip_known, file_name='sample_zip.csv') assert ['sample_zip.csv'] == expected assert os.path.exists(os.path.join( raw_dir_files.format(file_name='zip_known'), 'sample_zip.csv')) os.system("rm -r {}".format(zip_known)) def test_extract_unknown_zip(): """Test extraction of unknown zipped filename""" setup_functions() zip_unknown = raw_dir_files.format(file_name='zip_unknown') expected = test_engine.extract_zip(achive_zip, archivedir_write_path=zip_unknown) assert ['sample_zip.csv'] == expected assert os.path.exists(os.path.join(raw_dir_files.format( file_name='zip_unknown'), 'sample_zip.csv')) os.system('rm -r {}'.format(zip_unknown)) def test_extract_unknown_targz(): """Test extraction of unknown tarred filename""" setup_functions() archivedir_write_path = raw_dir_files.format(file_name="") expected = test_engine.extract_tar(achive_tar_gz, archivedir_write_path, archive_type='tar.gz', file_name=None) assert ['test/sample_tar.csv'] == expected assert os.path.exists( raw_dir_files.format(file_name='test/sample_tar.csv')) def test_extract_known_targz(): """Test extraction of known tarred filename""" setup_functions() archivedir_write_path = raw_dir_files.format(file_name="") expected = test_engine.extract_tar(achive_tar_gz, archivedir_write_path, archive_type='tar.gz', file_name='test/sample_tar.csv') assert ['test/sample_tar.csv'] == expected assert os.path.exists( raw_dir_files.format(file_name='test/sample_tar.csv')) def test_extract_known_gz(): """Test extraction of known gzipped filename""" setup_functions() archivedir_write_path = raw_dir_files.format(file_name="") expected = test_engine.extract_gz(achive_gz, archivedir_write_path, file_name='test/sample_tar.csv') assert ['test/sample_tar.csv'] == expected assert os.path.exists( raw_dir_files.format(file_name='test/sample_tar.csv')) def test_extract_unknown_gz(): """Test extraction of unknown gzipped filename""" setup_functions() archivedir_write_path = raw_dir_files.format(file_name="") expected = test_engine.extract_gz(achive_gz, archivedir_write_path, file_name=None) expected = [os.path.normpath(file_name) for file_name in expected] assert [os.path.normpath('test/sample_tar.csv')] == expected assert os.path.exists( raw_dir_files.format(file_name='test/sample_tar.csv')) def test_extract_values_fixed_width(): """Test extraction of values from line of fixed width data.""" test_engine.table.fixed_width = [5, 2, 2, 3, 4] assert test_engine.extract_fixed_width('abc 1 2 3 def ') == [ 'abc', '1', '2', '3', 'def'] def test_find_file_absent(): """Test if find_file() properly returns false if no file is present.""" assert test_engine.find_file('missingfile.txt') is False def test_find_file_present(): """Test if existing datafile is found. Using the bird-size dataset which is included for regression testing. We copy the raw_data directory to retriever_root_dir which is the current working directory. This enables the data to be in the DATA_SEARCH_PATHS. """ test_engine.script.name = 'bird-size' assert test_engine.find_file('5599229') == os.path.normpath( 'raw_data/bird-size/5599229') def test_format_data_dir(): """Test if directory for storing data is properly formated.""" test_engine.script.name = "TestName" r_path = '.retriever/raw_data/TestName' assert os.path.normpath(test_engine.format_data_dir()) == \ os.path.normpath(os.path.join(HOMEDIR, r_path)) def test_format_filename(): """Test if filenames for stored files are properly formated.""" test_engine.script.name = "TestName" r_path = '.retriever/raw_data/TestName/testfile.csv' assert os.path.normpath(test_engine.format_filename('testfile.csv')) == \ os.path.normpath(os.path.join(HOMEDIR, r_path)) def test_format_insert_value_int(): """Test formatting of values for insert statements.""" assert test_engine.format_insert_value(42, 'int') == 42 def test_format_insert_value_double(): """Test formatting of values for insert statements.""" assert test_engine.format_insert_value(26.22, 'double') == 26.22 def test_format_insert_value_string_simple(): """Test formatting of values for insert statements.""" test_str = "simple text" assert test_engine.format_insert_value(test_str, 'char') == test_str def test_format_insert_value_string_complex(): """Test formatting of values for insert statements.""" test_str = 'my notes: "have extra, stuff"' assert test_engine.format_insert_value(test_str, 'char') == test_str def test_get_script_citation(): """Test get citation of a script""" cite = rt.get_script_citation("iris") expected_cite = "R. A. Fisher. 1936." assert expected_cite.lower() in cite[0].lower() def test_getmd5_lines(): """Test md5 sum calculation given a line.""" lines = ['a,b,c', '1,2,3', '4,5,6'] exp_hash = 'ca471abda3ebd4ae8ce1b0814b8f470c' assert getmd5(data=lines, data_type='lines') == exp_hash def test_getmd5_line_end(): """Test md5 sum calculation given a line with end of line character.""" lines_end = ['a,b,c\n', '1,2,3\n', '4,5,6\n'] exp_hash = '0bec5bf6f93c547bc9c6774acaf85e1a' assert getmd5(data=lines_end, data_type='lines') == exp_hash def test_getmd5_path(): """Test md5 sum calculation given a path to data source.""" data_file = create_file(['a,b,c', '1,2,3', '4,5,6']) exp_hash = '0bec5bf6f93c547bc9c6774acaf85e1a' assert getmd5(data=data_file, data_type='file') == exp_hash @pytest.mark.parametrize("test_name, json_data, header_values, row_key, expected", json2csv_datasets) def test_json2csv(test_name, json_data, header_values, row_key, expected): """Test json2csv function. Creates a json file and tests the md5 sum calculation. """ json_file = create_file(json_data, 'output.json') output_json = json2csv(json_file, "output_json.csv", header_values=header_values, row_key=row_key) obs_out = file_2list(output_json) os.remove(output_json) assert obs_out == expected @pytest.mark.parametrize("test_name, table_name, geojson_data_url, expected", geojson2csv_dataset) def test_geojson2csv(test_name, table_name, geojson_data_url, expected): if not os.environ.get("CI"): r = requests.get(geojson_data_url, allow_redirects=True) open(table_name, 'wb').write(r.content) output_geojson = geojson2csv(table_name, "output_file_geojson.csv", encoding=test_engine.encoding) header_val = None with open(output_geojson, 'r') as fh: header_val = fh.readline().split() header_val = header_val[0].lower() os.remove(output_geojson) os.remove(table_name) assert header_val == expected @pytest.mark.parametrize("test_name, db_name, sqlite_data_url, table_name, expected", sqlite2csv_dataset) def test_sqlite2csv(test_name, db_name, sqlite_data_url, table_name, expected): r = requests.get(sqlite_data_url, allow_redirects=True) open(db_name, 'wb').write(r.content) output_sqlite = sqlite2csv(db_name, "output_file_sqlite.csv", table_name, encoding=test_engine.encoding) header_val = None with open(output_sqlite, 'r') as fh: header_val = fh.readline().split() os.remove(output_sqlite) os.remove(db_name) assert header_val == expected @pytest.mark.parametrize("test_name, xml_data, header_values, empty_rows, expected", xml2csv_dataset) def test_xml2csv(test_name, xml_data, header_values, empty_rows, expected): """Test xml2csv function. Creates a xml file and tests the md5 sum calculation. """ xml_file = create_file(xml_data, 'output.xml') input_file = xml_file outputfile = "output_xml.csv" output_xml = xml2csv_test(input_file, outputfile, header_values, row_tag="row") obs_out = file_2list(output_xml) os.remove(output_xml) assert obs_out == expected def test_sort_file(): """Test md5 sum calculation.""" data_file = create_file(['Ben,US,24', 'Alex,US,25', 'Alex,PT,25']) out_file = sort_file(data_file) obs_out = file_2list(out_file) os.remove(out_file) assert obs_out == ['Alex,PT,25', 'Alex,US,25', 'Ben,US,24'] def test_sort_csv(): """Test md5 sum calculation.""" data_file = create_file(['User,Country,Age', 'Ben,US,24', 'Alex,US,25', 'Alex,PT,25']) out_file = sort_csv(data_file) obs_out = file_2list(out_file) os.remove(out_file) assert obs_out == [ 'User,Country,Age', 'Alex,PT,25', 'Alex,US,25', 'Ben,US,24'] def test_is_empty_null_string(): """Test for null string.""" assert is_empty("") def test_is_empty_empty_list(): """Test for empty list.""" assert is_empty([]) def test_is_empty_not_null_string(): """Test for non-null string.""" assert is_empty("not empty") == False def test_is_empty_not_empty_list(): """Test for not empty list.""" assert is_empty(["not empty"]) == False def test_clean_input_empty_input_ignore_empty(monkeypatch): """Test with empty input ignored.""" def mock_input(prompt): return "" monkeypatch.setattr('retriever.lib.datapackage.input', mock_input) assert clean_input("", ignore_empty=True) == "" def test_clean_input_empty_input_not_ignore_empty(monkeypatch): """Test with empty input not ignored.""" def mock_input(prompt): mock_input.counter += 1 if mock_input.counter <= 1: return "" else: return "not empty" mock_input.counter = 0 monkeypatch.setattr('retriever.lib.datapackage.input', mock_input) assert clean_input("", ignore_empty=False) == "not empty" def test_clean_input_string_input(monkeypatch): """Test with non-empty input.""" def mock_input(prompt): return "not empty" monkeypatch.setattr('retriever.lib.datapackage.input', mock_input) assert clean_input("") == "not empty" def test_clean_input_empty_list_ignore_empty(monkeypatch): """Test with empty list ignored.""" def mock_input(prompt): return ", , ," monkeypatch.setattr('retriever.lib.datapackage.input', mock_input) assert clean_input("", ignore_empty=True, split_char=",") == [] def test_clean_input_empty_list_not_ignore_empty(monkeypatch): """Test with empty list not ignored.""" def mock_input(prompt): mock_input.counter += 1 if mock_input.counter <= 1: return ", , ," else: return "1 , 2, 3," mock_input.counter = 0 monkeypatch.setattr('retriever.lib.datapackage.input', mock_input) assert clean_input("", split_char=",") == ["1", "2", "3"] def test_clean_input_not_empty_list(monkeypatch): """Test with list input.""" def mock_input(prompt): return "1, 2, 3" monkeypatch.setattr('retriever.lib.datapackage.input', mock_input) assert clean_input("", ignore_empty=True, split_char=',', dtype=None) == \ ["1", "2", "3"] def test_clean_input_bool(monkeypatch): """Test with correct datatype input.""" def mock_input(prompt): return "True " monkeypatch.setattr('retriever.lib.datapackage.input', mock_input) assert clean_input("", dtype=bool) == "True" def test_clean_input_not_bool(monkeypatch): """Test with incorrect datatype input.""" def mock_input(prompt): mock_input.counter += 1 if mock_input.counter <= 1: return "non bool input" else: return "True " mock_input.counter = 0 monkeypatch.setattr('retriever.lib.datapackage.input', mock_input) assert clean_input("", dtype=bool) == "True" def test_reset_retriever(tmpdir): """Test the dataset reset function.""" pwd_name = os.getcwd() workdir = tmpdir.mkdtemp() workdir.chdir() offline_datasets = rt.dataset_names()['offline'] offline_datasets = [dataset for dataset in offline_datasets if not dataset.startswith('test-')] if not offline_datasets: return dataset = random.choice(offline_datasets) rt.reset_retriever(dataset) rt.reload_scripts() assert os.path.exists(os.path.join(HOME_DIR, dataset.replace("-", "_") + ".json")) == False assert os.path.exists(os.path.join(HOME_DIR, dataset.replace("-", "_") + ".py")) == False if dataset in RETRIEVER_DATASETS: rt.get_script_upstream(dataset, repo=RETRIEVER_REPOSITORY) else: rt.get_script_upstream(dataset) rt.reload_scripts() assert dataset in rt.dataset_names()['offline'] os.chdir(pwd_name) def test_setup_functions(): """Test the set up function. Function uses teardown_module and setup_module functions.""" file_path = raw_dir_files.format(file_name='') subprocess.call(['rm', '-r', file_path]) assert os.path.exists(raw_dir_files.format(file_name="")) is False setup_functions() assert os.path.exists(raw_dir_files.format(file_name=""))
{ "pile_set_name": "Github" }
grammar e :: 'e_' ::= | F f :: :: f | C c :: :: c a :: 'a_' ::= | B b :: :: b | 0 :: :: 0 b :: 'b_' ::= | A a :: :: a c :: 'c_' ::= | A a :: :: a d :: 'd_' ::= {{ isa string }} {{ coq nat }} {{ hol string }} | A a :: :: a f :: 'f_' ::= | EA e a :: :: ea
{ "pile_set_name": "Github" }
/**************************************************************************** * * * cryptlib HTTP Certstore Session Management * * Copyright Peter Gutmann 1998-2008 * * * ****************************************************************************/ #if defined( INC_ALL ) #include "crypt.h" #include "misc_rw.h" #include "session.h" #include "certstore.h" #else #include "crypt.h" #include "enc_dec/misc_rw.h" #include "session/session.h" #include "session/certstore.h" #endif /* Compiler-specific includes */ /* SCEP's bolted-on HTTP query mechanism requires that we use the HTTP certstore access routines to return responses to certificate queries, so we enable the use of this code if either certstores or SCEP are used */ #if defined( USE_CERTSTORE ) || defined( USE_SCEP ) /* Table mapping a query submitted as an HTTP GET to a cryptlib-internal keyset query. Note that the first letter must be lowercase for the case-insensitive quick match */ static const CERTSTORE_READ_INFO certstoreReadInfo[] = { { "certHash", 8, CRYPT_IKEYID_CERTID, CERTSTORE_FLAG_BASE64 }, { "name", 4, CRYPT_KEYID_NAME, CERTSTORE_FLAG_NONE }, { "uri", 3, CRYPT_KEYID_URI, CERTSTORE_FLAG_NONE }, { "email", 5, CRYPT_KEYID_URI, CERTSTORE_FLAG_NONE }, { "sHash", 5, CRYPT_IKEYID_ISSUERID, CERTSTORE_FLAG_BASE64 }, { "iHash", 5, CRYPT_IKEYID_ISSUERID, CERTSTORE_FLAG_BASE64 }, { "iAndSHash", 9, CRYPT_IKEYID_ISSUERANDSERIALNUMBER, CERTSTORE_FLAG_BASE64 }, { "sKIDHash", 8, CRYPT_IKEYID_KEYID, CERTSTORE_FLAG_BASE64 }, { NULL, 0, CRYPT_KEYID_NONE, CERTSTORE_FLAG_NONE }, { NULL, 0, CRYPT_KEYID_NONE, CERTSTORE_FLAG_NONE } }; /**************************************************************************** * * * Utility Functions * * * ****************************************************************************/ /* Convert a query attribute into a text string suitable for use with retExt() */ CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 3 ) ) \ static int queryAttributeToString( OUT_BUFFER_FIXED( textBufMaxLen ) char *textBuffer, IN_LENGTH_SHORT_MIN( 16 ) const int textBufMaxLen, IN_BUFFER( attributeLen ) const BYTE *attribute, IN_LENGTH_SHORT const int attributeLen ) { assert( isWritePtr( textBuffer, textBufMaxLen ) ); assert( isReadPtr( attribute, attributeLen ) ); REQUIRES( textBufMaxLen >= 16 && textBufMaxLen < MAX_INTLENGTH_SHORT ); REQUIRES( attributeLen > 0 && attributeLen < MAX_INTLENGTH_SHORT ); /* Copy as much of the attribute as will fit across and clean it up so that it can be returned to the user */ memcpy( textBuffer, attribute, min( attributeLen, textBufMaxLen ) ); sanitiseString( textBuffer, textBufMaxLen, attributeLen ); return( CRYPT_OK ); } /* Process a certificate query and return the requested certificate. See the comment above for why this is declared non-static */ CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3, 5 ) ) \ int processCertQuery( INOUT SESSION_INFO *sessionInfoPtr, const HTTP_URI_INFO *httpReqInfo, IN_ARRAY( queryReqInfoSize ) \ const CERTSTORE_READ_INFO *queryReqInfo, IN_RANGE( 1, 64 ) const int queryReqInfoSize, OUT_ATTRIBUTE_Z int *attributeID, OUT_BUFFER_OPT( attributeMaxLen, *attributeLen ) \ void *attribute, IN_LENGTH_SHORT_Z const int attributeMaxLen, OUT_OPT_LENGTH_SHORT_Z int *attributeLen ) { const CERTSTORE_READ_INFO *queryInfoPtr = NULL; const int firstChar = toLower( httpReqInfo->attribute[ 0 ] ); int i, status; assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) ); assert( isReadPtr( httpReqInfo, sizeof( HTTP_URI_INFO ) ) ); assert( isReadPtr( queryReqInfo, sizeof( CERTSTORE_READ_INFO ) * queryReqInfoSize ) ); assert( isWritePtr( attributeID, sizeof( int ) ) ); assert( ( attribute == NULL && attributeMaxLen == 0 && \ attributeLen == NULL ) || \ ( isWritePtr( attribute, attributeMaxLen ) && \ isWritePtr( attributeLen, sizeof( int ) ) ) ); REQUIRES( queryReqInfoSize > 0 && queryReqInfoSize <= 64 ); REQUIRES( ( attribute == NULL && attributeMaxLen == 0 && \ attributeLen == NULL ) || \ ( attribute != NULL && \ attributeMaxLen > 0 && \ attributeMaxLen < MAX_INTLENGTH_SHORT && \ attributeLen != NULL ) ); /* Clear return values */ *attributeID = CRYPT_ATTRIBUTE_NONE; if( attribute != NULL ) { memset( attribute, 0, min( 16, attributeMaxLen ) ); *attributeLen = 0; } /* Convert the search attribute type into a cryptlib key ID */ for( i = 0; i < queryReqInfoSize && \ queryReqInfo[ i ].attrName != NULL; i++ ) { if( httpReqInfo->attributeLen == queryReqInfo[ i ].attrNameLen && \ queryReqInfo[ i ].attrName[ 0 ] == firstChar && \ !strCompare( httpReqInfo->attribute, \ queryReqInfo[ i ].attrName, \ queryReqInfo[ i ].attrNameLen ) ) { queryInfoPtr = &queryReqInfo[ i ]; break; } } ENSURES( i < queryReqInfoSize ); if( queryInfoPtr == NULL ) { char queryText[ CRYPT_MAX_TEXTSIZE + 8 ]; status = queryAttributeToString( queryText, CRYPT_MAX_TEXTSIZE, httpReqInfo->attribute, httpReqInfo->attributeLen ); ENSURES( cryptStatusOK( status ) ); retExt( CRYPT_ERROR_BADDATA, ( CRYPT_ERROR_BADDATA, SESSION_ERRINFO, "Invalid certificate query attribute '%s'", queryText ) ); } /* We've got a valid attribute, let the caller know which one it is. If that's all the information that they're after, we're done */ *attributeID = queryInfoPtr->attrID; if( attribute == NULL ) return( CRYPT_OK ); /* If the query data wasn't encoded in any way, we're done */ if( !( queryInfoPtr->flags & CERTSTORE_FLAG_BASE64 ) ) { return( attributeCopyParams( attribute, attributeMaxLen, attributeLen, httpReqInfo->value, httpReqInfo->valueLen ) ); } /* The value was base64-encoded in transit, decode it to get the actual query data */ status = base64decode( attribute, attributeMaxLen, attributeLen, httpReqInfo->value, httpReqInfo->valueLen, CRYPT_CERTFORMAT_NONE ); if( cryptStatusError( status ) ) { char queryText[ CRYPT_MAX_TEXTSIZE + 8 ]; status = queryAttributeToString( queryText, CRYPT_MAX_TEXTSIZE, httpReqInfo->value, httpReqInfo->valueLen ); ENSURES( cryptStatusOK( status ) ); retExt( CRYPT_ERROR_BADDATA, ( CRYPT_ERROR_BADDATA, SESSION_ERRINFO, "Invalid base64-encoded query value '%s'", queryText ) ); } return( CRYPT_OK ); } /* Send an HTTP error response to the client (the error status value is mapped at the HTTP layer to an appropriate HTTP response). We don't return a status from this since the caller already has an error status available */ STDC_NONNULL_ARG( ( 1 ) ) \ void sendCertErrorResponse( INOUT SESSION_INFO *sessionInfoPtr, IN_ERROR const int errorStatus ) { HTTP_DATA_INFO httpDataInfo; assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) ); REQUIRES_V( cryptStatusError( errorStatus ) ); initHttpDataInfo( &httpDataInfo, sessionInfoPtr->receiveBuffer, sessionInfoPtr->receiveBufSize ); httpDataInfo.reqStatus = errorStatus; ( void ) swrite( &sessionInfoPtr->stream, &httpDataInfo, sizeof( HTTP_DATA_INFO ) ); } /**************************************************************************** * * * Init/Shutdown Functions * * * ****************************************************************************/ /* Exchange data with an HTTP client */ CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \ static int serverTransact( INOUT SESSION_INFO *sessionInfoPtr ) { HTTP_DATA_INFO httpDataInfo; HTTP_URI_INFO httpReqInfo; MESSAGE_KEYMGMT_INFO getkeyInfo; MESSAGE_DATA msgData; BYTE keyID[ CRYPT_MAX_TEXTSIZE + 8 ]; int keyIDtype, keyIDLen, status; assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) ); sioctlSet( &sessionInfoPtr->stream, STREAM_IOCTL_HTTPREQTYPES, STREAM_HTTPREQTYPE_GET ); /* Read the request data from the client. We do a direct read rather than using readPkiDatagram() since we're reading an idempotent HTTP GET request and not a PKI datagram submitted via an HTTP POST */ initHttpDataInfoEx( &httpDataInfo, sessionInfoPtr->receiveBuffer, sessionInfoPtr->receiveBufSize, &httpReqInfo ); status = sread( &sessionInfoPtr->stream, &httpDataInfo, sizeof( HTTP_DATA_INFO ) ); if( cryptStatusError( status ) ) { sNetGetErrorInfo( &sessionInfoPtr->stream, &sessionInfoPtr->errorInfo ); return( status ); } /* Convert the certificate query into a certstore search key */ status = processCertQuery( sessionInfoPtr, &httpReqInfo, certstoreReadInfo, FAILSAFE_ARRAYSIZE( certstoreReadInfo, \ CERTSTORE_READ_INFO ), &keyIDtype, keyID, CRYPT_MAX_TEXTSIZE, &keyIDLen ); if( cryptStatusError( status ) ) { sendCertErrorResponse( sessionInfoPtr, status ); return( status ); } /* Try and fetch the requested certificate. Note that this is somewhat suboptimal since we have to instantiate the certificate only to destroy it again as soon as we've exported the certificate data, for a proper high-performance implementation the server would query the certificate database directly and send the stored encoded value to the client */ setMessageKeymgmtInfo( &getkeyInfo, keyIDtype, keyID, keyIDLen, NULL, 0, KEYMGMT_FLAG_NONE ); status = krnlSendMessage( sessionInfoPtr->cryptKeyset, IMESSAGE_KEY_GETKEY, &getkeyInfo, KEYMGMT_ITEM_PUBLICKEY ); if( cryptStatusError( status ) ) { char queryText[ CRYPT_MAX_TEXTSIZE + 8 ]; char textBuffer[ 64 + CRYPT_MAX_TEXTSIZE + 8 ]; int textLength; /* Not finding a certificate in response to a request isn't a real error so all we do is return a warning to the caller. Unfortunately since we're not using retExt() we have to assemble the message string ourselves */ sendCertErrorResponse( sessionInfoPtr, status ); status = queryAttributeToString( queryText, CRYPT_MAX_TEXTSIZE, httpReqInfo.value, httpReqInfo.valueLen ); ENSURES( cryptStatusOK( status ) ); textLength = sprintf_s( textBuffer, 64 + CRYPT_MAX_TEXTSIZE, "Warning: Couldn't find certificate for '%s'", queryText ); setErrorString( SESSION_ERRINFO, textBuffer, textLength ); return( CRYPT_OK ); } /* Write the certificate to the session buffer */ setMessageData( &msgData, sessionInfoPtr->receiveBuffer, sessionInfoPtr->receiveBufSize ); status = krnlSendMessage( getkeyInfo.cryptHandle, IMESSAGE_CRT_EXPORT, &msgData, CRYPT_CERTFORMAT_CERTIFICATE ); krnlSendNotifier( getkeyInfo.cryptHandle, IMESSAGE_DESTROY ); if( cryptStatusError( status ) ) { char queryText[ CRYPT_MAX_TEXTSIZE + 8 ]; int altStatus; sendCertErrorResponse( sessionInfoPtr, status ); altStatus = queryAttributeToString( queryText, CRYPT_MAX_TEXTSIZE, httpReqInfo.value, httpReqInfo.valueLen ); ENSURES( cryptStatusOK( altStatus ) ); retExt( status, ( status, SESSION_ERRINFO, "Couldn't export requested certificate for '%s'", queryText ) ); } sessionInfoPtr->receiveBufEnd = msgData.length; /* Send the result to the client */ return( writePkiDatagram( sessionInfoPtr, CERTSTORE_CONTENT_TYPE, CERTSTORE_CONTENT_TYPE_LEN ) ); } /**************************************************************************** * * * Session Access Routines * * * ****************************************************************************/ CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \ int setAccessMethodCertstore( INOUT SESSION_INFO *sessionInfoPtr ) { static const PROTOCOL_INFO protocolInfo = { /* General session information */ TRUE, /* Request-response protocol */ SESSION_ISHTTPTRANSPORT, /* Flags */ 80, /* HTTP port */ 0, /* Client flags */ SESSION_NEEDS_KEYSET, /* Server flags */ 1, 1, 1 /* Version 1 */ /* Protocol-specific information */ }; assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) ); /* Set the access method pointers. The client-side implementation is just a standard HTTP fetch so there's no explicit certstore client implementation */ sessionInfoPtr->protocolInfo = &protocolInfo; if( isServer( sessionInfoPtr ) ) sessionInfoPtr->transactFunction = serverTransact; else return( CRYPT_ERROR_NOTAVAIL ); return( CRYPT_OK ); } #endif /* USE_CERTSTORE || USE_SCEP */
{ "pile_set_name": "Github" }
var xresetps__g_8c = [ [ "XResetPs_ConfigTable", "xresetps__g_8c.html#gab17d113e87eebe6bac64b56665f7159c", null ] ];
{ "pile_set_name": "Github" }
/* fp_sqr_comba_7.i * * Copyright (C) 2006-2016 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ #ifdef TFM_SQR7 void fp_sqr_comba7(fp_int *A, fp_int *B) { fp_digit *a, b[14], c0, c1, c2, sc0, sc1, sc2; #ifdef TFM_ISO fp_word tt; #endif a = A->dp; COMBA_START; /* clear carries */ CLEAR_CARRY; /* output 0 */ SQRADD(a[0],a[0]); COMBA_STORE(b[0]); /* output 1 */ CARRY_FORWARD; SQRADD2(a[0], a[1]); COMBA_STORE(b[1]); /* output 2 */ CARRY_FORWARD; SQRADD2(a[0], a[2]); SQRADD(a[1], a[1]); COMBA_STORE(b[2]); /* output 3 */ CARRY_FORWARD; SQRADD2(a[0], a[3]); SQRADD2(a[1], a[2]); COMBA_STORE(b[3]); /* output 4 */ CARRY_FORWARD; SQRADD2(a[0], a[4]); SQRADD2(a[1], a[3]); SQRADD(a[2], a[2]); COMBA_STORE(b[4]); /* output 5 */ CARRY_FORWARD; SQRADDSC(a[0], a[5]); SQRADDAC(a[1], a[4]); SQRADDAC(a[2], a[3]); SQRADDDB; COMBA_STORE(b[5]); /* output 6 */ CARRY_FORWARD; SQRADDSC(a[0], a[6]); SQRADDAC(a[1], a[5]); SQRADDAC(a[2], a[4]); SQRADDDB; SQRADD(a[3], a[3]); COMBA_STORE(b[6]); /* output 7 */ CARRY_FORWARD; SQRADDSC(a[1], a[6]); SQRADDAC(a[2], a[5]); SQRADDAC(a[3], a[4]); SQRADDDB; COMBA_STORE(b[7]); /* output 8 */ CARRY_FORWARD; SQRADD2(a[2], a[6]); SQRADD2(a[3], a[5]); SQRADD(a[4], a[4]); COMBA_STORE(b[8]); /* output 9 */ CARRY_FORWARD; SQRADD2(a[3], a[6]); SQRADD2(a[4], a[5]); COMBA_STORE(b[9]); /* output 10 */ CARRY_FORWARD; SQRADD2(a[4], a[6]); SQRADD(a[5], a[5]); COMBA_STORE(b[10]); /* output 11 */ CARRY_FORWARD; SQRADD2(a[5], a[6]); COMBA_STORE(b[11]); /* output 12 */ CARRY_FORWARD; SQRADD(a[6], a[6]); COMBA_STORE(b[12]); COMBA_STORE2(b[13]); COMBA_FINI; B->used = 14; B->sign = FP_ZPOS; XMEMCPY(B->dp, b, 14 * sizeof(fp_digit)); fp_clamp(B); } #endif
{ "pile_set_name": "Github" }
/* * Ubiquiti Networks XM (rev 1.0) board support * * Copyright (C) 2011 René Bolldorf <[email protected]> * * Derived from: mach-pb44.c * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include <linux/init.h> #include <linux/pci.h> #include <linux/gpio.h> #include <linux/platform_device.h> #include <linux/ath9k_platform.h> #include <linux/etherdevice.h> #include <linux/ar8216_platform.h> #include <linux/platform_data/phy-at803x.h> #include <asm/mach-ath79/ath79.h> #include <asm/mach-ath79/irq.h> #include <asm/mach-ath79/ar71xx_regs.h> #include <linux/platform_data/phy-at803x.h> #include "common.h" #include "dev-ap9x-pci.h" #include "dev-eth.h" #include "dev-gpio-buttons.h" #include "dev-leds-gpio.h" #include "dev-m25p80.h" #include "dev-usb.h" #include "dev-wmac.h" #include "machtypes.h" #define UBNT_XM_GPIO_LED_L1 0 #define UBNT_XM_GPIO_LED_L2 1 #define UBNT_XM_GPIO_LED_L3 11 #define UBNT_XM_GPIO_LED_L4 7 #define UBNT_XM_GPIO_BTN_RESET 12 #define UBNT_XM_KEYS_POLL_INTERVAL 20 #define UBNT_XM_KEYS_DEBOUNCE_INTERVAL (3 * UBNT_XM_KEYS_POLL_INTERVAL) #define UBNT_XM_EEPROM_ADDR 0x1fff1000 static struct gpio_led ubnt_xm_leds_gpio[] __initdata = { { .name = "ubnt:red:link1", .gpio = UBNT_XM_GPIO_LED_L1, .active_low = 0, }, { .name = "ubnt:orange:link2", .gpio = UBNT_XM_GPIO_LED_L2, .active_low = 0, }, { .name = "ubnt:green:link3", .gpio = UBNT_XM_GPIO_LED_L3, .active_low = 0, }, { .name = "ubnt:green:link4", .gpio = UBNT_XM_GPIO_LED_L4, .active_low = 0, }, }; static struct gpio_keys_button ubnt_xm_gpio_keys[] __initdata = { { .desc = "reset", .type = EV_KEY, .code = KEY_RESTART, .debounce_interval = UBNT_XM_KEYS_DEBOUNCE_INTERVAL, .gpio = UBNT_XM_GPIO_BTN_RESET, .active_low = 1, } }; #define UBNT_M_WAN_PHYMASK BIT(4) static void __init ubnt_xm_init(void) { u8 *eeprom = (u8 *) KSEG1ADDR(UBNT_XM_EEPROM_ADDR); u8 *mac1 = (u8 *) KSEG1ADDR(0x1fff0000); u8 *mac2 = (u8 *) KSEG1ADDR(0x1fff0000 + ETH_ALEN); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_xm_leds_gpio), ubnt_xm_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); ath79_register_m25p80(NULL); ap91_pci_init(eeprom, NULL); ath79_register_mdio(0, ~UBNT_M_WAN_PHYMASK); ath79_eth0_data.speed = SPEED_100; ath79_init_mac(ath79_eth0_data.mac_addr, mac1, 0); ath79_eth1_data.speed = SPEED_100; ath79_init_mac(ath79_eth1_data.mac_addr, mac2, 0); ath79_register_eth(0); } MIPS_MACHINE(ATH79_MACH_UBNT_XM, "UBNT-XM", "Ubiquiti Networks XM (rev 1.0) board", ubnt_xm_init); MIPS_MACHINE(ATH79_MACH_UBNT_BULLET_M, "UBNT-BM", "Ubiquiti Bullet M", ubnt_xm_init); static void __init ubnt_rocket_m_setup(void) { ubnt_xm_init(); ath79_register_usb(); } MIPS_MACHINE(ATH79_MACH_UBNT_ROCKET_M, "UBNT-RM", "Ubiquiti Rocket M", ubnt_rocket_m_setup); static void __init ubnt_nano_m_setup(void) { ubnt_xm_init(); ath79_register_eth(1); } MIPS_MACHINE(ATH79_MACH_UBNT_NANO_M, "UBNT-NM", "Ubiquiti Nanostation M", ubnt_nano_m_setup); static struct gpio_led ubnt_airrouter_leds_gpio[] __initdata = { { .name = "ubnt:green:globe", .gpio = 0, .active_low = 1, }, { .name = "ubnt:green:power", .gpio = 11, .active_low = 1, .default_state = LEDS_GPIO_DEFSTATE_ON, } }; static void __init ubnt_airrouter_setup(void) { u8 *mac1 = (u8 *) KSEG1ADDR(0x1fff0000); u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000); ath79_register_m25p80(NULL); ath79_register_mdio(0, ~UBNT_M_WAN_PHYMASK); ath79_init_mac(ath79_eth0_data.mac_addr, mac1, 0); ath79_init_local_mac(ath79_eth1_data.mac_addr, mac1); ath79_register_eth(1); ath79_register_eth(0); ath79_register_usb(); ap91_pci_init(ee, NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_airrouter_leds_gpio), ubnt_airrouter_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); } MIPS_MACHINE(ATH79_MACH_UBNT_AIRROUTER, "UBNT-AR", "Ubiquiti AirRouter", ubnt_airrouter_setup); static struct gpio_led ubnt_unifi_leds_gpio[] __initdata = { { .name = "ubnt:orange:dome", .gpio = 1, .active_low = 0, }, { .name = "ubnt:green:dome", .gpio = 0, .active_low = 0, } }; static struct gpio_led ubnt_unifi_outdoor_leds_gpio[] __initdata = { { .name = "ubnt:orange:front", .gpio = 1, .active_low = 0, }, { .name = "ubnt:green:front", .gpio = 0, .active_low = 0, } }; static struct gpio_led ubnt_unifi_outdoor_plus_leds_gpio[] __initdata = { { .name = "ubnt:white:front", .gpio = 1, .active_low = 0, }, { .name = "ubnt:blue:front", .gpio = 0, .active_low = 0, } }; static void __init ubnt_unifi_setup(void) { u8 *mac = (u8 *) KSEG1ADDR(0x1fff0000); u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000); ath79_register_m25p80(NULL); ath79_register_mdio(0, ~UBNT_M_WAN_PHYMASK); ath79_init_mac(ath79_eth0_data.mac_addr, mac, 0); ath79_register_eth(0); ap91_pci_init(ee, NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_unifi_leds_gpio), ubnt_unifi_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); } MIPS_MACHINE(ATH79_MACH_UBNT_UNIFI, "UBNT-UF", "Ubiquiti UniFi", ubnt_unifi_setup); #define UBNT_UNIFIOD_PRI_PHYMASK BIT(4) #define UBNT_UNIFIOD_2ND_PHYMASK (BIT(0) | BIT(1) | BIT(2) | BIT(3)) static void __init ubnt_unifi_outdoor_setup(void) { u8 *mac1 = (u8 *) KSEG1ADDR(0x1fff0000); u8 *mac2 = (u8 *) KSEG1ADDR(0x1fff0000 + ETH_ALEN); u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000); ath79_register_m25p80(NULL); ath79_register_mdio(0, ~(UBNT_UNIFIOD_PRI_PHYMASK | UBNT_UNIFIOD_2ND_PHYMASK)); ath79_init_mac(ath79_eth0_data.mac_addr, mac1, 0); ath79_init_mac(ath79_eth1_data.mac_addr, mac2, 0); ath79_register_eth(0); ath79_register_eth(1); ap91_pci_init(ee, NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_unifi_outdoor_leds_gpio), ubnt_unifi_outdoor_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); } MIPS_MACHINE(ATH79_MACH_UBNT_UNIFI_OUTDOOR, "UBNT-U20", "Ubiquiti UniFiAP Outdoor", ubnt_unifi_outdoor_setup); static void __init ubnt_unifi_outdoor_plus_setup(void) { u8 *mac1 = (u8 *) KSEG1ADDR(0x1fff0000); u8 *mac2 = (u8 *) KSEG1ADDR(0x1fff0000 + ETH_ALEN); u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000); ath79_register_m25p80(NULL); ath79_register_mdio(0, ~(UBNT_UNIFIOD_PRI_PHYMASK | UBNT_UNIFIOD_2ND_PHYMASK)); ath79_init_mac(ath79_eth0_data.mac_addr, mac1, 0); ath79_init_mac(ath79_eth1_data.mac_addr, mac2, 0); ath79_register_eth(0); ath79_register_eth(1); ap9x_pci_get_wmac_data(0)->ubnt_hsr = true; ap91_pci_init(ee, NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_unifi_outdoor_plus_leds_gpio), ubnt_unifi_outdoor_plus_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); } MIPS_MACHINE(ATH79_MACH_UBNT_UNIFI_OUTDOOR_PLUS, "UBNT-UOP", "Ubiquiti UniFiAP Outdoor+", ubnt_unifi_outdoor_plus_setup); static struct gpio_led ubnt_uap_pro_gpio_leds[] __initdata = { { .name = "ubnt:white:dome", .gpio = 12, }, { .name = "ubnt:blue:dome", .gpio = 13, } }; static struct gpio_keys_button uap_pro_gpio_keys[] __initdata = { { .desc = "reset", .type = EV_KEY, .code = KEY_RESTART, .debounce_interval = UBNT_XM_KEYS_DEBOUNCE_INTERVAL, .gpio = 17, .active_low = 1, } }; static struct ar8327_pad_cfg uap_pro_ar8327_pad0_cfg = { .mode = AR8327_PAD_MAC_RGMII, .txclk_delay_en = true, .rxclk_delay_en = true, .txclk_delay_sel = AR8327_CLK_DELAY_SEL1, .rxclk_delay_sel = AR8327_CLK_DELAY_SEL2, }; static struct ar8327_platform_data uap_pro_ar8327_data = { .pad0_cfg = &uap_pro_ar8327_pad0_cfg, .port0_cfg = { .force_link = 1, .speed = AR8327_PORT_SPEED_1000, .duplex = 1, .txpause = 1, .rxpause = 1, }, }; static struct mdio_board_info uap_pro_mdio0_info[] = { { .bus_id = "ag71xx-mdio.0", .mdio_addr = 0, .platform_data = &uap_pro_ar8327_data, }, }; #define UAP_PRO_MAC0_OFFSET 0x0000 #define UAP_PRO_MAC1_OFFSET 0x0006 #define UAP_PRO_WMAC_CALDATA_OFFSET 0x1000 #define UAP_PRO_PCI_CALDATA_OFFSET 0x5000 static void __init ubnt_uap_pro_setup(void) { u8 *eeprom = (u8 *) KSEG1ADDR(0x1fff0000); ath79_register_m25p80(NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_uap_pro_gpio_leds), ubnt_uap_pro_gpio_leds); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(uap_pro_gpio_keys), uap_pro_gpio_keys); ath79_register_wmac(eeprom + UAP_PRO_WMAC_CALDATA_OFFSET, NULL); ap91_pci_init(eeprom + UAP_PRO_PCI_CALDATA_OFFSET, NULL); ath79_register_mdio(0, 0x0); mdiobus_register_board_info(uap_pro_mdio0_info, ARRAY_SIZE(uap_pro_mdio0_info)); ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_RGMII_GMAC0); ath79_init_mac(ath79_eth0_data.mac_addr, eeprom + UAP_PRO_MAC0_OFFSET, 0); /* GMAC0 is connected to an AR8327 switch */ ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; ath79_eth0_data.phy_mask = BIT(0); ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev; ath79_eth0_pll_data.pll_1000 = 0x06000000; ath79_register_eth(0); } MIPS_MACHINE(ATH79_MACH_UBNT_UAP_PRO, "UAP-PRO", "Ubiquiti UniFi AP Pro", ubnt_uap_pro_setup); #define UBNT_XW_GPIO_LED_L1 11 #define UBNT_XW_GPIO_LED_L2 16 #define UBNT_XW_GPIO_LED_L3 13 #define UBNT_XW_GPIO_LED_L4 14 static struct gpio_led ubnt_xw_leds_gpio[] __initdata = { { .name = "ubnt:red:link1", .gpio = UBNT_XW_GPIO_LED_L1, .active_low = 1, }, { .name = "ubnt:orange:link2", .gpio = UBNT_XW_GPIO_LED_L2, .active_low = 1, }, { .name = "ubnt:green:link3", .gpio = UBNT_XW_GPIO_LED_L3, .active_low = 1, }, { .name = "ubnt:green:link4", .gpio = UBNT_XW_GPIO_LED_L4, .active_low = 1, }, }; #define UBNT_ROCKET_TI_GPIO_LED_L1 16 #define UBNT_ROCKET_TI_GPIO_LED_L2 17 #define UBNT_ROCKET_TI_GPIO_LED_L3 18 #define UBNT_ROCKET_TI_GPIO_LED_L4 19 #define UBNT_ROCKET_TI_GPIO_LED_L5 20 #define UBNT_ROCKET_TI_GPIO_LED_L6 21 static struct gpio_led ubnt_rocket_ti_leds_gpio[] __initdata = { { .name = "ubnt:green:link1", .gpio = UBNT_ROCKET_TI_GPIO_LED_L1, .active_low = 1, }, { .name = "ubnt:green:link2", .gpio = UBNT_ROCKET_TI_GPIO_LED_L2, .active_low = 1, }, { .name = "ubnt:green:link3", .gpio = UBNT_ROCKET_TI_GPIO_LED_L3, .active_low = 1, }, { .name = "ubnt:green:link4", .gpio = UBNT_ROCKET_TI_GPIO_LED_L4, .active_low = 0, }, { .name = "ubnt:green:link5", .gpio = UBNT_ROCKET_TI_GPIO_LED_L5, .active_low = 0, }, { .name = "ubnt:green:link6", .gpio = UBNT_ROCKET_TI_GPIO_LED_L6, .active_low = 0, }, }; static void __init ubnt_xw_init(void) { u8 *eeprom = (u8 *) KSEG1ADDR(0x1fff0000); ath79_register_m25p80(NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_xw_leds_gpio), ubnt_xw_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); ath79_register_wmac(eeprom + UAP_PRO_WMAC_CALDATA_OFFSET, NULL); ap91_pci_init(eeprom + UAP_PRO_PCI_CALDATA_OFFSET, NULL); ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_MII_GMAC0 | AR934X_ETH_CFG_MII_GMAC0_SLAVE); ath79_init_mac(ath79_eth0_data.mac_addr, eeprom + UAP_PRO_MAC0_OFFSET, 0); ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_MII; ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev; } static void __init ubnt_nano_m_xw_setup(void) { ubnt_xw_init(); /* GMAC0 is connected to an AR8326 switch */ ath79_register_mdio(0, ~(BIT(0) | BIT(1) | BIT(5))); ath79_eth0_data.phy_mask = (BIT(0) | BIT(1) | BIT(5)); ath79_eth0_data.speed = SPEED_100; ath79_eth0_data.duplex = DUPLEX_FULL; ath79_register_eth(0); } static struct at803x_platform_data ubnt_loco_m_xw_at803x_data = { .has_reset_gpio = 1, .reset_gpio = 0, }; static struct mdio_board_info ubnt_loco_m_xw_mdio_info[] = { { .bus_id = "ag71xx-mdio.0", .mdio_addr = 1, .platform_data = &ubnt_loco_m_xw_at803x_data, }, }; static void __init ubnt_loco_m_xw_setup(void) { ubnt_xw_init(); mdiobus_register_board_info(ubnt_loco_m_xw_mdio_info, ARRAY_SIZE(ubnt_loco_m_xw_mdio_info)); ath79_register_mdio(0, ~BIT(1)); ath79_eth0_data.phy_mask = BIT(1); ath79_register_eth(0); } #define UBNT_LBE_M5_GPIO_LED_LAN 13 #define UBNT_LBE_M5_GPIO_LED_WLAN 14 #define UBNT_LBE_M5_GPIO_LED_SYS 16 static struct gpio_led ubnt_lbe_m5_leds_gpio[] __initdata = { { .name = "ubnt:green:lan", .gpio = UBNT_LBE_M5_GPIO_LED_LAN, .active_low = 1, }, { .name = "ubnt:green:wlan", .gpio = UBNT_LBE_M5_GPIO_LED_WLAN, .active_low = 1, }, { .name = "ubnt:green:sys", .gpio = UBNT_LBE_M5_GPIO_LED_SYS, .active_low = 1, }, }; static void __init ubnt_lbe_m5_setup(void) { u8 *eeprom = (u8 *) KSEG1ADDR(0x1fff0000); ath79_register_m25p80(NULL); ath79_register_wmac(eeprom + UAP_PRO_WMAC_CALDATA_OFFSET, NULL); ap91_pci_init(eeprom + UAP_PRO_PCI_CALDATA_OFFSET, NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_lbe_m5_leds_gpio), ubnt_lbe_m5_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_MII_GMAC0 | AR934X_ETH_CFG_MII_GMAC0_SLAVE); ath79_init_mac(ath79_eth0_data.mac_addr, eeprom + UAP_PRO_MAC0_OFFSET, 0); ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_MII; ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev; gpio_request_one(0, GPIOF_OUT_INIT_LOW | GPIOF_ACTIVE_LOW | GPIOF_EXPORT_DIR_FIXED, "SPI nWP"); mdiobus_register_board_info(ubnt_loco_m_xw_mdio_info, ARRAY_SIZE(ubnt_loco_m_xw_mdio_info)); ath79_register_mdio(0, ~BIT(1)); ath79_eth0_data.phy_mask = BIT(1); ath79_register_eth(0); } static void __init ubnt_rocket_m_xw_setup(void) { u8 *eeprom = (u8 *) KSEG1ADDR(0x1fff0000); ath79_register_m25p80(NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_xw_leds_gpio), ubnt_xw_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); ath79_register_wmac(eeprom + UAP_PRO_WMAC_CALDATA_OFFSET, NULL); ap91_pci_init(eeprom + UAP_PRO_PCI_CALDATA_OFFSET, NULL); ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_RGMII_GMAC0); ath79_init_mac(ath79_eth0_data.mac_addr, eeprom + UAP_PRO_MAC0_OFFSET, 0); ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev; ath79_register_mdio(0, ~BIT(4)); ath79_eth0_data.phy_mask = BIT(4); ath79_eth0_pll_data.pll_1000 = 0x06000000; ath79_register_eth(0); } static struct at803x_platform_data ubnt_rocket_m_ti_at803_data = { .disable_smarteee = 1, .enable_rgmii_rx_delay = 1, .enable_rgmii_tx_delay = 1, }; static struct mdio_board_info ubnt_rocket_m_ti_mdio_info[] = { { .bus_id = "ag71xx-mdio.0", .mdio_addr = 4, .platform_data = &ubnt_rocket_m_ti_at803_data, }, }; static void __init ubnt_rocket_m_ti_setup(void) { u8 *eeprom = (u8 *) KSEG1ADDR(0x1fff0000); ath79_register_m25p80(NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_rocket_ti_leds_gpio), ubnt_rocket_ti_leds_gpio); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(ubnt_xm_gpio_keys), ubnt_xm_gpio_keys); ap91_pci_init(eeprom + 0x1000, NULL); ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_RGMII_GMAC0); ath79_setup_ar934x_eth_rx_delay(3, 3); ath79_init_mac(ath79_eth0_data.mac_addr, eeprom + UAP_PRO_MAC0_OFFSET, 0); ath79_init_mac(ath79_eth1_data.mac_addr, eeprom + UAP_PRO_MAC1_OFFSET, 0); ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev; ath79_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_GMII; ath79_eth1_data.mii_bus_dev = &ath79_mdio1_device.dev; mdiobus_register_board_info(ubnt_rocket_m_ti_mdio_info, ARRAY_SIZE(ubnt_rocket_m_ti_mdio_info)); ath79_register_mdio(0, 0x0); ath79_eth0_data.phy_mask = BIT(4); /* read out from vendor */ ath79_eth0_pll_data.pll_1000 = 0x2000000; ath79_eth0_pll_data.pll_10 = 0x1313; ath79_register_eth(0); ath79_register_mdio(1, 0x0); ath79_eth1_data.phy_mask = BIT(3); ath79_register_eth(1); } MIPS_MACHINE(ATH79_MACH_UBNT_NANO_M_XW, "UBNT-NM-XW", "Ubiquiti Nanostation M XW", ubnt_nano_m_xw_setup); MIPS_MACHINE(ATH79_MACH_UBNT_LBE_M5, "UBNT-LBE-M5", "Ubiquiti Litebeam M5", ubnt_lbe_m5_setup); MIPS_MACHINE(ATH79_MACH_UBNT_LOCO_M_XW, "UBNT-LOCO-XW", "Ubiquiti Loco M XW", ubnt_loco_m_xw_setup); MIPS_MACHINE(ATH79_MACH_UBNT_ROCKET_M_XW, "UBNT-RM-XW", "Ubiquiti Rocket M XW", ubnt_rocket_m_xw_setup); MIPS_MACHINE(ATH79_MACH_UBNT_BULLET_M_XW, "UBNT-BM-XW", "Ubiquiti Bullet M XW", ubnt_rocket_m_xw_setup); MIPS_MACHINE(ATH79_MACH_UBNT_ROCKET_M_TI, "UBNT-RM-TI", "Ubiquiti Rocket M TI", ubnt_rocket_m_ti_setup); static struct gpio_led ubnt_airgateway_gpio_leds[] __initdata = { { .name = "ubnt:blue:wlan", .gpio = 0, }, { .name = "ubnt:white:status", .gpio = 1, }, }; static struct gpio_keys_button airgateway_gpio_keys[] __initdata = { { .desc = "reset", .type = EV_KEY, .code = KEY_RESTART, .debounce_interval = UBNT_XM_KEYS_DEBOUNCE_INTERVAL, .gpio = 12, .active_low = 1, } }; static void __init ubnt_airgateway_setup(void) { u32 t; u8 *mac0 = (u8 *) KSEG1ADDR(0x1fff0000); u8 *mac1 = (u8 *) KSEG1ADDR(0x1fff0000 + ETH_ALEN); u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000); ath79_gpio_function_disable(AR933X_GPIO_FUNC_ETH_SWITCH_LED0_EN | AR933X_GPIO_FUNC_ETH_SWITCH_LED1_EN | AR933X_GPIO_FUNC_ETH_SWITCH_LED2_EN | AR933X_GPIO_FUNC_ETH_SWITCH_LED3_EN | AR933X_GPIO_FUNC_ETH_SWITCH_LED4_EN); t = ath79_reset_rr(AR933X_RESET_REG_BOOTSTRAP); t |= AR933X_BOOTSTRAP_MDIO_GPIO_EN; ath79_reset_wr(AR933X_RESET_REG_BOOTSTRAP, t); ath79_register_m25p80(NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_airgateway_gpio_leds), ubnt_airgateway_gpio_leds); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(airgateway_gpio_keys), airgateway_gpio_keys); ath79_init_mac(ath79_eth1_data.mac_addr, mac0, 0); ath79_init_mac(ath79_eth0_data.mac_addr, mac1, 0); ath79_register_mdio(0, 0x0); ath79_register_eth(1); ath79_register_eth(0); ath79_register_wmac(ee, NULL); } MIPS_MACHINE(ATH79_MACH_UBNT_AIRGW, "UBNT-AGW", "Ubiquiti AirGateway", ubnt_airgateway_setup); static struct gpio_led ubnt_airgateway_pro_gpio_leds[] __initdata = { { .name = "ubnt:blue:wlan", .gpio = 13, }, { .name = "ubnt:white:status", .gpio = 17, }, }; static struct gpio_keys_button airgateway_pro_gpio_keys[] __initdata = { { .desc = "reset", .type = EV_KEY, .code = KEY_RESTART, .debounce_interval = UBNT_XM_KEYS_DEBOUNCE_INTERVAL, .gpio = 12, .active_low = 1, } }; static void __init ubnt_airgateway_pro_setup(void) { u8 *eeprom = (u8 *) KSEG1ADDR(0x1fff0000); u8 *mac0 = (u8 *) KSEG1ADDR(0x1fff0000); ath79_register_m25p80(NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(ubnt_airgateway_pro_gpio_leds), ubnt_airgateway_pro_gpio_leds); ath79_register_gpio_keys_polled(-1, UBNT_XM_KEYS_POLL_INTERVAL, ARRAY_SIZE(airgateway_pro_gpio_keys), airgateway_pro_gpio_keys); ath79_register_wmac(eeprom + UAP_PRO_WMAC_CALDATA_OFFSET, NULL); ap91_pci_init(eeprom + UAP_PRO_PCI_CALDATA_OFFSET, NULL); ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_SW_ONLY_MODE); ath79_register_mdio(1, 0x0); /* GMAC0 is left unused in this configuration */ /* GMAC1 is connected to MAC0 on the internal switch */ /* The PoE/WAN port connects to port 5 on the internal switch */ /* The LAN port connects to port 4 on the internal switch */ ath79_init_mac(ath79_eth1_data.mac_addr, mac0, 0); ath79_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_GMII; ath79_register_eth(1); } MIPS_MACHINE(ATH79_MACH_UBNT_AIRGWP, "UBNT-AGWP", "Ubiquiti AirGateway Pro", ubnt_airgateway_pro_setup);
{ "pile_set_name": "Github" }
// // SerialDisposable.swift // Rx // // Created by Krunoslav Zaher on 3/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ public class SerialDisposable : DisposeBase, Cancelable { private var _lock = SpinLock() // state private var _current = nil as Disposable? private var _disposed = false /** - returns: Was resource disposed. */ public var disposed: Bool { return _disposed } /** Initializes a new instance of the `SerialDisposable`. */ override public init() { super.init() } /** Gets or sets the underlying disposable. Assigning this property disposes the previous disposable object. If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. */ public var disposable: Disposable { get { return _lock.calculateLocked { return self.disposable } } set (newDisposable) { let disposable: Disposable? = _lock.calculateLocked { if _disposed { return newDisposable } else { let toDispose = _current _current = newDisposable return toDispose } } if let disposable = disposable { disposable.dispose() } } } /** Disposes the underlying disposable as well as all future replacements. */ public func dispose() { _dispose()?.dispose() } private func _dispose() -> Disposable? { _lock.lock(); defer { _lock.unlock() } if _disposed { return nil } else { _disposed = true let current = _current _current = nil return current } } }
{ "pile_set_name": "Github" }
<!-- # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # --> # OpenWhisk Standalone Server OpenWhisk standalone server is meant to run a simple OpenWhisk server for local development and test purposes. It can be executed as a normal java application from command line. ```bash java -jar openwhisk-standalone.jar ``` This should start the OpenWhisk server on port 3233 by default and launch a Playground UI at port 3232. ![Playground UI](../../docs/images/playground-ui.png) The Playground UI can be used to try out simple actions. To make use of all OpenWhisk features [configure the cli][1] and then try out the [samples][2]. This server by default uses a memory based store and does not depend on any other external service like Kafka and CouchDB. It only needs Docker and Java to for running. Few key points related to it * Uses in memory store. Once the server is stopped all changes would be lost * Bootstraps the `guest` and `whisk.system` with default keys * Supports running on MacOS, Linux and Windows (experimental) setup * Can be customized to use any other storage like CouchDB ### Build To build this standalone server run ```bash $ ./gradlew :core:standalone:build ``` This would create the runnable jar in `bin/` directory. If you directly want to run the server then you can use following command ```bash $ ./gradlew :core:standalone:bootRun ``` To pass argument to the run command use ```bash $ ./gradlew :core:standalone:bootRun --args='-m runtimes.json' ``` You can also build a standalone docker image with: ```bash $ ./gradlew :core:standalone:distDocker ``` ### Usage OpenWhisk standalone server support various launch options ``` $ java -jar openwhisk-standalone.jar -h /\ \ / _ \ _ __ ___ _ __ | | | | |__ (_)___| | __ /\ /__\ \ | | | | '_ \ / _ \ '_ \| | | | '_ \| / __| |/ / / \____ \ / | |_| | |_) | __/ | | | |/\| | | | | \__ \ < \ \ / \/ \___/| .__/ \___|_| |_|__/\__|_| |_|_|___/_|\_\ \___\/ tm |_| -m, --manifest <arg> Manifest JSON defining the supported runtimes -c, --config-file <arg> application.conf which overrides the default standalone.conf --api-gw Enable API Gateway support --couchdb Enable CouchDB support --user-events Enable User Events along with Prometheus and Grafana --kafka Enable embedded Kafka support --kafka-ui Enable Kafka UI --all Enables all the optional services supported by Standalone OpenWhisk like CouchDB, Kafka etc --api-gw-port <arg> API Gateway Port --clean Clean any existing state like database -d, --data-dir <arg> Directory used for storage --dev-kcf Enables KubernetesContainerFactory for local development --dev-mode Developer mode speeds up the startup by disabling preflight checks and avoiding explicit pulls. --dev-user-events-port <arg> Specify the port for the user-event service. This mode can be used for local development of user-event service by configuring Prometheus to connect to existing running service instance --disable-color-logging Disables colored logging --enable-bootstrap Enable bootstrap of default users and actions like those needed for Api Gateway or Playground UI. By default bootstrap is done by default when using Memory store or default CouchDB support. When using other stores enable this flag to get bootstrap done --kafka-docker-port <arg> Kafka port for use by docker based services. If not specified then 9091 or some random free port (if 9091 is busy) would be used --kafka-port <arg> Kafka port. If not specified then 9092 or some random free port (if 9092 is busy) would be used --no-ui Disable Playground UI --ui-port <arg> Playground UI server port. If not specified then 3232 or some random free port (if org.apache.openwhisk.standalone.StandaloneOpenWhisk$@75a1cd57 is busy) would be used -p, --port <arg> Server port -v, --verbose --zk-port <arg> Zookeeper port. If not specified then 2181 or some random free port (if 2181 is busy) would be used -h, --help Show help message --version Show version of this program OpenWhisk standalone server ``` Sections below would illustrate some of the supported options To change the default config you can provide a custom `application.conf` file via `-c` option. The application conf file must always include the default `standalone.conf` ```hocon include classpath("standalone.conf") whisk { //Custom config } ``` Then pass this config file ```bash java -jar openwhisk-standalone.jar -c custom.conf ``` #### Adding custom namespaces If you need to register custom namespaces (aka users) then you can pass them via config file like below ```hocon include classpath("standalone.conf") whisk { users { whisk-test = "cafebabe-cafe-babe-cafe-babecafebabe:007zO3xZCLrMN6v2BKK1dXYFpXlPkccOFqm12CdAsMgRU4VrNZ9lyGVCGuMDGIwP" } } ``` Then pass this config file via `-c` option. You can check the users created from log ``` [2019-06-21T19:52:02.923Z] [INFO] [#tid_userBootstrap] [StandaloneOpenWhisk] Created user [guest] [2019-06-21T19:52:03.008Z] [INFO] [#tid_userBootstrap] [StandaloneOpenWhisk] Created user [whisk.system] [2019-06-21T19:52:03.094Z] [INFO] [#tid_userBootstrap] [StandaloneOpenWhisk] Created user [whisk.test] ``` #### Using custom runtimes To use custom runtime pass the runtime manifest via `-m` option ```json { "runtimes": { "ruby": [ { "kind": "ruby:2.5", "default": true, "deprecated": false, "attached": { "attachmentName": "codefile", "attachmentType": "text/plain" }, "image": { "prefix": "openwhisk", "name": "action-ruby-v2.5", "tag": "latest" } } ] } } ``` The pass this file at launch time ```bash java -jar openwhisk-standalone.jar -m custom-runtime.json ``` You can then see the runtime config reflect in `http://localhost:3233` #### Using CouchDB If you need to use CouchDB then you can launch the standalone server with `--couchdb` option. This would launch a CouchDB server which would configured to store files in user home directory under `.openwhisk/standalone` folder. If you need to connect to external CouchDB or any other supported artifact store then you can pass the required config ```hocon include classpath("standalone.conf") whisk { couchdb { protocol = "http" host = "172.17.0.1" port = "5984" username = "whisk_admin" password = "some_passw0rd" provider = "CouchDB" databases { WhiskAuth = "whisk_local_subjects" WhiskEntity = "whisk_local_whisks" WhiskActivation = "whisk_local_activations" } } } ``` Then pass this config file via `-c` option. Note that Standalone OpenWhisk will not bootstrap users and actions (e.g., API Gateway and Playground UI) when using an external database unless explicitly requested with `--enable-bootstrap`. This is to ensure that default users and actions are not added to your external artifact store. #### Using API Gateway API Gateway mode can be enabled via `--api-gw` flag. In this mode upon launch a separate container for [OpenWhisk API gateway][3] would be launched on port `3234` (can be changed with `--api-gw-port`). In this mode you can make use of the [API Gateway][4] support. #### Using Kafka Standalone OpenWhisk supports launching an [embedded kafka][5]. This mode is mostly useful for developers working on OpenWhisk implementation itself. ``` java -jar openwhisk-standalone.jar --kafka ``` It also supports launching a Kafka UI based on [Kafdrop 3][6] which enables seeing the topics created and structure of messages exchanged on those topics. ``` java -jar openwhisk-standalone.jar --kafka --kafka-ui ``` By default the ui server would be accessible at http://localhost:9000. In case 9000 port is busy then a random port would be selected. To find out the port look for message in log like below (or grep for `whisk-kafka-drop-ui`) ``` [ 9092 ] localhost:9092 (kafka) [ 9092 ] 192.168.65.2:9091 (kafka-docker) [ 2181 ] Zookeeper (zookeeper) [ 9000 ] http://localhost:9000 (whisk-kafka-drop-ui) ``` #### User Events Standalone OpenWhisk supports emitting [user events][7] and displaying them via Grafana Dashboard. The metrics are consumed by [User Event Service][8] which converts them into metrics consumed via Prometheus. ``` java -jar openwhisk-standalone.jar --user-events ``` This mode would launch an embedded Kafka, User Event service, Prometheus and Grafana with preconfigured dashboards. ``` Launched service details [ 9092 ] localhost:9092 (kafka) [ 9091 ] 192.168.65.2:9091 (kafka-docker) [ 2181 ] Zookeeper (zookeeper) [ 3235 ] http://localhost:3235 (whisk-user-events) [ 9090 ] http://localhost:9090 (whisk-prometheus) [ 3000 ] http://localhost:3000 (whisk-grafana) ``` #### Using KubernetesContainerFactory Standalone OpenWhisk can be configured to use KubernetesContainerFactory (KCF) via `--dev-kcf` option. This mode can be used to simplify developing KubernetesContainerFactory. Below mentioned steps are based on [Kind][9] tool for running local Kubernetes clusters using Docker container "nodes". However this mode should work against any Kubernetes cluster if the the `KUBECONFIG` is properly set. ##### 1. Install and configure Kind We would use Kind to setup a local k8s. Follow the steps [here][10] to create a simple cluster. ```bash $ kind create cluster --wait 5m # Export the kind config for kubectl usage $ export KUBECONFIG="$(kind get kubeconfig-path)" # Configure the default namespace $ kubectl config set-context --current --namespace=default # See the config path $ kind get kubeconfig-path /Users/example/.kube/kind-config-kind ``` ##### 2. Launch Standalone ```bash # Launch it with `kubeconfig` system property set to kind config $ java -Dkubeconfig="$(kind get kubeconfig-path)" -jar bin/openwhisk-standalone.jar --dev-kcf ``` Once started and required `.wskprops` configured to use the standalone server create a `hello.js` function ```js function main(params) { greeting = 'hello, world' var hello = {payload: greeting} var result = {...hello, ...process.env} console.log(greeting); return result } ``` ```bash $ wsk action create hello hello.js $ wsk action invoke hello -br ``` This shows an output like below indicating that KubernetesContainerFactory based invocation is working properly. ``` { "HOME": "/root", "HOSTNAME": "wsk0-2-prewarm-nodejs10", "KUBERNETES_PORT": "tcp://10.96.0.1:443", "KUBERNETES_PORT_443_TCP": "tcp://10.96.0.1:443", "KUBERNETES_PORT_443_TCP_ADDR": "10.96.0.1", "KUBERNETES_PORT_443_TCP_PORT": "443", "KUBERNETES_PORT_443_TCP_PROTO": "tcp", "KUBERNETES_SERVICE_HOST": "10.96.0.1", "KUBERNETES_SERVICE_PORT": "443", "KUBERNETES_SERVICE_PORT_HTTPS": "443", "NODE_VERSION": "10.15.3", "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "PWD": "/nodejsAction", "YARN_VERSION": "1.13.0", "__OW_ACTION_NAME": "/guest/hello", "__OW_ACTION_VERSION": "0.0.1", "__OW_ACTIVATION_ID": "71e48d2d62e142eca48d2d62e192ec2d", "__OW_API_HOST": "http://host.docker.internal:3233", "__OW_DEADLINE": "1570223213407", "__OW_NAMESPACE": "guest", "__OW_TRANSACTION_ID": "iSOoNklk6V7l7eh8KJnvugidKEmaNJmv", "payload": "hello, world" } ``` ## Launching OpenWhisk standalone with Docker If you have docker and bash installed, you can launch the standalone openwhisk from the docker image with just: `bash <(curl -sL https://s.apache.org/openwhisk.sh)` The script will start the standalone controller with Docker, and will also try to open the playground. It was tested on Linux, OSX and Windows with Git Bash. If a browser does not automatically open the OpenWhisk playground, you can access it at `http://localhost:3232`. The default standalone controller image is published as `openwhisk/standalone:nightly` for convenience. You can specify a different image to this script and also pass additional parameters to Docker. The general format is: `bash <(curl -sL https://s.apache.org/openwhisk.sh) [<image-name>] [<additional-docker-parameters>...]` If you do not want to execute arbitrary code straight from the net, you can look at [this script](start.sh), check it and run it when you feel safe. If the playground is not enough, you can then install the [wsk CLI](https://github.com/apache/openwhisk-cli/releases) and retrieve the command line to configure `wsk` with: `docker logs openwhisk | grep 'wsk property'` To properly shut down OpenWhisk and any additional containers it has created, use [this script](stop.sh) or run the command: `docker exec openwhisk stop` ### Extra Args for the Standalone OpenWhisk Docker Image When running OpenWhisk Standalone using the docker image, you can set environment variables to pass extra args with the `-e` flag. Extra args are useful to configure the JVM running OpenWhisk and to propagate additional environment variables to containers running images. This feature is useful for example to enable debugging for actions. You can pass additional parameters (for example set system properties) to the JVM running OpenWhisk setting the environment variable `JVM_EXTRA_ARGS`. For example `-e JVM_EXTRA_ARGS=-Dconfig.loads` allows to enable tracing of configuration. You can set any OpenWhisk parameter with feature. You can also set additional environment variables for each container running actions invoked by OpenWhisk by setting `CONTAINER_EXTRA_ENV`. For example, setting `-e CONTAINER_EXTRA_ENV=__OW_DEBUG_PORT=8081` enables debugging for those images supporting starting the action under a debugger, like the typescript runtime. [1]: https://github.com/apache/openwhisk/blob/master/docs/cli.md [2]: https://github.com/apache/openwhisk/blob/master/docs/samples.md [3]: https://github.com/apache/openwhisk-apigateway [4]: https://github.com/apache/openwhisk/blob/master/docs/apigateway.md [5]: https://github.com/embeddedkafka/embedded-kafka [6]: https://github.com/obsidiandynamics/kafdrop [7]: https://github.com/apache/openwhisk/blob/master/docs/metrics.md#user-specific-metrics [8]: https://github.com/apache/openwhisk/blob/master/core/monitoring/user-events/README.md [9]: https://kind.sigs.k8s.io/ [10]: https://kind.sigs.k8s.io/docs/user/quick-start/
{ "pile_set_name": "Github" }
# Event 22 - task_0 ###### Version: 0 ## Description None ## Data Dictionary |Standard Name|Field Name|Type|Description|Sample Value| |---|---|---|---|---| |TBD|Message1|UnicodeString|None|`None`| |TBD|HRESULT|HexInt32|None|`None`| ## Tags * etw_level_Error * etw_task_task_0
{ "pile_set_name": "Github" }
/*PLEASE DO NOT EDIT THIS CODE*/ /*This code was generated using the UMPLE @UMPLE_VERSION@ modeling language!*/ package example.mentor; import example.student.*; public class Mentor { //------------------------ // MEMBER VARIABLES //------------------------ //Mentor Associations private Student student; //------------------------ // CONSTRUCTOR //------------------------ public Mentor(Student aStudent) { if (!setStudent(aStudent)) { throw new RuntimeException("Unable to create Mentor due to aStudent. See http://manual.umple.org?RE002ViolationofAssociationMultiplicity.html"); } } //------------------------ // INTERFACE //------------------------ public Student getStudent() { return student; } public boolean setStudent(Student aNewStudent) { boolean wasSet = false; if (aNewStudent != null) { student = aNewStudent; wasSet = true; } return wasSet; } public void delete() { student = null; } }
{ "pile_set_name": "Github" }
package com.jubotech.framework.netty; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import com.jubotech.framework.netty.handler.WebSocketJsonHandler; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; @Service public class WebSocketServer { @Autowired private Environment env; @Autowired private WebSocketJsonHandler webSocketFrameHandler; // 日志记录器 Logger logger = LoggerFactory.getLogger(getClass()); // 程序初始方法入口注解,提示spring这个程序先执行这里 @PostConstruct public void nettyMain() { new Thread(new Runnable() { public void run() { // 1 创建线两个程组 // 一个是用于处理服务器端接收客户端连接的 // 一个是进行网络通信的(网络读写的) EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { // 2 创建辅助工具类,用于服务器通道的一系列配置 ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class);// 指定NIO的模式 b.option(ChannelOption.SO_KEEPALIVE, true); // 保持连接 b.childHandler(new ChannelInitializer<SocketChannel>(){ @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //websocket协议本身是基于http协议的,所以这边也要使用http解编码器 pipeline.addLast(new HttpServerCodec()); //以块的方式来写的处理器 pipeline.addLast(new ChunkedWriteHandler()); //netty是基于分段请求的,HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度 pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerProtocolHandler("/")); pipeline.addLast(webSocketFrameHandler); } }); // 3、绑定端口 同步等待成功 Integer port = getNettyPort(env); ChannelFuture f = b.bind(port).sync(); logger.info("netty启动成功。。。" + "websocket占用端口" + port); // 4、等待服务端监听端口关闭 f.channel().closeFuture().sync(); } catch (Exception e) { logger.info("netty启动失败。。。"); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } }).start(); } // 获取netty端口 private static Integer getNettyPort(Environment env) { return Integer.valueOf(env.getProperty("com.jubotech.netty.websocket.port")); } }
{ "pile_set_name": "Github" }
#include "UnitTest.h" #include "Gwen/Controls/TreeControl.h" using namespace Gwen; using namespace Gwen::Controls; class TreeControl2 : public GUnit { public: GWEN_CONTROL_INLINE( TreeControl2, GUnit ) { { Gwen::Controls::TreeControl* ctrl = new Gwen::Controls::TreeControl( this ); ctrl->SetKeyboardInputEnabled(true); ctrl->AddNode( L"Node One" ); Gwen::Controls::TreeNode* pNode = ctrl->AddNode( L"Node Two" ); pNode->AddNode( L"Node Two Inside" ); pNode->AddNode( L"Eyes" ); pNode->SetSelected(true); pNode->AddNode( L"Brown" )->AddNode( L"Node Two Inside" )->AddNode( L"Eyes" )->AddNode( L"Brown" ); ctrl->AddNode( L"Node Three" ); ctrl->Focus(); ctrl->SetKeyboardInputEnabled(true); ctrl->SetBounds( 30, 30, 200, 200 ); ctrl->ExpandAll(); } { Gwen::Controls::TreeControl* ctrl = new Gwen::Controls::TreeControl( this ); ctrl->AllowMultiSelect( true ); ctrl->AddNode( L"Node One" ); Gwen::Controls::TreeNode* pNode = ctrl->AddNode( L"Node Two" ); pNode->AddNode( L"Node Two Inside" ); pNode->AddNode( L"Eyes" ); Gwen::Controls::TreeNode* pNodeTwo = pNode->AddNode( L"Brown" )->AddNode( L"Node Two Inside" )->AddNode( L"Eyes" ); pNodeTwo->AddNode( L"Brown" ); pNodeTwo->AddNode( L"Green" ); pNodeTwo->AddNode( L"Slime" ); pNodeTwo->AddNode( L"Grass" ); pNodeTwo->AddNode( L"Pipe" ); ctrl->AddNode( L"Node Three" ); ctrl->SetBounds( 240, 30, 200, 200 ); ctrl->ExpandAll(); } } }; DEFINE_UNIT_TEST( TreeControl2, L"TreeControl" );
{ "pile_set_name": "Github" }
import { Component, EventEmitter, Input, OnDestroy, Output, } from '@angular/core'; import { ToasterService } from 'angular2-toaster'; import { Angulartics2 } from 'angulartics2'; import { CipherService } from 'jslib/abstractions/cipher.service'; import { EventService } from 'jslib/abstractions/event.service'; import { I18nService } from 'jslib/abstractions/i18n.service'; import { PlatformUtilsService } from 'jslib/abstractions/platformUtils.service'; import { SearchService } from 'jslib/abstractions/search.service'; import { CiphersComponent as BaseCiphersComponent } from 'jslib/angular/components/ciphers.component'; import { CipherType } from 'jslib/enums/cipherType'; import { EventType } from 'jslib/enums/eventType'; import { CipherView } from 'jslib/models/view/cipherView'; const MaxCheckedCount = 500; @Component({ selector: 'app-vault-ciphers', templateUrl: 'ciphers.component.html', }) export class CiphersComponent extends BaseCiphersComponent implements OnDestroy { @Input() showAddNew = true; @Output() onAttachmentsClicked = new EventEmitter<CipherView>(); @Output() onShareClicked = new EventEmitter<CipherView>(); @Output() onCollectionsClicked = new EventEmitter<CipherView>(); @Output() onCloneClicked = new EventEmitter<CipherView>(); cipherType = CipherType; actionPromise: Promise<any>; constructor(searchService: SearchService, protected analytics: Angulartics2, protected toasterService: ToasterService, protected i18nService: I18nService, protected platformUtilsService: PlatformUtilsService, protected cipherService: CipherService, protected eventService: EventService) { super(searchService); this.pageSize = 200; } ngOnDestroy() { this.selectAll(false); } launch(uri: string) { this.platformUtilsService.eventTrack('Launched Login URI'); this.platformUtilsService.launchUri(uri); } attachments(c: CipherView) { this.onAttachmentsClicked.emit(c); } share(c: CipherView) { this.onShareClicked.emit(c); } collections(c: CipherView) { this.onCollectionsClicked.emit(c); } clone(c: CipherView) { this.onCloneClicked.emit(c); } async delete(c: CipherView): Promise<boolean> { if (this.actionPromise != null) { return; } const permanent = c.isDeleted; const confirmed = await this.platformUtilsService.showDialog( this.i18nService.t(permanent ? 'permanentlyDeleteItemConfirmation' : 'deleteItemConfirmation'), this.i18nService.t(permanent ? 'permanentlyDeleteItem' : 'deleteItem'), this.i18nService.t('yes'), this.i18nService.t('no'), 'warning'); if (!confirmed) { return false; } try { this.actionPromise = this.deleteCipher(c.id, permanent); await this.actionPromise; this.analytics.eventTrack.next({ action: 'Deleted Cipher' }); this.toasterService.popAsync('success', null, this.i18nService.t(permanent ? 'permanentlyDeletedItem' : 'deletedItem')); this.refresh(); } catch { } this.actionPromise = null; } async restore(c: CipherView): Promise<boolean> { if (this.actionPromise != null || !c.isDeleted) { return; } const confirmed = await this.platformUtilsService.showDialog( this.i18nService.t('restoreItemConfirmation'), this.i18nService.t('restoreItem'), this.i18nService.t('yes'), this.i18nService.t('no'), 'warning'); if (!confirmed) { return false; } try { this.actionPromise = this.cipherService.restoreWithServer(c.id); await this.actionPromise; this.analytics.eventTrack.next({ action: 'Restored Cipher' }); this.toasterService.popAsync('success', null, this.i18nService.t('restoredItem')); this.refresh(); } catch { } this.actionPromise = null; } copy(cipher: CipherView, value: string, typeI18nKey: string, aType: string) { if (value == null) { return; } this.analytics.eventTrack.next({ action: 'Copied ' + aType.toLowerCase() + ' from listing.' }); this.platformUtilsService.copyToClipboard(value, { window: window }); this.toasterService.popAsync('info', null, this.i18nService.t('valueCopied', this.i18nService.t(typeI18nKey))); if (typeI18nKey === 'password') { this.eventService.collect(EventType.Cipher_ClientToggledHiddenFieldVisible, cipher.id); } else if (typeI18nKey === 'securityCode') { this.eventService.collect(EventType.Cipher_ClientCopiedCardCode, cipher.id); } } selectAll(select: boolean) { if (select) { this.selectAll(false); } const selectCount = select && this.ciphers.length > MaxCheckedCount ? MaxCheckedCount : this.ciphers.length; for (let i = 0; i < selectCount; i++) { this.checkCipher(this.ciphers[i], select); } } checkCipher(c: CipherView, select?: boolean) { (c as any).checked = select == null ? !(c as any).checked : select; } getSelected(): CipherView[] { if (this.ciphers == null) { return []; } return this.ciphers.filter((c) => !!(c as any).checked); } getSelectedIds(): string[] { return this.getSelected().map((c) => c.id); } protected deleteCipher(id: string, permanent: boolean) { return permanent ? this.cipherService.deleteWithServer(id) : this.cipherService.softDeleteWithServer(id); } protected showFixOldAttachments(c: CipherView) { return c.hasOldAttachments && c.organizationId == null; } }
{ "pile_set_name": "Github" }
// cgo -godefs types_darwin.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm64,darwin package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int32 _ [4]byte } type Timeval32 struct { Sec int32 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 _ [4]byte Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 } type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 } type Radvisory_t struct { Offset int64 Count int32 _ [4]byte } type Fbootstraptransfer_t struct { Offset int64 Length uint64 Buffer *byte } type Log2phys_t struct { Flags uint32 _ [8]byte _ [8]byte } type Fsid struct { Val [2]int32 } type Dirent struct { Ino uint64 Seekoff uint64 Reclen uint16 Namlen uint16 Type uint8 Name [1024]int8 _ [3]byte } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 _ [4]byte Iov *Iovec Iovlen int32 _ [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [32]int32 } const ( SizeofIfMsghdr = 0x70 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Data IfData } type IfData struct { Type uint8 Typelen uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Unused1 uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Recvtiming uint32 Xmittiming uint32 Lastchange Timeval32 Unused2 uint32 Hwassist uint32 Reserved1 uint32 Reserved2 uint32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte } type IfmaMsghdr2 struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Refcount int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 _ [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire int32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Filler [4]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 _ [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval32 Caplen uint32 Datalen uint32 Hdrlen uint16 _ [2]byte } type Termios struct { Iflag uint64 Oflag uint64 Cflag uint64 Lflag uint64 Cc [20]uint8 _ [4]byte Ispeed uint64 Ospeed uint64 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x80 AT_SYMLINK_FOLLOW = 0x40 AT_SYMLINK_NOFOLLOW = 0x20 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLERR = 0x8 POLLHUP = 0x10 POLLIN = 0x1 POLLNVAL = 0x20 POLLOUT = 0x4 POLLPRI = 0x2 POLLRDBAND = 0x80 POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) type Utsname struct { Sysname [256]byte Nodename [256]byte Release [256]byte Version [256]byte Machine [256]byte }
{ "pile_set_name": "Github" }
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # 255: Control characters that usually does not exist in any text # 254: Carriage/Return # 253: symbol (punctuation) that does not belong to word # 252: 0 - 9 # Character Mapping Table: Latin7_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253, 82,100,104, 94, 98,101,116,102,111,187,117, 92, 88,113, 85, # 40 79,118,105, 83, 67,114,119, 95, 99,109,188,253,253,253,253,253, # 50 253, 72, 70, 80, 81, 60, 96, 93, 89, 68,120, 97, 77, 86, 69, 55, # 60 78,115, 65, 66, 58, 76,106,103, 87,107,112,253,253,253,253,253, # 70 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 80 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 90 253,233, 90,253,253,253,253,253,253,253,253,253,253, 74,253,253, # a0 253,253,253,253,247,248, 61, 36, 46, 71, 73,253, 54,253,108,123, # b0 110, 31, 51, 43, 41, 34, 91, 40, 52, 47, 44, 53, 38, 49, 59, 39, # c0 35, 48,250, 37, 33, 45, 56, 50, 84, 57,120,121, 17, 18, 22, 15, # d0 124, 1, 29, 20, 21, 3, 32, 13, 25, 5, 11, 16, 10, 6, 30, 4, # e0 9, 8, 14, 7, 2, 12, 28, 23, 42, 24, 64, 75, 19, 26, 27,253, # f0 ) win1253_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253, 82,100,104, 94, 98,101,116,102,111,187,117, 92, 88,113, 85, # 40 79,118,105, 83, 67,114,119, 95, 99,109,188,253,253,253,253,253, # 50 253, 72, 70, 80, 81, 60, 96, 93, 89, 68,120, 97, 77, 86, 69, 55, # 60 78,115, 65, 66, 58, 76,106,103, 87,107,112,253,253,253,253,253, # 70 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 80 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 90 253,233, 61,253,253,253,253,253,253,253,253,253,253, 74,253,253, # a0 253,253,253,253,247,253,253, 36, 46, 71, 73,253, 54,253,108,123, # b0 110, 31, 51, 43, 41, 34, 91, 40, 52, 47, 44, 53, 38, 49, 59, 39, # c0 35, 48,250, 37, 33, 45, 56, 50, 84, 57,120,121, 17, 18, 22, 15, # d0 124, 1, 29, 20, 21, 3, 32, 13, 25, 5, 11, 16, 10, 6, 30, 4, # e0 9, 8, 14, 7, 2, 12, 28, 23, 42, 24, 64, 75, 19, 26, 27,253, # f0 ) # Model Table: # total sequences: 100% # first 512 sequences: 98.2851% # first 1024 sequences:1.7001% # rest sequences: 0.0359% # negative sequences: 0.0148% GreekLangModel = ( 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,2,2,3,3,3,3,3,3,3,3,1,3,3,3,0,2,2,3,3,0,3,0,3,2,0,3,3,3,0, 3,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,0,3,3,0,3,2,3,3,0,3,2,3,3,3,0,0,3,0,3,0,3,3,2,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0, 0,2,3,2,2,3,3,3,3,3,3,3,3,0,3,3,3,3,0,2,3,3,0,3,3,3,3,2,3,3,3,0, 2,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,2,1,3,3,3,3,2,3,3,2,3,3,2,0, 0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,2,3,3,0, 2,0,1,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,3,0,0,0,0,3,3,0,3,1,3,3,3,0,3,3,0,3,3,3,3,0,0,0,0, 2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,0,3,0,3,3,3,3,3,0,3,2,2,2,3,0,2,3,3,3,3,3,2,3,3,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,3,2,2,2,3,3,3,3,0,3,1,3,3,3,3,2,3,3,3,3,3,3,3,2,2,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,0,3,0,0,0,3,3,2,3,3,3,3,3,0,0,3,2,3,0,2,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,3,0,0,3,3,0,2,3,0,3,0,3,3,3,0,0,3,0,3,0,2,2,3,3,0,0, 0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,0,3,2,3,3,3,3,0,3,3,3,3,3,0,3,3,2,3,2,3,3,2,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,2,3,2,3,3,3,3,3,3,0,2,3,2,3,2,2,2,3,2,3,3,2,3,0,2,2,2,3,0, 2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,0,3,3,3,2,3,3,0,0,3,0,3,0,0,0,3,2,0,3,0,3,0,0,2,0,2,0, 0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,0,0,0,3,3,0,3,3,3,0,0,1,2,3,0, 3,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,2,0,0,3,2,2,3,3,0,3,3,3,3,3,2,1,3,0,3,2,3,3,2,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,3,0,2,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,3,0,3,2,3,0,0,3,3,3,0, 3,0,0,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,0,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,2,0,3,2,3,0,0,3,2,3,0, 2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,1,2,2,3,3,3,3,3,3,0,2,3,0,3,0,0,0,3,3,0,3,0,2,0,0,2,3,1,0, 2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,3,0,3,0,3,3,2,3,0,3,3,3,3,3,3,0,3,3,3,0,2,3,0,0,3,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,0,0,3,0,0,0,3,3,0,3,0,2,3,3,0,0,3,0,3,0,3,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,0,3,3,3,3,3,3,0,0,3,0,2,0,0,0,3,3,0,3,0,3,0,0,2,0,2,0, 0,0,0,0,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,3,0,3,0,2,0,3,2,0,3,2,3,2,3,0,0,3,2,3,2,3,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,2,3,3,3,3,3,0,0,0,3,0,2,1,0,0,3,2,2,2,0,3,0,0,2,2,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,2,0,3,0,3,0,3,3,0,2,1,2,3,3,0,0,3,0,3,0,3,3,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,3,3,3,0,3,3,3,3,3,3,0,2,3,0,3,0,0,0,2,1,0,2,2,3,0,0,2,2,2,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,2,3,3,3,2,3,0,0,1,3,0,2,0,0,0,0,3,0,1,0,2,0,0,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,1,0,3,0,0,0,3,2,0,3,2,3,3,3,0,0,3,0,3,2,2,2,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,3,3,0,0,3,0,0,0,0,2,0,2,3,3,2,2,2,2,3,0,2,0,2,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,2,0,0,0,0,0,0,2,3,0,2,0,2,3,2,0,0,3,0,3,0,3,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,3,2,3,3,2,2,3,0,2,0,3,0,0,0,2,0,0,0,0,1,2,0,2,0,2,0, 0,2,0,2,0,2,2,0,0,1,0,2,2,2,0,2,2,2,0,2,2,2,0,0,2,0,0,1,0,0,0,0, 0,2,0,3,3,2,0,0,0,0,0,0,1,3,0,2,0,2,2,2,0,0,2,0,3,0,0,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,2,3,2,0,2,2,0,2,0,2,2,0,2,0,2,2,2,0,0,0,0,0,0,2,3,0,0,0,2, 0,1,2,0,0,0,0,2,2,0,0,0,2,1,0,2,2,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0, 0,0,2,1,0,2,3,2,2,3,2,3,2,0,0,3,3,3,0,0,3,2,0,0,0,1,1,0,2,0,2,2, 0,2,0,2,0,2,2,0,0,2,0,2,2,2,0,2,2,2,2,0,0,2,0,0,0,2,0,1,0,0,0,0, 0,3,0,3,3,2,2,0,3,0,0,0,2,2,0,2,2,2,1,2,0,0,1,2,2,0,0,3,0,0,0,2, 0,1,2,0,0,0,1,2,0,0,0,0,0,0,0,2,2,0,1,0,0,2,0,0,0,2,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,3,3,2,2,0,0,0,2,0,2,3,3,0,2,0,0,0,0,0,0,2,2,2,0,2,2,0,2,0,2, 0,2,2,0,0,2,2,2,2,1,0,0,2,2,0,2,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0, 0,2,0,3,2,3,0,0,0,3,0,0,2,2,0,2,0,2,2,2,0,0,2,0,0,0,0,0,0,0,0,2, 0,0,2,2,0,0,2,2,2,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,3,2,0,2,2,2,2,2,0,0,0,2,0,0,0,0,2,0,1,0,0,2,0,1,0,0,0, 0,2,2,2,0,2,2,0,1,2,0,2,2,2,0,2,2,2,2,1,2,2,0,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,2,0,2,0,2,2,0,0,0,0,1,2,1,0,0,2,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,3,2,3,0,0,2,0,0,0,2,2,0,2,0,0,0,1,0,0,2,0,2,0,2,2,0,0,0,0, 0,0,2,0,0,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0, 0,2,2,3,2,2,0,0,0,0,0,0,1,3,0,2,0,2,2,0,0,0,1,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,2,0,3,2,0,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,2,0,0,0,0,1,1,0,0,2,1,2,0,2,2,0,1,0,0,1,0,0,0,2,0,0,0,0,0,0, 0,3,0,2,2,2,0,0,2,0,0,0,2,0,0,0,2,3,0,2,0,0,0,0,0,0,2,2,0,0,0,2, 0,1,2,0,0,0,1,2,2,1,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,1,2,0,2,2,0,2,0,0,2,0,0,0,0,1,2,1,0,2,1,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,0,3,1,2,2,0,2,0,0,0,0,2,0,0,0,2,0,0,3,0,0,0,0,2,2,2,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,1,0,2,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,2, 0,2,2,0,0,2,2,2,2,2,0,1,2,0,0,0,2,2,0,1,0,2,0,0,2,2,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,2, 0,1,2,0,0,0,0,2,2,1,0,1,0,1,0,2,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0, 0,2,0,1,2,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,0,0,0,0,1,0,0,0,0,0,0,2, 0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0, 0,2,2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,1, 0,0,2,0,0,0,0,1,2,0,0,0,0,0,0,2,2,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0, 0,2,0,2,2,2,0,0,2,0,0,0,0,0,0,0,2,2,2,0,0,0,2,0,0,0,0,0,0,0,0,2, 0,0,1,0,0,0,0,2,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,3,0,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,2, 0,0,2,0,0,0,0,2,2,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,2,2,1,0,0,0,0,0,0,2,0,0,2,0,2,2,2,0,0,0,0,0,0,2,0,0,0,0,2, 0,0,2,0,0,2,0,2,2,0,0,0,0,2,0,2,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0, 0,0,3,0,0,0,2,2,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0, 0,2,2,2,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1, 0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,2,0,0,0,2,0,0,0,0,0,1,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,2,0,0,0, 0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,2,0,2,0,0,0, 0,0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,2,0,0,0,1,2,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, ) Latin7GreekModel = { 'charToOrderMap': Latin7_CharToOrderMap, 'precedenceMatrix': GreekLangModel, 'mTypicalPositiveRatio': 0.982851, 'keepEnglishLetter': False, 'charsetName': "ISO-8859-7" } Win1253GreekModel = { 'charToOrderMap': win1253_CharToOrderMap, 'precedenceMatrix': GreekLangModel, 'mTypicalPositiveRatio': 0.982851, 'keepEnglishLetter': False, 'charsetName': "windows-1253" } # flake8: noqa
{ "pile_set_name": "Github" }
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package proc import ( "time" ) // Action is something that executes in the context of a process type Action func() type Context interface { // end (terminate) the execution context End() <-chan struct{} // return a signal chan that will close upon the termination of this process Done() <-chan struct{} } type Doer interface { // execute some action in some context. actions are to be executed in a // concurrency-safe manner: no two actions should execute at the same time. // errors are generated if the action cannot be executed (not by the execution // of the action) and should be testable with the error API of this package, // for example, IsProcessTerminated. Do(Action) <-chan error } // DoerFunc is an adapter func for Doer interface type DoerFunc func(Action) <-chan error // invoke the f on action a. returns an illegal state error if f is nil. func (f DoerFunc) Do(a Action) <-chan error { if f != nil { return f(a) } return ErrorChan(errIllegalState) } type Process interface { Context Doer // see top level OnError func. this implementation will terminate upon the arrival of // an error (and subsequently invoke the error handler, if given) or else the termination // of the process (testable via IsProcessTerminated). OnError(<-chan error, func(error)) <-chan struct{} // return a signal chan that will close once the process is ready to run actions Running() <-chan struct{} } // ErrorOnce an error promise. If we ever start building out support for other promise types it will probably // make sense to group them in some sort of "promises" package. type ErrorOnce interface { // Err returns a chan that only ever sends one error, either obtained via Report() or Forward(). Err() <-chan error // Report reports the given error via Err(), but only if no other errors have been reported or forwarded. Report(error) // Report reports an error via Err(), but only if no other errors have been reported or forwarded, using // fmt.Errorf to generate the error. Reportf(string, ...interface{}) // forward waits for an error on the incoming chan, the result of which is later obtained via Err() (if no // other errors have been reported or forwarded). forward(<-chan error) // Send is non-blocking; it spins up a goroutine that reports an error (if any) that occurs on the error chan. Send(<-chan error) ErrorOnce // WaitFor returns true if an error is received within the specified duration, otherwise false WaitFor(time.Duration) (error, bool) }
{ "pile_set_name": "Github" }
var SetCache = require('./_SetCache'), arrayIncludes = require('./_arrayIncludes'), arrayIncludesWith = require('./_arrayIncludesWith'), cacheHas = require('./_cacheHas'), createSet = require('./_createSet'), setToArray = require('./_setToArray'); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseUniq;
{ "pile_set_name": "Github" }
/* * 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. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package jdk.internal.org.objectweb.asm; /** * A {@link ClassVisitor} that generates classes in bytecode form. More * precisely this visitor generates a byte array conforming to the Java class * file format. It can be used alone, to generate a Java class "from scratch", * or with one or more {@link ClassReader ClassReader} and adapter class visitor * to generate a modified class from one or more existing Java classes. * * @author Eric Bruneton */ public class ClassWriter extends ClassVisitor { /** * Flag to automatically compute the maximum stack size and the maximum * number of local variables of methods. If this flag is set, then the * arguments of the {@link MethodVisitor#visitMaxs visitMaxs} method of the * {@link MethodVisitor} returned by the {@link #visitMethod visitMethod} * method will be ignored, and computed automatically from the signature and * the bytecode of each method. * * @see #ClassWriter(int) */ public static final int COMPUTE_MAXS = 1; /** * Flag to automatically compute the stack map frames of methods from * scratch. If this flag is set, then the calls to the * {@link MethodVisitor#visitFrame} method are ignored, and the stack map * frames are recomputed from the methods bytecode. The arguments of the * {@link MethodVisitor#visitMaxs visitMaxs} method are also ignored and * recomputed from the bytecode. In other words, computeFrames implies * computeMaxs. * * @see #ClassWriter(int) */ public static final int COMPUTE_FRAMES = 2; /** * Pseudo access flag to distinguish between the synthetic attribute and the * synthetic access flag. */ static final int ACC_SYNTHETIC_ATTRIBUTE = 0x40000; /** * Factor to convert from ACC_SYNTHETIC_ATTRIBUTE to Opcode.ACC_SYNTHETIC. */ static final int TO_ACC_SYNTHETIC = ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC; /** * The type of instructions without any argument. */ static final int NOARG_INSN = 0; /** * The type of instructions with an signed byte argument. */ static final int SBYTE_INSN = 1; /** * The type of instructions with an signed short argument. */ static final int SHORT_INSN = 2; /** * The type of instructions with a local variable index argument. */ static final int VAR_INSN = 3; /** * The type of instructions with an implicit local variable index argument. */ static final int IMPLVAR_INSN = 4; /** * The type of instructions with a type descriptor argument. */ static final int TYPE_INSN = 5; /** * The type of field and method invocations instructions. */ static final int FIELDORMETH_INSN = 6; /** * The type of the INVOKEINTERFACE/INVOKEDYNAMIC instruction. */ static final int ITFMETH_INSN = 7; /** * The type of the INVOKEDYNAMIC instruction. */ static final int INDYMETH_INSN = 8; /** * The type of instructions with a 2 bytes bytecode offset label. */ static final int LABEL_INSN = 9; /** * The type of instructions with a 4 bytes bytecode offset label. */ static final int LABELW_INSN = 10; /** * The type of the LDC instruction. */ static final int LDC_INSN = 11; /** * The type of the LDC_W and LDC2_W instructions. */ static final int LDCW_INSN = 12; /** * The type of the IINC instruction. */ static final int IINC_INSN = 13; /** * The type of the TABLESWITCH instruction. */ static final int TABL_INSN = 14; /** * The type of the LOOKUPSWITCH instruction. */ static final int LOOK_INSN = 15; /** * The type of the MULTIANEWARRAY instruction. */ static final int MANA_INSN = 16; /** * The type of the WIDE instruction. */ static final int WIDE_INSN = 17; /** * The instruction types of all JVM opcodes. */ static final byte[] TYPE; /** * The type of CONSTANT_Class constant pool items. */ static final int CLASS = 7; /** * The type of CONSTANT_Fieldref constant pool items. */ static final int FIELD = 9; /** * The type of CONSTANT_Methodref constant pool items. */ static final int METH = 10; /** * The type of CONSTANT_InterfaceMethodref constant pool items. */ static final int IMETH = 11; /** * The type of CONSTANT_String constant pool items. */ static final int STR = 8; /** * The type of CONSTANT_Integer constant pool items. */ static final int INT = 3; /** * The type of CONSTANT_Float constant pool items. */ static final int FLOAT = 4; /** * The type of CONSTANT_Long constant pool items. */ static final int LONG = 5; /** * The type of CONSTANT_Double constant pool items. */ static final int DOUBLE = 6; /** * The type of CONSTANT_NameAndType constant pool items. */ static final int NAME_TYPE = 12; /** * The type of CONSTANT_Utf8 constant pool items. */ static final int UTF8 = 1; /** * The type of CONSTANT_MethodType constant pool items. */ static final int MTYPE = 16; /** * The type of CONSTANT_MethodHandle constant pool items. */ static final int HANDLE = 15; /** * The type of CONSTANT_InvokeDynamic constant pool items. */ static final int INDY = 18; /** * The base value for all CONSTANT_MethodHandle constant pool items. * Internally, ASM store the 9 variations of CONSTANT_MethodHandle into 9 * different items. */ static final int HANDLE_BASE = 20; /** * Normal type Item stored in the ClassWriter {@link ClassWriter#typeTable}, * instead of the constant pool, in order to avoid clashes with normal * constant pool items in the ClassWriter constant pool's hash table. */ static final int TYPE_NORMAL = 30; /** * Uninitialized type Item stored in the ClassWriter * {@link ClassWriter#typeTable}, instead of the constant pool, in order to * avoid clashes with normal constant pool items in the ClassWriter constant * pool's hash table. */ static final int TYPE_UNINIT = 31; /** * Merged type Item stored in the ClassWriter {@link ClassWriter#typeTable}, * instead of the constant pool, in order to avoid clashes with normal * constant pool items in the ClassWriter constant pool's hash table. */ static final int TYPE_MERGED = 32; /** * The type of BootstrapMethods items. These items are stored in a special * class attribute named BootstrapMethods and not in the constant pool. */ static final int BSM = 33; /** * The class reader from which this class writer was constructed, if any. */ ClassReader cr; /** * Minor and major version numbers of the class to be generated. */ int version; /** * Index of the next item to be added in the constant pool. */ int index; /** * The constant pool of this class. */ final ByteVector pool; /** * The constant pool's hash table data. */ Item[] items; /** * The threshold of the constant pool's hash table. */ int threshold; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key2; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key3; /** * A reusable key used to look for items in the {@link #items} hash table. */ final Item key4; /** * A type table used to temporarily store internal names that will not * necessarily be stored in the constant pool. This type table is used by * the control flow and data flow analysis algorithm used to compute stack * map frames from scratch. This array associates to each index <tt>i</tt> * the Item whose index is <tt>i</tt>. All Item objects stored in this array * are also stored in the {@link #items} hash table. These two arrays allow * to retrieve an Item from its index or, conversely, to get the index of an * Item from its value. Each Item stores an internal name in its * {@link Item#strVal1} field. */ Item[] typeTable; /** * Number of elements in the {@link #typeTable} array. */ private short typeCount; /** * The access flags of this class. */ private int access; /** * The constant pool item that contains the internal name of this class. */ private int name; /** * The internal name of this class. */ String thisName; /** * The constant pool item that contains the signature of this class. */ private int signature; /** * The constant pool item that contains the internal name of the super class * of this class. */ private int superName; /** * Number of interfaces implemented or extended by this class or interface. */ private int interfaceCount; /** * The interfaces implemented or extended by this class or interface. More * precisely, this array contains the indexes of the constant pool items * that contain the internal names of these interfaces. */ private int[] interfaces; /** * The index of the constant pool item that contains the name of the source * file from which this class was compiled. */ private int sourceFile; /** * The SourceDebug attribute of this class. */ private ByteVector sourceDebug; /** * The constant pool item that contains the name of the enclosing class of * this class. */ private int enclosingMethodOwner; /** * The constant pool item that contains the name and descriptor of the * enclosing method of this class. */ private int enclosingMethod; /** * The runtime visible annotations of this class. */ private AnnotationWriter anns; /** * The runtime invisible annotations of this class. */ private AnnotationWriter ianns; /** * The runtime visible type annotations of this class. */ private AnnotationWriter tanns; /** * The runtime invisible type annotations of this class. */ private AnnotationWriter itanns; /** * The non standard attributes of this class. */ private Attribute attrs; /** * The number of entries in the InnerClasses attribute. */ private int innerClassesCount; /** * The InnerClasses attribute. */ private ByteVector innerClasses; /** * The number of entries in the BootstrapMethods attribute. */ int bootstrapMethodsCount; /** * The BootstrapMethods attribute. */ ByteVector bootstrapMethods; /** * The fields of this class. These fields are stored in a linked list of * {@link FieldWriter} objects, linked to each other by their * {@link FieldWriter#fv} field. This field stores the first element of this * list. */ FieldWriter firstField; /** * The fields of this class. These fields are stored in a linked list of * {@link FieldWriter} objects, linked to each other by their * {@link FieldWriter#fv} field. This field stores the last element of this * list. */ FieldWriter lastField; /** * The methods of this class. These methods are stored in a linked list of * {@link MethodWriter} objects, linked to each other by their * {@link MethodWriter#mv} field. This field stores the first element of * this list. */ MethodWriter firstMethod; /** * The methods of this class. These methods are stored in a linked list of * {@link MethodWriter} objects, linked to each other by their * {@link MethodWriter#mv} field. This field stores the last element of this * list. */ MethodWriter lastMethod; /** * <tt>true</tt> if the maximum stack size and number of local variables * must be automatically computed. */ private boolean computeMaxs; /** * <tt>true</tt> if the stack map frames must be recomputed from scratch. */ private boolean computeFrames; /** * <tt>true</tt> if the stack map tables of this class are invalid. The * {@link MethodWriter#resizeInstructions} method cannot transform existing * stack map tables, and so produces potentially invalid classes when it is * executed. In this case the class is reread and rewritten with the * {@link #COMPUTE_FRAMES} option (the resizeInstructions method can resize * stack map tables when this option is used). */ boolean invalidFrames; // ------------------------------------------------------------------------ // Static initializer // ------------------------------------------------------------------------ /** * Computes the instruction types of JVM opcodes. */ static { int i; byte[] b = new byte[220]; String s = "AAAAAAAAAAAAAAAABCLMMDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADD" + "DDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAANAAAAAAAAAAAAAAAAAAAAJJJJJJJJJJJJJJJJDOPAA" + "AAAAGGGGGGGHIFBFAAFFAARQJJKKJJJJJJJJJJJJJJJJJJ"; for (i = 0; i < b.length; ++i) { b[i] = (byte) (s.charAt(i) - 'A'); } TYPE = b; // code to generate the above string // // // SBYTE_INSN instructions // b[Constants.NEWARRAY] = SBYTE_INSN; // b[Constants.BIPUSH] = SBYTE_INSN; // // // SHORT_INSN instructions // b[Constants.SIPUSH] = SHORT_INSN; // // // (IMPL)VAR_INSN instructions // b[Constants.RET] = VAR_INSN; // for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) { // b[i] = VAR_INSN; // } // for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) { // b[i] = VAR_INSN; // } // for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3 // b[i] = IMPLVAR_INSN; // } // for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3 // b[i] = IMPLVAR_INSN; // } // // // TYPE_INSN instructions // b[Constants.NEW] = TYPE_INSN; // b[Constants.ANEWARRAY] = TYPE_INSN; // b[Constants.CHECKCAST] = TYPE_INSN; // b[Constants.INSTANCEOF] = TYPE_INSN; // // // (Set)FIELDORMETH_INSN instructions // for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) { // b[i] = FIELDORMETH_INSN; // } // b[Constants.INVOKEINTERFACE] = ITFMETH_INSN; // b[Constants.INVOKEDYNAMIC] = INDYMETH_INSN; // // // LABEL(W)_INSN instructions // for (i = Constants.IFEQ; i <= Constants.JSR; ++i) { // b[i] = LABEL_INSN; // } // b[Constants.IFNULL] = LABEL_INSN; // b[Constants.IFNONNULL] = LABEL_INSN; // b[200] = LABELW_INSN; // GOTO_W // b[201] = LABELW_INSN; // JSR_W // // temporary opcodes used internally by ASM - see Label and // MethodWriter // for (i = 202; i < 220; ++i) { // b[i] = LABEL_INSN; // } // // // LDC(_W) instructions // b[Constants.LDC] = LDC_INSN; // b[19] = LDCW_INSN; // LDC_W // b[20] = LDCW_INSN; // LDC2_W // // // special instructions // b[Constants.IINC] = IINC_INSN; // b[Constants.TABLESWITCH] = TABL_INSN; // b[Constants.LOOKUPSWITCH] = LOOK_INSN; // b[Constants.MULTIANEWARRAY] = MANA_INSN; // b[196] = WIDE_INSN; // WIDE // // for (i = 0; i < b.length; ++i) { // System.err.print((char)('A' + b[i])); // } // System.err.println(); } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new {@link ClassWriter} object. * * @param flags * option flags that can be used to modify the default behavior * of this class. See {@link #COMPUTE_MAXS}, * {@link #COMPUTE_FRAMES}. */ public ClassWriter(final int flags) { super(Opcodes.ASM5); index = 1; pool = new ByteVector(); items = new Item[256]; threshold = (int) (0.75d * items.length); key = new Item(); key2 = new Item(); key3 = new Item(); key4 = new Item(); this.computeMaxs = (flags & COMPUTE_MAXS) != 0; this.computeFrames = (flags & COMPUTE_FRAMES) != 0; } /** * Constructs a new {@link ClassWriter} object and enables optimizations for * "mostly add" bytecode transformations. These optimizations are the * following: * * <ul> * <li>The constant pool from the original class is copied as is in the new * class, which saves time. New constant pool entries will be added at the * end if necessary, but unused constant pool entries <i>won't be * removed</i>.</li> * <li>Methods that are not transformed are copied as is in the new class, * directly from the original class bytecode (i.e. without emitting visit * events for all the method instructions), which saves a <i>lot</i> of * time. Untransformed methods are detected by the fact that the * {@link ClassReader} receives {@link MethodVisitor} objects that come from * a {@link ClassWriter} (and not from any other {@link ClassVisitor} * instance).</li> * </ul> * * @param classReader * the {@link ClassReader} used to read the original class. It * will be used to copy the entire constant pool from the * original class and also to copy other fragments of original * bytecode where applicable. * @param flags * option flags that can be used to modify the default behavior * of this class. <i>These option flags do not affect methods * that are copied as is in the new class. This means that the * maximum stack size nor the stack frames will be computed for * these methods</i>. See {@link #COMPUTE_MAXS}, * {@link #COMPUTE_FRAMES}. */ public ClassWriter(final ClassReader classReader, final int flags) { this(flags); classReader.copyPool(this); this.cr = classReader; } // ------------------------------------------------------------------------ // Implementation of the ClassVisitor abstract class // ------------------------------------------------------------------------ @Override public final void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { this.version = version; this.access = access; this.name = newClass(name); thisName = name; if (ClassReader.SIGNATURES && signature != null) { this.signature = newUTF8(signature); } this.superName = superName == null ? 0 : newClass(superName); if (interfaces != null && interfaces.length > 0) { interfaceCount = interfaces.length; this.interfaces = new int[interfaceCount]; for (int i = 0; i < interfaceCount; ++i) { this.interfaces[i] = newClass(interfaces[i]); } } } @Override public final void visitSource(final String file, final String debug) { if (file != null) { sourceFile = newUTF8(file); } if (debug != null) { sourceDebug = new ByteVector().encodeUTF8(debug, 0, Integer.MAX_VALUE); } } @Override public final void visitOuterClass(final String owner, final String name, final String desc) { enclosingMethodOwner = newClass(owner); if (name != null && desc != null) { enclosingMethod = newNameType(name, desc); } } @Override public final AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write type, and reserve space for values count bv.putShort(newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv, 2); if (visible) { aw.next = anns; anns = aw; } else { aw.next = ianns; ianns = aw; } return aw; } @Override public final AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write target_type and target_info AnnotationWriter.putTarget(typeRef, typePath, bv); // write type, and reserve space for values count bv.putShort(newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv, bv.length - 2); if (visible) { aw.next = tanns; tanns = aw; } else { aw.next = itanns; itanns = aw; } return aw; } @Override public final void visitAttribute(final Attribute attr) { attr.next = attrs; attrs = attr; } @Override public final void visitInnerClass(final String name, final String outerName, final String innerName, final int access) { if (innerClasses == null) { innerClasses = new ByteVector(); } // Sec. 4.7.6 of the JVMS states "Every CONSTANT_Class_info entry in the // constant_pool table which represents a class or interface C that is // not a package member must have exactly one corresponding entry in the // classes array". To avoid duplicates we keep track in the intVal field // of the Item of each CONSTANT_Class_info entry C whether an inner // class entry has already been added for C (this field is unused for // class entries, and changing its value does not change the hashcode // and equality tests). If so we store the index of this inner class // entry (plus one) in intVal. This hack allows duplicate detection in // O(1) time. Item nameItem = newClassItem(name); if (nameItem.intVal == 0) { ++innerClassesCount; innerClasses.putShort(nameItem.index); innerClasses.putShort(outerName == null ? 0 : newClass(outerName)); innerClasses.putShort(innerName == null ? 0 : newUTF8(innerName)); innerClasses.putShort(access); nameItem.intVal = innerClassesCount; } else { // Compare the inner classes entry nameItem.intVal - 1 with the // arguments of this method and throw an exception if there is a // difference? } } @Override public final FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) { return new FieldWriter(this, access, name, desc, signature, value); } @Override public final MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { return new MethodWriter(this, access, name, desc, signature, exceptions, computeMaxs, computeFrames); } @Override public final void visitEnd() { } // ------------------------------------------------------------------------ // Other public methods // ------------------------------------------------------------------------ /** * Returns the bytecode of the class that was build with this class writer. * * @return the bytecode of the class that was build with this class writer. */ public byte[] toByteArray() { if (index > 0xFFFF) { throw new RuntimeException("Class file too large!"); } // computes the real size of the bytecode of this class int size = 24 + 2 * interfaceCount; int nbFields = 0; FieldWriter fb = firstField; while (fb != null) { ++nbFields; size += fb.getSize(); fb = (FieldWriter) fb.fv; } int nbMethods = 0; MethodWriter mb = firstMethod; while (mb != null) { ++nbMethods; size += mb.getSize(); mb = (MethodWriter) mb.mv; } int attributeCount = 0; if (bootstrapMethods != null) { // we put it as first attribute in order to improve a bit // ClassReader.copyBootstrapMethods ++attributeCount; size += 8 + bootstrapMethods.length; newUTF8("BootstrapMethods"); } if (ClassReader.SIGNATURES && signature != 0) { ++attributeCount; size += 8; newUTF8("Signature"); } if (sourceFile != 0) { ++attributeCount; size += 8; newUTF8("SourceFile"); } if (sourceDebug != null) { ++attributeCount; size += sourceDebug.length + 6; newUTF8("SourceDebugExtension"); } if (enclosingMethodOwner != 0) { ++attributeCount; size += 10; newUTF8("EnclosingMethod"); } if ((access & Opcodes.ACC_DEPRECATED) != 0) { ++attributeCount; size += 6; newUTF8("Deprecated"); } if ((access & Opcodes.ACC_SYNTHETIC) != 0) { if ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0) { ++attributeCount; size += 6; newUTF8("Synthetic"); } } if (innerClasses != null) { ++attributeCount; size += 8 + innerClasses.length; newUTF8("InnerClasses"); } if (ClassReader.ANNOTATIONS && anns != null) { ++attributeCount; size += 8 + anns.getSize(); newUTF8("RuntimeVisibleAnnotations"); } if (ClassReader.ANNOTATIONS && ianns != null) { ++attributeCount; size += 8 + ianns.getSize(); newUTF8("RuntimeInvisibleAnnotations"); } if (ClassReader.ANNOTATIONS && tanns != null) { ++attributeCount; size += 8 + tanns.getSize(); newUTF8("RuntimeVisibleTypeAnnotations"); } if (ClassReader.ANNOTATIONS && itanns != null) { ++attributeCount; size += 8 + itanns.getSize(); newUTF8("RuntimeInvisibleTypeAnnotations"); } if (attrs != null) { attributeCount += attrs.getCount(); size += attrs.getSize(this, null, 0, -1, -1); } size += pool.length; // allocates a byte vector of this size, in order to avoid unnecessary // arraycopy operations in the ByteVector.enlarge() method ByteVector out = new ByteVector(size); out.putInt(0xCAFEBABE).putInt(version); out.putShort(index).putByteArray(pool.data, 0, pool.length); int mask = Opcodes.ACC_DEPRECATED | ACC_SYNTHETIC_ATTRIBUTE | ((access & ACC_SYNTHETIC_ATTRIBUTE) / TO_ACC_SYNTHETIC); out.putShort(access & ~mask).putShort(name).putShort(superName); out.putShort(interfaceCount); for (int i = 0; i < interfaceCount; ++i) { out.putShort(interfaces[i]); } out.putShort(nbFields); fb = firstField; while (fb != null) { fb.put(out); fb = (FieldWriter) fb.fv; } out.putShort(nbMethods); mb = firstMethod; while (mb != null) { mb.put(out); mb = (MethodWriter) mb.mv; } out.putShort(attributeCount); if (bootstrapMethods != null) { out.putShort(newUTF8("BootstrapMethods")); out.putInt(bootstrapMethods.length + 2).putShort( bootstrapMethodsCount); out.putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length); } if (ClassReader.SIGNATURES && signature != 0) { out.putShort(newUTF8("Signature")).putInt(2).putShort(signature); } if (sourceFile != 0) { out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile); } if (sourceDebug != null) { int len = sourceDebug.length; out.putShort(newUTF8("SourceDebugExtension")).putInt(len); out.putByteArray(sourceDebug.data, 0, len); } if (enclosingMethodOwner != 0) { out.putShort(newUTF8("EnclosingMethod")).putInt(4); out.putShort(enclosingMethodOwner).putShort(enclosingMethod); } if ((access & Opcodes.ACC_DEPRECATED) != 0) { out.putShort(newUTF8("Deprecated")).putInt(0); } if ((access & Opcodes.ACC_SYNTHETIC) != 0) { if ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0) { out.putShort(newUTF8("Synthetic")).putInt(0); } } if (innerClasses != null) { out.putShort(newUTF8("InnerClasses")); out.putInt(innerClasses.length + 2).putShort(innerClassesCount); out.putByteArray(innerClasses.data, 0, innerClasses.length); } if (ClassReader.ANNOTATIONS && anns != null) { out.putShort(newUTF8("RuntimeVisibleAnnotations")); anns.put(out); } if (ClassReader.ANNOTATIONS && ianns != null) { out.putShort(newUTF8("RuntimeInvisibleAnnotations")); ianns.put(out); } if (ClassReader.ANNOTATIONS && tanns != null) { out.putShort(newUTF8("RuntimeVisibleTypeAnnotations")); tanns.put(out); } if (ClassReader.ANNOTATIONS && itanns != null) { out.putShort(newUTF8("RuntimeInvisibleTypeAnnotations")); itanns.put(out); } if (attrs != null) { attrs.put(this, null, 0, -1, -1, out); } if (invalidFrames) { anns = null; ianns = null; attrs = null; innerClassesCount = 0; innerClasses = null; bootstrapMethodsCount = 0; bootstrapMethods = null; firstField = null; lastField = null; firstMethod = null; lastMethod = null; computeMaxs = false; computeFrames = true; invalidFrames = false; new ClassReader(out.data).accept(this, ClassReader.SKIP_FRAMES); return toByteArray(); } return out.data; } // ------------------------------------------------------------------------ // Utility methods: constant pool management // ------------------------------------------------------------------------ /** * Adds a number or string constant to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. * * @param cst * the value of the constant to be added to the constant pool. * This parameter must be an {@link Integer}, a {@link Float}, a * {@link Long}, a {@link Double}, a {@link String} or a * {@link Type}. * @return a new or already existing constant item with the given value. */ Item newConstItem(final Object cst) { if (cst instanceof Integer) { int val = ((Integer) cst).intValue(); return newInteger(val); } else if (cst instanceof Byte) { int val = ((Byte) cst).intValue(); return newInteger(val); } else if (cst instanceof Character) { int val = ((Character) cst).charValue(); return newInteger(val); } else if (cst instanceof Short) { int val = ((Short) cst).intValue(); return newInteger(val); } else if (cst instanceof Boolean) { int val = ((Boolean) cst).booleanValue() ? 1 : 0; return newInteger(val); } else if (cst instanceof Float) { float val = ((Float) cst).floatValue(); return newFloat(val); } else if (cst instanceof Long) { long val = ((Long) cst).longValue(); return newLong(val); } else if (cst instanceof Double) { double val = ((Double) cst).doubleValue(); return newDouble(val); } else if (cst instanceof String) { return newString((String) cst); } else if (cst instanceof Type) { Type t = (Type) cst; int s = t.getSort(); if (s == Type.OBJECT) { return newClassItem(t.getInternalName()); } else if (s == Type.METHOD) { return newMethodTypeItem(t.getDescriptor()); } else { // s == primitive type or array return newClassItem(t.getDescriptor()); } } else if (cst instanceof Handle) { Handle h = (Handle) cst; return newHandleItem(h.tag, h.owner, h.name, h.desc); } else { throw new IllegalArgumentException("value " + cst); } } /** * Adds a number or string constant to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param cst * the value of the constant to be added to the constant pool. * This parameter must be an {@link Integer}, a {@link Float}, a * {@link Long}, a {@link Double} or a {@link String}. * @return the index of a new or already existing constant item with the * given value. */ public int newConst(final Object cst) { return newConstItem(cst).index; } /** * Adds an UTF8 string to the constant pool of the class being build. Does * nothing if the constant pool already contains a similar item. <i>This * method is intended for {@link Attribute} sub classes, and is normally not * needed by class generators or adapters.</i> * * @param value * the String value. * @return the index of a new or already existing UTF8 item. */ public int newUTF8(final String value) { key.set(UTF8, value, null, null); Item result = get(key); if (result == null) { pool.putByte(UTF8).putUTF8(value); result = new Item(index++, key); put(result); } return result.index; } /** * Adds a class reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param value * the internal name of the class. * @return a new or already existing class reference item. */ Item newClassItem(final String value) { key2.set(CLASS, value, null, null); Item result = get(key2); if (result == null) { pool.put12(CLASS, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; } /** * Adds a class reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param value * the internal name of the class. * @return the index of a new or already existing class reference item. */ public int newClass(final String value) { return newClassItem(value).index; } /** * Adds a method type reference to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param methodDesc * method descriptor of the method type. * @return a new or already existing method type reference item. */ Item newMethodTypeItem(final String methodDesc) { key2.set(MTYPE, methodDesc, null, null); Item result = get(key2); if (result == null) { pool.put12(MTYPE, newUTF8(methodDesc)); result = new Item(index++, key2); put(result); } return result; } /** * Adds a method type reference to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param methodDesc * method descriptor of the method type. * @return the index of a new or already existing method type reference * item. */ public int newMethodType(final String methodDesc) { return newMethodTypeItem(methodDesc).index; } /** * Adds a handle to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. <i>This method is * intended for {@link Attribute} sub classes, and is normally not needed by * class generators or adapters.</i> * * @param tag * the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, * {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, * {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, * {@link Opcodes#H_INVOKESTATIC}, * {@link Opcodes#H_INVOKESPECIAL}, * {@link Opcodes#H_NEWINVOKESPECIAL} or * {@link Opcodes#H_INVOKEINTERFACE}. * @param owner * the internal name of the field or method owner class. * @param name * the name of the field or method. * @param desc * the descriptor of the field or method. * @return a new or an already existing method type reference item. */ Item newHandleItem(final int tag, final String owner, final String name, final String desc) { key4.set(HANDLE_BASE + tag, owner, name, desc); Item result = get(key4); if (result == null) { if (tag <= Opcodes.H_PUTSTATIC) { put112(HANDLE, tag, newField(owner, name, desc)); } else { put112(HANDLE, tag, newMethod(owner, name, desc, tag == Opcodes.H_INVOKEINTERFACE)); } result = new Item(index++, key4); put(result); } return result; } /** * Adds a handle to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. <i>This method is * intended for {@link Attribute} sub classes, and is normally not needed by * class generators or adapters.</i> * * @param tag * the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, * {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, * {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, * {@link Opcodes#H_INVOKESTATIC}, * {@link Opcodes#H_INVOKESPECIAL}, * {@link Opcodes#H_NEWINVOKESPECIAL} or * {@link Opcodes#H_INVOKEINTERFACE}. * @param owner * the internal name of the field or method owner class. * @param name * the name of the field or method. * @param desc * the descriptor of the field or method. * @return the index of a new or already existing method type reference * item. */ public int newHandle(final int tag, final String owner, final String name, final String desc) { return newHandleItem(tag, owner, name, desc).index; } /** * Adds an invokedynamic reference to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param name * name of the invoked method. * @param desc * descriptor of the invoke method. * @param bsm * the bootstrap method. * @param bsmArgs * the bootstrap method constant arguments. * * @return a new or an already existing invokedynamic type reference item. */ Item newInvokeDynamicItem(final String name, final String desc, final Handle bsm, final Object... bsmArgs) { // cache for performance ByteVector bootstrapMethods = this.bootstrapMethods; if (bootstrapMethods == null) { bootstrapMethods = this.bootstrapMethods = new ByteVector(); } int position = bootstrapMethods.length; // record current position int hashCode = bsm.hashCode(); bootstrapMethods.putShort(newHandle(bsm.tag, bsm.owner, bsm.name, bsm.desc)); int argsLength = bsmArgs.length; bootstrapMethods.putShort(argsLength); for (int i = 0; i < argsLength; i++) { Object bsmArg = bsmArgs[i]; hashCode ^= bsmArg.hashCode(); bootstrapMethods.putShort(newConst(bsmArg)); } byte[] data = bootstrapMethods.data; int length = (1 + 1 + argsLength) << 1; // (bsm + argCount + arguments) hashCode &= 0x7FFFFFFF; Item result = items[hashCode % items.length]; loop: while (result != null) { if (result.type != BSM || result.hashCode != hashCode) { result = result.next; continue; } // because the data encode the size of the argument // we don't need to test if these size are equals int resultPosition = result.intVal; for (int p = 0; p < length; p++) { if (data[position + p] != data[resultPosition + p]) { result = result.next; continue loop; } } break; } int bootstrapMethodIndex; if (result != null) { bootstrapMethodIndex = result.index; bootstrapMethods.length = position; // revert to old position } else { bootstrapMethodIndex = bootstrapMethodsCount++; result = new Item(bootstrapMethodIndex); result.set(position, hashCode); put(result); } // now, create the InvokeDynamic constant key3.set(name, desc, bootstrapMethodIndex); result = get(key3); if (result == null) { put122(INDY, bootstrapMethodIndex, newNameType(name, desc)); result = new Item(index++, key3); put(result); } return result; } /** * Adds an invokedynamic reference to the constant pool of the class being * build. Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param name * name of the invoked method. * @param desc * descriptor of the invoke method. * @param bsm * the bootstrap method. * @param bsmArgs * the bootstrap method constant arguments. * * @return the index of a new or already existing invokedynamic reference * item. */ public int newInvokeDynamic(final String name, final String desc, final Handle bsm, final Object... bsmArgs) { return newInvokeDynamicItem(name, desc, bsm, bsmArgs).index; } /** * Adds a field reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * * @param owner * the internal name of the field's owner class. * @param name * the field's name. * @param desc * the field's descriptor. * @return a new or already existing field reference item. */ Item newFieldItem(final String owner, final String name, final String desc) { key3.set(FIELD, owner, name, desc); Item result = get(key3); if (result == null) { put122(FIELD, newClass(owner), newNameType(name, desc)); result = new Item(index++, key3); put(result); } return result; } /** * Adds a field reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param owner * the internal name of the field's owner class. * @param name * the field's name. * @param desc * the field's descriptor. * @return the index of a new or already existing field reference item. */ public int newField(final String owner, final String name, final String desc) { return newFieldItem(owner, name, desc).index; } /** * Adds a method reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * * @param owner * the internal name of the method's owner class. * @param name * the method's name. * @param desc * the method's descriptor. * @param itf * <tt>true</tt> if <tt>owner</tt> is an interface. * @return a new or already existing method reference item. */ Item newMethodItem(final String owner, final String name, final String desc, final boolean itf) { int type = itf ? IMETH : METH; key3.set(type, owner, name, desc); Item result = get(key3); if (result == null) { put122(type, newClass(owner), newNameType(name, desc)); result = new Item(index++, key3); put(result); } return result; } /** * Adds a method reference to the constant pool of the class being build. * Does nothing if the constant pool already contains a similar item. * <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param owner * the internal name of the method's owner class. * @param name * the method's name. * @param desc * the method's descriptor. * @param itf * <tt>true</tt> if <tt>owner</tt> is an interface. * @return the index of a new or already existing method reference item. */ public int newMethod(final String owner, final String name, final String desc, final boolean itf) { return newMethodItem(owner, name, desc, itf).index; } /** * Adds an integer to the constant pool of the class being build. Does * nothing if the constant pool already contains a similar item. * * @param value * the int value. * @return a new or already existing int item. */ Item newInteger(final int value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(INT).putInt(value); result = new Item(index++, key); put(result); } return result; } /** * Adds a float to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. * * @param value * the float value. * @return a new or already existing float item. */ Item newFloat(final float value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(FLOAT).putInt(key.intVal); result = new Item(index++, key); put(result); } return result; } /** * Adds a long to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. * * @param value * the long value. * @return a new or already existing long item. */ Item newLong(final long value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(LONG).putLong(value); result = new Item(index, key); index += 2; put(result); } return result; } /** * Adds a double to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. * * @param value * the double value. * @return a new or already existing double item. */ Item newDouble(final double value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(DOUBLE).putLong(key.longVal); result = new Item(index, key); index += 2; put(result); } return result; } /** * Adds a string to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. * * @param value * the String value. * @return a new or already existing string item. */ private Item newString(final String value) { key2.set(STR, value, null, null); Item result = get(key2); if (result == null) { pool.put12(STR, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; } /** * Adds a name and type to the constant pool of the class being build. Does * nothing if the constant pool already contains a similar item. <i>This * method is intended for {@link Attribute} sub classes, and is normally not * needed by class generators or adapters.</i> * * @param name * a name. * @param desc * a type descriptor. * @return the index of a new or already existing name and type item. */ public int newNameType(final String name, final String desc) { return newNameTypeItem(name, desc).index; } /** * Adds a name and type to the constant pool of the class being build. Does * nothing if the constant pool already contains a similar item. * * @param name * a name. * @param desc * a type descriptor. * @return a new or already existing name and type item. */ Item newNameTypeItem(final String name, final String desc) { key2.set(NAME_TYPE, name, desc, null); Item result = get(key2); if (result == null) { put122(NAME_TYPE, newUTF8(name), newUTF8(desc)); result = new Item(index++, key2); put(result); } return result; } /** * Adds the given internal name to {@link #typeTable} and returns its index. * Does nothing if the type table already contains this internal name. * * @param type * the internal name to be added to the type table. * @return the index of this internal name in the type table. */ int addType(final String type) { key.set(TYPE_NORMAL, type, null, null); Item result = get(key); if (result == null) { result = addType(key); } return result.index; } /** * Adds the given "uninitialized" type to {@link #typeTable} and returns its * index. This method is used for UNINITIALIZED types, made of an internal * name and a bytecode offset. * * @param type * the internal name to be added to the type table. * @param offset * the bytecode offset of the NEW instruction that created this * UNINITIALIZED type value. * @return the index of this internal name in the type table. */ int addUninitializedType(final String type, final int offset) { key.type = TYPE_UNINIT; key.intVal = offset; key.strVal1 = type; key.hashCode = 0x7FFFFFFF & (TYPE_UNINIT + type.hashCode() + offset); Item result = get(key); if (result == null) { result = addType(key); } return result.index; } /** * Adds the given Item to {@link #typeTable}. * * @param item * the value to be added to the type table. * @return the added Item, which a new Item instance with the same value as * the given Item. */ private Item addType(final Item item) { ++typeCount; Item result = new Item(typeCount, key); put(result); if (typeTable == null) { typeTable = new Item[16]; } if (typeCount == typeTable.length) { Item[] newTable = new Item[2 * typeTable.length]; System.arraycopy(typeTable, 0, newTable, 0, typeTable.length); typeTable = newTable; } typeTable[typeCount] = result; return result; } /** * Returns the index of the common super type of the two given types. This * method calls {@link #getCommonSuperClass} and caches the result in the * {@link #items} hash table to speedup future calls with the same * parameters. * * @param type1 * index of an internal name in {@link #typeTable}. * @param type2 * index of an internal name in {@link #typeTable}. * @return the index of the common super type of the two given types. */ int getMergedType(final int type1, final int type2) { key2.type = TYPE_MERGED; key2.longVal = type1 | (((long) type2) << 32); key2.hashCode = 0x7FFFFFFF & (TYPE_MERGED + type1 + type2); Item result = get(key2); if (result == null) { String t = typeTable[type1].strVal1; String u = typeTable[type2].strVal1; key2.intVal = addType(getCommonSuperClass(t, u)); result = new Item((short) 0, key2); put(result); } return result.intVal; } /** * Returns the common super type of the two given types. The default * implementation of this method <i>loads</i> the two given classes and uses * the java.lang.Class methods to find the common super class. It can be * overridden to compute this common super type in other ways, in particular * without actually loading any class, or to take into account the class * that is currently being generated by this ClassWriter, which can of * course not be loaded since it is under construction. * * @param type1 * the internal name of a class. * @param type2 * the internal name of another class. * @return the internal name of the common super class of the two given * classes. */ protected String getCommonSuperClass(final String type1, final String type2) { Class<?> c, d; ClassLoader classLoader = getClass().getClassLoader(); try { c = Class.forName(type1.replace('/', '.'), false, classLoader); d = Class.forName(type2.replace('/', '.'), false, classLoader); } catch (Exception e) { throw new RuntimeException(e.toString()); } if (c.isAssignableFrom(d)) { return type1; } if (d.isAssignableFrom(c)) { return type2; } if (c.isInterface() || d.isInterface()) { return "java/lang/Object"; } else { do { c = c.getSuperclass(); } while (!c.isAssignableFrom(d)); return c.getName().replace('.', '/'); } } /** * Returns the constant pool's hash table item which is equal to the given * item. * * @param key * a constant pool item. * @return the constant pool's hash table item which is equal to the given * item, or <tt>null</tt> if there is no such item. */ private Item get(final Item key) { Item i = items[key.hashCode % items.length]; while (i != null && (i.type != key.type || !key.isEqualTo(i))) { i = i.next; } return i; } /** * Puts the given item in the constant pool's hash table. The hash table * <i>must</i> not already contains this item. * * @param i * the item to be added to the constant pool's hash table. */ private void put(final Item i) { if (index + typeCount > threshold) { int ll = items.length; int nl = ll * 2 + 1; Item[] newItems = new Item[nl]; for (int l = ll - 1; l >= 0; --l) { Item j = items[l]; while (j != null) { int index = j.hashCode % newItems.length; Item k = j.next; j.next = newItems[index]; newItems[index] = j; j = k; } } items = newItems; threshold = (int) (nl * 0.75); } int index = i.hashCode % items.length; i.next = items[index]; items[index] = i; } /** * Puts one byte and two shorts into the constant pool. * * @param b * a byte. * @param s1 * a short. * @param s2 * another short. */ private void put122(final int b, final int s1, final int s2) { pool.put12(b, s1).putShort(s2); } /** * Puts two bytes and one short into the constant pool. * * @param b1 * a byte. * @param b2 * another byte. * @param s * a short. */ private void put112(final int b1, final int b2, final int s) { pool.put11(b1, b2).putShort(s); } }
{ "pile_set_name": "Github" }
package com.jnape.palatable.lambda.functions; import com.jnape.palatable.lambda.adt.product.Product2; import com.jnape.palatable.lambda.functor.Applicative; import com.jnape.palatable.lambda.internal.Runtime; import static com.jnape.palatable.lambda.functions.Fn6.fn6; import static com.jnape.palatable.lambda.functions.builtin.fn1.Constantly.constantly; /** * A function taking five arguments. Defined in terms of {@link Fn4}, so similarly auto-curried. * * @param <A> The first argument type * @param <B> The second argument type * @param <C> The third argument type * @param <D> The fourth argument type * @param <E> The fifth argument type * @param <F> The return type * @see Fn4 */ @FunctionalInterface public interface Fn5<A, B, C, D, E, F> extends Fn4<A, B, C, D, Fn1<E, F>> { F checkedApply(A a, B b, C c, D d, E e) throws Throwable; /** * Invoke this function with the given arguments. * * @param a the first argument * @param b the second argument * @param c the third argument * @param d the fourth argument * @param e the fifth argument * @return the result of the function application */ default F apply(A a, B b, C c, D d, E e) { try { return checkedApply(a, b, c, d, e); } catch (Throwable t) { throw Runtime.throwChecked(t); } } /** * {@inheritDoc} */ @Override default Fn1<E, F> checkedApply(A a, B b, C c, D d) throws Throwable { return e -> checkedApply(a, b, c, d, e); } /** * {@inheritDoc} */ @Override default <Z> Fn6<Z, A, B, C, D, E, F> widen() { return fn6(constantly(this)); } /** * Partially apply this function by taking its first argument. * * @param a the first argument * @return an {@link Fn5} that takes the remaining arguments and returns the result */ @Override default Fn4<B, C, D, E, F> apply(A a) { return (b, c, d, e) -> apply(a, b, c, d, e); } /** * Partially apply this function by taking its first two arguments. * * @param a the first argument * @param b the second argument * @return an {@link Fn3} that takes the remaining arguments and returns the result */ @Override default Fn3<C, D, E, F> apply(A a, B b) { return (c, d, e) -> apply(a, b, c, d, e); } /** * Partially apply this function by taking its first three arguments. * * @param a the first argument * @param b the second argument * @param c the third argument * @return an {@link Fn2} that takes remaining arguments and returns the result */ @Override default Fn2<D, E, F> apply(A a, B b, C c) { return (d, e) -> apply(a, b, c, d, e); } /** * Partially apply this function by taking its first four arguments. * * @param a the first argument * @param b the second argument * @param c the third argument * @param d the fourth argument * @return an {@link Fn1} that takes the remaining argument and returns the result */ @Override default Fn1<E, F> apply(A a, B b, C c, D d) { return (e) -> apply(a, b, c, d, e); } /** * Flip the order of the first two arguments. * * @return an {@link Fn5} that takes the first and second arguments in reversed order */ @Override default Fn5<B, A, C, D, E, F> flip() { return (b, a, c, d, e) -> apply(a, b, c, d, e); } /** * Returns an {@link Fn4} that takes the first two arguments as a <code>{@link Product2}&lt;A, B&gt;</code> and the * remaining arguments. * * @return an {@link Fn4} taking a {@link Product2} and the remaining arguments */ @Override default Fn4<? super Product2<? extends A, ? extends B>, C, D, E, F> uncurry() { return (ab, c, d, e) -> apply(ab._1(), ab._2(), c, d, e); } @Override default <G> Fn5<A, B, C, D, E, F> discardR(Applicative<G, Fn1<A, ?>> appB) { return fn5(Fn4.super.discardR(appB)); } @Override default <Z> Fn5<Z, B, C, D, E, F> diMapL(Fn1<? super Z, ? extends A> fn) { return fn5(Fn4.super.diMapL(fn)); } @Override default <Z> Fn5<Z, B, C, D, E, F> contraMap(Fn1<? super Z, ? extends A> fn) { return fn5(Fn4.super.contraMap(fn)); } @Override default <Y, Z> Fn6<Y, Z, B, C, D, E, F> compose(Fn2<? super Y, ? super Z, ? extends A> before) { return fn6(Fn4.super.compose(before)); } /** * Static factory method for wrapping a curried {@link Fn1} in an {@link Fn5}. * * @param curriedFn1 the curried fn1 to adapt * @param <A> the first input argument type * @param <B> the second input argument type * @param <C> the third input argument type * @param <D> the fourth input argument type * @param <E> the fifth input argument type * @param <F> the output type * @return the {@link Fn5} */ static <A, B, C, D, E, F> Fn5<A, B, C, D, E, F> fn5(Fn1<A, Fn4<B, C, D, E, F>> curriedFn1) { return (a, b, c, d, e) -> curriedFn1.apply(a).apply(b, c, d, e); } /** * Static factory method for wrapping a curried {@link Fn2} in an {@link Fn5}. * * @param curriedFn2 the curried fn2 to adapt * @param <A> the first input argument type * @param <B> the second input argument type * @param <C> the third input argument type * @param <D> the fourth input argument type * @param <E> the fifth input argument type * @param <F> the output type * @return the {@link Fn5} */ static <A, B, C, D, E, F> Fn5<A, B, C, D, E, F> fn5(Fn2<A, B, Fn3<C, D, E, F>> curriedFn2) { return (a, b, c, d, e) -> curriedFn2.apply(a, b).apply(c, d, e); } /** * Static factory method for wrapping a curried {@link Fn3} in an {@link Fn5}. * * @param curriedFn3 the curried fn3 to adapt * @param <A> the first input argument type * @param <B> the second input argument type * @param <C> the third input argument type * @param <D> the fourth input argument type * @param <E> the fifth input argument type * @param <F> the output type * @return the {@link Fn5} */ static <A, B, C, D, E, F> Fn5<A, B, C, D, E, F> fn5(Fn3<A, B, C, Fn2<D, E, F>> curriedFn3) { return (a, b, c, d, e) -> curriedFn3.apply(a, b, c).apply(d, e); } /** * Static factory method for wrapping a curried {@link Fn4} in an {@link Fn5}. * * @param curriedFn4 the curried fn4 to adapt * @param <A> the first input argument type * @param <B> the second input argument type * @param <C> the third input argument type * @param <D> the fourth input argument type * @param <E> the fifth input argument type * @param <F> the output type * @return the {@link Fn5} */ static <A, B, C, D, E, F> Fn5<A, B, C, D, E, F> fn5(Fn4<A, B, C, D, Fn1<E, F>> curriedFn4) { return (a, b, c, d, e) -> curriedFn4.apply(a, b, c, d).apply(e); } /** * Static factory method for coercing a lambda to an {@link Fn5}. * * @param fn the lambda to coerce * @param <A> the first input argument type * @param <B> the second input argument type * @param <C> the third input argument type * @param <D> the fourth input argument type * @param <E> the fifth input argument type * @param <F> the output type * @return the {@link Fn5} */ static <A, B, C, D, E, F> Fn5<A, B, C, D, E, F> fn5(Fn5<A, B, C, D, E, F> fn) { return fn; } }
{ "pile_set_name": "Github" }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`prints console.logs when run with forceExit 1`] = ` "PASS __tests__/a-banana.js ✓ banana Force exiting Jest Have you considered using \`--detectOpenHandles\` to detect async operations that kept running after all tests finished?" `; exports[`prints console.logs when run with forceExit 2`] = ` "Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: <<REPLACED>> Ran all test suites." `; exports[`prints console.logs when run with forceExit 3`] = ` " console.log __tests__/a-banana.js:2 Hey " `;
{ "pile_set_name": "Github" }
/* Copyright (c) 2011, Intel 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 Intel 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************** * Content : Eigen bindings to LAPACKe * LU decomposition with partial pivoting based on LAPACKE_?getrf function. ******************************************************************************** */ #ifndef EIGEN_PARTIALLU_LAPACK_H #define EIGEN_PARTIALLU_LAPACK_H namespace Eigen { namespace internal { /** \internal Specialization for the data types supported by LAPACKe */ #define EIGEN_LAPACKE_LU_PARTPIV(EIGTYPE, LAPACKE_TYPE, LAPACKE_PREFIX) \ template<int StorageOrder> \ struct partial_lu_impl<EIGTYPE, StorageOrder, lapack_int> \ { \ /* \internal performs the LU decomposition in-place of the matrix represented */ \ static lapack_int blocked_lu(Index rows, Index cols, EIGTYPE* lu_data, Index luStride, lapack_int* row_transpositions, lapack_int& nb_transpositions, lapack_int maxBlockSize=256) \ { \ EIGEN_UNUSED_VARIABLE(maxBlockSize);\ lapack_int matrix_order, first_zero_pivot; \ lapack_int m, n, lda, *ipiv, info; \ EIGTYPE* a; \ /* Set up parameters for ?getrf */ \ matrix_order = StorageOrder==RowMajor ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; \ lda = convert_index<lapack_int>(luStride); \ a = lu_data; \ ipiv = row_transpositions; \ m = convert_index<lapack_int>(rows); \ n = convert_index<lapack_int>(cols); \ nb_transpositions = 0; \ \ info = LAPACKE_##LAPACKE_PREFIX##getrf( matrix_order, m, n, (LAPACKE_TYPE*)a, lda, ipiv ); \ \ for(int i=0;i<m;i++) { ipiv[i]--; if (ipiv[i]!=i) nb_transpositions++; } \ \ eigen_assert(info >= 0); \ /* something should be done with nb_transpositions */ \ \ first_zero_pivot = info; \ return first_zero_pivot; \ } \ }; EIGEN_LAPACKE_LU_PARTPIV(double, double, d) EIGEN_LAPACKE_LU_PARTPIV(float, float, s) EIGEN_LAPACKE_LU_PARTPIV(dcomplex, lapack_complex_double, z) EIGEN_LAPACKE_LU_PARTPIV(scomplex, lapack_complex_float, c) } // end namespace internal } // end namespace Eigen #endif // EIGEN_PARTIALLU_LAPACK_H
{ "pile_set_name": "Github" }
<?php namespace Hamcrest\Text; class IsEqualIgnoringWhiteSpaceTest extends \Hamcrest\AbstractMatcherTest { private $_matcher; protected function setUp() { $this->_matcher = \Hamcrest\Text\IsEqualIgnoringWhiteSpace::equalToIgnoringWhiteSpace( "Hello World how\n are we? " ); } protected function createMatcher() { return $this->_matcher; } public function testPassesIfWordsAreSameButWhitespaceDiffers() { assertThat('Hello World how are we?', $this->_matcher); assertThat(" Hello \rWorld \t how are\nwe?", $this->_matcher); } public function testFailsIfTextOtherThanWhitespaceDiffers() { assertThat('Hello PLANET how are we?', not($this->_matcher)); assertThat('Hello World how are we', not($this->_matcher)); } public function testFailsIfWhitespaceIsAddedOrRemovedInMidWord() { assertThat('HelloWorld how are we?', not($this->_matcher)); assertThat('Hello Wo rld how are we?', not($this->_matcher)); } public function testFailsIfMatchingAgainstNull() { assertThat(null, not($this->_matcher)); } public function testHasAReadableDescription() { $this->assertDescription( "equalToIgnoringWhiteSpace(\"Hello World how\\n are we? \")", $this->_matcher ); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>SchemeUserState</key> <dict> <key>自定义状态栏.xcscheme</key> <dict> <key>orderHint</key> <integer>0</integer> </dict> </dict> <key>SuppressBuildableAutocreation</key> <dict> <key>8EB7D7A519C2BA0E0071BCF1</key> <dict> <key>primary</key> <true/> </dict> <key>8EB7D7C019C2BA0E0071BCF1</key> <dict> <key>primary</key> <true/> </dict> </dict> </dict> </plist>
{ "pile_set_name": "Github" }
#!/bin/ksh -p # # CDDL HEADER START # # This file and its contents are supplied under the terms of the # Common Development and Distribution License ("CDDL"), version 1.0. # You may only use this file in accordance with the terms of version # 1.0 of the CDDL. # # A full copy of the text of the CDDL should have accompanied this # source. A copy of the CDDL is also available via the Internet at # http://www.illumos.org/license/CDDL. # # CDDL HEADER END # # # Copyright (c) 2017 Datto, Inc. All rights reserved. # . $STF_SUITE/include/libtest.shlib . $STF_SUITE/tests/functional/cli_root/zfs_load-key/zfs_load-key_common.kshlib # # DESCRIPTION: # 'zfs unload-key' should only unload the key of an unmounted dataset. # # STRATEGY: # 1. Attempt to unload the default dataset's key # 2. Unmount the dataset # 3. Attempt to unload the default dataset's key # 4. Create an encrypted dataset # 5. Attempt to unload the dataset's key # 6. Verify the key is loaded # 7. Unmount the dataset # 8. Attempt to unload the dataset's key # 9. Verify the key is not loaded # 10. Attempt to unload the dataset's key # verify_runnable "both" function cleanup { datasetexists $TESTPOOL/$TESTFS1 && \ log_must zfs destroy $TESTPOOL/$TESTFS1 } log_onexit cleanup log_assert "'zfs unload-key' should unload the key for an unmounted" \ "encrypted dataset" log_mustnot zfs unload-key $TESTPOOL/$TESTFS log_must zfs unmount $TESTPOOL/$TESTFS log_mustnot zfs unload-key $TESTPOOL/$TESTFS log_must eval "echo $PASSPHRASE | zfs create -o encryption=on" \ "-o keyformat=passphrase -o keylocation=prompt $TESTPOOL/$TESTFS1" log_mustnot zfs unload-key $TESTPOOL/$TESTFS1 log_must key_available $TESTPOOL/$TESTFS1 log_must zfs unmount $TESTPOOL/$TESTFS1 log_must zfs unload-key $TESTPOOL/$TESTFS1 log_must key_unavailable $TESTPOOL/$TESTFS1 log_mustnot zfs unload-key $TESTPOOL/$TESTFS1 log_pass "'zfs unload-key' unloads the key for an unmounted encrypted dataset"
{ "pile_set_name": "Github" }
Index: usb-modeswitch-2.6.0/Makefile =================================================================== --- usb-modeswitch-2.6.0.orig/Makefile +++ usb-modeswitch-2.6.0/Makefile @@ -5,17 +5,24 @@ CFLAGS += -Wall -Wno-deprecated-dec LIBS = `pkg-config --libs --cflags libusb-1.0` RM = /bin/rm -f OBJS = usb_modeswitch.c -PREFIX = $(DESTDIR)/usr -ETCDIR = $(DESTDIR)/etc +PREFIX = /usr/local +ETCDIR = $(PREFIX)/etc SYSDIR = $(ETCDIR)/systemd/system UPSDIR = $(ETCDIR)/init -UDEVDIR = $(DESTDIR)/lib/udev +UDEVDIR = $(PREFIX)/lib/udev SBINDIR = $(PREFIX)/sbin MANDIR = $(PREFIX)/share/man/man1 +USE_UPSTART=$(shell if command -v initctl > /dev/null; then echo "true"; fi) +USE_SYSTEMD=$(shell if command -v systemctl > /dev/null; then echo "true"; fi) + .PHONY: clean install install-common uninstall \ dispatcher-script dispatcher-dynlink dispatcher-statlink \ - install-script install-dynlink install-statlink + install-script install-dynlink install-statlink \ + install-upstart install-systemd \ + configure-dispatcher configure-script \ + configure-upstart configure-systemd \ + configure all: all-with-script-dispatcher @@ -28,7 +35,25 @@ all-with-statlink-dispatcher: $(PROG) di $(PROG): $(OBJS) usb_modeswitch.h $(CC) -o $(PROG) $(OBJS) $(CFLAGS) $(LIBS) $(LDFLAGS) -dispatcher-script: usb_modeswitch_dispatcher.tcl +configure-dispatcher: + sed -i \ + -e 's,^\(set setup(sbindir) \).*$$,\1$(SBINDIR),' \ + -e 's,^\(set setup(etcdir) \).*$$,\1$(ETCDIR),' \ + usb_modeswitch_dispatcher.tcl + +configure-script: + sed -i -e 's,^\(SBINDIR=\).*$$,\1$(SBINDIR),' usb_modeswitch.sh + +configure-systemd: + sed -i -e 's,@sbindir@,$(SBINDIR),' [email protected] + +configure-upstart: + sed -i -e 's,@sbindir@,$(SBINDIR),' usb-modeswitch-upstart.conf + +configure: configure-dispatcher configure-script \ + configure-systemd configure-upstart + +dispatcher-script: configure-dispatcher usb_modeswitch_dispatcher.tcl DISPATCH=dispatcher-script cp -f usb_modeswitch_dispatcher.tcl usb_modeswitch_dispatcher @@ -53,16 +78,28 @@ distclean: clean # If the systemd folder is present, install the service for starting the dispatcher # If not, use the dispatcher directly from the udev rule as in previous versions -install-common: $(PROG) $(DISPATCH) - install -D --mode=755 usb_modeswitch $(SBINDIR)/usb_modeswitch - install -D --mode=755 usb_modeswitch.sh $(UDEVDIR)/usb_modeswitch - install -D --mode=644 usb_modeswitch.conf $(ETCDIR)/usb_modeswitch.conf - install -D --mode=644 usb_modeswitch.1 $(MANDIR)/usb_modeswitch.1 - install -D --mode=644 usb_modeswitch_dispatcher.1 $(MANDIR)/usb_modeswitch_dispatcher.1 - install -D --mode=755 usb_modeswitch_dispatcher $(SBINDIR)/usb_modeswitch_dispatcher +install-common: $(PROG) configure $(DISPATCH) + install -D --mode=755 usb_modeswitch $(DESTDIR)$(SBINDIR)/usb_modeswitch + install -D --mode=755 usb_modeswitch.sh $(DESTDIR)$(UDEVDIR)/usb_modeswitch + install -D --mode=644 usb_modeswitch.conf $(DESTDIR)$(ETCDIR)/usb_modeswitch.conf + install -D --mode=644 usb_modeswitch.1 $(DESTDIR)$(MANDIR)/usb_modeswitch.1 + install -D --mode=644 usb_modeswitch_dispatcher.1 $(DESTDIR)$(MANDIR)/usb_modeswitch_dispatcher.1 + install -D --mode=755 usb_modeswitch_dispatcher $(DESTDIR)$(SBINDIR)/usb_modeswitch_dispatcher install -d $(DESTDIR)/var/lib/usb_modeswitch - test -d $(UPSDIR) -a -e /sbin/initctl && install --mode=644 usb-modeswitch-upstart.conf $(UPSDIR) || test 1 - test -d $(SYSDIR) -a \( -e /usr/bin/systemctl -o -e /bin/systemctl \) && install --mode=644 [email protected] $(SYSDIR) || test 1 + +install-upstart: + install -D --mode=644 usb-modeswitch-upstart.conf $(DESTDIR)$(UPSDIR)/usb-modeswitch-upstart.conf + +install-systemd: + install -D --mode=644 [email protected] $(DESTDIR)$(SYSDIR)/[email protected] + +ifeq ($(USE_UPSTART),true) +install-common: install-upstart +endif + +ifeq ($(USE_SYSTEMD),true) +install-common: install-systemd +endif install: install-script @@ -73,10 +110,10 @@ install-dynlink: dispatcher-dynlink inst install-statlink: dispatcher-statlink install-common uninstall: - $(RM) $(SBINDIR)/usb_modeswitch - $(RM) $(SBINDIR)/usb_modeswitch_dispatcher - $(RM) $(UDEVDIR)/usb_modeswitch - $(RM) $(ETCDIR)/usb_modeswitch.conf - $(RM) $(MANDIR)/usb_modeswitch.1 + $(RM) $(DESTDIR)$(SBINDIR)/usb_modeswitch + $(RM) $(DESTDIR)$(SBINDIR)/usb_modeswitch_dispatcher + $(RM) $(DESTDIR)$(UDEVDIR)/usb_modeswitch + $(RM) $(DESTDIR)$(ETCDIR)/usb_modeswitch.conf + $(RM) $(DESTDIR)$(MANDIR)/usb_modeswitch.1 $(RM) -R $(DESTDIR)/var/lib/usb_modeswitch - $(RM) $(SYSDIR)/[email protected] + $(RM) $(DESTDIR)$(SYSDIR)/[email protected] Index: usb-modeswitch-2.6.0/usb-modeswitch-upstart.conf =================================================================== --- usb-modeswitch-2.6.0.orig/usb-modeswitch-upstart.conf +++ usb-modeswitch-2.6.0/usb-modeswitch-upstart.conf @@ -1,5 +1,5 @@ start on usb-modeswitch-upstart task script - exec /usr/sbin/usb_modeswitch_dispatcher --switch-mode $UMS_PARAM + exec @sbindir@/usb_modeswitch_dispatcher --switch-mode $UMS_PARAM end script Index: usb-modeswitch-2.6.0/usb_modeswitch.sh =================================================================== --- usb-modeswitch-2.6.0.orig/usb_modeswitch.sh +++ usb-modeswitch-2.6.0/usb_modeswitch.sh @@ -1,5 +1,9 @@ #!/bin/sh # part of usb_modeswitch 2.6.0 + +# Compile time configuration, injected by the Makefile +SBINDIR=/usr/sbin + device_in() { if [ ! -e /var/lib/usb_modeswitch/$1 ]; then @@ -37,7 +41,7 @@ if [ $(expr "$1" : "--.*") ]; then v_id=$3 fi fi -PATH=/sbin:/usr/sbin:$PATH + case "$1" in --driver-bind) # driver binding code removed @@ -46,9 +50,7 @@ case "$1" in --symlink-name) device_in "link_list" $v_id $p_id if [ "$?" = "1" ]; then - if [ -e "/usr/sbin/usb_modeswitch_dispatcher" ]; then - exec usb_modeswitch_dispatcher $1 $2 2>>/dev/null - fi + exec $SBINDIR/usb_modeswitch_dispatcher $1 $2 2>>/dev/null fi exit 0 ;; @@ -61,15 +63,13 @@ if [ "$p2" = "" -a "$p1" != "" ]; then p2=$p1 fi -PATH=/bin:/sbin:/usr/bin:/usr/sbin -init_path=`readlink -f /sbin/init` -if [ `basename $init_path` = "systemd" ]; then +if command -v systemctl > /dev/null; then systemctl --no-block restart usb_modeswitch@$p2.service -elif [ -e "/etc/init/usb-modeswitch-upstart.conf" ]; then +elif command -v initctl > /dev/null; then initctl emit --no-wait usb-modeswitch-upstart UMS_PARAM=$p2 else # only old distros, new udev will kill all subprocesses exec 1<&- 2<&- 5<&- 7<&- - exec usb_modeswitch_dispatcher --switch-mode $p2 & + exec $SBINDIR/usb_modeswitch_dispatcher --switch-mode $p2 & fi exit 0 Index: usb-modeswitch-2.6.0/[email protected] =================================================================== --- usb-modeswitch-2.6.0.orig/[email protected] +++ usb-modeswitch-2.6.0/[email protected] @@ -3,6 +3,6 @@ Description=USB_ModeSwitch_%i [Service] Type=oneshot -ExecStart=/usr/sbin/usb_modeswitch_dispatcher --switch-mode %i +ExecStart=@sbindir@/usb_modeswitch_dispatcher --switch-mode %i #ExecStart=/bin/echo %i Index: usb-modeswitch-2.6.0/usb_modeswitch_dispatcher.tcl =================================================================== --- usb-modeswitch-2.6.0.orig/usb_modeswitch_dispatcher.tcl +++ usb-modeswitch-2.6.0/usb_modeswitch_dispatcher.tcl @@ -12,6 +12,16 @@ # Part of usb-modeswitch-2.6.0 package # (C) Josua Dietze 2009-2019 +# Compile-time configuration, injected by the Makefile. +set setup(sbindir) /usr/sbin +set setup(etcdir) /etc + +# External dependency default location +set setup(dbdir) /usr/share/usb_modeswitch + +# Derived configuration +set setup(dbdir_etc) $setup(etcdir)/usb_modeswitch.d + set arg0 [lindex $argv 0] if [regexp {\.tcl$} $arg0] { if [file exists $arg0] { @@ -115,10 +125,8 @@ if {![regexp {(.*?):.*$} $arg1 d device] } } -set setup(dbdir) /usr/share/usb_modeswitch -set setup(dbdir_etc) /etc/usb_modeswitch.d if {![file exists $setup(dbdir)] && ![file exists $setup(dbdir_etc)]} { - Log "\nError: no config database found in /usr/share or /etc. Exit" + Log "\nError: no config database found in $setup(dbdir) or $setup(dbdir_etc). Exit" SafeExit } @@ -285,7 +293,7 @@ if {$config(NoMBIMCheck)==0 && $usb(bNum if [CheckMBIM] { Log " driver for MBIM devices is available" Log "Find MBIM configuration number ..." - if [catch {set cfgno [exec /usr/sbin/usb_modeswitch -j -Q $busParam $devParam -v $usb(idVendor) -p $usb(idProduct)]} err] { + if [catch {set cfgno [exec $setup(sbindir)/usb_modeswitch -j -Q $busParam $devParam -v $usb(idVendor) -p $usb(idProduct)]} err] { Log "Error when trying to find MBIM configuration, switch to legacy modem mode" } else { set cfgno [string trim $cfgno] @@ -321,7 +329,7 @@ if {$report == ""} { # Now we are actually switching if $flags(logging) { Log "Command line:\nusb_modeswitch -W -D $configParam $busParam $devParam -v $usb(idVendor) -p $usb(idProduct) -f \$flags(config)" - catch {set report [exec /usr/sbin/usb_modeswitch -W -D $configParam $busParam $devParam -v $usb(idVendor) -p $usb(idProduct) -f "$flags(config)" 2>@1]} report + catch {set report [exec $setup(sbindir)/usb_modeswitch -W -D $configParam $busParam $devParam -v $usb(idVendor) -p $usb(idProduct) -f "$flags(config)" 2>@1]} report Log "\nVerbose debug output of usb_modeswitch and libusb follows" Log "(Note that some USB errors are to be expected in the process)" Log "--------------------------------" @@ -329,7 +337,7 @@ if {$report == ""} { Log "--------------------------------" Log "(end of usb_modeswitch output)\n" } else { - catch {set report [exec /usr/sbin/usb_modeswitch -Q -D $configParam $busParam $devParam -v $usb(idVendor) -p $usb(idProduct) -f "$flags(config)" 2>@1]} report + catch {set report [exec $setup(sbindir)/usb_modeswitch -Q -D $configParam $busParam $devParam -v $usb(idVendor) -p $usb(idProduct) -f "$flags(config)" 2>@1]} report } } @@ -522,12 +530,12 @@ return 1 proc {ParseGlobalConfig} {path} { -global flags +global flags setup set configFile "" if [string length $path] { set places [list $path] } else { - set places [list /etc/usb_modeswitch.conf /etc/sysconfig/usb_modeswitch /etc/default/usb_modeswitch] + set places [list $setup(etcdir)/usb_modeswitch.conf $setup(etcdir)/sysconfig/usb_modeswitch $setup(etcdir)/default/usb_modeswitch] } foreach cfg $places { if [file exists $cfg] { @@ -923,10 +931,12 @@ proc {SysLog} {msg} { global flags if {![info exists flags(logger)]} { - set flags(logger) "" - foreach fn {/bin/logger /usr/bin/logger} { - if [file exists $fn] { - set flags(logger) $fn + set flags(logger) [exec sh -c "command -v logger || true"] + if {$flags(logger) == ""} { + foreach fn {/bin/logger /usr/bin/logger} { + if [file exists $fn] { + set flags(logger) $fn + } } } Log "Logger is $flags(logger)"
{ "pile_set_name": "Github" }
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from . import archives import unittest import os from filebrowser.lib.archives import IllegalPathException from nose.tools import assert_true, assert_equal class ArchiveTest(unittest.TestCase): def test_zip(self): FILE = os.path.realpath('apps/filebrowser/src/filebrowser/test_data/test.zip') # Extract the file # This file should only have 'test.txt' in it directory = archives.archive_factory(FILE, 'zip').extract() assert_true(os.path.exists(directory)) assert_true(os.path.isdir(directory)) assert_true(os.path.isfile(directory + '/test.txt')) assert_equal(os.path.getsize(directory + '/test.txt'), 4) FILE = os.path.realpath('apps/filebrowser/src/filebrowser/test_data/test5.zip') # Extract the file # This file should only have 'test.txt' in it directory = archives.archive_factory(FILE, 'zip').extract() assert_true(os.path.exists(directory)) assert_true(os.path.isdir(directory)) assert_true(os.path.isfile(directory + '/tmp/temp/test.txt')) assert_equal(os.path.getsize(directory + '/tmp/temp/test.txt'), 5) def test_tgz(self): FILE = os.path.realpath('apps/filebrowser/src/filebrowser/test_data/test.tar.gz') # Extract the file # This file should only have 'test.txt' in it directory = archives.archive_factory(FILE, 'tgz').extract() assert_true(os.path.exists(directory)) assert_true(os.path.isdir(directory)) assert_true(os.path.isfile(directory + '/test.txt')) assert_equal(os.path.getsize(directory + '/test.txt'), 4) FILE = os.path.realpath('apps/filebrowser/src/filebrowser/test_data/test2.tar.gz') # Extract the file # This file should only have 'test.txt' in it directory = archives.archive_factory(FILE, 'tar.gz').extract() assert_true(os.path.exists(directory)) assert_true(os.path.isdir(directory)) assert_true(os.path.isfile(directory + '/home/docs/test.txt')) assert_equal(os.path.getsize(directory + '/home/docs/test.txt'), 4) # This file should not be extracted as it contains illegal path '../../../Desktop/test.txt' FILE = os.path.realpath('apps/filebrowser/src/filebrowser/test_data/test3.tar.gz') factory = archives.archive_factory(FILE, 'tar.gz') self.assertRaises(IllegalPathException, factory.extract) # This file should not be extracted as it contains absolute path FILE = os.path.realpath('apps/filebrowser/src/filebrowser/test_data/test4.tar.gz') factory = archives.archive_factory(FILE, 'tar.gz') self.assertRaises(IllegalPathException, factory.extract) if __name__ == "__main__": unittest.main()
{ "pile_set_name": "Github" }
/* Copyright 2011 Etay Meiri This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include "engine_common.h" #include "mesh.h" Mesh::MeshEntry::MeshEntry() { VB = INVALID_OGL_VALUE; IB = INVALID_OGL_VALUE; NumIndices = 0; MaterialIndex = INVALID_MATERIAL; }; Mesh::MeshEntry::~MeshEntry() { if (VB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &VB); } if (IB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &IB); } } bool Mesh::MeshEntry::Init(const std::vector<Vertex>& Vertices, const std::vector<unsigned int>& Indices) { NumIndices = Indices.size(); glGenBuffers(1, &VB); glBindBuffer(GL_ARRAY_BUFFER, VB); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * Vertices.size(), &Vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &IB); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * NumIndices, &Indices[0], GL_STATIC_DRAW); return GLCheckError(); } Mesh::Mesh() { } Mesh::~Mesh() { Clear(); } void Mesh::Clear() { for (unsigned int i = 0 ; i < m_Textures.size() ; i++) { SAFE_DELETE(m_Textures[i]); } } bool Mesh::LoadMesh(const std::string& Filename) { // Release the previously loaded mesh (if it exists) Clear(); bool Ret = false; Assimp::Importer Importer; const aiScene* pScene = Importer.ReadFile(Filename.c_str(), aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs); if (pScene) { Ret = InitFromScene(pScene, Filename); } else { printf("Error parsing '%s': '%s'\n", Filename.c_str(), Importer.GetErrorString()); } return Ret; } bool Mesh::InitFromScene(const aiScene* pScene, const std::string& Filename) { m_Entries.resize(pScene->mNumMeshes); m_Textures.resize(pScene->mNumMaterials); // Initialize the meshes in the scene one by one for (unsigned int i = 0 ; i < m_Entries.size() ; i++) { const aiMesh* paiMesh = pScene->mMeshes[i]; InitMesh(i, paiMesh); } return InitMaterials(pScene, Filename); } void Mesh::InitMesh(unsigned int Index, const aiMesh* paiMesh) { m_Entries[Index].MaterialIndex = paiMesh->mMaterialIndex; std::vector<Vertex> Vertices; std::vector<unsigned int> Indices; const aiVector3D Zero3D(0.0f, 0.0f, 0.0f); for (unsigned int i = 0 ; i < paiMesh->mNumVertices ; i++) { const aiVector3D* pPos = &(paiMesh->mVertices[i]); const aiVector3D* pNormal = &(paiMesh->mNormals[i]); const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D; Vertex v(Vector3f(pPos->x, pPos->y, pPos->z), Vector2f(pTexCoord->x, pTexCoord->y), Vector3f(pNormal->x, pNormal->y, pNormal->z)); Vertices.push_back(v); } for (unsigned int i = 0 ; i < paiMesh->mNumFaces ; i++) { const aiFace& Face = paiMesh->mFaces[i]; assert(Face.mNumIndices == 3); Indices.push_back(Face.mIndices[0]); Indices.push_back(Face.mIndices[1]); Indices.push_back(Face.mIndices[2]); } m_Entries[Index].Init(Vertices, Indices); } bool Mesh::InitMaterials(const aiScene* pScene, const std::string& Filename) { // Extract the directory part from the file name std::string::size_type SlashIndex = Filename.find_last_of("/"); std::string Dir; if (SlashIndex == std::string::npos) { Dir = "."; } else if (SlashIndex == 0) { Dir = "/"; } else { Dir = Filename.substr(0, SlashIndex); } bool Ret = true; // Initialize the materials for (unsigned int i = 0 ; i < pScene->mNumMaterials ; i++) { const aiMaterial* pMaterial = pScene->mMaterials[i]; m_Textures[i] = NULL; if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0) { aiString Path; if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &Path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) { std::string p(Path.data); if (p.substr(0, 2) == ".\\") { p = p.substr(2, p.size() - 2); } std::string FullPath = Dir + "/" + p; m_Textures[i] = new Texture(GL_TEXTURE_2D, FullPath.c_str()); if (!m_Textures[i]->Load()) { printf("Error loading texture '%s'\n", FullPath.c_str()); delete m_Textures[i]; m_Textures[i] = NULL; Ret = false; } else { printf("Loaded texture '%s'\n", FullPath.c_str()); } } } } return Ret; } void Mesh::Render(IRenderCallbacks* pRenderCallbacks) { glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); for (unsigned int i = 0 ; i < m_Entries.size() ; i++) { glBindBuffer(GL_ARRAY_BUFFER, m_Entries[i].VB); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)12); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)20); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Entries[i].IB); const unsigned int MaterialIndex = m_Entries[i].MaterialIndex; if (MaterialIndex < m_Textures.size() && m_Textures[MaterialIndex]) { m_Textures[MaterialIndex]->Bind(COLOR_TEXTURE_UNIT); } if (pRenderCallbacks) { pRenderCallbacks->DrawStartCB(i); } glDrawElements(GL_PATCHES, m_Entries[i].NumIndices, GL_UNSIGNED_INT, 0); } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); } void Mesh::Render(unsigned int DrawIndex, unsigned int PrimID) { assert(DrawIndex < m_Entries.size()); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, m_Entries[DrawIndex].VB); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)12); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)20); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Entries[DrawIndex].IB); glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, (const GLvoid*)(PrimID * 3 * sizeof(GLuint))); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); }
{ "pile_set_name": "Github" }
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck var f = 0] in func f<S { class A { extension NSSet { } struct c) -> { } func c<h: c == Sw
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="RunConfigurationProducerService"> <option name="ignoredProducers"> <set> <option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" /> <option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" /> <option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" /> </set> </option> </component> </project>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2001, 2003, 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. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <sys/utsname.h> #include <jni.h> #include <jni_util.h> #include "fontscalerdefs.h" #include "X11FontScaler.h" #ifndef HEADLESS #include <X11/Xlib.h> #include <X11/Xutil.h> #include <awt.h> static GC pixmapGC = 0; static Pixmap pixmap = 0; static Atom psAtom = 0; static Atom fullNameAtom = 0; static int pixmapWidth = 0; static int pixmapHeight = 0; #define FONT_AWT_LOCK() \ env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); \ AWT_LOCK(); int CreatePixmapAndGC (int width, int height) { /* REMIND: use the actual screen, not the default screen */ Window awt_defaultRoot = RootWindow(awt_display, DefaultScreen(awt_display)); if (width < 100) { width = 100; } if (height < 100) { height = 100; } pixmapHeight = height; pixmapWidth = width; if (pixmap != 0) { XFreePixmap (awt_display, pixmap); } if (pixmapGC != NULL) { XFreeGC (awt_display, pixmapGC); } pixmap = XCreatePixmap (awt_display, awt_defaultRoot, pixmapWidth, pixmapHeight, 1); if (pixmap == 0) { return BadAlloc; } pixmapGC = XCreateGC (awt_display, pixmap, 0, 0); if (pixmapGC == NULL) { return BadAlloc; } XFillRectangle (awt_display, pixmap, pixmapGC, 0, 0, pixmapWidth, pixmapHeight); XSetForeground (awt_display, pixmapGC, 1); return Success; } #ifdef DUMP_IMAGES static void dumpXImage(XImage *ximage) { int height = ximage->height; int width = ximage->width; int row; int column; fprintf(stderr, "-------------------------------------------\n"); for (row = 0; row < height; ++row) { for (column = 0; column < width; ++column) { int pixel = ximage->f.get_pixel(ximage, column, row); fprintf(stderr, (pixel == 0) ? " " : "XX"); } fprintf(stderr, "\n"); } fprintf(stderr, "-------------------------------------------\n"); } #endif #endif /* !HEADLESS */ JNIEXPORT int JNICALL AWTCountFonts(char* xlfd) { #ifdef HEADLESS return 0; #else char **names; int count; JNIEnv *env; FONT_AWT_LOCK(); names = XListFonts(awt_display, xlfd, 3, &count); XFreeFontNames(names); AWT_UNLOCK(); return count; #endif /* !HEADLESS */ } JNIEXPORT void JNICALL AWTLoadFont(char* name, AWTFont *pReturn) { JNIEnv *env; *pReturn = NULL; #ifndef HEADLESS FONT_AWT_LOCK(); *pReturn = (AWTFont)XLoadQueryFont(awt_display, name); AWT_UNLOCK(); #endif /* !HEADLESS */ } JNIEXPORT void JNICALL AWTFreeFont(AWTFont font) { #ifndef HEADLESS JNIEnv *env; FONT_AWT_LOCK(); XFreeFont(awt_display, (XFontStruct *)font); AWT_UNLOCK(); #endif /* !HEADLESS */ } JNIEXPORT unsigned JNICALL AWTFontMinByte1(AWTFont font) { #ifdef HEADLESS return 0; #else return ((XFontStruct *)font)->min_byte1; #endif /* !HEADLESS */ } JNIEXPORT unsigned JNICALL AWTFontMaxByte1(AWTFont font) { #ifdef HEADLESS return 0; #else return ((XFontStruct *)font)->max_byte1; #endif /* !HEADLESS */ } JNIEXPORT unsigned JNICALL AWTFontMinCharOrByte2(AWTFont font) { #ifdef HEADLESS return 0; #else return ((XFontStruct *)font)->min_char_or_byte2; #endif /* !HEADLESS */ } JNIEXPORT unsigned JNICALL AWTFontMaxCharOrByte2(AWTFont font) { #ifdef HEADLESS return 0; #else return ((XFontStruct *)font)->max_char_or_byte2; #endif /* !HEADLESS */ } JNIEXPORT unsigned JNICALL AWTFontDefaultChar(AWTFont font) { #ifdef HEADLESS return 0; #else return ((XFontStruct *)font)->default_char; #endif /* !HEADLESS */ } JNIEXPORT AWTChar JNICALL AWTFontPerChar(AWTFont font, int index) { #ifdef HEADLESS return NULL; #else XFontStruct *fXFont = (XFontStruct *)font; XCharStruct *perChar = fXFont->per_char; if (perChar == NULL) { return NULL; } return (AWTChar)&(perChar[index]); #endif /* !HEADLESS */ } JNIEXPORT AWTChar JNICALL AWTFontMaxBounds(AWTFont font) { #ifdef HEADLESS return 0; #else return (AWTChar)&((XFontStruct *)font)->max_bounds; #endif /* !HEADLESS */ } JNIEXPORT int JNICALL AWTFontAscent(AWTFont font) { #ifdef HEADLESS return 0; #else return ((XFontStruct *)font)->ascent; #endif /* !HEADLESS */ } JNIEXPORT int JNICALL AWTFontDescent(AWTFont font) { #ifdef HEADLESS return 0; #else return ((XFontStruct *)font)->descent; #endif /* !HEADLESS */ } JNIEXPORT void JNICALL AWTFontTextExtents16(AWTFont font, AWTChar2b* xChar, AWTChar* overall) { #ifndef HEADLESS JNIEnv *env; int ascent, descent, direction; XFontStruct* xFont = (XFontStruct*)font; XCharStruct* newChar = (XCharStruct*)malloc(sizeof(XCharStruct)); *overall = (AWTChar)newChar; /* There is a claim from the pre 1.5 source base that the info in the * XFontStruct is flaky for 16 byte chars. This seems plausible as * for info to be valid, that struct would need a large number of * XCharStructs. But there's nothing in the X APIs which warns you of * this. If it really is flaky you must question why there's an * XTextExtents16 API call. Try XTextExtents16 for now and if it fails * go back to XQueryTextExtents16 in this function. * Indeed the metrics from the Solaris 9 JA font * -ricoh-gothic-medium-r-normal--*-140-72-72-m-*-jisx0208.1983-0 * do appear different so revert to the query api */ FONT_AWT_LOCK(); XQueryTextExtents16(awt_display,xFont->fid, xChar, 1, &direction, &ascent, &descent, newChar); /* XTextExtents16(xFont, xChar, 1, &direction, &ascent, &descent, newChar); */ AWT_UNLOCK(); #endif /* !HEADLESS */ } JNIEXPORT void JNICALL AWTFreeChar(AWTChar xChar) { #ifndef HEADLESS free(xChar); #endif /* !HEADLESS */ } JNIEXPORT jlong JNICALL AWTFontGenerateImage(AWTFont pFont, AWTChar2b* xChar) { #ifndef HEADLESS int width, height, direction, ascent, descent; GlyphInfo *glyphInfo; XFontStruct* xFont = (XFontStruct*)pFont; XCharStruct xcs; XImage *ximage; int h, i, j, nbytes; unsigned char *srcRow, *dstRow, *dstByte; int wholeByteCount, remainingBitsCount; unsigned int imageSize; JNIEnv *env; FONT_AWT_LOCK(); /* XTextExtents16(xFont, xChar, 1, &direction, &ascent, &descent, &xcs); */ XQueryTextExtents16(awt_display,xFont->fid, xChar, 1, &direction, &ascent, &descent, &xcs); width = xcs.rbearing - xcs.lbearing; height = xcs.ascent+xcs.descent; imageSize = width*height; glyphInfo = (GlyphInfo*)malloc(sizeof(GlyphInfo)+imageSize); if (glyphInfo == NULL) { AWT_UNLOCK(); return (jlong)(uintptr_t)NULL; } glyphInfo->cellInfo = NULL; glyphInfo->width = width; glyphInfo->height = height; glyphInfo->topLeftX = xcs.lbearing; glyphInfo->topLeftY = -xcs.ascent; glyphInfo->advanceX = xcs.width; glyphInfo->advanceY = 0; if (imageSize == 0) { glyphInfo->image = NULL; AWT_UNLOCK(); return (jlong)(uintptr_t)glyphInfo; } else { glyphInfo->image = (unsigned char*)glyphInfo+sizeof(GlyphInfo); } if ((pixmap == 0) || (width > pixmapWidth) || (height > pixmapHeight)) { if (CreatePixmapAndGC(width, height) != Success) { glyphInfo->image = NULL; AWT_UNLOCK(); return (jlong)(uintptr_t)glyphInfo; } } XSetFont(awt_display, pixmapGC, xFont->fid); XSetForeground(awt_display, pixmapGC, 0); XFillRectangle(awt_display, pixmap, pixmapGC, 0, 0, pixmapWidth, pixmapHeight); XSetForeground(awt_display, pixmapGC, 1); XDrawString16(awt_display, pixmap, pixmapGC, -xcs.lbearing, xcs.ascent, xChar, 1); ximage = XGetImage(awt_display, pixmap, 0, 0, width, height, AllPlanes, XYPixmap); if (ximage == NULL) { glyphInfo->image = NULL; AWT_UNLOCK(); return (jlong)(uintptr_t)glyphInfo; } #ifdef DUMP_IMAGES dumpXImage(ximage); #endif nbytes = ximage->bytes_per_line; srcRow = (unsigned char*)ximage->data; dstRow = (unsigned char*)glyphInfo->image; wholeByteCount = width >> 3; remainingBitsCount = width & 7; for (h=0; h<height; h++) { const UInt8* src8 = srcRow; UInt8 *dstByte = dstRow; UInt32 srcValue; srcRow += nbytes; dstRow += width; for (i = 0; i < wholeByteCount; i++) { srcValue = *src8++; for (j = 0; j < 8; j++) { if (ximage->bitmap_bit_order == LSBFirst) { *dstByte++ = (srcValue & 0x01) ? 0xFF : 0; srcValue >>= 1; } else { /* MSBFirst */ *dstByte++ = (srcValue & 0x80) ? 0xFF : 0; srcValue <<= 1; } } } if (remainingBitsCount) { srcValue = *src8; for (j = 0; j < remainingBitsCount; j++) { if (ximage->bitmap_bit_order == LSBFirst) { *dstByte++ = (srcValue & 0x01) ? 0xFF : 0; srcValue >>= 1; } else { /* MSBFirst */ *dstByte++ = (srcValue & 0x80) ? 0xFF : 0; srcValue <<= 1; } } } } XDestroyImage (ximage); AWT_UNLOCK(); return (jlong)(uintptr_t)glyphInfo; #else return (jlong)0; #endif /* !HEADLESS */ } JNIEXPORT short JNICALL AWTCharAdvance(AWTChar xChar) { #ifdef HEADLESS return 0; #else return ((XCharStruct *)xChar)->width; #endif /* !HEADLESS */ } JNIEXPORT short JNICALL AWTCharLBearing(AWTChar xChar) { #ifdef HEADLESS return 0; #else return ((XCharStruct *)xChar)->lbearing; #endif /* !HEADLESS */ } JNIEXPORT short JNICALL AWTCharRBearing(AWTChar xChar) { #ifdef HEADLESS return 0; #else return ((XCharStruct *)xChar)->rbearing; #endif /* !HEADLESS */ } JNIEXPORT short JNICALL AWTCharAscent(AWTChar xChar) { #ifdef HEADLESS return 0; #else return ((XCharStruct *)xChar)->ascent; #endif /* !HEADLESS */ } JNIEXPORT short JNICALL AWTCharDescent(AWTChar xChar) { #ifdef HEADLESS return 0; #else return ((XCharStruct *)xChar)->descent; #endif /* !HEADLESS */ }
{ "pile_set_name": "Github" }
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import { Droppable } from "react-beautiful-dnd"; import Attribute from "./Attribute"; import isNil from "lodash/isNil"; export default class FormColumnMapMapping extends PureComponent { static displayName = "Form.ColumnMap.Mapping"; static propTypes = { name: PropTypes.string.isRequired, id: PropTypes.string.isRequired, index: PropTypes.number.isRequired, match: PropTypes.string, unLink: PropTypes.func }; render() { const { match } = this.props; return ( <div className={`mapping ${match ? "matched" : ""}`}> <div className="column-label"> {this.props.name ? ( <span className="truncate">{this.props.name}</span> ) : ( <span className="truncate">&nbsp;</span> )} </div> <Droppable droppableId={this.props.id} isDropDisabled={!isNil(match)}> {(provided, snapshot) => { // Set a class if element is being dragged over const wellClass = classNames("well", { "drag-over": snapshot.isDraggingOver, matched: match }); return ( <div className={wellClass} ref={provided.innerRef}> {this.props.match ? ( <Attribute name={this.props.match} index={this.props.index} unLink={this.props.unLink} mapping={this.props.name} /> ) : null} <span className="placeholder">{"Drag column ..."}</span> {provided.placeholder} </div> ); }} </Droppable> </div> ); } }
{ "pile_set_name": "Github" }
/* * Copyright 2007-2009 Freescale Semiconductor, Inc. * * SPDX-License-Identifier: GPL-2.0+ */ #include "config.h" /* CONFIG_BOARDDIR */ #ifndef RESET_VECTOR_ADDRESS #ifdef CONFIG_RESET_VECTOR_ADDRESS #define RESET_VECTOR_ADDRESS CONFIG_RESET_VECTOR_ADDRESS #else #define RESET_VECTOR_ADDRESS 0xfffffffc #endif #endif OUTPUT_ARCH(powerpc) PHDRS { text PT_LOAD; bss PT_LOAD; } SECTIONS { /* Read-only sections, merged into text segment: */ . = + SIZEOF_HEADERS; .text : { *(.text*) } :text _etext = .; PROVIDE (etext = .); .rodata : { *(SORT_BY_ALIGNMENT(SORT_BY_NAME(.rodata*))) } :text /* Read-write section, merged into data segment: */ . = (. + 0x00FF) & 0xFFFFFF00; _erotext = .; PROVIDE (erotext = .); .reloc : { _GOT2_TABLE_ = .; KEEP(*(.got2)) KEEP(*(.got)) PROVIDE(_GLOBAL_OFFSET_TABLE_ = . + 4); _FIXUP_TABLE_ = .; KEEP(*(.fixup)) } __got2_entries = ((_GLOBAL_OFFSET_TABLE_ - _GOT2_TABLE_) >> 2) - 1; __fixup_entries = (. - _FIXUP_TABLE_) >> 2; .data : { *(.data*) *(.sdata*) } _edata = .; PROVIDE (edata = .); . = .; . = ALIGN(4); .u_boot_list : { KEEP(*(SORT(.u_boot_list*))); } . = .; __start___ex_table = .; __ex_table : { *(__ex_table) } __stop___ex_table = .; . = ALIGN(256); __init_begin = .; .text.init : { *(.text.init) } .data.init : { *(.data.init) } . = ALIGN(256); __init_end = .; #ifndef CONFIG_SPL #ifdef CONFIG_440 .bootpg RESET_VECTOR_ADDRESS - 0xffc : { arch/powerpc/cpu/ppc4xx/start.o (.bootpg) /* * PPC440 board need a board specific object with the * TLB definitions. This needs to get included right after * start.o, since the first shadow TLB only covers 4k * of address space. */ #ifdef CONFIG_INIT_TLB CONFIG_INIT_TLB (.bootpg) #else CONFIG_BOARDDIR/init.o (.bootpg) #endif } :text = 0xffff #endif .resetvec RESET_VECTOR_ADDRESS : { KEEP(*(.resetvec)) } :text = 0xffff . = RESET_VECTOR_ADDRESS + 0x4; /* * Make sure that the bss segment isn't linked at 0x0, otherwise its * address won't be updated during relocation fixups. Note that * this is a temporary fix. Code to dynamically the fixup the bss * location will be added in the future. When the bss relocation * fixup code is present this workaround should be removed. */ #if (RESET_VECTOR_ADDRESS == 0xfffffffc) . |= 0x10; #endif #endif /* CONFIG_SPL */ __bss_start = .; .bss (NOLOAD) : { *(.bss*) *(.sbss*) *(COMMON) } :bss . = ALIGN(4); __bss_end = . ; PROVIDE (end = .); }
{ "pile_set_name": "Github" }
[ { "colorId": 0, "hexString": "#000000", "rgb": { "r": 0, "g": 0, "b": 0 }, "hsl": { "h": 0, "s": 0, "l": 0 }, "name": "Black" }, { "colorId": 1, "hexString": "#800000", "rgb": { "r": 128, "g": 0, "b": 0 }, "hsl": { "h": 0, "s": 100, "l": 25 }, "name": "Maroon" }, { "colorId": 2, "hexString": "#008000", "rgb": { "r": 0, "g": 128, "b": 0 }, "hsl": { "h": 120, "s": 100, "l": 25 }, "name": "Green" }, { "colorId": 3, "hexString": "#808000", "rgb": { "r": 128, "g": 128, "b": 0 }, "hsl": { "h": 60, "s": 100, "l": 25 }, "name": "Olive" }, { "colorId": 4, "hexString": "#000080", "rgb": { "r": 0, "g": 0, "b": 128 }, "hsl": { "h": 240, "s": 100, "l": 25 }, "name": "Navy" }, { "colorId": 5, "hexString": "#800080", "rgb": { "r": 128, "g": 0, "b": 128 }, "hsl": { "h": 300, "s": 100, "l": 25 }, "name": "Purple" }, { "colorId": 6, "hexString": "#008080", "rgb": { "r": 0, "g": 128, "b": 128 }, "hsl": { "h": 180, "s": 100, "l": 25 }, "name": "Teal" }, { "colorId": 7, "hexString": "#c0c0c0", "rgb": { "r": 192, "g": 192, "b": 192 }, "hsl": { "h": 0, "s": 0, "l": 75 }, "name": "Silver" } ]
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:73cc615d470f897ba18376e4e6676598dde48eef7a581dd9cb212c7fa825b1ee size 19287
{ "pile_set_name": "Github" }
// Copyright 2018 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 !gccgo #include "textflag.h" // // System calls for ppc64, AIX are implemented in runtime/syscall_aix.go // TEXT ·syscall6(SB),NOSPLIT,$0-88 JMP syscall·syscall6(SB) TEXT ·rawSyscall6(SB),NOSPLIT,$0-88 JMP syscall·rawSyscall6(SB)
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## 准备数据" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "import os\n", "import tensorflow as tf\n", "from tensorflow import keras\n", "from tensorflow.keras import layers, optimizers, datasets\n", "from tensorflow.keras.layers import Dense, Dropout, Flatten\n", "from tensorflow.keras.layers import Conv2D, MaxPooling2D\n", "\n", "os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # or any {'0', '1', '2'}\n", "\n", "def mnist_dataset():\n", " (x, y), (x_test, y_test) = datasets.mnist.load_data()\n", " x = x.reshape(x.shape[0], 28, 28,1)\n", " x_test = x_test.reshape(x_test.shape[0], 28, 28,1)\n", " \n", " ds = tf.data.Dataset.from_tensor_slices((x, y))\n", " ds = ds.map(prepare_mnist_features_and_labels)\n", " ds = ds.take(20000).shuffle(20000).batch(32)\n", " \n", " test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n", " test_ds = test_ds.map(prepare_mnist_features_and_labels)\n", " test_ds = test_ds.take(20000).shuffle(20000).batch(20000)\n", " return ds, test_ds\n", "\n", "def prepare_mnist_features_and_labels(x, y):\n", " x = tf.cast(x, tf.float32) / 255.0\n", " y = tf.cast(y, tf.int64)\n", " return x, y" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 建立模型" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "class myConvModel(keras.Model):\n", " def __init__(self):\n", " super(myConvModel, self).__init__()\n", " self.l1_conv = Conv2D(32, (5, 5), activation='relu', padding='same')\n", " self.l2_conv = Conv2D(64, (5, 5), activation='relu', padding='same')\n", " self.pool = MaxPooling2D(pool_size=(2, 2), strides=2)\n", " self.flat = Flatten()\n", " self.dense1 = layers.Dense(100, activation='tanh')\n", " self.dense2 = layers.Dense(10)\n", " @tf.function\n", " def call(self, x):\n", " h1 = self.l1_conv(x)\n", " h1_pool = self.pool(h1)\n", " h2 = self.l2_conv(h1_pool)\n", " h2_pool = self.pool(h2)\n", " flat_h = self.flat(h2_pool)\n", " dense1 = self.dense1(flat_h)\n", " logits = self.dense2(dense1)\n", " return logits\n", "\n", "model = myConvModel()\n", "optimizer = optimizers.Adam()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 定义loss以及train loop" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "@tf.function\n", "def compute_loss(logits, labels):\n", " return tf.reduce_mean(\n", " tf.nn.sparse_softmax_cross_entropy_with_logits(\n", " logits=logits, labels=labels))\n", "\n", "@tf.function\n", "def compute_accuracy(logits, labels):\n", " predictions = tf.argmax(logits, axis=1)\n", " return tf.reduce_mean(tf.cast(tf.equal(predictions, labels), tf.float32))\n", "\n", "@tf.function\n", "def train_one_step(model, optimizer, x, y):\n", "\n", " with tf.GradientTape() as tape:\n", " logits = model(x)\n", " loss = compute_loss(logits, y)\n", "\n", " # compute gradient\n", " grads = tape.gradient(loss, model.trainable_variables)\n", " # update to weights\n", " optimizer.apply_gradients(zip(grads, model.trainable_variables))\n", "\n", " accuracy = compute_accuracy(logits, y)\n", "\n", " # loss and accuracy is scalar tensor\n", " return loss, accuracy\n", "\n", "@tf.function\n", "def test_step(model, x, y):\n", " logits = model(x)\n", " loss = compute_loss(logits, y)\n", " accuracy = compute_accuracy(logits, y)\n", " return loss, accuracy\n", "\n", "def train(epoch, model, optimizer, ds):\n", " loss = 0.0\n", " accuracy = 0.0\n", " for step, (x, y) in enumerate(ds):\n", " loss, accuracy = train_one_step(model, optimizer, x, y)\n", "\n", " if step % 500 == 0:\n", " print('epoch', epoch, ': loss', loss.numpy(), '; accuracy', accuracy.numpy())\n", "\n", " return loss, accuracy\n", "def test(model, ds):\n", " loss = 0.0\n", " accuracy = 0.0\n", " for step, (x, y) in enumerate(ds):\n", " loss, accuracy = test_step(model, x, y)\n", "\n", " \n", " print('test loss', loss.numpy(), '; accuracy', accuracy.numpy())\n", "\n", " return loss, accuracy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 训练" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "epoch 0 : loss 2.307023 ; accuracy 0.09375\n", "epoch 0 : loss 0.16172078 ; accuracy 0.96875\n", "epoch 1 : loss 0.15242997 ; accuracy 0.9375\n", "epoch 1 : loss 0.24359244 ; accuracy 0.9375\n", "test loss 0.057900324 ; accuracy 0.9812\n" ] } ], "source": [ "train_ds, test_ds = mnist_dataset()\n", "for epoch in range(2):\n", " loss, accuracy = train(epoch, model, optimizer, train_ds)\n", "loss, accuracy = test(model, test_ds)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }
{ "pile_set_name": "Github" }
## @file # Create makefile for MS nmake and GNU make # # Copyright (c) 2019, Intel Corporation. All rights reserved.<BR> # SPDX-License-Identifier: BSD-2-Clause-Patent # from __future__ import absolute_import from Workspace.WorkspaceDatabase import BuildDB from Workspace.WorkspaceCommon import GetModuleLibInstances import Common.GlobalData as GlobalData import os import pickle from pickle import HIGHEST_PROTOCOL from Common import EdkLogger class PCD_DATA(): def __init__(self,TokenCName,TokenSpaceGuidCName,Type,DatumType,SkuInfoList,DefaultValue, MaxDatumSize,UserDefinedDefaultStoresFlag,validateranges, validlists,expressions,CustomAttribute,TokenValue): self.TokenCName = TokenCName self.TokenSpaceGuidCName = TokenSpaceGuidCName self.Type = Type self.DatumType = DatumType self.SkuInfoList = SkuInfoList self.DefaultValue = DefaultValue self.MaxDatumSize = MaxDatumSize self.UserDefinedDefaultStoresFlag = UserDefinedDefaultStoresFlag self.validateranges = validateranges self.validlists = validlists self.expressions = expressions self.CustomAttribute = CustomAttribute self.TokenValue = TokenValue class DataPipe(object): def __init__(self, BuildDir=None): self.data_container = {} self.BuildDir = BuildDir self.dump_file = "" class MemoryDataPipe(DataPipe): def Get(self,key): return self.data_container.get(key) def dump(self,file_path): self.dump_file = file_path with open(file_path,'wb') as fd: pickle.dump(self.data_container,fd,pickle.HIGHEST_PROTOCOL) def load(self,file_path): with open(file_path,'rb') as fd: self.data_container = pickle.load(fd) @property def DataContainer(self): return self.data_container @DataContainer.setter def DataContainer(self,data): self.data_container.update(data) def FillData(self,PlatformInfo): #Platform Pcds self.DataContainer = { "PLA_PCD" : [PCD_DATA( pcd.TokenCName,pcd.TokenSpaceGuidCName,pcd.Type, pcd.DatumType,pcd.SkuInfoList,pcd.DefaultValue, pcd.MaxDatumSize,pcd.UserDefinedDefaultStoresFlag,pcd.validateranges, pcd.validlists,pcd.expressions,pcd.CustomAttribute,pcd.TokenValue) for pcd in PlatformInfo.Platform.Pcds.values()] } #Platform Module Pcds ModulePcds = {} for m in PlatformInfo.Platform.Modules: m_pcds = PlatformInfo.Platform.Modules[m].Pcds if m_pcds: ModulePcds[(m.File,m.Root,m.Arch)] = [PCD_DATA( pcd.TokenCName,pcd.TokenSpaceGuidCName,pcd.Type, pcd.DatumType,pcd.SkuInfoList,pcd.DefaultValue, pcd.MaxDatumSize,pcd.UserDefinedDefaultStoresFlag,pcd.validateranges, pcd.validlists,pcd.expressions,pcd.CustomAttribute,pcd.TokenValue) for pcd in PlatformInfo.Platform.Modules[m].Pcds.values()] self.DataContainer = {"MOL_PCDS":ModulePcds} #Module's Library Instance ModuleLibs = {} libModules = {} for m in PlatformInfo.Platform.Modules: module_obj = BuildDB.BuildObject[m,PlatformInfo.Arch,PlatformInfo.BuildTarget,PlatformInfo.ToolChain] Libs = GetModuleLibInstances(module_obj, PlatformInfo.Platform, BuildDB.BuildObject, PlatformInfo.Arch,PlatformInfo.BuildTarget,PlatformInfo.ToolChain,PlatformInfo.MetaFile,EdkLogger) for lib in Libs: try: libModules[(lib.MetaFile.File,lib.MetaFile.Root,lib.Arch,lib.MetaFile.Path)].append((m.File,m.Root,module_obj.Arch,m.Path)) except: libModules[(lib.MetaFile.File,lib.MetaFile.Root,lib.Arch,lib.MetaFile.Path)] = [(m.File,m.Root,module_obj.Arch,m.Path)] ModuleLibs[(m.File,m.Root,module_obj.Arch,m.Path)] = [(l.MetaFile.File,l.MetaFile.Root,l.Arch,l.MetaFile.Path) for l in Libs] self.DataContainer = {"DEPS":ModuleLibs} self.DataContainer = {"REFS":libModules} #Platform BuildOptions platform_build_opt = PlatformInfo.EdkIIBuildOption ToolDefinition = PlatformInfo.ToolDefinition module_build_opt = {} for m in PlatformInfo.Platform.Modules: ModuleTypeOptions, PlatformModuleOptions = PlatformInfo.GetGlobalBuildOptions(BuildDB.BuildObject[m,PlatformInfo.Arch,PlatformInfo.BuildTarget,PlatformInfo.ToolChain]) if ModuleTypeOptions or PlatformModuleOptions: module_build_opt.update({(m.File,m.Root): {"ModuleTypeOptions":ModuleTypeOptions, "PlatformModuleOptions":PlatformModuleOptions}}) self.DataContainer = {"PLA_BO":platform_build_opt, "TOOLDEF":ToolDefinition, "MOL_BO":module_build_opt } #Platform Info PInfo = { "WorkspaceDir":PlatformInfo.Workspace.WorkspaceDir, "Target":PlatformInfo.BuildTarget, "ToolChain":PlatformInfo.Workspace.ToolChain, "BuildRuleFile":PlatformInfo.BuildRule, "Arch": PlatformInfo.Arch, "ArchList":PlatformInfo.Workspace.ArchList, "ActivePlatform":PlatformInfo.MetaFile } self.DataContainer = {'P_Info':PInfo} self.DataContainer = {'M_Name':PlatformInfo.UniqueBaseName} self.DataContainer = {"ToolChainFamily": PlatformInfo.ToolChainFamily} self.DataContainer = {"BuildRuleFamily": PlatformInfo.BuildRuleFamily} self.DataContainer = {"MixedPcd":GlobalData.MixedPcd} self.DataContainer = {"BuildOptPcd":GlobalData.BuildOptionPcd} self.DataContainer = {"BuildCommand": PlatformInfo.BuildCommand} self.DataContainer = {"AsBuildModuleList": PlatformInfo._AsBuildModuleList} self.DataContainer = {"G_defines": GlobalData.gGlobalDefines} self.DataContainer = {"CL_defines": GlobalData.gCommandLineDefines} self.DataContainer = {"Env_Var": {k:v for k, v in os.environ.items()}} self.DataContainer = {"PackageList": [(dec.MetaFile,dec.Arch) for dec in PlatformInfo.PackageList]} self.DataContainer = {"GuidDict": PlatformInfo.Platform._GuidDict} self.DataContainer = {"DatabasePath":GlobalData.gDatabasePath} self.DataContainer = {"FdfParser": True if GlobalData.gFdfParser else False} self.DataContainer = {"LogLevel": EdkLogger.GetLevel()} self.DataContainer = {"BinCacheSource":GlobalData.gBinCacheSource} self.DataContainer = {"BinCacheDest":GlobalData.gBinCacheDest} self.DataContainer = {"EnableGenfdsMultiThread":GlobalData.gEnableGenfdsMultiThread}
{ "pile_set_name": "Github" }
{ "type": "minecraft:block", "pools": [ { "rolls": 1, "entries": [ { "type": "minecraft:item", "functions": [ { "function": "minecraft:set_count", "conditions": [ { "condition": "minecraft:block_state_property", "block": "quark:green_stained_planks_vertical_slab", "properties": { "type": "double" } } ], "count": 2 }, { "function": "minecraft:explosion_decay" } ], "name": "quark:green_stained_planks_vertical_slab" } ] } ] }
{ "pile_set_name": "Github" }
RUN: obj2yaml %p/Inputs/trivial-object-test.coff-i386 | FileCheck %s --check-prefix COFF-I386 RUN: obj2yaml %p/Inputs/trivial-object-test.coff-x86-64 | FileCheck %s --check-prefix COFF-X86-64 RUN: obj2yaml %p/Inputs/trivial-object-test.elf-mipsel | FileCheck %s --check-prefix ELF-MIPSEL RUN: obj2yaml %p/Inputs/trivial-object-test.elf-mips64el | FileCheck %s --check-prefix ELF-MIPS64EL RUN: obj2yaml %p/Inputs/trivial-object-test.elf-x86-64 | FileCheck %s --check-prefix ELF-X86-64 RUN: obj2yaml %p/Inputs/unwind-section.elf-x86-64 \ RUN: | FileCheck %s --check-prefix ELF-X86-64-UNWIND COFF-I386: header: COFF-I386-NEXT: Machine: IMAGE_FILE_MACHINE_I386 COFF-I386: sections: COFF-I386-NEXT: - Name: .text COFF-I386-NEXT: Characteristics: [ IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ ] COFF-I386-NEXT: Alignment: 16 COFF-I386-NEXT: SectionData: 83EC0CC744240800000000C7042400000000E800000000E8000000008B44240883C40CC3 COFF-I386: Relocations: COFF-I386-NEXT: - VirtualAddress: 14 COFF-I386-NEXT: SymbolName: L_.str COFF-I386-NEXT: Type: IMAGE_REL_I386_DIR32 COFF-I386: - VirtualAddress: 19 COFF-I386-NEXT: SymbolName: _puts COFF-I386-NEXT: Type: IMAGE_REL_I386_REL32 COFF-I386: - VirtualAddress: 24 COFF-I386-NEXT: SymbolName: _SomeOtherFunction COFF-I386-NEXT: Type: IMAGE_REL_I386_REL32 COFF-I386: - Name: .data COFF-I386-NEXT: Characteristics: [ IMAGE_SCN_CNT_INITIALIZED_DATA, IMAGE_SCN_MEM_READ, IMAGE_SCN_MEM_WRITE ] COFF-I386-NEXT: Alignment: 1 COFF-I386-NEXT: SectionData: 48656C6C6F20576F726C642100 COFF-I386: symbols: COFF-I386-NEXT: - Name: .text COFF-I386-NEXT: Value: 0 COFF-I386-NEXT: SectionNumber: 1 COFF-I386-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-I386-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-I386-NEXT: StorageClass: IMAGE_SYM_CLASS_STATIC COFF-I386-NEXT: SectionDefinition: COFF-I386-NEXT: Length: 36 COFF-I386-NEXT: NumberOfRelocations: 3 COFF-I386-NEXT: NumberOfLinenumbers: 0 COFF-I386-NEXT: CheckSum: 0 COFF-I386-NEXT: Number: 1 COFF-I386: - Name: .data COFF-I386-NEXT: Value: 0 COFF-I386-NEXT: SectionNumber: 2 COFF-I386-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-I386-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-I386-NEXT: StorageClass: IMAGE_SYM_CLASS_STATIC COFF-I386-NEXT: SectionDefinition: COFF-I386-NEXT: Length: 13 COFF-I386-NEXT: NumberOfRelocations: 0 COFF-I386-NEXT: NumberOfLinenumbers: 0 COFF-I386-NEXT: CheckSum: 0 COFF-I386-NEXT: Number: 2 COFF-I386: - Name: _main COFF-I386-NEXT: Value: 0 COFF-I386-NEXT: SectionNumber: 1 COFF-I386-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-I386-NEXT: ComplexType: IMAGE_SYM_DTYPE_FUNCTION COFF-I386-NEXT: StorageClass: IMAGE_SYM_CLASS_EXTERNAL COFF-I386: - Name: L_.str COFF-I386-NEXT: Value: 0 COFF-I386-NEXT: SectionNumber: 2 COFF-I386-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-I386-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-I386-NEXT: StorageClass: IMAGE_SYM_CLASS_STATIC COFF-I386: - Name: _puts COFF-I386-NEXT: Value: 0 COFF-I386-NEXT: SectionNumber: 0 COFF-I386-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-I386-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-I386-NEXT: StorageClass: IMAGE_SYM_CLASS_EXTERNAL COFF-I386: - Name: _SomeOtherFunction COFF-I386-NEXT: Value: 0 COFF-I386-NEXT: SectionNumber: 0 COFF-I386-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-I386-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-I386-NEXT: StorageClass: IMAGE_SYM_CLASS_EXTERNAL COFF-X86-64: header: COFF-X86-64-NEXT: Machine: IMAGE_FILE_MACHINE_AMD64 COFF-X86-64: sections: COFF-X86-64-NEXT: - Name: .text COFF-X86-64-NEXT: Characteristics: [ IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ ] COFF-X86-64-NEXT: Alignment: 16 COFF-X86-64-NEXT: SectionData: 4883EC28C744242400000000488D0D00000000E800000000E8000000008B4424244883C428C3 COFF-X86-64: Relocations: COFF-X86-64-NEXT: - VirtualAddress: 15 COFF-X86-64-NEXT: SymbolName: L.str COFF-X86-64-NEXT: Type: IMAGE_REL_AMD64_REL32 COFF-X86-64: - VirtualAddress: 20 COFF-X86-64-NEXT: SymbolName: puts COFF-X86-64-NEXT: Type: IMAGE_REL_AMD64_REL32 COFF-X86-64: - VirtualAddress: 25 COFF-X86-64-NEXT: SymbolName: SomeOtherFunction COFF-X86-64-NEXT: Type: IMAGE_REL_AMD64_REL32 COFF-X86-64: - Name: .data COFF-X86-64-NEXT: Characteristics: [ IMAGE_SCN_CNT_INITIALIZED_DATA, IMAGE_SCN_MEM_READ, IMAGE_SCN_MEM_WRITE ] COFF-X86-64-NEXT: Alignment: 1 COFF-X86-64-NEXT: SectionData: 48656C6C6F20576F726C642100 COFF-X86-64: - Name: '.CRT$XCU' COFF-X86-64-NEXT: Characteristics: [ IMAGE_SCN_CNT_INITIALIZED_DATA, IMAGE_SCN_MEM_READ ] COFF-X86-64-NEXT: Alignment: 8 COFF-X86-64-NEXT: SectionData: '0000000000000000' COFF-X86-64: Relocations: COFF-X86-64-NEXT: - VirtualAddress: 0 COFF-X86-64-NEXT: SymbolName: '??__Ex@@YAXXZ' COFF-X86-64-NEXT: Type: IMAGE_REL_AMD64_ADDR64 COFF-X86-64: symbols: COFF-X86-64-NEXT: - Name: .text COFF-X86-64-NEXT: Value: 0 COFF-X86-64-NEXT: SectionNumber: 1 COFF-X86-64-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-X86-64-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-X86-64-NEXT: StorageClass: IMAGE_SYM_CLASS_STATIC COFF-X86-64-NEXT: SectionDefinition: COFF-X86-64-NEXT: Length: 38 COFF-X86-64-NEXT: NumberOfRelocations: 3 COFF-X86-64-NEXT: NumberOfLinenumbers: 0 COFF-X86-64-NEXT: CheckSum: 0 COFF-X86-64-NEXT: Number: 1 COFF-X86-64: - Name: .data COFF-X86-64-NEXT: Value: 0 COFF-X86-64-NEXT: SectionNumber: 2 COFF-X86-64-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-X86-64-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-X86-64-NEXT: StorageClass: IMAGE_SYM_CLASS_STATIC COFF-X86-64-NEXT: SectionDefinition: COFF-X86-64-NEXT: Length: 13 COFF-X86-64-NEXT: NumberOfRelocations: 0 COFF-X86-64-NEXT: NumberOfLinenumbers: 0 COFF-X86-64-NEXT: CheckSum: 0 COFF-X86-64-NEXT: Number: 2 COFF-X86-64: - Name: main COFF-X86-64-NEXT: Value: 0 COFF-X86-64-NEXT: SectionNumber: 1 COFF-X86-64-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-X86-64-NEXT: ComplexType: IMAGE_SYM_DTYPE_FUNCTION COFF-X86-64-NEXT: StorageClass: IMAGE_SYM_CLASS_EXTERNAL COFF-X86-64: - Name: L.str COFF-X86-64-NEXT: Value: 0 COFF-X86-64-NEXT: SectionNumber: 2 COFF-X86-64-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-X86-64-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-X86-64-NEXT: StorageClass: IMAGE_SYM_CLASS_STATIC COFF-X86-64: - Name: puts COFF-X86-64-NEXT: Value: 0 COFF-X86-64-NEXT: SectionNumber: 0 COFF-X86-64-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-X86-64-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-X86-64-NEXT: StorageClass: IMAGE_SYM_CLASS_EXTERNAL COFF-X86-64: - Name: SomeOtherFunction COFF-X86-64-NEXT: Value: 0 COFF-X86-64-NEXT: SectionNumber: 0 COFF-X86-64-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-X86-64-NEXT: ComplexType: IMAGE_SYM_DTYPE_NULL COFF-X86-64-NEXT: StorageClass: IMAGE_SYM_CLASS_EXTERNAL COFF-X86-64: - Name: '??__Ex@@YAXXZ' COFF-X86-64-NEXT: Value: 0 COFF-X86-64-NEXT: SectionNumber: 3 COFF-X86-64-NEXT: SimpleType: IMAGE_SYM_TYPE_NULL COFF-X86-64-NEXT: ComplexType: IMAGE_SYM_DTYPE_FUNCTION COFF-X86-64-NEXT: StorageClass: IMAGE_SYM_CLASS_STATIC ELF-MIPSEL: FileHeader: ELF-MIPSEL-NEXT: Class: ELFCLASS32 ELF-MIPSEL-NEXT: Data: ELFDATA2LSB ELF-MIPSEL-NEXT: OSABI: ELFOSABI_GNU ELF-MIPSEL-NEXT: Type: ET_REL ELF-MIPSEL-NEXT: Machine: EM_MIPS ELF-MIPSEL-NEXT: Flags: [ EF_MIPS_NOREORDER, EF_MIPS_PIC, EF_MIPS_CPIC, EF_MIPS_ABI_O32, EF_MIPS_ARCH_32 ] ELF-MIPSEL-NEXT: Sections: ELF-MIPSEL-NEXT: - Name: .text ELF-MIPSEL-NEXT: Type: SHT_PROGBITS ELF-MIPSEL-NEXT: Flags: [ SHF_ALLOC, SHF_EXECINSTR ] ELF-MIPSEL-NEXT: AddressAlign: 0x0000000000000004 ELF-MIPSEL-NEXT: Content: 0000023C00004224E8FFBD271400BFAF1000B0AF218059000000018E000024240000198E09F8200321E000020000198E09F8200321E00002000002241000B08F1400BF8F0800E0031800BD27 ELF-MIPSEL-NEXT: - Name: .rel.text ELF-MIPSEL-NEXT: Type: SHT_REL ELF-MIPSEL-NEXT: Link: .symtab ELF-MIPSEL-NEXT: AddressAlign: 0x0000000000000004 ELF-MIPSEL-NEXT: Info: .text ELF-MIPSEL-NEXT: Relocations: ELF-MIPSEL-NEXT: - Offset: 0x0000000000000000 ELF-MIPSEL-NEXT: Symbol: _gp_disp ELF-MIPSEL-NEXT: Type: R_MIPS_HI16 ELF-MIPSEL-NEXT: - Offset: 0x0000000000000004 ELF-MIPSEL-NEXT: Symbol: _gp_disp ELF-MIPSEL-NEXT: Type: R_MIPS_LO16 ELF-MIPSEL-NEXT: - Offset: 0x0000000000000018 ELF-MIPSEL-NEXT: Symbol: '$.str' ELF-MIPSEL-NEXT: Type: R_MIPS_GOT16 ELF-MIPSEL-NEXT: - Offset: 0x000000000000001C ELF-MIPSEL-NEXT: Symbol: '$.str' ELF-MIPSEL-NEXT: Type: R_MIPS_LO16 ELF-MIPSEL-NEXT: - Offset: 0x0000000000000020 ELF-MIPSEL-NEXT: Symbol: puts ELF-MIPSEL-NEXT: Type: R_MIPS_CALL16 ELF-MIPSEL-NEXT: - Offset: 0x000000000000002C ELF-MIPSEL-NEXT: Symbol: SomeOtherFunction ELF-MIPSEL-NEXT: Type: R_MIPS_CALL16 ELF-MIPSEL-NEXT: - Name: .data ELF-MIPSEL-NEXT: Type: SHT_PROGBITS ELF-MIPSEL-NEXT: Flags: [ SHF_WRITE, SHF_ALLOC ] ELF-MIPSEL-NEXT: AddressAlign: 0x0000000000000004 ELF-MIPSEL-NEXT: Content: '' ELF-MIPSEL-NEXT: - Name: .bss ELF-MIPSEL-NEXT: Type: SHT_NOBITS ELF-MIPSEL-NEXT: Flags: [ SHF_WRITE, SHF_ALLOC ] ELF-MIPSEL-NEXT: AddressAlign: 0x0000000000000004 ELF-MIPSEL-NEXT: Size: 0x0000000000000004 ELF-MIPSEL-NEXT: - Name: .mdebug.abi32 ELF-MIPSEL-NEXT: Type: SHT_PROGBITS ELF-MIPSEL-NEXT: AddressAlign: 0x0000000000000001 ELF-MIPSEL-NEXT: Content: '' ELF-MIPSEL-NEXT: - Name: .rodata.str1.1 ELF-MIPSEL-NEXT: Type: SHT_PROGBITS ELF-MIPSEL-NEXT: Flags: [ SHF_ALLOC, SHF_MERGE, SHF_STRINGS ] ELF-MIPSEL-NEXT: AddressAlign: 0x0000000000000001 ELF-MIPSEL-NEXT: Content: 48656C6C6F20576F726C640A00 ELF-MIPSEL-NEXT: - Name: .reginfo ELF-MIPSEL-NEXT: Type: SHT_MIPS_REGINFO ELF-MIPSEL-NEXT: Flags: [ SHF_ALLOC ] ELF-MIPSEL-NEXT: AddressAlign: 0x0000000000000001 ELF-MIPSEL-NEXT: Content: '000000000000000000000000000000000000000000000000' ELF-MIPSEL-NEXT: - Name: .MIPS.abiflags ELF-MIPSEL-NEXT: Type: SHT_MIPS_ABIFLAGS ELF-MIPSEL-NEXT: Flags: [ SHF_ALLOC ] ELF-MIPSEL-NEXT: AddressAlign: 0x0000000000000008 ELF-MIPSEL-NEXT: ISA: MIPS32 ELF-MIPSEL-NEXT: ISARevision: 0x01 ELF-MIPSEL-NEXT: FpABI: FP_DOUBLE ELF-MIPSEL-NEXT: GPRSize: REG_32 ELF-MIPSEL-NEXT: CPR1Size: REG_32 ELF-MIPSEL-NEXT: Flags1: [ ODDSPREG ] ELF-MIPSEL-NEXT: Symbols: ELF-MIPSEL-NEXT: Local: ELF-MIPSEL-NEXT: - Name: trivial.ll ELF-MIPSEL-NEXT: Type: STT_FILE ELF-MIPSEL-NEXT: - Name: '$.str' ELF-MIPSEL-NEXT: Type: STT_OBJECT ELF-MIPSEL-NEXT: Section: .rodata.str1.1 ELF-MIPSEL-NEXT: Size: 0x000000000000000D ELF-MIPSEL-NEXT: - Type: STT_SECTION ELF-MIPSEL-NEXT: Section: .text ELF-MIPSEL-NEXT: - Type: STT_SECTION ELF-MIPSEL-NEXT: Section: .data ELF-MIPSEL-NEXT: - Type: STT_SECTION ELF-MIPSEL-NEXT: Section: .bss ELF-MIPSEL-NEXT: - Type: STT_SECTION ELF-MIPSEL-NEXT: Section: .mdebug.abi32 ELF-MIPSEL-NEXT: - Type: STT_SECTION ELF-MIPSEL-NEXT: Section: .rodata.str1.1 ELF-MIPSEL-NEXT: - Type: STT_SECTION ELF-MIPSEL-NEXT: Section: .reginfo ELF-MIPSEL-NEXT: - Type: STT_SECTION ELF-MIPSEL-NEXT: Section: .MIPS.abiflags ELF-MIPSEL-NEXT: Global: ELF-MIPSEL-NEXT: - Name: main ELF-MIPSEL-NEXT: Type: STT_FUNC ELF-MIPSEL-NEXT: Section: .text ELF-MIPSEL-NEXT: Size: 0x000000000000004C ELF-MIPSEL-NEXT: - Name: var ELF-MIPSEL-NEXT: Type: STT_OBJECT ELF-MIPSEL-NEXT: Section: .bss ELF-MIPSEL-NEXT: Size: 0x0000000000000004 ELF-MIPSEL-NEXT: - Name: SomeOtherFunction ELF-MIPSEL-NEXT: - Name: _gp_disp ELF-MIPSEL-NEXT: - Name: puts ELF-MIPS64EL: FileHeader: ELF-MIPS64EL-NEXT: Class: ELFCLASS64 ELF-MIPS64EL-NEXT: Data: ELFDATA2LSB ELF-MIPS64EL-NEXT: Type: ET_REL ELF-MIPS64EL-NEXT: Machine: EM_MIPS ELF-MIPS64EL-NEXT: Flags: [ EF_MIPS_ARCH_3 ] ELF-MIPS64EL-NEXT: Sections: ELF-MIPS64EL-NEXT: - Name: .text ELF-MIPS64EL-NEXT: Type: SHT_PROGBITS ELF-MIPS64EL-NEXT: Flags: [ SHF_ALLOC, SHF_EXECINSTR ] ELF-MIPS64EL-NEXT: AddressAlign: 0x0000000000000010 ELF-MIPS64EL-NEXT: Content: '' ELF-MIPS64EL-NEXT: - Name: .data ELF-MIPS64EL-NEXT: Type: SHT_PROGBITS ELF-MIPS64EL-NEXT: Flags: [ SHF_WRITE, SHF_ALLOC ] ELF-MIPS64EL-NEXT: AddressAlign: 0x0000000000000010 ELF-MIPS64EL-NEXT: Content: '00000000000000000000000000000000' ELF-MIPS64EL-NEXT: - Name: .rela.data ELF-MIPS64EL-NEXT: Type: SHT_RELA ELF-MIPS64EL-NEXT: Link: .symtab ELF-MIPS64EL-NEXT: AddressAlign: 0x0000000000000008 ELF-MIPS64EL-NEXT: Info: .data ELF-MIPS64EL-NEXT: Relocations: ELF-MIPS64EL-NEXT: - Offset: 0 ELF-MIPS64EL-NEXT: Symbol: zed ELF-MIPS64EL-NEXT: Type: R_MIPS_64 ELF-MIPS64EL-NEXT: - Name: .bss ELF-MIPS64EL-NEXT: Type: SHT_NOBITS ELF-MIPS64EL-NEXT: Flags: [ SHF_WRITE, SHF_ALLOC ] ELF-MIPS64EL-NEXT: AddressAlign: 0x0000000000000010 ELF-MIPS64EL-NEXT: - Name: .MIPS.options ELF-MIPS64EL-NEXT: Type: SHT_MIPS_OPTIONS ELF-MIPS64EL-NEXT: Flags: [ SHF_ALLOC ] ELF-MIPS64EL-NEXT: AddressAlign: 0x0000000000000008 ELF-MIPS64EL-NEXT: Content: '01280000000000000000000000000000000000000000000000000000000000000000000000000000' ELF-MIPS64EL-NEXT: - Name: .pdr ELF-MIPS64EL-NEXT: Type: SHT_PROGBITS ELF-MIPS64EL-NEXT: AddressAlign: 0x0000000000000004 ELF-MIPS64EL-NEXT: Content: '' ELF-MIPS64EL-NEXT: Symbols: ELF-MIPS64EL-NEXT: Local: ELF-MIPS64EL-NEXT: - Type: STT_SECTION ELF-MIPS64EL-NEXT: Section: .text ELF-MIPS64EL-NEXT: - Type: STT_SECTION ELF-MIPS64EL-NEXT: Section: .data ELF-MIPS64EL-NEXT: - Type: STT_SECTION ELF-MIPS64EL-NEXT: Section: .bss ELF-MIPS64EL-NEXT: - Name: bar ELF-MIPS64EL-NEXT: Section: .data ELF-MIPS64EL-NEXT: - Type: STT_SECTION ELF-MIPS64EL-NEXT: Section: .MIPS.options ELF-MIPS64EL-NEXT: - Type: STT_SECTION ELF-MIPS64EL-NEXT: Section: .pdr ELF-MIPS64EL-NEXT: Global: ELF-MIPS64EL-NEXT: - Name: zed ELF-X86-64: FileHeader: ELF-X86-64-NEXT: Class: ELFCLASS64 ELF-X86-64-NEXT: Data: ELFDATA2LSB ELF-X86-64-NEXT: OSABI: ELFOSABI_GNU ELF-X86-64-NEXT: Type: ET_REL ELF-X86-64-NEXT: Machine: EM_X86_64 ELF-X86-64-NEXT: Sections: ELF-X86-64-NEXT: - Name: .text ELF-X86-64-NEXT: Type: SHT_PROGBITS ELF-X86-64-NEXT: Flags: [ SHF_ALLOC, SHF_EXECINSTR ] ELF-X86-64-NEXT: AddressAlign: 0x0000000000000010 ELF-X86-64-NEXT: Content: 4883EC08C744240400000000BF00000000E80000000030C0E8000000008B4424044883C408C3 ELF-X86-64-NEXT: - Name: .rodata.str1.1 ELF-X86-64-NEXT: Type: SHT_PROGBITS ELF-X86-64-NEXT: Flags: [ SHF_ALLOC, SHF_MERGE, SHF_STRINGS ] ELF-X86-64-NEXT: Address: 0x0000000000000026 ELF-X86-64-NEXT: AddressAlign: 0x0000000000000001 ELF-X86-64-NEXT: Content: 48656C6C6F20576F726C642100 ELF-X86-64-NEXT: - Name: .note.GNU-stack ELF-X86-64-NEXT: Type: SHT_PROGBITS ELF-X86-64-NEXT: Address: 0x0000000000000033 ELF-X86-64-NEXT: AddressAlign: 0x0000000000000001 ELF-X86-64-NEXT: Content: '' ELF-X86-64-NEXT: - Name: .rela.text ELF-X86-64-NEXT: Type: SHT_RELA ELF-X86-64-NEXT: Address: 0x0000000000000038 ELF-X86-64-NEXT: Link: .symtab ELF-X86-64-NEXT: AddressAlign: 0x0000000000000008 ELF-X86-64-NEXT: Info: .text ELF-X86-64-NEXT: Relocations: ELF-X86-64-NEXT: - Offset: 0x000000000000000D ELF-X86-64-NEXT: Symbol: '' ELF-X86-64-NEXT: Type: R_X86_64_32S ELF-X86-64-NEXT: - Offset: 0x0000000000000012 ELF-X86-64-NEXT: Symbol: puts ELF-X86-64-NEXT: Type: R_X86_64_PC32 ELF-X86-64-NEXT: Addend: -4 ELF-X86-64-NEXT: - Offset: 0x0000000000000019 ELF-X86-64-NEXT: Symbol: SomeOtherFunction ELF-X86-64-NEXT: Type: R_X86_64_PC32 ELF-X86-64-NEXT: Addend: -4 ELF-X86-64-NEXT: Symbols: ELF-X86-64-NEXT: Local: ELF-X86-64-NEXT: - Name: trivial-object-test.s ELF-X86-64-NEXT: Type: STT_FILE ELF-X86-64-NEXT: - Type: STT_SECTION ELF-X86-64-NEXT: Section: .text ELF-X86-64-NEXT: - Type: STT_SECTION ELF-X86-64-NEXT: Section: .rodata.str1.1 ELF-X86-64-NEXT: - Type: STT_SECTION ELF-X86-64-NEXT: Section: .note.GNU-stack ELF-X86-64-NEXT: Global: ELF-X86-64-NEXT: - Name: main ELF-X86-64-NEXT: Type: STT_FUNC ELF-X86-64-NEXT: Section: .text ELF-X86-64-NEXT: Size: 0x0000000000000026 ELF-X86-64-NEXT: - Name: SomeOtherFunction ELF-X86-64-NEXT: - Name: puts ELF-X86-64-UNWIND: - Name: .eh_frame ELF-X86-64-UNWIND-NEXT: Type: SHT_X86_64_UNWIND ELF-X86-64-UNWIND-NEXT: Flags: [ SHF_ALLOC ] ELF-X86-64-UNWIND-NEXT: AddressAlign: 0x0000000000000001 ELF-X86-64-UNWIND-NEXT: Content: ''
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Mon Jun 29 06:45:45 CEST 2015 --> <title>SilentLogger (Apache Ant API)</title> <meta name="date" content="2015-06-29"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="SilentLogger (Apache Ant API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/tools/ant/listener/ProfileLogger.html" title="class in org.apache.tools.ant.listener"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/tools/ant/listener/SimpleBigProjectLogger.html" title="class in org.apache.tools.ant.listener"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/tools/ant/listener/SilentLogger.html" target="_top">Frames</a></li> <li><a href="SilentLogger.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.apache.tools.ant.DefaultLogger">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.tools.ant.listener</div> <h2 title="Class SilentLogger" class="title">Class SilentLogger</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">org.apache.tools.ant.DefaultLogger</a></li> <li> <ul class="inheritance"> <li>org.apache.tools.ant.listener.SilentLogger</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.util.EventListener, <a href="../../../../../org/apache/tools/ant/BuildListener.html" title="interface in org.apache.tools.ant">BuildListener</a>, <a href="../../../../../org/apache/tools/ant/BuildLogger.html" title="interface in org.apache.tools.ant">BuildLogger</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">SilentLogger</span> extends <a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></pre> <div class="block">A logger which logs nothing but build failure and what task might output</div> <dl><dt><span class="strong">Since:</span></dt> <dd>1.9.0</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_org.apache.tools.ant.DefaultLogger"> <!-- --> </a> <h3>Fields inherited from class&nbsp;org.apache.tools.ant.<a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></h3> <code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#emacsMode">emacsMode</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#err">err</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#LEFT_COLUMN_SIZE">LEFT_COLUMN_SIZE</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#lSep">lSep</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#msgOutputLevel">msgOutputLevel</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#out">out</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../org/apache/tools/ant/listener/SilentLogger.html#SilentLogger()">SilentLogger</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/listener/SilentLogger.html#buildFinished(org.apache.tools.ant.BuildEvent)">buildFinished</a></strong>(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</code> <div class="block">Prints whether the build succeeded or failed, any errors the occurred during the build, and how long the build took.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/listener/SilentLogger.html#buildStarted(org.apache.tools.ant.BuildEvent)">buildStarted</a></strong>(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</code> <div class="block">Responds to a build being started by just remembering the current time.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/listener/SilentLogger.html#targetFinished(org.apache.tools.ant.BuildEvent)">targetFinished</a></strong>(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</code> <div class="block">No-op implementation.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/listener/SilentLogger.html#targetStarted(org.apache.tools.ant.BuildEvent)">targetStarted</a></strong>(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</code> <div class="block">Logs a message to say that the target has started if this logger allows information-level messages.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/listener/SilentLogger.html#taskFinished(org.apache.tools.ant.BuildEvent)">taskFinished</a></strong>(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</code> <div class="block">No-op implementation.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/listener/SilentLogger.html#taskStarted(org.apache.tools.ant.BuildEvent)">taskStarted</a></strong>(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</code> <div class="block">No-op implementation.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.apache.tools.ant.DefaultLogger"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.tools.ant.<a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></h3> <code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#extractProjectName(org.apache.tools.ant.BuildEvent)">extractProjectName</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#formatTime(long)">formatTime</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#getBuildFailedMessage()">getBuildFailedMessage</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#getBuildSuccessfulMessage()">getBuildSuccessfulMessage</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#getTimestamp()">getTimestamp</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#log(java.lang.String)">log</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#messageLogged(org.apache.tools.ant.BuildEvent)">messageLogged</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#printMessage(java.lang.String,%20java.io.PrintStream,%20int)">printMessage</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#setEmacsMode(boolean)">setEmacsMode</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#setErrorPrintStream(java.io.PrintStream)">setErrorPrintStream</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#setMessageOutputLevel(int)">setMessageOutputLevel</a>, <a href="../../../../../org/apache/tools/ant/DefaultLogger.html#setOutputPrintStream(java.io.PrintStream)">setOutputPrintStream</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="SilentLogger()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>SilentLogger</h4> <pre>public&nbsp;SilentLogger()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="buildStarted(org.apache.tools.ant.BuildEvent)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>buildStarted</h4> <pre>public&nbsp;void&nbsp;buildStarted(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#buildStarted(org.apache.tools.ant.BuildEvent)">DefaultLogger</a></code></strong></div> <div class="block">Responds to a build being started by just remembering the current time.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/BuildListener.html#buildStarted(org.apache.tools.ant.BuildEvent)">buildStarted</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../org/apache/tools/ant/BuildListener.html" title="interface in org.apache.tools.ant">BuildListener</a></code></dd> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#buildStarted(org.apache.tools.ant.BuildEvent)">buildStarted</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>event</code> - Ignored.</dd></dl> </li> </ul> <a name="buildFinished(org.apache.tools.ant.BuildEvent)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>buildFinished</h4> <pre>public&nbsp;void&nbsp;buildFinished(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#buildFinished(org.apache.tools.ant.BuildEvent)">DefaultLogger</a></code></strong></div> <div class="block">Prints whether the build succeeded or failed, any errors the occurred during the build, and how long the build took.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/BuildListener.html#buildFinished(org.apache.tools.ant.BuildEvent)">buildFinished</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../org/apache/tools/ant/BuildListener.html" title="interface in org.apache.tools.ant">BuildListener</a></code></dd> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#buildFinished(org.apache.tools.ant.BuildEvent)">buildFinished</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>event</code> - An event with any relevant extra information. Must not be <code>null</code>.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../org/apache/tools/ant/BuildEvent.html#getException()"><code>BuildEvent.getException()</code></a></dd></dl> </li> </ul> <a name="targetStarted(org.apache.tools.ant.BuildEvent)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>targetStarted</h4> <pre>public&nbsp;void&nbsp;targetStarted(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#targetStarted(org.apache.tools.ant.BuildEvent)">DefaultLogger</a></code></strong></div> <div class="block">Logs a message to say that the target has started if this logger allows information-level messages.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/BuildListener.html#targetStarted(org.apache.tools.ant.BuildEvent)">targetStarted</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../org/apache/tools/ant/BuildListener.html" title="interface in org.apache.tools.ant">BuildListener</a></code></dd> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#targetStarted(org.apache.tools.ant.BuildEvent)">targetStarted</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>event</code> - An event with any relevant extra information. Must not be <code>null</code>.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../org/apache/tools/ant/BuildEvent.html#getTarget()"><code>BuildEvent.getTarget()</code></a></dd></dl> </li> </ul> <a name="targetFinished(org.apache.tools.ant.BuildEvent)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>targetFinished</h4> <pre>public&nbsp;void&nbsp;targetFinished(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#targetFinished(org.apache.tools.ant.BuildEvent)">DefaultLogger</a></code></strong></div> <div class="block">No-op implementation.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/BuildListener.html#targetFinished(org.apache.tools.ant.BuildEvent)">targetFinished</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../org/apache/tools/ant/BuildListener.html" title="interface in org.apache.tools.ant">BuildListener</a></code></dd> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#targetFinished(org.apache.tools.ant.BuildEvent)">targetFinished</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>event</code> - Ignored.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../org/apache/tools/ant/BuildEvent.html#getException()"><code>BuildEvent.getException()</code></a></dd></dl> </li> </ul> <a name="taskStarted(org.apache.tools.ant.BuildEvent)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>taskStarted</h4> <pre>public&nbsp;void&nbsp;taskStarted(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#taskStarted(org.apache.tools.ant.BuildEvent)">DefaultLogger</a></code></strong></div> <div class="block">No-op implementation.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/BuildListener.html#taskStarted(org.apache.tools.ant.BuildEvent)">taskStarted</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../org/apache/tools/ant/BuildListener.html" title="interface in org.apache.tools.ant">BuildListener</a></code></dd> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#taskStarted(org.apache.tools.ant.BuildEvent)">taskStarted</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>event</code> - Ignored.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../org/apache/tools/ant/BuildEvent.html#getTask()"><code>BuildEvent.getTask()</code></a></dd></dl> </li> </ul> <a name="taskFinished(org.apache.tools.ant.BuildEvent)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>taskFinished</h4> <pre>public&nbsp;void&nbsp;taskFinished(<a href="../../../../../org/apache/tools/ant/BuildEvent.html" title="class in org.apache.tools.ant">BuildEvent</a>&nbsp;event)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#taskFinished(org.apache.tools.ant.BuildEvent)">DefaultLogger</a></code></strong></div> <div class="block">No-op implementation.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/BuildListener.html#taskFinished(org.apache.tools.ant.BuildEvent)">taskFinished</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../org/apache/tools/ant/BuildListener.html" title="interface in org.apache.tools.ant">BuildListener</a></code></dd> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html#taskFinished(org.apache.tools.ant.BuildEvent)">taskFinished</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/DefaultLogger.html" title="class in org.apache.tools.ant">DefaultLogger</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>event</code> - Ignored.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../org/apache/tools/ant/BuildEvent.html#getException()"><code>BuildEvent.getException()</code></a></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/tools/ant/listener/ProfileLogger.html" title="class in org.apache.tools.ant.listener"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/tools/ant/listener/SimpleBigProjectLogger.html" title="class in org.apache.tools.ant.listener"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/tools/ant/listener/SilentLogger.html" target="_top">Frames</a></li> <li><a href="SilentLogger.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.apache.tools.ant.DefaultLogger">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "pile_set_name": "Github" }
/* Copyright (C) 2003-2009 Paul Brossier <[email protected]> This file is part of aubio. aubio is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. aubio 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 aubio. If not, see <http://www.gnu.org/licenses/>. */ #include "aubio_priv.h" #include "fvec.h" #include "utils/scale.h" struct _aubio_scale_t { smpl_t ilow; smpl_t ihig; smpl_t olow; smpl_t ohig; smpl_t scaler; smpl_t irange; /* not implemented yet : type in/out data bool inint; bool outint; */ }; aubio_scale_t * new_aubio_scale (smpl_t ilow, smpl_t ihig, smpl_t olow, smpl_t ohig) { aubio_scale_t * s = AUBIO_NEW(aubio_scale_t); aubio_scale_set_limits (s, ilow, ihig, olow, ohig); return s; } void del_aubio_scale(aubio_scale_t *s) { AUBIO_FREE(s); } uint_t aubio_scale_set_limits (aubio_scale_t *s, smpl_t ilow, smpl_t ihig, smpl_t olow, smpl_t ohig) { smpl_t inputrange = ihig - ilow; smpl_t outputrange= ohig - olow; s->ilow = ilow; s->ihig = ihig; s->olow = olow; s->ohig = ohig; if (inputrange == 0) { s->scaler = 0.0; } else { s->scaler = outputrange/inputrange; if (inputrange < 0) { inputrange = inputrange * -1.0f; } } return AUBIO_OK; } void aubio_scale_do (aubio_scale_t *s, fvec_t *input) { uint_t j; for (j=0; j < input->length; j++){ input->data[j] -= s->ilow; input->data[j] *= s->scaler; input->data[j] += s->olow; } }
{ "pile_set_name": "Github" }
<?php /** * The template part for displaying an Author biography * * @package WordPress * @subpackage Twenty_Sixteen * @since Twenty Sixteen 1.0 */ ?> <div class="author-info"> <div class="author-avatar"> <?php /** * Filter the Twenty Sixteen author bio avatar size. * * @since Twenty Sixteen 1.0 * * @param int $size The avatar height and width size in pixels. */ $author_bio_avatar_size = apply_filters( 'twentysixteen_author_bio_avatar_size', 42 ); echo get_avatar( get_the_author_meta( 'user_email' ), $author_bio_avatar_size ); ?> </div><!-- .author-avatar --> <div class="author-description"> <h2 class="author-title"><span class="author-heading"><?php _e( 'Author:', 'twentysixteen' ); ?></span> <?php echo get_the_author(); ?></h2> <p class="author-bio"> <?php the_author_meta( 'description' ); ?> <a class="author-link" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" rel="author"> <?php printf( __( 'View all posts by %s', 'twentysixteen' ), get_the_author() ); ?> </a> </p><!-- .author-bio --> </div><!-- .author-description --> </div><!-- .author-info -->
{ "pile_set_name": "Github" }
class FixOverlordFranchiseV2 < ActiveRecord::Migration[5.2] def change ids = Anime.where(franchise: 'overlord').pluck :id Anime.where(id: ids).update_all franchise: nil Animes::UpdateFranchises.new.call Anime.where(id: ids) end end
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <title>The page you were looking for doesn't exist (404)</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <style> body { background-color: #EFEFEF; color: #2E2F30; text-align: center; font-family: arial, sans-serif; margin: 0; } div.dialog { width: 95%; max-width: 33em; margin: 4em auto 0; } div.dialog > div { border: 1px solid #CCC; border-right-color: #999; border-left-color: #999; border-bottom-color: #BBB; border-top: #B00100 solid 4px; border-top-left-radius: 9px; border-top-right-radius: 9px; background-color: white; padding: 7px 12% 0; box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); } h1 { font-size: 100%; color: #730E15; line-height: 1.5em; } div.dialog > p { margin: 0 0 1em; padding: 1em; background-color: #F7F7F7; border: 1px solid #CCC; border-right-color: #999; border-left-color: #999; border-bottom-color: #999; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-color: #DADADA; color: #666; box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); } </style> </head> <body> <!-- This file lives in public/404.html --> <div class="dialog"> <div> <h1>The page you were looking for doesn't exist.</h1> <p>You may have mistyped the address or the page may have moved.</p> </div> <p>If you are the application owner check the logs for more information.</p> </div> </body> </html>
{ "pile_set_name": "Github" }
{ "problemMatcher": [ { "owner": "yaspeller", "pattern": [ { "regexp": "^✗\\s(.*)\\s\\d+\\sms$", "file": 1 }, { "regexp": "^\\d+\\. (.+) \\((\\d+):(\\d+).*$", "message": 1, "line": 2, "column": 3, "loop": true } ] } ] }
{ "pile_set_name": "Github" }
1362 1565597724816 httpcache-v1 Method: POST URL: https://www.notion.so/api/v3/getRecordValues Body:+110 { "requests": [ { "id": "6c25289d-4040-4368-9d74-9bc204ee2856", "table": "block" } ] } Response:+1162 { "results": [ { "role": "comment_only", "value": { "alive": true, "content": [ "d9572d1f-0df0-4d91-9f90-0f153ae25c31", "6461c974-b236-4792-ac01-e18ea8084d7e", "b7cf5a87-9337-4e0b-8845-ad1dedf05c5e", "e0b0f625-0ca5-402e-8ae1-c26fee04acea", "c3abcb17-9064-4594-b716-84e5b0df0083", "b919d926-2778-4e18-90b8-5139b7ae0f56", "4ed893aa-e8f6-4aa0-aa42-9baa20546864" ], "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293802, "format": { "page_full_width": true, "page_small_text": true }, "id": "6c25289d-4040-4368-9d74-9bc204ee2856", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293802, "parent_id": "dad9079e-f86e-45ca-a86d-64c83fac38ae", "parent_table": "block", "properties": { "title": [ [ "Defining a method" ] ] }, "type": "page", "version": 3 } } ] } 16287 1565597724818 httpcache-v1 Method: POST URL: https://www.notion.so/api/v3/loadPageChunk Body:+152 { "chunkNumber": 0, "cursor": { "stack": [] }, "limit": 50, "pageId": "6c25289d-4040-4368-9d74-9bc204ee2856", "verticalColumns": false } Response:+16046 { "cursor": { "stack": [] }, "recordMap": { "block": { "4ed893aa-e8f6-4aa0-aa42-9baa20546864": { "role": "comment_only", "value": { "alive": true, "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293802, "id": "4ed893aa-e8f6-4aa0-aa42-9baa20546864", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293802, "parent_id": "6c25289d-4040-4368-9d74-9bc204ee2856", "parent_table": "block", "properties": { "language": [ [ "Plain Text" ] ], "title": [ [ "hello(\"World\")\n# =\u003e \"Hello, World\"\nhello(\"All\")\n# =\u003e \"Hello, All\"" ] ] }, "type": "code", "version": 1 } }, "51f7633c-df1f-4ab1-a777-8e8095f599bd": { "role": "comment_only", "value": { "alive": true, "content": [ "c644c69a-7b97-448a-a252-970bcba3dbc5", "15c95d8e-ee3b-4cbc-916b-22ba9be56012", "3efb1b78-3f39-4bb2-9cf8-9795f8fdeacb", "d02a2bbf-2a24-4c97-802e-aa220f4dbe24", "526b98b2-3732-4941-ae3c-1e34440107c3", "5d7c03e8-234e-44ac-99c0-de7bac145d55", "6d75b2af-48c2-4f57-a52d-16232196c696", "bd841f16-9559-465f-bd31-488dd383c486", "d037520d-b311-450d-93c0-56ebd4112937", "09e1b5cf-1a4d-40ce-9988-4288a4269d46", "d43d4630-d5f4-4667-982d-03e02440c201", "9cce7d8d-7d75-4c89-8d3d-4b403c63ca7a", "dad9079e-f86e-45ca-a86d-64c83fac38ae", "c257caf4-7140-4773-b69e-7886cfebc866", "98460cdd-6994-4ad2-97d6-27deab14079c", "d879941a-3f7c-4970-b09f-cbd77cb932d2", "04e23c6b-c2cd-4606-81d6-13cc2dce5d78", "f6d62287-fb0f-4bcb-afb4-5cf3437a357c", "39077d16-6763-4235-9e51-82d2579b35df", "c5283f07-4be2-4750-9418-3727592670e2", "1833e628-8643-4e8c-ad78-0531e86722ae", "541465a3-a3f8-453c-a793-f17d5824260e", "fb26c2f8-f71d-4bc9-ae23-a82861d8ea47", "e9481ae9-ca5e-4b9f-b722-d570649c2cfe", "d3393ec6-47a7-47e4-ba42-d101db781d0a", "4bb329de-b3fd-45b4-a19c-735d2948a10e", "37bbd008-8fcb-44e6-a318-2023467879c3", "421c1221-be5c-42b4-89bc-611d14ed995b", "bb7b92de-fe97-478d-b6fb-13a05cc83213", "0d7a4d19-fb72-485a-8da6-7465910936ff", "79781265-6a05-4558-8302-be7fd30fa720", "0beba742-561b-4cc3-bb40-d171ebf4b35f", "d8406e27-f8d8-4f50-a58a-e03727420eb3", "bcfaa3e1-f118-49ad-b63f-82d373de34f3", "226323b1-302c-4a19-9833-dcd38be20f9d", "b12e295c-908d-4ace-a221-5922b63999b9", "fcfe325e-bfdb-4741-9e78-def959689142", "0fef2d80-34e3-4dde-813f-ca18453232c1", "2cd9e159-28d5-46d8-979d-8949da1379cd", "7f9f1e81-fd42-4952-8f40-7145b0bfd61f", "35eddfe7-54d2-4a0e-a602-87477eb8d3bc", "60275fdc-4f50-440f-a917-b0c36e3fc177", "cb0e2d47-43c5-4809-b173-e764dfc894dc", "104208bf-54bf-4328-af5c-f6aeb0105199", "1ba86719-188e-4bf3-af1d-d5522aac14d9", "56ead039-5a17-41ac-aabb-8b32453caa32", "7eb3d215-c3b9-459b-91a2-50b351cb9a27", "646950e5-562c-4def-ac73-f11050db3526", "e2c0d93a-60f5-4355-88ec-feb8992fee94", "acd30baa-c28d-44b3-b3e4-3bffc6f38270", "bd282be1-56e1-4d1d-8027-7d824c9f0418", "f4a09b0e-5917-4616-bb2e-8271c834ddff", "36398b40-cb12-4fd8-829a-5dd8aa2617b5", "ae5dd55a-c2f8-453c-b48e-0019de81a71a", "3d619f09-c104-4572-a105-9167b3454634", "fd9f55c7-eaa9-432f-b822-84aafb3636ed", "26effae7-5f43-4caf-862c-0413d8a3b33a", "503b869c-facb-4daf-9429-76956c6e6073", "05086c82-1b0a-43ec-ae42-dfd5af1cce18", "ef09b0ce-fe8b-4767-8f8b-16cf766bcf5b", "ff17ee6e-cf45-4e7e-9f1f-2d198c0da86f", "9c88dbdc-003f-4bf8-8cd2-91e2af392489", "2e5841e2-43c9-4064-856b-bd6e8a71db8b", "6e074c20-aa26-42a0-90a8-e0af35c0ad06", "cad04a1a-1384-444d-9772-f66e5db944c5", "5742d364-d071-465e-95f8-1cd23bd1e88d", "ef591f05-8c85-4797-9c81-2d7c75cd2621", "35d129d5-0bd0-4afc-98ed-750fb5c3c535", "ba664011-d11f-48ca-9190-965b7ab51da5", "f7fe2f0b-28ed-4ce0-b500-3c33542c0316", "af1e59e1-5fbe-4c1a-a9bc-d8692da82213", "9650f45f-a495-462c-8fed-8d47c6532a9a" ], "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101097821, "format": { "page_full_width": true, "page_small_text": true }, "id": "51f7633c-df1f-4ab1-a777-8e8095f599bd", "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1553725980000, "parent_id": "a253ec1b-9a22-4fed-8092-48668a5c15df", "parent_table": "block", "permissions": [ { "allow_search_engine_indexing": false, "role": "comment_only", "type": "public_permission" } ], "properties": { "title": [ [ "Essential Ruby" ] ] }, "type": "page", "version": 125 } }, "6461c974-b236-4792-ac01-e18ea8084d7e": { "role": "comment_only", "value": { "alive": true, "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293801, "id": "6461c974-b236-4792-ac01-e18ea8084d7e", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293801, "parent_id": "6c25289d-4040-4368-9d74-9bc204ee2856", "parent_table": "block", "properties": { "language": [ [ "Plain Text" ] ], "title": [ [ "def hello(name)\n \"Hello, #{name}\"\nend" ] ] }, "type": "code", "version": 1 } }, "6c25289d-4040-4368-9d74-9bc204ee2856": { "role": "comment_only", "value": { "alive": true, "content": [ "d9572d1f-0df0-4d91-9f90-0f153ae25c31", "6461c974-b236-4792-ac01-e18ea8084d7e", "b7cf5a87-9337-4e0b-8845-ad1dedf05c5e", "e0b0f625-0ca5-402e-8ae1-c26fee04acea", "c3abcb17-9064-4594-b716-84e5b0df0083", "b919d926-2778-4e18-90b8-5139b7ae0f56", "4ed893aa-e8f6-4aa0-aa42-9baa20546864" ], "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293802, "format": { "page_full_width": true, "page_small_text": true }, "id": "6c25289d-4040-4368-9d74-9bc204ee2856", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293802, "parent_id": "dad9079e-f86e-45ca-a86d-64c83fac38ae", "parent_table": "block", "properties": { "title": [ [ "Defining a method" ] ] }, "type": "page", "version": 3 } }, "b7cf5a87-9337-4e0b-8845-ad1dedf05c5e": { "role": "comment_only", "value": { "alive": true, "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293801, "id": "b7cf5a87-9337-4e0b-8845-ad1dedf05c5e", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293801, "parent_id": "6c25289d-4040-4368-9d74-9bc204ee2856", "parent_table": "block", "properties": { "title": [ [ "A method invocation specifies the method name, the object on which it is to be invoked (sometimes called the receiver), and zero or more argument values that are assigned to the named method parameters." ] ] }, "type": "text", "version": 1 } }, "b919d926-2778-4e18-90b8-5139b7ae0f56": { "role": "comment_only", "value": { "alive": true, "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293802, "id": "b919d926-2778-4e18-90b8-5139b7ae0f56", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293802, "parent_id": "6c25289d-4040-4368-9d74-9bc204ee2856", "parent_table": "block", "properties": { "title": [ [ "Parameter names can be used as variables within the method body, and the values of these named parameters come from the arguments to a method invocation." ] ] }, "type": "text", "version": 1 } }, "c3abcb17-9064-4594-b716-84e5b0df0083": { "role": "comment_only", "value": { "alive": true, "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293802, "id": "c3abcb17-9064-4594-b716-84e5b0df0083", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293802, "parent_id": "6c25289d-4040-4368-9d74-9bc204ee2856", "parent_table": "block", "properties": { "title": [ [ "When the receiver is not explicit, it is " ], [ "self", [ [ "c" ] ] ], [ "." ] ] }, "type": "text", "version": 1 } }, "d9572d1f-0df0-4d91-9f90-0f153ae25c31": { "role": "comment_only", "value": { "alive": true, "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293799, "id": "d9572d1f-0df0-4d91-9f90-0f153ae25c31", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293799, "parent_id": "6c25289d-4040-4368-9d74-9bc204ee2856", "parent_table": "block", "properties": { "title": [ [ "Methods are defined with the " ], [ "def", [ [ "c" ] ] ], [ " keyword, followed by the " ], [ "method name", [ [ "i" ] ] ], [ " and an optional list of " ], [ "parameter names", [ [ "i" ] ] ], [ " in parentheses. The Ruby code between " ], [ "def", [ [ "c" ] ] ], [ " and " ], [ "end", [ [ "c" ] ] ], [ " represents the " ], [ "body", [ [ "i" ] ] ], [ " of the method." ] ] }, "type": "text", "version": 1 } }, "dad9079e-f86e-45ca-a86d-64c83fac38ae": { "role": "comment_only", "value": { "alive": true, "content": [ "df585836-d34f-4c66-b6da-e8427da2ca45", "6c25289d-4040-4368-9d74-9bc204ee2856", "c73936f8-2449-415e-866c-f1e66759bb44", "1e2b6d1f-4de9-4929-a9ff-8e15b20ff49e", "95c6510a-9097-4e94-ab19-dd05e81a1e83", "b98c821e-a951-441e-a468-34381f84360b", "383a7880-5eca-41af-a946-5d34bc5cc4c0", "e3148dff-870d-4747-aced-42f5c21c404d", "4c71a412-270e-471b-9281-c50026652ee4", "d83c3b98-8648-44ee-8fee-3ecdec6656c3", "12670eb3-95c7-4b6d-be96-0d34a43fd219", "db913877-6e4f-45c4-9ffb-d122b254c0e3" ], "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101240000, "format": { "page_full_width": true, "page_small_text": true }, "id": "dad9079e-f86e-45ca-a86d-64c83fac38ae", "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101600000, "parent_id": "51f7633c-df1f-4ab1-a777-8e8095f599bd", "parent_table": "block", "permissions": [ { "role": "editor", "type": "user_permission", "user_id": "bb760e2d-d679-4b64-b2a9-03005b21870a" } ], "properties": { "title": [ [ "Methods" ] ] }, "type": "page", "version": 29 } }, "e0b0f625-0ca5-402e-8ae1-c26fee04acea": { "role": "comment_only", "value": { "alive": true, "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "created_time": 1552101293801, "id": "e0b0f625-0ca5-402e-8ae1-c26fee04acea", "ignore_block_count": true, "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a", "last_edited_time": 1552101293801, "parent_id": "6c25289d-4040-4368-9d74-9bc204ee2856", "parent_table": "block", "properties": { "language": [ [ "Plain Text" ] ], "title": [ [ "hello(\"World\")\n# =\u003e \"Hello, World\"" ] ] }, "type": "code", "version": 1 } } }, "notion_user": { "bb760e2d-d679-4b64-b2a9-03005b21870a": { "role": "reader", "value": { "clipper_onboarding_completed": true, "email": "[email protected]", "family_name": "Kowalczyk", "given_name": "Krzysztof", "id": "bb760e2d-d679-4b64-b2a9-03005b21870a", "mobile_onboarding_completed": true, "onboarding_completed": true, "profile_photo": "https://s3-us-west-2.amazonaws.com/public.notion-static.com/2dcaa66c-7674-4ff6-9924-601785b63561/head-bw-640x960.png", "version": 179 } } }, "space": {} } }
{ "pile_set_name": "Github" }
/* Decomposed printf argument list. Copyright (C) 1999, 2002-2003, 2005-2007, 2009-2013 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ /* This file can be parametrized with the following macros: ENABLE_UNISTDIO Set to 1 to enable the unistdio extensions. PRINTF_FETCHARGS Name of the function to be defined. STATIC Set to 'static' to declare the function static. */ #ifndef PRINTF_FETCHARGS # include <config.h> #endif /* Specification. */ #ifndef PRINTF_FETCHARGS # include "printf-args.h" #endif #ifdef STATIC STATIC #endif int PRINTF_FETCHARGS (va_list args, arguments *a) { size_t i; argument *ap; for (i = 0, ap = &a->arg[0]; i < a->count; i++, ap++) switch (ap->type) { case TYPE_SCHAR: ap->a.a_schar = va_arg (args, /*signed char*/ int); break; case TYPE_UCHAR: ap->a.a_uchar = va_arg (args, /*unsigned char*/ int); break; case TYPE_SHORT: ap->a.a_short = va_arg (args, /*short*/ int); break; case TYPE_USHORT: ap->a.a_ushort = va_arg (args, /*unsigned short*/ int); break; case TYPE_INT: ap->a.a_int = va_arg (args, int); break; case TYPE_UINT: ap->a.a_uint = va_arg (args, unsigned int); break; case TYPE_LONGINT: ap->a.a_longint = va_arg (args, long int); break; case TYPE_ULONGINT: ap->a.a_ulongint = va_arg (args, unsigned long int); break; #if HAVE_LONG_LONG_INT case TYPE_LONGLONGINT: ap->a.a_longlongint = va_arg (args, long long int); break; case TYPE_ULONGLONGINT: ap->a.a_ulonglongint = va_arg (args, unsigned long long int); break; #endif case TYPE_DOUBLE: ap->a.a_double = va_arg (args, double); break; case TYPE_LONGDOUBLE: ap->a.a_longdouble = va_arg (args, long double); break; case TYPE_CHAR: ap->a.a_char = va_arg (args, int); break; #if HAVE_WINT_T case TYPE_WIDE_CHAR: /* Although ISO C 99 7.24.1.(2) says that wint_t is "unchanged by default argument promotions", this is not the case in mingw32, where wint_t is 'unsigned short'. */ ap->a.a_wide_char = (sizeof (wint_t) < sizeof (int) ? (wint_t) va_arg (args, int) : va_arg (args, wint_t)); break; #endif case TYPE_STRING: ap->a.a_string = va_arg (args, const char *); /* A null pointer is an invalid argument for "%s", but in practice it occurs quite frequently in printf statements that produce debug output. Use a fallback in this case. */ if (ap->a.a_string == NULL) ap->a.a_string = "(NULL)"; break; #if HAVE_WCHAR_T case TYPE_WIDE_STRING: ap->a.a_wide_string = va_arg (args, const wchar_t *); /* A null pointer is an invalid argument for "%ls", but in practice it occurs quite frequently in printf statements that produce debug output. Use a fallback in this case. */ if (ap->a.a_wide_string == NULL) { static const wchar_t wide_null_string[] = { (wchar_t)'(', (wchar_t)'N', (wchar_t)'U', (wchar_t)'L', (wchar_t)'L', (wchar_t)')', (wchar_t)0 }; ap->a.a_wide_string = wide_null_string; } break; #endif case TYPE_POINTER: ap->a.a_pointer = va_arg (args, void *); break; case TYPE_COUNT_SCHAR_POINTER: ap->a.a_count_schar_pointer = va_arg (args, signed char *); break; case TYPE_COUNT_SHORT_POINTER: ap->a.a_count_short_pointer = va_arg (args, short *); break; case TYPE_COUNT_INT_POINTER: ap->a.a_count_int_pointer = va_arg (args, int *); break; case TYPE_COUNT_LONGINT_POINTER: ap->a.a_count_longint_pointer = va_arg (args, long int *); break; #if HAVE_LONG_LONG_INT case TYPE_COUNT_LONGLONGINT_POINTER: ap->a.a_count_longlongint_pointer = va_arg (args, long long int *); break; #endif #if ENABLE_UNISTDIO /* The unistdio extensions. */ case TYPE_U8_STRING: ap->a.a_u8_string = va_arg (args, const uint8_t *); /* A null pointer is an invalid argument for "%U", but in practice it occurs quite frequently in printf statements that produce debug output. Use a fallback in this case. */ if (ap->a.a_u8_string == NULL) { static const uint8_t u8_null_string[] = { '(', 'N', 'U', 'L', 'L', ')', 0 }; ap->a.a_u8_string = u8_null_string; } break; case TYPE_U16_STRING: ap->a.a_u16_string = va_arg (args, const uint16_t *); /* A null pointer is an invalid argument for "%lU", but in practice it occurs quite frequently in printf statements that produce debug output. Use a fallback in this case. */ if (ap->a.a_u16_string == NULL) { static const uint16_t u16_null_string[] = { '(', 'N', 'U', 'L', 'L', ')', 0 }; ap->a.a_u16_string = u16_null_string; } break; case TYPE_U32_STRING: ap->a.a_u32_string = va_arg (args, const uint32_t *); /* A null pointer is an invalid argument for "%llU", but in practice it occurs quite frequently in printf statements that produce debug output. Use a fallback in this case. */ if (ap->a.a_u32_string == NULL) { static const uint32_t u32_null_string[] = { '(', 'N', 'U', 'L', 'L', ')', 0 }; ap->a.a_u32_string = u32_null_string; } break; #endif default: /* Unknown type. */ return -1; } return 0; }
{ "pile_set_name": "Github" }
DEFINED_PHASES=compile configure install postinst postrm setup test DEPEND=>=dev-haskell/connection-0.2.5:=[profile?] dev-haskell/data-default:=[profile?] >=dev-haskell/http-client-0.6:=[profile?] <dev-haskell/http-client-0.7:=[profile?] >=dev-haskell/http-client-tls-0.3.2:=[profile?] <dev-haskell/http-client-tls-0.4:=[profile?] >=dev-haskell/network-3.0.0.0:=[profile?] dev-haskell/network-bsd:=[profile?] dev-haskell/utf8-string:=[profile?] >=dev-lang/ghc-8.4.3:= >=dev-haskell/cabal-2.2.0.1 doc? ( || ( dev-haskell/haddock >=dev-lang/ghc-7.10.2 ) ) hscolour? ( dev-haskell/hscolour ) DESCRIPTION=restricting the servers that http-client will use EAPI=7 HOMEPAGE=https://hackage.haskell.org/package/http-client-restricted IUSE=doc hscolour profile KEYWORDS=~amd64 ~x86 LICENSE=MIT RDEPEND=>=dev-haskell/connection-0.2.5:=[profile?] dev-haskell/data-default:=[profile?] >=dev-haskell/http-client-0.6:=[profile?] <dev-haskell/http-client-0.7:=[profile?] >=dev-haskell/http-client-tls-0.3.2:=[profile?] <dev-haskell/http-client-tls-0.4:=[profile?] >=dev-haskell/network-3.0.0.0:=[profile?] dev-haskell/network-bsd:=[profile?] dev-haskell/utf8-string:=[profile?] >=dev-lang/ghc-8.4.3:= SLOT=0/0.0.3 SRC_URI=https://hackage.haskell.org/package/http-client-restricted-0.0.3/http-client-restricted-0.0.3.tar.gz _eclasses_=edos2unix 33e347e171066657f91f8b0c72ec8773 eutils 2d5b3f4b315094768576b6799e4f926e ghc-package e3a4a688accbd5f1226e46b379cc1c3e haskell-cabal 433b5153bec6b0ffe21c7be2210e8396 l10n 8cdd85e169b835d518bc2fd59f780d8e multilib 98584e405e2b0264d37e8f728327fed1 multiprocessing cac3169468f893670dac3e7cb940e045 toolchain-funcs 605c126bed8d87e4378d5ff1645330cb wrapper 4251d4c84c25f59094fd557e0063a974 _md5_=4fa8eb38be64aef405f44eac68a4277b
{ "pile_set_name": "Github" }
/* * Copyright (c) 2010-2019 Belledonne Communications SARL. * * This file is part of linphone-android * (see https://www.linphone.org). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.linphone.settings; import android.Manifest; import android.os.Bundle; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.List; import org.linphone.LinphoneManager; import org.linphone.R; import org.linphone.core.Core; import org.linphone.core.Factory; import org.linphone.core.PayloadType; import org.linphone.core.VideoDefinition; import org.linphone.core.tools.Log; import org.linphone.mediastream.Version; import org.linphone.settings.widget.ListSetting; import org.linphone.settings.widget.SettingListenerBase; import org.linphone.settings.widget.SwitchSetting; import org.linphone.settings.widget.TextSetting; public class VideoSettingsFragment extends SettingsFragment { private View mRootView; private LinphonePreferences mPrefs; private SwitchSetting mEnable, mAutoInitiate, mAutoAccept, mOverlay, mVideoPreview; private ListSetting mPreset, mSize, mFps; private TextSetting mBandwidth; private LinearLayout mVideoCodecs; private TextView mVideoCodecsHeader; private ListSetting mCameraDevices; @Nullable @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.settings_video, container, false); loadSettings(); return mRootView; } @Override public void onResume() { super.onResume(); mPrefs = LinphonePreferences.instance(); updateValues(); } private void loadSettings() { mEnable = mRootView.findViewById(R.id.pref_video_enable); mVideoPreview = mRootView.findViewById(R.id.pref_video_preview); mAutoInitiate = mRootView.findViewById(R.id.pref_video_initiate_call_with_video); mAutoAccept = mRootView.findViewById(R.id.pref_video_automatically_accept_video); mCameraDevices = mRootView.findViewById(R.id.pref_video_camera_device); initCameraDevicesList(); mOverlay = mRootView.findViewById(R.id.pref_overlay); mPreset = mRootView.findViewById(R.id.pref_video_preset); mSize = mRootView.findViewById(R.id.pref_preferred_video_size); initVideoSizeList(); mFps = mRootView.findViewById(R.id.pref_preferred_fps); initFpsList(); mBandwidth = mRootView.findViewById(R.id.pref_bandwidth_limit); mBandwidth.setInputType(InputType.TYPE_CLASS_NUMBER); mVideoCodecs = mRootView.findViewById(R.id.pref_video_codecs); mVideoCodecsHeader = mRootView.findViewById(R.id.pref_video_codecs_header); } private void setListeners() { mEnable.setListener( new SettingListenerBase() { @Override public void onBoolValueChanged(boolean newValue) { mPrefs.enableVideo(newValue); if (!newValue) { mVideoPreview.setChecked(false); mAutoAccept.setChecked(false); mAutoInitiate.setChecked(false); } updateVideoSettingsVisibility(newValue); } }); mVideoPreview.setListener( new SettingListenerBase() { @Override public void onBoolValueChanged(boolean newValue) { if (newValue) { if (!((SettingsActivity) getActivity()) .checkPermission(Manifest.permission.CAMERA)) { ((SettingsActivity) getActivity()) .requestPermissionIfNotGranted(Manifest.permission.CAMERA); } else { mPrefs.setVideoPreviewEnabled(true); } } else { mPrefs.setVideoPreviewEnabled(false); } } }); mAutoInitiate.setListener( new SettingListenerBase() { @Override public void onBoolValueChanged(boolean newValue) { mPrefs.setInitiateVideoCall(newValue); } }); mAutoAccept.setListener( new SettingListenerBase() { @Override public void onBoolValueChanged(boolean newValue) { mPrefs.setAutomaticallyAcceptVideoRequests(newValue); } }); mCameraDevices.setListener( new SettingListenerBase() { @Override public void onListValueChanged(int position, String newLabel, String newValue) { mPrefs.setCameraDevice(newValue); } }); mOverlay.setListener( new SettingListenerBase() { @Override public void onBoolValueChanged(boolean newValue) { mPrefs.enableOverlay( newValue && ((SettingsActivity) getActivity()) .checkAndRequestOverlayPermission()); } }); mPreset.setListener( new SettingListenerBase() { @Override public void onListValueChanged(int position, String newLabel, String newValue) { mPrefs.setVideoPreset(newValue); mFps.setVisibility(newValue.equals("custom") ? View.VISIBLE : View.GONE); mBandwidth.setVisibility( newValue.equals("custom") ? View.VISIBLE : View.GONE); } }); mSize.setListener( new SettingListenerBase() { @Override public void onListValueChanged(int position, String newLabel, String newValue) { mPrefs.setPreferredVideoSize(newValue); } }); mFps.setListener( new SettingListenerBase() { @Override public void onListValueChanged(int position, String newLabel, String newValue) { try { mPrefs.setPreferredVideoFps(Integer.valueOf(newValue)); } catch (NumberFormatException nfe) { Log.e(nfe); } } }); mBandwidth.setListener( new SettingListenerBase() { @Override public void onTextValueChanged(String newValue) { try { mPrefs.setBandwidthLimit(Integer.valueOf(newValue)); } catch (NumberFormatException nfe) { Log.e(nfe); } } }); } private void updateValues() { mEnable.setChecked(mPrefs.isVideoEnabled()); updateVideoSettingsVisibility(mPrefs.isVideoEnabled()); mVideoPreview.setChecked(mPrefs.isVideoPreviewEnabled()); mAutoInitiate.setChecked(mPrefs.shouldInitiateVideoCall()); mAutoAccept.setChecked(mPrefs.shouldAutomaticallyAcceptVideoRequests()); mCameraDevices.setValue(mPrefs.getCameraDevice()); mOverlay.setChecked(mPrefs.isOverlayEnabled()); if (Version.sdkAboveOrEqual(Version.API26_O_80) && getResources().getBoolean(R.bool.allow_pip_while_video_call)) { // Disable overlay and use PIP feature mOverlay.setVisibility(View.GONE); } mBandwidth.setValue(mPrefs.getBandwidthLimit()); mBandwidth.setVisibility( mPrefs.getVideoPreset().equals("custom") ? View.VISIBLE : View.GONE); mPreset.setValue(mPrefs.getVideoPreset()); mSize.setValue(mPrefs.getPreferredVideoSize()); mFps.setValue(mPrefs.getPreferredVideoFps()); mFps.setVisibility(mPrefs.getVideoPreset().equals("custom") ? View.VISIBLE : View.GONE); populateVideoCodecs(); setListeners(); } private void initVideoSizeList() { List<String> entries = new ArrayList<>(); List<String> values = new ArrayList<>(); for (VideoDefinition vd : Factory.instance().getSupportedVideoDefinitions()) { entries.add(vd.getName()); values.add(vd.getName()); } mSize.setItems(entries, values); } private void initFpsList() { List<String> entries = new ArrayList<>(); List<String> values = new ArrayList<>(); entries.add(getString(R.string.pref_none)); values.add("0"); for (int i = 5; i <= 30; i += 5) { String str = Integer.toString(i); entries.add(str); values.add(str); } mFps.setItems(entries, values); } private void populateVideoCodecs() { mVideoCodecs.removeAllViews(); Core core = LinphoneManager.getCore(); if (core != null) { for (final PayloadType pt : core.getVideoPayloadTypes()) { final SwitchSetting codec = new SwitchSetting(getActivity()); codec.setTitle(pt.getMimeType()); if (pt.enabled()) { // Never use codec.setChecked(pt.enabled) ! codec.setChecked(true); } codec.setListener( new SettingListenerBase() { @Override public void onBoolValueChanged(boolean newValue) { pt.enable(newValue); } }); mVideoCodecs.addView(codec); } } } private void updateVideoSettingsVisibility(boolean show) { mVideoPreview.setVisibility( show && getResources().getBoolean(R.bool.isTablet) && getResources() .getBoolean(R.bool.show_camera_preview_on_dialer_on_tablets) ? View.VISIBLE : View.GONE); mAutoInitiate.setVisibility(show ? View.VISIBLE : View.GONE); mAutoAccept.setVisibility(show ? View.VISIBLE : View.GONE); mCameraDevices.setVisibility(show ? View.VISIBLE : View.GONE); mOverlay.setVisibility(show ? View.VISIBLE : View.GONE); mBandwidth.setVisibility(show ? View.VISIBLE : View.GONE); mPreset.setVisibility(show ? View.VISIBLE : View.GONE); mSize.setVisibility(show ? View.VISIBLE : View.GONE); mFps.setVisibility(show ? View.VISIBLE : View.GONE); mVideoCodecs.setVisibility(show ? View.VISIBLE : View.GONE); mVideoCodecsHeader.setVisibility(show ? View.VISIBLE : View.GONE); if (show) { if (Version.sdkAboveOrEqual(Version.API26_O_80) && getResources().getBoolean(R.bool.allow_pip_while_video_call)) { // Disable overlay and use PIP feature mOverlay.setVisibility(View.GONE); } mBandwidth.setVisibility( mPrefs.getVideoPreset().equals("custom") ? View.VISIBLE : View.GONE); mFps.setVisibility(mPrefs.getVideoPreset().equals("custom") ? View.VISIBLE : View.GONE); } } private void initCameraDevicesList() { List<String> entries = new ArrayList<>(); List<String> values = new ArrayList<>(); Core core = LinphoneManager.getCore(); if (core != null) { for (String camera : core.getVideoDevicesList()) { entries.add(camera); values.add(camera); } } mCameraDevices.setItems(entries, values); } }
{ "pile_set_name": "Github" }
<?php namespace League\Flysystem\Util; use Finfo; use ErrorException; /** * @internal */ class MimeType { /** * Detects MIME Type based on given content. * * @param mixed $content * * @return string|null MIME Type or NULL if no mime type detected */ public static function detectByContent($content) { if ( ! class_exists('Finfo') || ! is_string($content)) { return; } try { $finfo = new Finfo(FILEINFO_MIME_TYPE); return $finfo->buffer($content) ?: null; } catch( ErrorException $e ) { // This is caused by an array to string conversion error. } } /** * Detects MIME Type based on file extension. * * @param string $extension * * @return string|null MIME Type or NULL if no extension detected */ public static function detectByFileExtension($extension) { static $extensionToMimeTypeMap; if (! $extensionToMimeTypeMap) { $extensionToMimeTypeMap = static::getExtensionToMimeTypeMap(); } if (isset($extensionToMimeTypeMap[$extension])) { return $extensionToMimeTypeMap[$extension]; } return 'text/plain'; } /** * @param string $filename * * @return string */ public static function detectByFilename($filename) { $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); return empty($extension) ? 'text/plain' : static::detectByFileExtension($extension); } /** * @return array Map of file extension to MIME Type */ public static function getExtensionToMimeTypeMap() { return [ 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'csv' => 'text/x-comma-separated-values', 'bin' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'class' => 'application/octet-stream', 'psd' => 'application/x-photoshop', 'so' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/pdf', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/powerpoint', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'wbxml' => 'application/wbxml', 'wmlc' => 'application/wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'gzip' => 'application/x-gzip', 'php' => 'application/x-httpd-php', 'php4' => 'application/x-httpd-php', 'php3' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', 'js' => 'application/javascript', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', 'tgz' => 'application/x-tar', 'z' => 'application/x-compress', 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', 'zip' => 'application/x-zip', 'rar' => 'application/x-rar', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'rv' => 'video/vnd.rn-realvideo', 'wav' => 'audio/x-wav', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'shtml' => 'text/html', 'txt' => 'text/plain', 'text' => 'text/plain', 'log' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'xml' => 'application/xml', 'xsl' => 'application/xml', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dot' => 'application/msword', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'word' => 'application/msword', 'xl' => 'application/excel', 'eml' => 'message/rfc822', 'json' => 'application/json', 'pem' => 'application/x-x509-user-cert', 'p10' => 'application/x-pkcs10', 'p12' => 'application/x-pkcs12', 'p7a' => 'application/x-pkcs7-signature', 'p7c' => 'application/pkcs7-mime', 'p7m' => 'application/pkcs7-mime', 'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/pkcs7-signature', 'crt' => 'application/x-x509-ca-cert', 'crl' => 'application/pkix-crl', 'der' => 'application/x-x509-ca-cert', 'kdb' => 'application/octet-stream', 'pgp' => 'application/pgp', 'gpg' => 'application/gpg-keys', 'sst' => 'application/octet-stream', 'csr' => 'application/octet-stream', 'rsa' => 'application/x-pkcs7', 'cer' => 'application/pkix-cert', '3g2' => 'video/3gpp2', '3gp' => 'video/3gp', 'mp4' => 'video/mp4', 'm4a' => 'audio/x-m4a', 'f4v' => 'video/mp4', 'webm' => 'video/webm', 'aac' => 'audio/x-acc', 'm4u' => 'application/vnd.mpegurl', 'm3u' => 'text/plain', 'xspf' => 'application/xspf+xml', 'vlc' => 'application/videolan', 'wmv' => 'video/x-ms-wmv', 'au' => 'audio/x-au', 'ac3' => 'audio/ac3', 'flac' => 'audio/x-flac', 'ogg' => 'audio/ogg', 'kmz' => 'application/vnd.google-earth.kmz', 'kml' => 'application/vnd.google-earth.kml+xml', 'ics' => 'text/calendar', 'zsh' => 'text/x-scriptzsh', '7zip' => 'application/x-7z-compressed', 'cdr' => 'application/cdr', 'wma' => 'audio/x-ms-wma', 'jar' => 'application/java-archive', ]; } }
{ "pile_set_name": "Github" }
/* * (C) Copyright 2002 * Rich Ireland, Enterasys Networks, [email protected]. * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/processor.h> #include <asm/mmu.h> #include <asm/io.h> #include <linux/compiler.h> #ifdef CONFIG_ADDR_MAP #include <addr_map.h> #endif DECLARE_GLOBAL_DATA_PTR; int write_bat (ppc_bat_t bat, unsigned long upper, unsigned long lower) { __maybe_unused int batn = -1; sync(); switch (bat) { case DBAT0: mtspr (DBAT0L, lower); mtspr (DBAT0U, upper); batn = 0; break; case IBAT0: mtspr (IBAT0L, lower); mtspr (IBAT0U, upper); break; case DBAT1: mtspr (DBAT1L, lower); mtspr (DBAT1U, upper); batn = 1; break; case IBAT1: mtspr (IBAT1L, lower); mtspr (IBAT1U, upper); break; case DBAT2: mtspr (DBAT2L, lower); mtspr (DBAT2U, upper); batn = 2; break; case IBAT2: mtspr (IBAT2L, lower); mtspr (IBAT2U, upper); break; case DBAT3: mtspr (DBAT3L, lower); mtspr (DBAT3U, upper); batn = 3; break; case IBAT3: mtspr (IBAT3L, lower); mtspr (IBAT3U, upper); break; #ifdef CONFIG_HIGH_BATS case DBAT4: mtspr (DBAT4L, lower); mtspr (DBAT4U, upper); batn = 4; break; case IBAT4: mtspr (IBAT4L, lower); mtspr (IBAT4U, upper); break; case DBAT5: mtspr (DBAT5L, lower); mtspr (DBAT5U, upper); batn = 5; break; case IBAT5: mtspr (IBAT5L, lower); mtspr (IBAT5U, upper); break; case DBAT6: mtspr (DBAT6L, lower); mtspr (DBAT6U, upper); batn = 6; break; case IBAT6: mtspr (IBAT6L, lower); mtspr (IBAT6U, upper); break; case DBAT7: mtspr (DBAT7L, lower); mtspr (DBAT7U, upper); batn = 7; break; case IBAT7: mtspr (IBAT7L, lower); mtspr (IBAT7U, upper); break; #endif default: return (-1); } #ifdef CONFIG_ADDR_MAP if ((gd->flags & GD_FLG_RELOC) && (batn >= 0)) { phys_size_t size; if (!BATU_VALID(upper)) size = 0; else size = BATU_SIZE(upper); addrmap_set_entry(BATU_VADDR(upper), BATL_PADDR(lower), size, batn); } #endif sync(); isync(); return (0); } int read_bat (ppc_bat_t bat, unsigned long *upper, unsigned long *lower) { unsigned long register u; unsigned long register l; switch (bat) { case DBAT0: l = mfspr (DBAT0L); u = mfspr (DBAT0U); break; case IBAT0: l = mfspr (IBAT0L); u = mfspr (IBAT0U); break; case DBAT1: l = mfspr (DBAT1L); u = mfspr (DBAT1U); break; case IBAT1: l = mfspr (IBAT1L); u = mfspr (IBAT1U); break; case DBAT2: l = mfspr (DBAT2L); u = mfspr (DBAT2U); break; case IBAT2: l = mfspr (IBAT2L); u = mfspr (IBAT2U); break; case DBAT3: l = mfspr (DBAT3L); u = mfspr (DBAT3U); break; case IBAT3: l = mfspr (IBAT3L); u = mfspr (IBAT3U); break; #ifdef CONFIG_HIGH_BATS case DBAT4: l = mfspr (DBAT4L); u = mfspr (DBAT4U); break; case IBAT4: l = mfspr (IBAT4L); u = mfspr (IBAT4U); break; case DBAT5: l = mfspr (DBAT5L); u = mfspr (DBAT5U); break; case IBAT5: l = mfspr (IBAT5L); u = mfspr (IBAT5U); break; case DBAT6: l = mfspr (DBAT6L); u = mfspr (DBAT6U); break; case IBAT6: l = mfspr (IBAT6L); u = mfspr (IBAT6U); break; case DBAT7: l = mfspr (DBAT7L); u = mfspr (DBAT7U); break; case IBAT7: l = mfspr (IBAT7L); u = mfspr (IBAT7U); break; #endif default: return (-1); } *upper = u; *lower = l; return (0); } void print_bats(void) { printf("BAT registers:\n"); printf ("\tIBAT0L = 0x%08X ", mfspr (IBAT0L)); printf ("\tIBAT0U = 0x%08X\n", mfspr (IBAT0U)); printf ("\tDBAT0L = 0x%08X ", mfspr (DBAT0L)); printf ("\tDBAT0U = 0x%08X\n", mfspr (DBAT0U)); printf ("\tIBAT1L = 0x%08X ", mfspr (IBAT1L)); printf ("\tIBAT1U = 0x%08X\n", mfspr (IBAT1U)); printf ("\tDBAT1L = 0x%08X ", mfspr (DBAT1L)); printf ("\tDBAT1U = 0x%08X\n", mfspr (DBAT1U)); printf ("\tIBAT2L = 0x%08X ", mfspr (IBAT2L)); printf ("\tIBAT2U = 0x%08X\n", mfspr (IBAT2U)); printf ("\tDBAT2L = 0x%08X ", mfspr (DBAT2L)); printf ("\tDBAT2U = 0x%08X\n", mfspr (DBAT2U)); printf ("\tIBAT3L = 0x%08X ", mfspr (IBAT3L)); printf ("\tIBAT3U = 0x%08X\n", mfspr (IBAT3U)); printf ("\tDBAT3L = 0x%08X ", mfspr (DBAT3L)); printf ("\tDBAT3U = 0x%08X\n", mfspr (DBAT3U)); #ifdef CONFIG_HIGH_BATS printf ("\tIBAT4L = 0x%08X ", mfspr (IBAT4L)); printf ("\tIBAT4U = 0x%08X\n", mfspr (IBAT4U)); printf ("\tDBAT4L = 0x%08X ", mfspr (DBAT4L)); printf ("\tDBAT4U = 0x%08X\n", mfspr (DBAT4U)); printf ("\tIBAT5L = 0x%08X ", mfspr (IBAT5L)); printf ("\tIBAT5U = 0x%08X\n", mfspr (IBAT5U)); printf ("\tDBAT5L = 0x%08X ", mfspr (DBAT5L)); printf ("\tDBAT5U = 0x%08X\n", mfspr (DBAT5U)); printf ("\tIBAT6L = 0x%08X ", mfspr (IBAT6L)); printf ("\tIBAT6U = 0x%08X\n", mfspr (IBAT6U)); printf ("\tDBAT6L = 0x%08X ", mfspr (DBAT6L)); printf ("\tDBAT6U = 0x%08X\n", mfspr (DBAT6U)); printf ("\tIBAT7L = 0x%08X ", mfspr (IBAT7L)); printf ("\tIBAT7U = 0x%08X\n", mfspr (IBAT7U)); printf ("\tDBAT7L = 0x%08X ", mfspr (DBAT7L)); printf ("\tDBAT7U = 0x%08X\n", mfspr (DBAT7U)); #endif }
{ "pile_set_name": "Github" }
# WWW::SwaggerClient::Object::ClassModel ## Load the model package ```perl use WWW::SwaggerClient::Object::ClassModel; ``` ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **_class** | **string** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{ "pile_set_name": "Github" }
/* * Copyright 2014-2020 Real Logic Limited. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Subscription.h" #include "ClientConductor.h" #include "ChannelUri.h" #include "concurrent/status/LocalSocketAddressStatus.h" using namespace aeron; using namespace aeron::concurrent::status; Subscription::Subscription( ClientConductor &conductor, std::int64_t registrationId, const std::string &channel, std::int32_t streamId, std::int32_t channelStatusId) : m_conductor(conductor), m_channel(channel), m_channelStatusId(channelStatusId), m_streamId(streamId), m_registrationId(registrationId), m_imageArray(), m_isClosed(false) { static_cast<void>(m_paddingBefore); static_cast<void>(m_paddingAfter); } Subscription::~Subscription() { auto imageArrayPair = m_imageArray.load(); m_conductor.releaseSubscription(m_registrationId, imageArrayPair.first, imageArrayPair.second); } std::int64_t Subscription::addDestination(const std::string &endpointChannel) { if (isClosed()) { throw util::IllegalStateException(std::string("Subscription is closed"), SOURCEINFO); } return m_conductor.addRcvDestination(m_registrationId, endpointChannel); } std::int64_t Subscription::removeDestination(const std::string &endpointChannel) { if (isClosed()) { throw util::IllegalStateException(std::string("Subscription is closed"), SOURCEINFO); } return m_conductor.removeRcvDestination(m_registrationId, endpointChannel); } bool Subscription::findDestinationResponse(std::int64_t correlationId) { return m_conductor.findDestinationResponse(correlationId); } std::int64_t Subscription::channelStatus() const { if (isClosed()) { return ChannelEndpointStatus::NO_ID_ALLOCATED; } return m_conductor.channelStatus(m_channelStatusId); } std::vector<std::string> Subscription::localSocketAddresses() const { return LocalSocketAddressStatus::findAddresses( m_conductor.countersReader(), channelStatus(), channelStatusId()); } std::string Subscription::tryResolveChannelEndpointPort() const { const int64_t currentChannelStatus = channelStatus(); if (ChannelEndpointStatus::CHANNEL_ENDPOINT_ACTIVE == currentChannelStatus) { std::vector<std::string> localSocketAddresses = LocalSocketAddressStatus::findAddresses( m_conductor.countersReader(), currentChannelStatus, m_channelStatusId); if (1 == localSocketAddresses.size()) { std::shared_ptr<ChannelUri> channelUriPtr = ChannelUri::parse(m_channel); std::string endpoint = channelUriPtr->get(ENDPOINT_PARAM_NAME); if (!endpoint.empty() && endsWith(endpoint, std::string(":0"))) { std::string &resolvedEndpoint = localSocketAddresses.at(0); std::size_t i = resolvedEndpoint.find_last_of(':'); std::string newEndpoint = endpoint.substr(0, endpoint.length() - 2) + resolvedEndpoint.substr(i); channelUriPtr->put(ENDPOINT_PARAM_NAME, newEndpoint); return channelUriPtr->toString(); } } return m_channel; } return {}; }
{ "pile_set_name": "Github" }
package(default_visibility = ["//visibility:public"]) load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", srcs = [ "doc.go", "register.go", "types.go", "zz_generated.conversion.go", "zz_generated.deepcopy.go", ], importmap = "k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion", importpath = "k8s.io/apimachinery/pkg/apis/meta/internalversion", deps = [ "//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1beta1:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/conversion:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/fields:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/labels:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", ], ) filegroup( name = "package-srcs", srcs = glob(["**"]), tags = ["automanaged"], visibility = ["//visibility:private"], ) filegroup( name = "all-srcs", srcs = [ ":package-srcs", "//staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme:all-srcs", "//staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/validation:all-srcs", ], tags = ["automanaged"], )
{ "pile_set_name": "Github" }
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- Resource dictionary entries should be defined here. --> </ResourceDictionary>
{ "pile_set_name": "Github" }
# ************************************************************************************** # * * # * BOLTS - Open Library of Technical Specifications * # * * # * Copyright (C) 2014 Johannes Reinhardt <[email protected]> * # * * # * This library is free software; you can redistribute it and/or * # * modify it under the terms of the GNU Lesser General Public * # * License as published by the Free Software Foundation; either * # * version 2.1 of the License, or any later version. * # * * # * This library is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * # * Lesser General Public License for more details. * # * * # * You should have received a copy of the GNU Lesser General Public * # * License along with this library; if not, write to the Free Software * # * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * # * * # ************************************************************************************** import math import Part from FreeCAD import Vector from DraftGeomUtils import fillet as draft_fillet # ************************************************************************************************ def vslot20x20( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 8 * [vslot_outline] fillets = [5, 17, 29, 41] corner_offset = 0 circle_offsets = [0] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # color if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) # ************************************************************************************************ def vslot20x40( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-w, 0, True, False, True, False), (-w, 0, False, False, True, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 12 * [vslot_outline] fillets = [5, 29, 41, 65] corner_offset = -1 * w circle_offsets = [0, -w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # color if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) # ************************************************************************************************ def vslot20x60(params, document): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-2 * w, 0, True, True, False, False), (-2 * w, 0, False, True, True, False), (-2 * w, 0, True, False, True, False), (-2 * w, 0, False, False, True, True), (-2 * w, 0, True, True, True, True), (-2 * w, 0, False, True, False, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 16 * [vslot_outline] # add fillets in reverse order, as this inserts additional edges fillets = [5, 41, 53, 89] corner_offset = -2 * w circle_offsets = [0, -w, -2 * w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # color if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) # ************************************************************************************************ def vslot20x80(params, document): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-2 * w, 0, True, True, False, False), (-2 * w, 0, False, True, True, False), (-3 * w, 0, True, True, False, False), (-3 * w, 0, False, True, True, False), (-3 * w, 0, True, False, True, False), (-3 * w, 0, False, False, True, True), (-3 * w, 0, True, True, True, True), (-3 * w, 0, False, True, False, True), (-2 * w, 0, True, True, True, True), (-2 * w, 0, False, True, False, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 20 * [vslot_outline] # add fillets in reverse order, as this inserts additional edges fillets = [5, 53, 65, 113] corner_offset = -3 * w circle_offsets = [0, -w, -2 * w, -3 * w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # color if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) # ************************************************************************************************ def tslot20x20( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 8 * [tslot_outline] fillets = [5, 17, 29, 41] corner_offset = 0 circle_offsets = [0] face = tslot(symmetry, vertices, fillets, [], [], corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ def tslot20x20_three_slot( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 2 * [tslot_closed] + 5 * [tslot_outline] fillets = [5, 7, 19, 31] closed_symmetry = [ (0, 0, False, True, False, False), ] closed_vertices = [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ def tslot20x20_two_slot( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 4 * [tslot_closed] + 3 * [tslot_outline] fillets = [5, 7, 9, 21] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, False, True, False), ] closed_vertices = 2 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ def tslot20x20_two_slot_opp( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = ( [tslot_outline] + 2 * [tslot_closed] + 2 * [tslot_outline] + 2 * [tslot_closed] + [tslot_outline] ) fillets = [5, 7, 19, 21] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, True, False, True), ] closed_vertices = 2 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ def tslot20x20_one_slot( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 6 * [tslot_closed] + [tslot_outline] fillets = [5, 7, 9, 11] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, False, True, False), (0, 0, False, True, False, True), ] closed_vertices = 3 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ # helper def fillet( lines, indices, radius ): """ fillets the corner between the segments and their successors in lines indicated by indices """ lines = lines[:] # sort them in descending order, as filleting inserts additional edges indices.sort() indices.reverse() for i in indices: lines[slice(i, i + 2)] = draft_fillet(lines[slice(i, i + 2)], radius) return lines def assemble( symmetry, vertices, offset_global=(0, 0) ): """ Assemble a wire from a list of symmetry information and a list of list of vertices symmetry information is a tuple of offset x, offset y, bool reverse, bool switch_comp, bool mirror_x, bool mirror_y """ offset = Vector(offset_global[0], offset_global[1], 0) lines = [] vlast = None vcur = None for sym, verts in zip(symmetry, vertices): o_x, o_y, reverse, switch, mir_x, mir_y = sym mir_x = -1 if mir_x else 1 mir_y = -1 if mir_y else 1 if reverse: verts = verts[::-1] if vcur is None: vcur = Vector(verts[0]) if switch: vcur[0], vcur[1] = vcur[1], vcur[0] vcur[0] = mir_x * vcur[0] + o_x + offset[0] vcur[1] = mir_y * vcur[1] + o_y + offset[1] for v in verts[1:]: vlast = vcur vcur = Vector(v) if switch: vcur[0], vcur[1] = vcur[1], vcur[0] vcur[0] = mir_x * vcur[0] + o_x + offset[0] vcur[1] = mir_y * vcur[1] + o_y + offset[1] lines.append(Part.makeLine(vlast, vcur)) return lines # ************************************************************************************************ # profile size w = 20 # ************************************************************************************************ # Vslot profile: # the size of the inner square d = 5.68 + 3 / math.sqrt(2) # one eight of the outline vslot_outline = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 1.8 - 1.64, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2), 0), (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2), 0), (0.5 * w - 1.8, 0.5 * 5.68, 0), (0.5 * w, 0.5 * 5.68 + 1.8, 0), (0.5 * w, 0.5 * w, 0) ] space_symmetry = [ (0, 0, False, False, True, False), (-w, 0, True, False, False, False), (-w, 0, False, False, False, True), (0, 0, True, False, True, True) ] # big spaces vslot_space = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 2.7, 0.5 * w - 1.8 - 1.96, 0), (0.5 * w - 2.7, 0.5 * w - 1.8, 0), (0.5 * w, 0.5 * w - 1.8, 0), ] # corner holes vslot_cornerhole = [ (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0), (0.5 * w - 1.8, 0.5 * w - 1.8, 0), (0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0.5 * w - 1.8, 0), (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0) ] def vslot( symmetry, vertices, fillets, corner_offset, circle_offsets ): outline = assemble(symmetry, vertices) outline = fillet(outline, fillets, 1.5) outline = Part.Wire(outline) holes = [] # corners # x offset, y offset, reverse, switch, mir_x, mir_y corner_symmetry = [ (0, 0, False, False, False, False), (corner_offset, 0, False, False, True, False), (corner_offset, 0, False, False, True, True), (0, 0, False, False, False, True), ] for sym in corner_symmetry: holes.append(Part.Wire(assemble([sym], [vslot_cornerhole]))) if sym[4] == sym[5]: holes[-1].reverse() # circular holes for offset in circle_offsets: holes.append(Part.Wire(Part.makeCircle(2.1, Vector(offset, 0, 0)))) holes[-1].reverse() # big spaces print("Space") for offset in circle_offsets[:-1]: print(space_symmetry, vslot_space) holes.append(Part.Wire(assemble(space_symmetry, 4 * [vslot_space], (offset, 0)))) holes[-1].reverse() print("Space") # put everything together return Part.Face([outline] + holes) # ************************************************************************************************ # T slot profile: # outline tslot_outline = [ (5.0, 0, 0), (5.0, 3.5, 0), (7.5, 6.0, 0), (9.0, 6.0, 0), (9.0, 3.0, 0), (10.0, 3.0, 0), (10.0, 10.0, 0), ] # closed slots ouline tslot_closed = [ (10.0, 0.0, 0), (10.0, 10.0, 0), ] # closed slots spaces tslot_closed_space = [ (5.0, 0, 0), (5.0, 3.5, 0), (7.5, 6.0, 0), (9.0, 6.0, 0), (9.0, -6.0, 0), (7.5, -6.0, 0), (5.0, -3.5, 0), (5.0, 0, 0), ] # big spaces tslot_space = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 2.7, 0.5 * w - 1.8 - 1.96, 0), (0.5 * w - 2.7, 0.5 * w - 1.8, 0), (0.5 * w, 0.5 * w - 1.8, 0), ] def tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets ): outline = assemble(symmetry, vertices) outline = fillet(outline, fillets, 1.5) outline = Part.Wire(outline) holes = [] # closed holes for sym, vert in zip(closed_symmetry, closed_vertices): holes.append(Part.Wire(assemble([sym], [vert]))) if not sym[5]: holes[-1].reverse() # circular holes for offset in circle_offsets: holes.append(Part.Wire(Part.makeCircle(2.25, Vector(offset, 0, 0)))) holes[-1].reverse() # put everything together return Part.Face([outline] + holes)
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>base64encode - Documentation</title> <script src="scripts/prettify/prettify.js"></script> <script src="scripts/prettify/lang-css.js"></script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <input type="checkbox" id="nav-trigger" class="nav-trigger" /> <label for="nav-trigger" class="navicon-button x"> <div class="navicon"></div> </label> <label for="nav-trigger" class="overlay"></label> <nav> <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-append.html">append</a></li><li><a href="module-appendArray.html">appendArray</a></li><li><a href="module-at.html">at</a></li><li><a href="module-base64decode.html">base64decode</a></li><li><a href="module-base64encode.html">base64encode</a></li><li><a href="module-between.html">between</a></li><li><a href="module-binDecode.html">binDecode</a></li><li><a href="module-binEncode.html">binEncode</a></li><li><a href="module-chars.html">chars</a></li><li><a href="module-collapseWhitespace.html">collapseWhitespace</a></li><li><a href="module-compare.html">compare</a></li><li><a href="module-contains.html">contains</a></li><li><a href="module-containsAll.html">containsAll</a></li><li><a href="module-containsAny.html">containsAny</a></li><li><a href="module-countSubstr.html">countSubstr</a></li><li><a href="module-decDecode.html">decDecode</a></li><li><a href="module-decEncode.html">decEncode</a></li><li><a href="module-endsWith.html">endsWith</a></li><li><a href="module-ensureLeft.html">ensureLeft</a></li><li><a href="module-ensureRight.html">ensureRight</a></li><li><a href="module-equal.html">equal</a></li><li><a href="module-first.html">first</a></li><li><a href="module-format.html">format</a></li><li><a href="module-hexDecode.html">hexDecode</a></li><li><a href="module-hexEncode.html">hexEncode</a></li><li><a href="module-htmlDecode.html">htmlDecode</a></li><li><a href="module-htmlEncode.html">htmlEncode</a></li><li><a href="module-inequal.html">inequal</a></li><li><a href="module-insert.html">insert</a></li><li><a href="module-isLowerCase.html">isLowerCase</a></li><li><a href="module-isString.html">isString</a></li><li><a href="module-isUpperCase.html">isUpperCase</a></li><li><a href="module-last.html">last</a></li><li><a href="module-lastIndefOf.html">lastIndefOf</a></li><li><a href="module-leftPad.html">leftPad</a></li><li><a href="module-leftTrim.html">leftTrim</a></li><li><a href="module-prepend.html">prepend</a></li><li><a href="module-prependArray.html">prependArray</a></li><li><a href="module-removeEmptyStrings.html">removeEmptyStrings</a></li><li><a href="module-removeLeft.html">removeLeft</a></li><li><a href="module-removeNonWords.html">removeNonWords</a></li><li><a href="module-removeSpaces.html">removeSpaces</a></li><li><a href="module-repeat.html">repeat</a></li><li><a href="module-replace.html">replace</a></li><li><a href="module-reverse.html">reverse</a></li><li><a href="module-rightPad.html">rightPad</a></li><li><a href="module-rightTrim.html">rightTrim</a></li><li><a href="module-safeTruncate.html">safeTruncate</a></li><li><a href="module-shuffle.html">shuffle</a></li><li><a href="module-slugify.html">slugify</a></li><li><a href="module-split.html">split</a></li><li><a href="module-startsWith.html">startsWith</a></li><li><a href="module-substr.html">substr</a></li><li><a href="module-surround.html">surround</a></li><li><a href="module-toCamelCase.html">toCamelCase</a></li><li><a href="module-toDecamelize.html">toDecamelize</a></li><li><a href="module-toKebabCase.html">toKebabCase</a></li><li><a href="module-toLowerCase.html">toLowerCase</a></li><li><a href="module-toSnakeCase.html">toSnakeCase</a></li><li><a href="module-toStudlyCaps.html">toStudlyCaps</a></li><li><a href="module-toUpperCase.html">toUpperCase</a></li><li><a href="module-transliterate.html">transliterate</a></li><li><a href="module-trim.html">trim</a></li><li><a href="module-truncate.html">truncate</a></li><li><a href="module-urlDecode.html">urlDecode</a></li><li><a href="module-urlEncode.html">urlEncode</a></li></ul> </nav> <div id="main"> <h1 class="page-title">base64encode</h1> <section> <header> </header> <article> <div class="container-overview"> <div class="description"><p>Encodes data with MIME base64.</p> <p>Base64-encoded data takes about 33% more space than the original data.</p> <h2>Install</h2><p>Install all functions of strman</p> <pre class="prettyprint source lang-sh"><code>yarn add strman</code></pre><p>or just the base64encode function</p> <pre class="prettyprint source lang-sh"><code>yarn add strman.base64encode</code></pre><h2>Usage</h2><pre class="prettyprint source lang-javascript"><code>import { base64encode } from 'strman' // OR import base64encode from 'strman.base64encode'</code></pre></div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>value</code></td> <td class="type"> <span class="param-type">String</span> </td> <td class="description last"><p>The data to encode.</p></td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="base64encode.js.html">base64encode.js</a>, <a href="base64encode.js.html#line7">line 7</a> </li></ul></dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>The base64 encoded data.</p> </div> <dl class="param-type"> <dt> Type </dt> <dd> <span class="param-type">String</span> </dd> </dl> <h5>Example</h5> <pre class="prettyprint"><code>base64Encode('strman') // => 'c3RybWFu'</code></pre> </div> </article> </section> </div> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.3</a> on Sun Mar 26 2017 19:48:28 GMT-0300 (BRT) using the Minami theme. </footer> <script>prettyPrint();</script> <script src="scripts/linenumber.js"></script> </body> </html>
{ "pile_set_name": "Github" }
<?php namespace Tests\Browser\[name]; use Illuminate\Support\Facades\View; use Livewire\Component as BaseComponent; class Component extends BaseComponent { public function render() { return View::file(__DIR__.'/view.blade.php'); } }
{ "pile_set_name": "Github" }
using Surging.Core.Caching; using Surging.Core.Common; using Surging.Core.CPlatform.EventBus.Events; using Surging.Core.CPlatform.Filters.Implementation; using Surging.Core.CPlatform.Ioc; using Surging.Core.CPlatform.Runtime.Client.Address.Resolvers.Implementation.Selectors.Implementation; using Surging.Core.CPlatform.Runtime.Server.Implementation.ServiceDiscovery.Attributes; using Surging.Core.CPlatform.Support; using Surging.Core.CPlatform.Support.Attributes; using Surging.Core.KestrelHttpServer; using Surging.Core.KestrelHttpServer.Internal; using Surging.Core.System.Intercept; using Surging.IModuleServices.Common.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Surging.Core.CPlatform.Validation; using Metadatas=Surging.Core.ProxyGenerator.Interceptors.Implementation.Metadatas; namespace Surging.IModuleServices.Common { [ServiceBundle("api/{Service}/{Method}")] //[ServiceBundle("api/{Service}")] //[ServiceBundle("api/{Service}/{Method}/test")] //[ServiceBundle("api/{Service}/{Method}/test",false)] public interface IUserService: IServiceKey { /// <summary> /// 用戶授权 /// </summary> /// <param name="requestData">请求参数</param> /// <returns>用户模型</returns> Task<UserModel> Authentication(AuthenticationRequestData requestData); /// <summary> /// 获取用户姓名 /// </summary> /// <param name="id">用户编号</param> /// <returns></returns> [ServiceRoute("{id}")] Task<string> GetUserName([Validate] [Range(1, 10, ErrorMessage = "只能为1到10")] int id); /// <summary> /// 判断是否存在 /// </summary> /// <param name="id">用户编号</param> /// <returns></returns> [ServiceRoute("{id}")] [HttpPost(true),HttpPut(true), HttpDelete(true), HttpGet(true)] // [ServiceBundle("api/{Service}/{id}", false)] Task<bool> Exists(int id); /// <summary> /// 报错用户 /// </summary> /// <param name="requestData">请求参数</param> /// <returns></returns> [Authorization(AuthType = AuthorizationType.JWT)] [HttpPost(true),HttpPut(true)] Task<IdentityUser> Save(IdentityUser requestData); /// <summary> /// 根据用户名获取用户ID /// </summary> /// <param name="userName">用户名</param> /// <returns></returns> [Authorization(AuthType = AuthorizationType.JWT)] [Command(Strategy = StrategyType.Injection, ShuntStrategy = AddressSelectorMode.HashAlgorithm, ExecutionTimeoutInMilliseconds = 1500, BreakerRequestVolumeThreshold = 3, Injection = @"return 1;", RequestCacheEnabled = false)] [InterceptMethod(CachingMethod.Get, Key = "GetUserId_{0}", CacheSectionType = SectionType.ddlCache, L2Key= "GetUserId_{0}", EnableL2Cache = true, Mode = CacheTargetType.Redis, Time = 480)] [Metadatas.ServiceCacheIntercept(Metadatas.CachingMethod.Get, Key = "GetUserId_{0}", CacheSectionType = "ddlCache", L2Key= "GetUserId_{0}", EnableL2Cache = true, Mode = Metadatas.CacheTargetType.Redis, Time = 480)] [Metadatas.ServiceLogIntercept()] [ServiceRoute("{userName}")] Task<int> GetUserId(string userName); Task Try(); /// <summary> /// 获取用户最后次sign时间 /// </summary> /// <param name="id">用户ID</param> /// <returns></returns> Task<DateTime> GetUserLastSignInTime(int id); /// <summary> /// 获取用户 /// </summary> /// <param name="user">用户模型</param> /// <returns></returns> [Command(Strategy = StrategyType.Injection, Injection = @"return new Surging.IModuleServices.Common.Models.UserModel { Name=""fanly"", Age=19 };", RequestCacheEnabled = true, InjectionNamespaces = new string[] { "Surging.IModuleServices.Common" })] [InterceptMethod(CachingMethod.Get, Key = "GetUser_id_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis, Time = 480)] [Metadatas.ServiceCacheIntercept(Metadatas.CachingMethod.Get, Key = "GetUser_{0}_{1}", L2Key = "GetUser_{0}_{1}",EnableL2Cache =true, CacheSectionType = "ddlCache", Mode = Metadatas.CacheTargetType.Redis, Time = 480)] [Validate] Task<UserModel> GetUser(UserModel user); /// <summary> /// 更新用户 /// </summary> /// <param name="id">用户ID</param> /// <param name="model">用户模型</param> /// <returns></returns> [Authorization(AuthType = AuthorizationType.JWT)] [Command(Strategy = StrategyType.FallBack,FallBackName = "UpdateFallBackName", RequestCacheEnabled = true, InjectionNamespaces = new string[] { "Surging.IModuleServices.Common" })] [InterceptMethod(CachingMethod.Remove, "GetUser_id_{0}", "GetUserName_name_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis)] Task<bool> Update(int id, UserModel model); /// <summary> /// 测试List参数调用 /// </summary> /// <param name="users">用户列表</param> /// <returns>返回是否成功</returns> Task<bool> Get(List<UserModel> users); /// <summary> /// 测试无参数调用 /// </summary> /// <returns>返回是否成功</returns> Task<bool> GetDictionary(); /// <summary> /// 测试异常 /// </summary> /// <returns></returns> Task TryThrowException(); [ServiceRoute("{sex}")] Task<Sex> SetSex(Sex sex); /// <summary> /// 测试基于eventbus 推送消息 /// </summary> /// <param name="evt1">Event 模型</param> /// <returns></returns> Task PublishThroughEventBusAsync(IntegrationEvent evt1); /// <summary> /// 测试无参调用,返回泛型结果 /// </summary> /// <returns></returns> [Command(Strategy = StrategyType.Injection, ShuntStrategy = AddressSelectorMode.HashAlgorithm, ExecutionTimeoutInMilliseconds = 2500, BreakerRequestVolumeThreshold = 3, Injection = @"return null;", RequestCacheEnabled = false)] Task<ApiResult<UserModel>> GetApiResult(); /// <summary> /// 测试参数list参数 /// </summary> /// <param name="idList">list 类型参数</param> /// <returns></returns> [ServiceMetadata("IsOverload", true)] Task<string> GetUser(List<int> idList); /// <summary> /// 测序guid /// </summary> /// <param name="id"></param> /// <returns></returns> [ServiceRoute("{id}")] Task<UserModel> GetUserById(Guid id); /// <summary> /// 测试上传文件 /// </summary> /// <param name="form">HttpFormCollection 类型参数</param> /// <returns></returns> Task<bool> UploadFile(HttpFormCollection form1); /// <summary> /// 测试下载文件 /// </summary> /// <param name="fileName">文件名</param> /// <param name="contentType">Content-Type</param> /// <returns></returns> [ServiceRoute("{fileName}/{contentType}")] Task<IActionResult> DownFile(string fileName, string contentType); /// <summary> /// /// </summary> /// <returns></returns> Task<Dictionary<string, object>> GetAllThings(); [Metadatas.ServiceCacheIntercept(Metadatas.CachingMethod.Remove, "GetUser_{0}_{1}", CacheSectionType ="ddlCache", Mode = Metadatas.CacheTargetType.Redis)] public Task<bool> RemoveUser(UserModel user); } }
{ "pile_set_name": "Github" }
package saros.intellij.ui.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; /** Parent class for all Saros actions */ public abstract class AbstractSarosAction { protected static final Logger log = Logger.getLogger(AbstractSarosAction.class); private final List<ActionListener> actionListeners = new ArrayList<>(); protected void actionPerformed() { for (ActionListener actionListener : actionListeners) { actionListener.actionPerformed(new ActionEvent(this, 0, getActionName())); } } public void addActionListener(ActionListener actionListener) { actionListeners.add(actionListener); } public abstract String getActionName(); public abstract void execute(); }
{ "pile_set_name": "Github" }
'use strict'; var macros = { who: function (msgObj) { return msgObj.get('user_name'); }, someone: function () { var presentUsers = document.getElementById('sidebar') .getElementsByClassName('present-user'); // the chat keeps a low opacity for users who remained silent for long, // and high opacity for those who recently talked var user = Array.filter(presentUsers, function (user) { return Number(user.style.opacity) >= 0.5; }).random(); if (!user) { return 'Nobody'; } return user.getElementsByTagName('img')[0].title; }, digit: function () { return Math.floor(Math.random() * 10); }, encode: function (msgObj, string) { return encodeURIComponent(string); }, // random number, min <= n <= max // treats non-numeric inputs like they don't exist rand: function (msgObj, min, max) { // rand() === rand( 0, 10 ) if (!min) { min = 0; max = 10; } // rand( max ) === rand( 0, max ) else if (!max) { max = min; min = 0; } else { min = Number(min); max = Number(max); } return Math.rand(min, max); } }; var macroRegex = /(?:.|^)\$(\w+)(?:\((.*?)\))?/g; exports.parseMacro = function parse (source, extraVars) { return source.replace(macroRegex, replaceMacro); function replaceMacro ($0, filler, fillerArgs) { // $$ makes a literal $ if ($0.startsWith('$$')) { return $0.slice(1); } // include the character that was matched in the $$ check, unless // it's a $ var ret = ''; if ($0[0] !== '$') { ret = $0[0]; } var macro = findMacro(filler); // not found? bummer. if (!macro) { return filler; } console.log(macro, filler, fillerArgs, '/parse replaceMacro'); // when the macro is a function if (macro.apply) { ret += macro.apply(null, parseMacroArgs(fillerArgs)); } // when the macro is simply a substitution else { ret += macro; } return ret; } function parseMacroArgs (macroArgs) { console.log(macroArgs, '/parse parseMacroArgs'); if (!macroArgs) { return [source]; } // parse the arguments, split them into individual arguments, // and trim'em (to cover the case of "arg,arg" and "arg, arg") var parsedArgs = parse(macroArgs, extraVars); return [source].concat(parsedArgs.split(',').invoke('trim')); // this is not good code } function findMacro (macro) { var container = [macros, extraVars].first(hasMacro); return (container || {})[macro]; function hasMacro (obj) { return obj && obj.hasOwnProperty(macro); } } };
{ "pile_set_name": "Github" }
body { margin: 0; font-family: Arial, sans-serif; background-color: #fff; line-height: 1.3; text-align: center; color: #222; } pre, code { font-family: Menlo, monospace; font-size: 0.875rem; } pre { line-height: 1.4; overflow-x: auto; } pre .comment { color: #006600; } pre .highlight, pre .highlight-comment, pre .selection-highlight, pre .selection-highlight-comment { background: #FFFF00; } pre .selection, pre .selection-comment { background: #FF9632; } pre .ln { color: #999; background: #efefef; } .ln { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } a, .exampleHeading .text, .expandAll { color: #375EAB; text-decoration: none; } a:hover, .exampleHeading .text:hover, .expandAll:hover { text-decoration: underline; } .article a { text-decoration: underline; } .article .title a { text-decoration: none; } .permalink { display: none; } :hover > .permalink { display: inline; } p, li { max-width: 50rem; word-wrap: break-word; } p, pre, ul, ol { margin: 1.25rem; } pre { background: #EFEFEF; padding: 0.625rem; border-radius: 0.3125rem; } h1, h2, h3, h4, .rootHeading { margin: 1.25rem 0 1.25rem; padding: 0; color: #375EAB; font-weight: bold; } h1 { font-size: 1.75rem; line-height: 1; } h1 .text-muted { color:#777; } h2 { font-size: 1.25rem; background: #E0EBF5; padding: 0.5rem; line-height: 1.25; font-weight: normal; } h2 a { font-weight: bold; } h3 { font-size: 1.25rem; } h3, h4 { margin: 1.25rem 0.3125rem; } h4 { font-size: 1rem; } .rootHeading { font-size: 1.25rem; margin: 0; } dl { margin: 1.25rem; } dd { margin: 0 0 0 1.25rem; } dl, dd { font-size: 0.875rem; } div#nav table td { vertical-align: top; } #pkg-index h3 { font-size: 1rem; } .pkg-dir { padding: 0 0.625rem; } .pkg-dir table { border-collapse: collapse; border-spacing: 0; } .pkg-name { padding-right: 0.625rem; } .alert { color: #AA0000; } .top-heading { float: left; padding: 1.313rem 0; font-size: 1.25rem; font-weight: normal; } .top-heading a { color: #222; text-decoration: none; } #pkg-examples h3 { float: left; } #pkg-examples dl { clear: both; } .expandAll { cursor: pointer; float: left; margin: 1.25rem 0; } div#topbar { background: #E0EBF5; height: 4rem; overflow: hidden; } div#page { width: 100%; } div#page > .container, div#topbar > .container { text-align: left; margin-left: auto; margin-right: auto; padding: 0 1.25rem; } div#topbar > .container, div#page > .container { max-width: 59.38rem; } div#page.wide > .container, div#topbar.wide > .container { max-width: none; } div#plusone { float: right; clear: right; margin-top: 0.3125rem; } div#footer { text-align: center; color: #666; font-size: 0.875rem; margin: 2.5rem 0; } div#menu > a, input#search, div#learn .buttons a, div.play .buttons a, div#blog .read a, #menu-button { padding: 0.625rem; text-decoration: none; font-size: 1rem; border-radius: 0.3125rem; } div#playground .buttons a, div#menu > a, input#search, #menu-button { border: 0.0625rem solid #375EAB; } div#playground .buttons a, div#menu > a, #menu-button { color: white; background: #375EAB; } #playgroundButton.active { background: white; color: #375EAB; } a#start, div#learn .buttons a, div.play .buttons a, div#blog .read a { color: #222; border: 0.0625rem solid #375EAB; background: #E0EBF5; } .download { width: 9.375rem; } div#menu { text-align: right; padding: 0.625rem; white-space: nowrap; max-height: 0; -moz-transition: max-height .25s linear; transition: max-height .25s linear; width: 100%; } div#menu.menu-visible { max-height: 31.25rem; } div#menu > a, #menu-button { margin: 0.625rem 0.125rem; padding: 0.625rem; } ::-webkit-input-placeholder { color: #7f7f7f; opacity: 1; } ::placeholder { color: #7f7f7f; opacity: 1; } #menu .search-box { display: inline-flex; width: 8.75rem; } input#search { background: white; color: #222; box-sizing: border-box; -webkit-appearance: none; border-top-right-radius: 0; border-bottom-right-radius: 0; border-right: 0; margin-right: 0; flex-grow: 1; max-width: 100%; min-width: 5.625rem; } input#search:-moz-ui-invalid { box-shadow: unset; } input#search + button { display: inline; font-size: 1em; background-color: #375EAB; color: white; border: 0.0625rem solid #375EAB; border-top-left-radius: 0; border-top-right-radius: 0.3125rem; border-bottom-left-radius: 0; border-bottom-right-radius: 0.3125rem; margin-left: 0; cursor: pointer; } input#search + button span { display: flex; } input#search + button svg { fill: white } #menu-button { display: none; position: absolute; right: 0.3125rem; top: 0; margin-right: 0.3125rem; } #menu-button-arrow { display: inline-block; } .vertical-flip { transform: rotate(-180deg); } div.left { float: left; clear: left; margin-right: 2.5%; } div.right { float: right; clear: right; margin-left: 2.5%; } div.left, div.right { width: 45%; } div#learn, div#about { padding-top: 1.25rem; } div#learn h2, div#about { margin: 0; } div#about { font-size: 1.25rem; margin: 0 auto 1.875rem; } div#gopher { background: url(/doc/gopher/frontpage.png) no-repeat; background-position: center top; height: 9.688rem; max-height: 200px; /* Setting in px to prevent the gopher from blowing up in very high default font-sizes */ } a#start { display: block; padding: 0.625rem; text-align: center; text-decoration: none; border-radius: 0.3125rem; } a#start .big { display: block; font-weight: bold; font-size: 1.25rem; } a#start .desc { display: block; font-size: 0.875rem; font-weight: normal; margin-top: 0.3125rem; } div#learn .popout { float: right; display: block; cursor: pointer; font-size: 0.75rem; background: url(/doc/share.png) no-repeat; background-position: right center; padding: 0.375rem 1.688rem; } div#learn pre, div#learn textarea { padding: 0; margin: 0; font-family: Menlo, monospace; font-size: 0.875rem; } div#learn .input { padding: 0.625rem; margin-top: 0.625rem; height: 9.375rem; border-top-left-radius: 0.3125rem; border-top-right-radius: 0.3125rem; } div#learn .input textarea { width: 100%; height: 100%; border: none; outline: none; resize: none; } div#learn .output { border-top: none !important; padding: 0.625rem; height: 3.688rem; overflow: auto; border-bottom-right-radius: 0.3125rem; border-bottom-left-radius: 0.3125rem; } div#learn .output pre { padding: 0; border-radius: 0; } div#learn .input, div#learn .input textarea, div#learn .output, div#learn .output pre { background: #FFFFD8; } div#learn .input, div#learn .output { border: 0.0625rem solid #375EAB; } div#learn .buttons { float: right; padding: 1.25rem 0 0.625rem 0; text-align: right; } div#learn .buttons a { height: 1rem; margin-left: 0.3125rem; padding: 0.625rem; } div#learn .toys { margin-top: 0.5rem; } div#learn .toys select { font-size: 0.875rem; border: 0.0625rem solid #375EAB; margin: 0; } div#learn .output .exit { display: none; } div#video { max-width: 100%; } div#blog, div#video { margin-top: 2.5rem; } div#blog > a, div#blog > div, div#blog > h2, div#video > a, div#video > div, div#video > h2 { margin-bottom: 0.625rem; } div#blog .title, div#video .title { display: block; font-size: 1.25rem; } div#blog .when { color: #666; font-size: 0.875rem; } div#blog .read { text-align: right; } @supports (--c: 0) { [style*="--aspect-ratio-padding:"] { position: relative; overflow: hidden; padding-top: var(--aspect-ratio-padding); } [style*="--aspect-ratio-padding:"]>* { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } } .toggleButton { cursor: pointer; } .toggle > .collapsed { display: block; } .toggle > .expanded { display: none; } .toggleVisible > .collapsed { display: none; } .toggleVisible > .expanded { display: block; } table.codetable { margin-left: auto; margin-right: auto; border-style: none; } table.codetable td { padding-right: 0.625rem; } hr { border-style: none; border-top: 0.0625rem solid black; } img.gopher { float: right; margin-left: 0.625rem; margin-bottom: 0.625rem; z-index: -1; } h2 { clear: right; } /* example and drop-down playground */ div.play { padding: 0 1.25rem 2.5rem 1.25rem; } div.play pre, div.play textarea, div.play .lines { padding: 0; margin: 0; font-family: Menlo, monospace; font-size: 0.875rem; } div.play .input { padding: 0.625rem; margin-top: 0.625rem; border-top-left-radius: 0.3125rem; border-top-right-radius: 0.3125rem; overflow: hidden; } div.play .input textarea { width: 100%; height: 100%; border: none; outline: none; resize: none; overflow: hidden; } div#playground .input textarea { overflow: auto; resize: auto; } div.play .output { border-top: none !important; padding: 0.625rem; max-height: 12.5rem; overflow: auto; border-bottom-right-radius: 0.3125rem; border-bottom-left-radius: 0.3125rem; } div.play .output pre { padding: 0; border-radius: 0; } div.play .input, div.play .input textarea, div.play .output, div.play .output pre { background: #FFFFD8; } div.play .input, div.play .output { border: 0.0625rem solid #375EAB; } div.play .buttons { float: right; padding: 1.25rem 0 0.625rem 0; text-align: right; } div.play .buttons a { height: 1rem; margin-left: 0.3125rem; padding: 0.625rem; cursor: pointer; } .output .stderr { color: #933; } .output .system { color: #999; } /* drop-down playground */ #playgroundButton, div#playground { /* start hidden; revealed by javascript */ display: none; } div#playground { position: absolute; top: 3.938rem; right: 1.25rem; padding: 0 0.625rem 0.625rem 0.625rem; z-index: 1; text-align: left; background: #E0EBF5; border: 0.0625rem solid #B0BBC5; border-top: none; border-bottom-left-radius: 0.3125rem; border-bottom-right-radius: 0.3125rem; } div#playground .code { width: 32.5rem; height: 12.5rem; } div#playground .output { height: 6.25rem; } /* Inline runnable snippets (play.js/initPlayground) */ #content .code pre, #content .playground pre, #content .output pre { margin: 0; padding: 0; background: none; border: none; outline: 0 solid transparent; overflow: auto; } #content .playground .number, #content .code .number { color: #999; } #content .code, #content .playground, #content .output { width: auto; margin: 1.25rem; padding: 0.625rem; border-radius: 0.3125rem; } #content .code, #content .playground { background: #e9e9e9; } #content .output { background: #202020; } #content .output .stdout, #content .output pre { color: #e6e6e6; } #content .output .stderr, #content .output .error { color: rgb(244, 74, 63); } #content .output .system, #content .output .exit { color: rgb(255, 209, 77) } #content .buttons { position: relative; float: right; top: -3.125rem; right: 1.875rem; } #content .output .buttons { top: -3.75rem; right: 0; height: 0; } #content .buttons .kill { display: none; visibility: hidden; } a.error { font-weight: bold; color: white; background-color: darkred; border-bottom-left-radius: 0.25rem; border-bottom-right-radius: 0.25rem; border-top-left-radius: 0.25rem; border-top-right-radius: 0.25rem; padding: 0.125rem 0.25rem 0.125rem 0.25rem; /* TRBL */ } #heading-narrow { display: none; } .downloading { background: #F9F9BE; padding: 0.625rem; text-align: center; border-radius: 0.3125rem; } @media (max-width: 58.125em) { #heading-wide { display: none; } #heading-narrow { display: block; } } @media (max-width: 47.5em) { .container .left, .container .right { width: auto; float: none; } div#about { max-width: 31.25rem; text-align: center; } } @media (min-width: 43.75em) and (max-width: 62.5em) { div#menu > a { margin: 0.3125rem 0; font-size: 0.875rem; } input#search { font-size: 0.875rem; } } @media (max-width: 43.75em) { body { font-size: 0.9375rem; } pre, code { font-size: 0.866rem; } div#page > .container { padding: 0 0.625rem; } div#topbar { height: auto; padding: 0.625rem; } div#topbar > .container { padding: 0; } #heading-wide { display: block; } #heading-narrow { display: none; } .top-heading { float: none; display: inline-block; padding: 0.75rem; } div#menu { padding: 0; min-width: 0; text-align: left; float: left; } div#menu > a { display: block; margin-left: 0; margin-right: 0; } #menu .search-box { display: flex; width: 100%; } #menu-button { display: inline-block; } p, pre, ul, ol { margin: 0.625rem; } .pkg-synopsis { display: none; } img.gopher { display: none; } } @media (max-width: 30em) { #heading-wide { display: none; } #heading-narrow { display: block; } } @media print { pre { background: #FFF; border: 0.0625rem solid #BBB; white-space: pre-wrap; } }
{ "pile_set_name": "Github" }
type=item items=minecraft:experience_bottle texture=./exec.png nbt.display.Lore.*=ipattern:*Execute*
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE QtCreatorProject> <!-- Written by QtCreator 3.5.1, 2019-07-02T08:46:19. --> <qtcreator> <data> <variable>EnvironmentId</variable> <value type="QByteArray">{95862750-6f9b-42a5-ba87-c0a0e09c1b0c}</value> </data> <data> <variable>ProjectExplorer.Project.ActiveTarget</variable> <value type="int">0</value> </data> <data> <variable>ProjectExplorer.Project.EditorSettings</variable> <valuemap type="QVariantMap"> <value type="bool" key="EditorConfiguration.AutoIndent">true</value> <value type="bool" key="EditorConfiguration.AutoSpacesForTabs">false</value> <value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value> <valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0"> <value type="QString" key="language">Cpp</value> <valuemap type="QVariantMap" key="value"> <value type="QByteArray" key="CurrentPreferences">CppGlobal</value> </valuemap> </valuemap> <valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.1"> <value type="QString" key="language">QmlJS</value> <valuemap type="QVariantMap" key="value"> <value type="QByteArray" key="CurrentPreferences">QmlJSGlobal</value> </valuemap> </valuemap> <value type="int" key="EditorConfiguration.CodeStyle.Count">2</value> <value type="QByteArray" key="EditorConfiguration.Codec">UTF-8</value> <value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value> <value type="int" key="EditorConfiguration.IndentSize">4</value> <value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value> <value type="int" key="EditorConfiguration.MarginColumn">80</value> <value type="bool" key="EditorConfiguration.MouseHiding">true</value> <value type="bool" key="EditorConfiguration.MouseNavigation">true</value> <value type="int" key="EditorConfiguration.PaddingMode">1</value> <value type="bool" key="EditorConfiguration.ScrollWheelZooming">true</value> <value type="bool" key="EditorConfiguration.ShowMargin">false</value> <value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</value> <value type="bool" key="EditorConfiguration.SpacesForTabs">true</value> <value type="int" key="EditorConfiguration.TabKeyBehavior">0</value> <value type="int" key="EditorConfiguration.TabSize">8</value> <value type="bool" key="EditorConfiguration.UseGlobal">true</value> <value type="int" key="EditorConfiguration.Utf8BomBehavior">1</value> <value type="bool" key="EditorConfiguration.addFinalNewLine">true</value> <value type="bool" key="EditorConfiguration.cleanIndentation">true</value> <value type="bool" key="EditorConfiguration.cleanWhitespace">true</value> <value type="bool" key="EditorConfiguration.inEntireDocument">false</value> </valuemap> </data> <data> <variable>ProjectExplorer.Project.PluginSettings</variable> <valuemap type="QVariantMap"/> </data> <data> <variable>ProjectExplorer.Project.Target.0</variable> <valuemap type="QVariantMap"> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{d9b5798d-b250-4cc5-8f4d-2d12aec5466a}</value> <value type="int" key="ProjectExplorer.Target.ActiveBuildConfiguration">0</value> <value type="int" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value> <value type="int" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value> <valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0"> <value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/home/ubuntu/Project/retinaFaceReImp/build-calibra-Desktop-Debug</value> <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0"> <valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0"> <value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">qmake</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QtProjectManager.QMakeBuildStep</value> <value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">false</value> <value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibraryAuto">true</value> <value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments"></value> <value type="bool" key="QtProjectManager.QMakeBuildStep.QMakeForced">false</value> <value type="bool" key="QtProjectManager.QMakeBuildStep.SeparateDebugInfo">false</value> <value type="bool" key="QtProjectManager.QMakeBuildStep.UseQtQuickCompiler">false</value> </valuemap> <valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.1"> <value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value> <valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments"> <value type="QString">-w</value> <value type="QString">-r</value> </valuelist> <value type="bool" key="Qt4ProjectManager.MakeStep.Clean">false</value> <value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments"></value> <value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value> </valuemap> <value type="int" key="ProjectExplorer.BuildStepList.StepsCount">2</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value> </valuemap> <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1"> <valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0"> <value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value> <valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments"> <value type="QString">-w</value> <value type="QString">-r</value> </valuelist> <value type="bool" key="Qt4ProjectManager.MakeStep.Clean">true</value> <value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments">clean</value> <value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value> </valuemap> <value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Clean</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value> </valuemap> <value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value> <value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value> <valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Debug</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4BuildConfiguration</value> <value type="int" key="Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration">2</value> <value type="bool" key="Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild">true</value> </valuemap> <valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.1"> <value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/home/ubuntu/Project/retinaFaceReImp/build-calibra-Desktop-Release</value> <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0"> <valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0"> <value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">qmake</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QtProjectManager.QMakeBuildStep</value> <value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">false</value> <value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibraryAuto">true</value> <value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments"></value> <value type="bool" key="QtProjectManager.QMakeBuildStep.QMakeForced">false</value> <value type="bool" key="QtProjectManager.QMakeBuildStep.SeparateDebugInfo">false</value> <value type="bool" key="QtProjectManager.QMakeBuildStep.UseQtQuickCompiler">false</value> </valuemap> <valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.1"> <value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value> <valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments"> <value type="QString">-w</value> <value type="QString">-r</value> </valuelist> <value type="bool" key="Qt4ProjectManager.MakeStep.Clean">false</value> <value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments"></value> <value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value> </valuemap> <value type="int" key="ProjectExplorer.BuildStepList.StepsCount">2</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value> </valuemap> <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1"> <valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0"> <value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value> <valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments"> <value type="QString">-w</value> <value type="QString">-r</value> </valuelist> <value type="bool" key="Qt4ProjectManager.MakeStep.Clean">true</value> <value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments">clean</value> <value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value> </valuemap> <value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Clean</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value> </valuemap> <value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value> <value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value> <valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Release</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4BuildConfiguration</value> <value type="int" key="Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration">0</value> <value type="bool" key="Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild">true</value> </valuemap> <value type="int" key="ProjectExplorer.Target.BuildConfigurationCount">2</value> <valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0"> <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0"> <value type="int" key="ProjectExplorer.BuildStepList.StepsCount">0</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value> </valuemap> <value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy locally</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.DefaultDeployConfiguration</value> </valuemap> <value type="int" key="ProjectExplorer.Target.DeployConfigurationCount">1</value> <valuemap type="QVariantMap" key="ProjectExplorer.Target.PluginSettings"/> <valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0"> <valuelist type="QVariantList" key="Analyzer.Valgrind.AddedSuppressionFiles"/> <value type="bool" key="Analyzer.Valgrind.Callgrind.CollectBusEvents">false</value> <value type="bool" key="Analyzer.Valgrind.Callgrind.CollectSystime">false</value> <value type="bool" key="Analyzer.Valgrind.Callgrind.EnableBranchSim">false</value> <value type="bool" key="Analyzer.Valgrind.Callgrind.EnableCacheSim">false</value> <value type="bool" key="Analyzer.Valgrind.Callgrind.EnableEventToolTips">true</value> <value type="double" key="Analyzer.Valgrind.Callgrind.MinimumCostRatio">0.01</value> <value type="double" key="Analyzer.Valgrind.Callgrind.VisualisationMinimumCostRatio">10</value> <value type="bool" key="Analyzer.Valgrind.FilterExternalIssues">true</value> <value type="int" key="Analyzer.Valgrind.LeakCheckOnFinish">1</value> <value type="int" key="Analyzer.Valgrind.NumCallers">25</value> <valuelist type="QVariantList" key="Analyzer.Valgrind.RemovedSuppressionFiles"/> <value type="int" key="Analyzer.Valgrind.SelfModifyingCodeDetection">1</value> <value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value> <value type="bool" key="Analyzer.Valgrind.ShowReachable">false</value> <value type="bool" key="Analyzer.Valgrind.TrackOrigins">true</value> <value type="QString" key="Analyzer.Valgrind.ValgrindExecutable">valgrind</value> <valuelist type="QVariantList" key="Analyzer.Valgrind.VisibleErrorKinds"> <value type="int">0</value> <value type="int">1</value> <value type="int">2</value> <value type="int">3</value> <value type="int">4</value> <value type="int">5</value> <value type="int">6</value> <value type="int">7</value> <value type="int">8</value> <value type="int">9</value> <value type="int">10</value> <value type="int">11</value> <value type="int">12</value> <value type="int">13</value> <value type="int">14</value> </valuelist> <value type="int" key="PE.EnvironmentAspect.Base">2</value> <valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">calibra</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4RunConfiguration:/home/ubuntu/Project/retinaFaceReImp/INT8-Calibration-Tool/calibra.pro</value> <value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.CommandLineArguments"></value> <value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.ProFile">calibra.pro</value> <value type="bool" key="Qt4ProjectManager.Qt4RunConfiguration.UseDyldImageSuffix">false</value> <value type="bool" key="Qt4ProjectManager.Qt4RunConfiguration.UseTerminal">true</value> <value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.UserWorkingDirectory"></value> <value type="uint" key="RunConfiguration.QmlDebugServerPort">3768</value> <value type="bool" key="RunConfiguration.UseCppDebugger">false</value> <value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value> <value type="bool" key="RunConfiguration.UseMultiProcess">false</value> <value type="bool" key="RunConfiguration.UseQmlDebugger">false</value> <value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value> </valuemap> <value type="int" key="ProjectExplorer.Target.RunConfigurationCount">1</value> </valuemap> </data> <data> <variable>ProjectExplorer.Project.TargetCount</variable> <value type="int">1</value> </data> <data> <variable>ProjectExplorer.Project.Updater.FileVersion</variable> <value type="int">18</value> </data> <data> <variable>Version</variable> <value type="int">18</value> </data> </qtcreator>
{ "pile_set_name": "Github" }
// SNES GSU Test SUB (Subtraction) demo (GSU Code) by krom (Peter Lemon): arch snes.gsu GSUStart: //////////////////////////// // SUB register //////////////////////////// iwt r1, #$7FFF // R1 = $7FFF iwt r0, #$7FFF // R0 = $7FFF with r1 ; sub r0 // R1 -= R0 stop // Stop GSU nop // Delay Slot iwt r1, #$7FFF // R1 = $7FFF iwt r0, #$8000 // R0 = $8000 with r1 ; sub r0 // R1 -= R0 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r1, #$7FFF // R1 = $7FFF sub r1 // R0 -= R1 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r1, #$8000 // R1 = $8000 sub r1 // R0 -= R1 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r2, #$7FFF // R2 = $7FFF sub r2 // R0 -= R2 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r2, #$8000 // R2 = $8000 sub r2 // R0 -= R2 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r3, #$7FFF // R3 = $7FFF sub r3 // R0 -= R3 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r3, #$8000 // R3 = $8000 sub r3 // R0 -= R3 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r4, #$7FFF // R4 = $7FFF sub r4 // R0 -= R4 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r4, #$8000 // R4 = $8000 sub r4 // R0 -= R4 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r5, #$7FFF // R5 = $7FFF sub r5 // R0 -= R5 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r5, #$8000 // R5 = $8000 sub r5 // R0 -= R5 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r6, #$7FFF // R6 = $7FFF sub r6 // R0 -= R6 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r6, #$8000 // R6 = $8000 sub r6 // R0 -= R6 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r7, #$7FFF // R7 = $7FFF sub r7 // R0 -= R7 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r7, #$8000 // R7 = $8000 sub r7 // R0 -= R7 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r8, #$7FFF // R8 = $7FFF sub r8 // R0 -= R8 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r8, #$8000 // R8 = $8000 sub r8 // R0 -= R8 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r9, #$7FFF // R9 = $7FFF sub r9 // R0 -= R7 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r9, #$8000 // R9 = $8000 sub r9 // R0 -= R9 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r10, #$7FFF // R10 = $7FFF sub r10 // R0 -= R10 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r10, #$8000 // R10 = $8000 sub r10 // R0 -= R10 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r11, #$7FFF // R11 = $7FFF sub r11 // R0 -= R11 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r11, #$8000 // R11 = $8000 sub r11 // R0 -= R11 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r12, #$7FFF // R12 = $7FFF sub r12 // R0 -= R12 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r12, #$8000 // R12 = $8000 sub r12 // R0 -= R12 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r13, #$7FFF // R13 = $7FFF sub r13 // R0 -= R13 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r13, #$8000 // R13 = $8000 sub r13 // R0 -= R13 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r14, #$7FFF // R14 = $7FFF sub r14 // R0 -= R14 stop // Stop GSU nop // Delay Slot iwt r0, #$7FFF // R0 = $7FFF iwt r14, #$8000 // R14 = $8000 sub r14 // R0 -= R14 stop // Stop GSU nop // Delay Slot iwt r0, #$BDD0 // R0 = $BDD0 sub r15 // R0 -= R15 stop // Stop GSU nop // Delay Slot iwt r0, #$BDD5 // R0 = $BDD5 sub r15 // R0 -= R15 stop // Stop GSU nop // Delay Slot //////////////////////////// // SUB #const //////////////////////////// iwt r0, #$0000 // R0 = $0000 sub #0 // R0 -= 0 stop // Stop GSU nop // Delay Slot iwt r0, #$8000 // R0 = $8000 sub #0 // R0 -= 0 stop // Stop GSU nop // Delay Slot iwt r0, #$0001 // R0 = $0001 sub #1 // R0 -= 1 stop // Stop GSU nop // Delay Slot iwt r0, #$8001 // R0 = $8001 sub #1 // R0 -= 1 stop // Stop GSU nop // Delay Slot iwt r0, #$0002 // R0 = $0002 sub #2 // R0 -= 2 stop // Stop GSU nop // Delay Slot iwt r0, #$8002 // R0 = $8002 sub #2 // R0 -= 2 stop // Stop GSU nop // Delay Slot iwt r0, #$0003 // R0 = $0003 sub #3 // R0 -= 3 stop // Stop GSU nop // Delay Slot iwt r0, #$8003 // R0 = $8003 sub #3 // R0 -= 3 stop // Stop GSU nop // Delay Slot iwt r0, #$0004 // R0 = $0004 sub #4 // R0 -= 4 stop // Stop GSU nop // Delay Slot iwt r0, #$8004 // R0 = $8004 sub #4 // R0 -= 4 stop // Stop GSU nop // Delay Slot iwt r0, #$0005 // R0 = $0005 sub #5 // R0 -= 5 stop // Stop GSU nop // Delay Slot iwt r0, #$8005 // R0 = $8005 sub #5 // R0 -= 5 stop // Stop GSU nop // Delay Slot iwt r0, #$0006 // R0 = $0006 sub #6 // R0 -= 6 stop // Stop GSU nop // Delay Slot iwt r0, #$8006 // R0 = $8006 sub #6 // R0 -= 6 stop // Stop GSU nop // Delay Slot iwt r0, #$0007 // R0 = $0007 sub #7 // R0 -= 7 stop // Stop GSU nop // Delay Slot iwt r0, #$8007 // R0 = $8007 sub #7 // R0 -= 7 stop // Stop GSU nop // Delay Slot iwt r0, #$0008 // R0 = $0008 sub #8 // R0 -= 8 stop // Stop GSU nop // Delay Slot iwt r0, #$8008 // R0 = $8008 sub #8 // R0 -= 8 stop // Stop GSU nop // Delay Slot iwt r0, #$0009 // R0 = $0009 sub #9 // R0 -= 9 stop // Stop GSU nop // Delay Slot iwt r0, #$8009 // R0 = $8009 sub #9 // R0 -= 9 stop // Stop GSU nop // Delay Slot iwt r0, #$000A // R0 = $000A sub #10 // R0 -= 10 stop // Stop GSU nop // Delay Slot iwt r0, #$800A // R0 = $800A sub #10 // R0 -= 10 stop // Stop GSU nop // Delay Slot iwt r0, #$000B // R0 = $000B sub #11 // R0 -= 11 stop // Stop GSU nop // Delay Slot iwt r0, #$800B // R0 = $800B sub #11 // R0 -= 11 stop // Stop GSU nop // Delay Slot iwt r0, #$000C // R0 = $000C sub #12 // R0 -= 12 stop // Stop GSU nop // Delay Slot iwt r0, #$800C // R0 = $800C sub #12 // R0 -= 12 stop // Stop GSU nop // Delay Slot iwt r0, #$000D // R0 = $000D sub #13 // R0 -= 13 stop // Stop GSU nop // Delay Slot iwt r0, #$800D // R0 = $800D sub #13 // R0 -= 13 stop // Stop GSU nop // Delay Slot iwt r0, #$000E // R0 = $000E sub #14 // R0 -= 14 stop // Stop GSU nop // Delay Slot iwt r0, #$800E // R0 = $800E sub #14 // R0 -= 14 stop // Stop GSU nop // Delay Slot iwt r0, #$000F // R0 = $000F sub #15 // R0 -= 15 stop // Stop GSU nop // Delay Slot iwt r0, #$800F // R0 = $800F sub #15 // R0 -= 15 stop // Stop GSU nop // Delay Slot
{ "pile_set_name": "Github" }
#ifndef HEADER_CURL_NTLM_MSGS_H #define HEADER_CURL_NTLM_MSGS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_NTLM /* This is to generate a base64 encoded NTLM type-1 message */ CURLcode Curl_ntlm_create_type1_message(const char *userp, const char *passwdp, struct ntlmdata *ntlm, char **outptr, size_t *outlen); /* This is to generate a base64 encoded NTLM type-3 message */ CURLcode Curl_ntlm_create_type3_message(struct SessionHandle *data, const char *userp, const char *passwdp, struct ntlmdata *ntlm, char **outptr, size_t *outlen); /* This is to decode a NTLM type-2 message */ CURLcode Curl_ntlm_decode_type2_message(struct SessionHandle *data, const char* header, struct ntlmdata* ntlm); /* This is to decode target info received in NTLM type-2 message */ CURLcode Curl_ntlm_decode_type2_target(struct SessionHandle *data, unsigned char* buffer, size_t size, struct ntlmdata* ntlm); /* This is to clean up the ntlm data structure */ #ifdef USE_WINDOWS_SSPI void Curl_ntlm_sspi_cleanup(struct ntlmdata *ntlm); #else #define Curl_ntlm_sspi_cleanup(x) #endif /* NTLM buffer fixed size, large enough for long user + host + domain */ #define NTLM_BUFSIZE 1024 /* Stuff only required for curl_ntlm_msgs.c */ #ifdef BUILDING_CURL_NTLM_MSGS_C /* Flag bits definitions based on http://davenport.sourceforge.net/ntlm.html */ #define NTLMFLAG_NEGOTIATE_UNICODE (1<<0) /* Indicates that Unicode strings are supported for use in security buffer data. */ #define NTLMFLAG_NEGOTIATE_OEM (1<<1) /* Indicates that OEM strings are supported for use in security buffer data. */ #define NTLMFLAG_REQUEST_TARGET (1<<2) /* Requests that the server's authentication realm be included in the Type 2 message. */ /* unknown (1<<3) */ #define NTLMFLAG_NEGOTIATE_SIGN (1<<4) /* Specifies that authenticated communication between the client and server should carry a digital signature (message integrity). */ #define NTLMFLAG_NEGOTIATE_SEAL (1<<5) /* Specifies that authenticated communication between the client and server should be encrypted (message confidentiality). */ #define NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE (1<<6) /* Indicates that datagram authentication is being used. */ #define NTLMFLAG_NEGOTIATE_LM_KEY (1<<7) /* Indicates that the LAN Manager session key should be used for signing and sealing authenticated communications. */ #define NTLMFLAG_NEGOTIATE_NETWARE (1<<8) /* unknown purpose */ #define NTLMFLAG_NEGOTIATE_NTLM_KEY (1<<9) /* Indicates that NTLM authentication is being used. */ /* unknown (1<<10) */ #define NTLMFLAG_NEGOTIATE_ANONYMOUS (1<<11) /* Sent by the client in the Type 3 message to indicate that an anonymous context has been established. This also affects the response fields. */ #define NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED (1<<12) /* Sent by the client in the Type 1 message to indicate that a desired authentication realm is included in the message. */ #define NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED (1<<13) /* Sent by the client in the Type 1 message to indicate that the client workstation's name is included in the message. */ #define NTLMFLAG_NEGOTIATE_LOCAL_CALL (1<<14) /* Sent by the server to indicate that the server and client are on the same machine. Implies that the client may use a pre-established local security context rather than responding to the challenge. */ #define NTLMFLAG_NEGOTIATE_ALWAYS_SIGN (1<<15) /* Indicates that authenticated communication between the client and server should be signed with a "dummy" signature. */ #define NTLMFLAG_TARGET_TYPE_DOMAIN (1<<16) /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a domain. */ #define NTLMFLAG_TARGET_TYPE_SERVER (1<<17) /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a server. */ #define NTLMFLAG_TARGET_TYPE_SHARE (1<<18) /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a share. Presumably, this is for share-level authentication. Usage is unclear. */ #define NTLMFLAG_NEGOTIATE_NTLM2_KEY (1<<19) /* Indicates that the NTLM2 signing and sealing scheme should be used for protecting authenticated communications. */ #define NTLMFLAG_REQUEST_INIT_RESPONSE (1<<20) /* unknown purpose */ #define NTLMFLAG_REQUEST_ACCEPT_RESPONSE (1<<21) /* unknown purpose */ #define NTLMFLAG_REQUEST_NONNT_SESSION_KEY (1<<22) /* unknown purpose */ #define NTLMFLAG_NEGOTIATE_TARGET_INFO (1<<23) /* Sent by the server in the Type 2 message to indicate that it is including a Target Information block in the message. */ /* unknown (1<24) */ /* unknown (1<25) */ /* unknown (1<26) */ /* unknown (1<27) */ /* unknown (1<28) */ #define NTLMFLAG_NEGOTIATE_128 (1<<29) /* Indicates that 128-bit encryption is supported. */ #define NTLMFLAG_NEGOTIATE_KEY_EXCHANGE (1<<30) /* Indicates that the client will provide an encrypted master key in the "Session Key" field of the Type 3 message. */ #define NTLMFLAG_NEGOTIATE_56 (1<<31) /* Indicates that 56-bit encryption is supported. */ #ifdef UNICODE # define SECFLAG_WINNT_AUTH_IDENTITY \ (unsigned long)SEC_WINNT_AUTH_IDENTITY_UNICODE #else # define SECFLAG_WINNT_AUTH_IDENTITY \ (unsigned long)SEC_WINNT_AUTH_IDENTITY_ANSI #endif #endif /* BUILDING_CURL_NTLM_MSGS_C */ #endif /* USE_NTLM */ #endif /* HEADER_CURL_NTLM_MSGS_H */
{ "pile_set_name": "Github" }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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. */ using QuantConnect.Data; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.Statistics; using System.Collections.Generic; using System.Linq; using System; using QuantConnect.Indicators; using static QuantConnect.StringExtensions; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This algorithm uses Math.NET Numerics library, specifically Linear Algebra object (Vector and Matrix) and operations, in order to solve a portfolio optimization problem. /// </summary> /// <meta name="tag" content="strategy example" /> /// <meta name="tag" content="portfolio optimization" /> public class PortfolioOptimizationNumericsAlgorithm : QCAlgorithm { private const double _targetReturn = 0.1; private const double _riskFreeRate = 0.01; private double _lagrangeMultiplier; private double _portfolioRisk; private Matrix<double> Sigma; private List<SymbolData> SymbolDataList; public Vector<double> DiscountMeanVector { get { if (SymbolDataList == null) { return null; } return Vector<double>.Build.DenseOfArray(SymbolDataList.Select(x => (double)x.Return).ToArray()) - Vector<double>.Build.Dense(SymbolDataList.Count, _riskFreeRate); } } /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 07); //Set Start Date SetEndDate(2013, 10, 11); //Set End Date SetCash(100000); //Set Strategy Cash // Find more symbols here: http://quantconnect.com/data AddEquity("SPY", Resolution.Daily); AddEquity("AIG", Resolution.Daily); AddEquity("BAC", Resolution.Daily); AddEquity("IBM", Resolution.Daily); var allHistoryBars = new List<double[]>(); SymbolDataList = new List<SymbolData>(); foreach (var security in Securities) { var history = History(security.Key, TimeSpan.FromDays(365)); allHistoryBars.Add(history.Select(x => (double)x.Value).ToArray()); SymbolDataList.Add(new SymbolData(security.Key, history)); } // Diagonal Matrix with each security risk (standard deviation) var S = Matrix<double>.Build.DenseOfDiagonalArray(SymbolDataList.Select(x => (double)x.Risk).ToArray()); // Computes Correlation Matrix (using Math.NET Numerics Statistics) var R = Correlation.PearsonMatrix(allHistoryBars); // Computes Covariance Matrix (using Math.NET Numerics Linear Algebra) Sigma = S * R * S; ComputeLagrangeMultiplier(); ComputeWeights(); ComputePortfolioRisk(); Log($"Lagrange Multiplier: {_lagrangeMultiplier.ToStringInvariant("7:F4")}"); Log($"Portfolio Risk: {_portfolioRisk.ToStringInvariant("7:P2")} "); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!Portfolio.Invested) { foreach (var symbolData in SymbolDataList.OrderBy(x => x.Weight)) { SetHoldings(symbolData.Symbol, symbolData.Weight); Debug("Purchased Stock: " + symbolData); } } } /// <summary> /// Computes Lagrange Multiplier /// </summary> private void ComputeLagrangeMultiplier() { var denominatorMatrix = DiscountMeanVector * Sigma.Inverse() * DiscountMeanVector.ToColumnMatrix(); _lagrangeMultiplier = (_targetReturn - _riskFreeRate) / denominatorMatrix.ToArray().First(); } /// <summary> /// Computes weight for each risky asset /// </summary> private void ComputeWeights() { var weights = _lagrangeMultiplier * Sigma.Inverse() * DiscountMeanVector.ToColumnMatrix(); for (var i = 0; i < weights.RowCount; i++) { SymbolDataList[i].SetWeight(weights.ToArray()[i, 0]); } } /// <summary> /// Computes Portfolio Risk /// </summary> private void ComputePortfolioRisk() { var weights = Vector<double>.Build.DenseOfArray(SymbolDataList.Select(x => (double)x.Return).ToArray()); var portfolioVarianceMatrix = weights * Sigma * weights.ToColumnMatrix(); _portfolioRisk = Math.Sqrt(portfolioVarianceMatrix.ToArray().First()); } /// <summary> /// Symbol Data class to store security data (Return, Risk, Weight) /// </summary> class SymbolData { private RateOfChange ROC = new RateOfChange(2); private SimpleMovingAverage SMA; private StandardDeviation STD; public Symbol Symbol { get; private set; } public decimal Return { get { return SMA.Current; } } public decimal Risk { get { return STD.Current; } } public decimal Weight { get; private set; } public SymbolData(Symbol symbol, IEnumerable<BaseData> history) { Symbol = symbol; SMA = new SimpleMovingAverage(365).Of(ROC); STD = new StandardDeviation(365).Of(ROC); foreach (var data in history) { Update(data); } } public void Update(BaseData data) { ROC.Update(data.Time, data.Value); } public void SetWeight(double value) { Weight = (decimal)value; } public override string ToString() { return Invariant($"{Symbol.Value}: {Weight,10:P2}\t{Return,10:P2}\t{Risk,10:P2}"); } } } }
{ "pile_set_name": "Github" }
## RAG This is a non-finetuned version of the RAG-Token model of the the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/pdf/2005.11401.pdf) by Patrick Lewis, Ethan Perez, Aleksandara Piktus et al. Rag consits of a *question encoder*, *retriever* and a *generator*. The retriever should be a `RagRetriever` instance. The *question encoder* can be any model that can be loaded with `AutoModel` and the *generator* can be any model that can be loaded with `AutoModelForSeq2SeqLM`. This model is a non-finetuned RAG-Token model and was created as follows: ```python from transformers import RagTokenizer, RagRetriever, RagTokenForGeneration, AutoTokenizer model = RagTokenForGeneration.from_pretrained_question_encoder_generator("facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large") question_encoder_tokenizer = AutoTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base") generator_tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large") tokenizer = RagTokenizer(question_encoder_tokenizer, generator_tokenizer) model.config.use_dummy_dataset = True model.config.index_name = "exact" retriever = RagRetriever(model.config, question_encoder_tokenizer, generator_tokenizer) model.save_pretrained("./") tokenizer.save_pretrained("./") retriever.save_pretrained("./") ``` Note that the model is *uncased* so that all capital input letters are converted to lower-case. ## Usage: *Note*: the model uses the *dummy* retriever as a default. Better results are obtained by using the full retriever, by setting `config.index_name="legacy"` and `config.use_dummy_dataset=False`. The model can be fine-tuned as follows: ```python from transformers import RagTokenizer, RagRetriever, RagTokenForGeneration tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-base") retriever = RagRetriever.from_pretrained("facebook/rag-token-base") model = RagTokenForGeneration.from_pretrained("facebook/rag-token-base", retriever=retriever) input_dict = tokenizer.prepare_seq2seq_batch("who holds the record in 100m freestyle", "michael phelps", return_tensors="pt") outputs = model(input_dict["input_ids"], labels=input_dict["labels"]) loss = outputs.loss # train on loss ```
{ "pile_set_name": "Github" }
X+Ya/dvfBESbJClaUqGgN9PzFEGjzsE4t/AQLbhu8TI=
{ "pile_set_name": "Github" }
-- EMACS settings: -*- tab-width: 2; indent-tabs-mode: t -*- -- vim: tabstop=2:shiftwidth=2:noexpandtab -- kate: tab-width 2; replace-tabs off; indent-width 2; -- ============================================================================= -- Authors: Patrick Lehmann -- -- Entity: Creates a histogram of all input data -- -- Description: -- ------------------------------------- -- .. TODO:: No documentation available. -- -- License: -- ============================================================================= -- Copyright 2007-2016 Technische Universitaet Dresden - Germany -- Chair of VLSI-Design, Diagnostics and Architecture -- -- 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. -- ============================================================================= library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; library PoC; use PoC.utils.all; use PoC.vectors.all; entity stat_Histogram is generic ( DATA_BITS : positive := 16; COUNTER_BITS : positive := 16 ); port ( Clock : in std_logic; Reset : in std_logic; Enable : in std_logic; DataIn : in std_logic_vector(DATA_BITS - 1 downto 0); Histogram : out T_SLM(2**DATA_BITS - 1 downto 0, COUNTER_BITS - 1 downto 0) ); end entity; architecture rtl of stat_Histogram is type T_HISTOGRAM_MEMORY is array(natural range <>) of unsigned(COUNTER_BITS downto 0); -- create matrix from vector-vector function to_slm(usv : T_HISTOGRAM_MEMORY) return T_SLM is variable slm : T_SLM(usv'range, COUNTER_BITS - 1 downto 0); begin for i in usv'range loop if (usv(i)(COUNTER_BITS) = '0') then for j in COUNTER_BITS - 1 downto 0 loop slm(i, j) := usv(i)(j); end loop; else for j in COUNTER_BITS - 1 downto 0 loop slm(i, j) := '1'; end loop; end if; end loop; return slm; end function; signal HistogramMemory : T_HISTOGRAM_MEMORY(2**DATA_BITS - 1 downto 0) := (others => (others => '0')); begin process(Clock) begin if rising_edge(Clock) then if (Reset = '1') then HistogramMemory <= (others => (others => '0')); elsif ((Enable = '1') and (HistogramMemory(to_index(DataIn))(COUNTER_BITS) = '0')) then HistogramMemory(to_index(DataIn)) <= HistogramMemory(to_index(DataIn)) + 1; end if; end if; end process; Histogram <= to_slm(HistogramMemory); end architecture;
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }