text
stringlengths
2
99.9k
meta
dict
declare interface CommMessage { buffers: DataView[] content: { data: string } } declare interface Comm { messages: AsyncGenerator<CommMessage> } declare namespace google.colab { export const kernel: { comms: { registerTarget(target: string, fn: (comm: Comm) => void): void } } }
{ "pile_set_name": "Github" }
/** * This file is part of lavagna. * * lavagna 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. * * lavagna 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 lavagna. If not, see <http://www.gnu.org/licenses/>. */ package io.lavagna.model; import io.lavagna.model.CardLabel.LabelDomain; import io.lavagna.model.CardLabel.LabelType; import org.junit.Assert; import org.junit.Test; public class CardLabelTest { @Test public void set() { CardLabel cl = new CardLabel(42, 42, false, LabelType.STRING, LabelDomain.USER, "label", 42); CardLabel cl1 = cl.color(84); Assert.assertEquals(84, cl1.getColor()); CardLabel cl2 = cl1.name("label2"); Assert.assertEquals("label2", cl2.getName()); CardLabel cl3 = cl2.set("label3", LabelType.STRING, 0); Assert.assertEquals("label3", cl3.getName()); Assert.assertEquals(0, cl3.getColor()); } @Test public void equality() { CardLabel cl1 = new CardLabel(42, 42, false, LabelType.STRING, LabelDomain.USER, "label", 42); CardLabel cl2 = new CardLabel(42, 42, false, LabelType.STRING, LabelDomain.USER, "label", 42); CardLabel cl3 = new CardLabel(42, 42, false, LabelType.STRING, LabelDomain.USER, "label2", 42); Assert.assertFalse(cl1.equals(null)); Assert.assertFalse(cl1.equals(new Object())); Assert.assertEquals(cl1, cl2); Assert.assertEquals(cl2, cl1); Assert.assertNotEquals(cl2, cl3); Assert.assertNotEquals(cl3, cl2); Assert.assertNotEquals(cl1, cl3); Assert.assertEquals(cl1.hashCode(), cl2.hashCode()); Assert.assertNotEquals(cl1.hashCode(), cl3.hashCode()); } }
{ "pile_set_name": "Github" }
//===-- PPCSchedule.td - PowerPC Scheduling Definitions ----*- tablegen -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Instruction Itinerary classes used for PowerPC // def IIC_IntSimple : InstrItinClass; def IIC_IntGeneral : InstrItinClass; def IIC_IntCompare : InstrItinClass; def IIC_IntISEL : InstrItinClass; def IIC_IntDivD : InstrItinClass; def IIC_IntDivW : InstrItinClass; def IIC_IntMFFS : InstrItinClass; def IIC_IntMFVSCR : InstrItinClass; def IIC_IntMTFSB0 : InstrItinClass; def IIC_IntMTSRD : InstrItinClass; def IIC_IntMulHD : InstrItinClass; def IIC_IntMulHW : InstrItinClass; def IIC_IntMulHWU : InstrItinClass; def IIC_IntMulLI : InstrItinClass; def IIC_IntRFID : InstrItinClass; def IIC_IntRotateD : InstrItinClass; def IIC_IntRotateDI : InstrItinClass; def IIC_IntRotate : InstrItinClass; def IIC_IntShift : InstrItinClass; def IIC_IntTrapD : InstrItinClass; def IIC_IntTrapW : InstrItinClass; def IIC_BrB : InstrItinClass; def IIC_BrCR : InstrItinClass; def IIC_BrMCR : InstrItinClass; def IIC_BrMCRX : InstrItinClass; def IIC_LdStDCBA : InstrItinClass; def IIC_LdStDCBF : InstrItinClass; def IIC_LdStDCBI : InstrItinClass; def IIC_LdStLoad : InstrItinClass; def IIC_LdStLoadUpd : InstrItinClass; def IIC_LdStLoadUpdX : InstrItinClass; def IIC_LdStStore : InstrItinClass; def IIC_LdStDSS : InstrItinClass; def IIC_LdStICBI : InstrItinClass; def IIC_LdStLD : InstrItinClass; def IIC_LdStLDU : InstrItinClass; def IIC_LdStLDUX : InstrItinClass; def IIC_LdStLDARX : InstrItinClass; def IIC_LdStLFD : InstrItinClass; def IIC_LdStLFDU : InstrItinClass; def IIC_LdStLFDUX : InstrItinClass; def IIC_LdStLHA : InstrItinClass; def IIC_LdStLHAU : InstrItinClass; def IIC_LdStLHAUX : InstrItinClass; def IIC_LdStLMW : InstrItinClass; def IIC_LdStLVecX : InstrItinClass; def IIC_LdStLWA : InstrItinClass; def IIC_LdStLWARX : InstrItinClass; def IIC_LdStSLBIA : InstrItinClass; def IIC_LdStSLBIE : InstrItinClass; def IIC_LdStSTD : InstrItinClass; def IIC_LdStSTDCX : InstrItinClass; def IIC_LdStSTU : InstrItinClass; def IIC_LdStSTUX : InstrItinClass; def IIC_LdStSTFD : InstrItinClass; def IIC_LdStSTFDU : InstrItinClass; def IIC_LdStSTVEBX : InstrItinClass; def IIC_LdStSTWCX : InstrItinClass; def IIC_LdStSync : InstrItinClass; def IIC_LdStCOPY : InstrItinClass; def IIC_LdStPASTE : InstrItinClass; def IIC_SprISYNC : InstrItinClass; def IIC_SprMFSR : InstrItinClass; def IIC_SprMTMSR : InstrItinClass; def IIC_SprMTSR : InstrItinClass; def IIC_SprTLBSYNC : InstrItinClass; def IIC_SprMFCR : InstrItinClass; def IIC_SprMFCRF : InstrItinClass; def IIC_SprMFMSR : InstrItinClass; def IIC_SprMFSPR : InstrItinClass; def IIC_SprMFTB : InstrItinClass; def IIC_SprMTSPR : InstrItinClass; def IIC_SprMTSRIN : InstrItinClass; def IIC_SprRFI : InstrItinClass; def IIC_SprSC : InstrItinClass; def IIC_FPGeneral : InstrItinClass; def IIC_FPDGeneral : InstrItinClass; def IIC_FPSGeneral : InstrItinClass; def IIC_FPAddSub : InstrItinClass; def IIC_FPCompare : InstrItinClass; def IIC_FPDivD : InstrItinClass; def IIC_FPDivS : InstrItinClass; def IIC_FPFused : InstrItinClass; def IIC_FPRes : InstrItinClass; def IIC_FPSqrtD : InstrItinClass; def IIC_FPSqrtS : InstrItinClass; def IIC_VecGeneral : InstrItinClass; def IIC_VecFP : InstrItinClass; def IIC_VecFPCompare : InstrItinClass; def IIC_VecComplex : InstrItinClass; def IIC_VecPerm : InstrItinClass; def IIC_VecFPRound : InstrItinClass; def IIC_VecVSL : InstrItinClass; def IIC_VecVSR : InstrItinClass; def IIC_SprMTMSRD : InstrItinClass; def IIC_SprSLIE : InstrItinClass; def IIC_SprSLBIE : InstrItinClass; def IIC_SprSLBIEG : InstrItinClass; def IIC_SprSLBMTE : InstrItinClass; def IIC_SprSLBMFEE : InstrItinClass; def IIC_SprSLBMFEV : InstrItinClass; def IIC_SprSLBIA : InstrItinClass; def IIC_SprSLBSYNC : InstrItinClass; def IIC_SprTLBIA : InstrItinClass; def IIC_SprTLBIEL : InstrItinClass; def IIC_SprTLBIE : InstrItinClass; def IIC_SprABORT : InstrItinClass; def IIC_SprMSGSYNC : InstrItinClass; def IIC_SprSTOP : InstrItinClass; def IIC_SprMFPMR : InstrItinClass; def IIC_SprMTPMR : InstrItinClass; //===----------------------------------------------------------------------===// // Processor instruction itineraries. include "PPCScheduleG3.td" include "PPCSchedule440.td" include "PPCScheduleG4.td" include "PPCScheduleG4Plus.td" include "PPCScheduleG5.td" include "PPCScheduleP7.td" include "PPCScheduleP8.td" include "PPCScheduleP9.td" include "PPCScheduleA2.td" include "PPCScheduleE500.td" include "PPCScheduleE500mc.td" include "PPCScheduleE5500.td"
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <ostream> // template <class charT, class traits = char_traits<charT> > // class basic_ostream // : virtual public basic_ios<charT,traits> // { // public: // // types (inherited from basic_ios (27.5.4)): // typedef charT char_type; // typedef traits traits_type; // typedef typename traits_type::int_type int_type; // typedef typename traits_type::pos_type pos_type; // typedef typename traits_type::off_type off_type; #include <ostream> #include <type_traits> #include "test_macros.h" int main(int, char**) { static_assert((std::is_base_of<std::basic_ios<char>, std::basic_ostream<char> >::value), ""); static_assert((std::is_same<std::basic_ostream<char>::char_type, char>::value), ""); static_assert((std::is_same<std::basic_ostream<char>::traits_type, std::char_traits<char> >::value), ""); static_assert((std::is_same<std::basic_ostream<char>::int_type, std::char_traits<char>::int_type>::value), ""); static_assert((std::is_same<std::basic_ostream<char>::pos_type, std::char_traits<char>::pos_type>::value), ""); static_assert((std::is_same<std::basic_ostream<char>::off_type, std::char_traits<char>::off_type>::value), ""); return 0; }
{ "pile_set_name": "Github" }
--- title: WIA Transfer Constants description: WIA Transfer Constants ms.assetid: 69f76919-5bbb-4968-997c-2d51f19aab6b ms.date: 04/20/2017 ms.localizationpriority: medium --- # WIA Transfer Constants This topic contains a list of the constants that are used for WIA **IStream**-based transfers. These constants are divided into three subgroups: - Item type - Callback messages - Transfer flags ### Item Type The following table shows which WIA item type bits relate to stream-based data transfer. <table> <colgroup> <col width="50%" /> <col width="50%" /> </colgroup> <thead> <tr class="header"> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr class="odd"> <td><p><strong>WiaItemTypeTransfer</strong></p></td> <td><p>This <a href="/windows-hardware/drivers/image/wia-ipa-item-flags" data-raw-source="[&lt;strong&gt;WIA_IPA_ITEM_FLAGS&lt;/strong&gt;](./wia-ipa-item-flags.md)"><strong>WIA_IPA_ITEM_FLAGS</strong></a> bit should be set on all items that are capable of transferring data; that is, an application can initiate a download or upload on items that have this bit set.</p></td> </tr> </tbody> </table> ### Callback Messages The following table shows possible values for the *lFlags* parameter of **IWiaTransferCallback::TransferCallback**. <table> <colgroup> <col width="50%" /> <col width="50%" /> </colgroup> <thead> <tr class="header"> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr class="odd"> <td><p>WIA_TRANSFER_MSG_STATUS</p></td> <td><p>Notifies the application of the progress of the transfer.</p> <p><em>pWiaTransferParams</em>-&gt; <em>lPercentComplete</em> contains the percent complete for this item and the page that is being transferred.</p></td> </tr> <tr class="even"> <td><p>WIA_TRANSFER_MSG_END_OF_STREAM</p></td> <td><p>Notifies the application that there is no more data to be transferred to the current data stream and that the stream may be closed.</p> <p>A new stream may subsequently be requested in a multi-item or multipage transfer.</p> <p>Drivers do not send this message manually--the WIA service will automatically send this message when the driver asks for the next stream.</p></td> </tr> <tr class="odd"> <td><p>WIA_TRANSFER_MSG_END_OF_TRANSFER</p></td> <td><p>Received by the application at the end of the transfer.</p> <p>The driver does not send this message--the WIA service will send this message automatically after the transfer has ended (that is, the call to <strong>IWiaMiniDrv::drvAcquiItemData</strong> returns).</p></td> </tr> <tr class="even"> <td><p>WIA_TRANSFER_MSG_ERROR</p></td> <td><p>Reserved by Microsoft for future use.</p></td> </tr> <tr class="odd"> <td><p>WIA_TRANSFER_MSG_DEVICE_STATUS</p></td> <td><p>Indicates an error during the transfer (for example, a paper jam).</p> <p><em>pWiaTransferParams</em>-&gt;<em>hrErrorStatus</em> contains the error status code.</p></td> </tr> <tr class="even"> <td><p>WIA_TRANSFER_MSG_NEW_PAGE</p></td> <td><p>Indicates that a new page is being transferred during a multipage transfer when a format that supports multiple pages in one file (such as multifile TIFF) is being used.</p></td> </tr> </tbody> </table> ### Transfer Flags The following table shows the flags that may be passed into [**IWiaMiniDrv::drvAcquireItemData**](/windows-hardware/drivers/ddi/wiamindr_lh/nf-wiamindr_lh-iwiaminidrv-drvacquireitemdata). <table> <colgroup> <col width="50%" /> <col width="50%" /> </colgroup> <thead> <tr class="header"> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr class="odd"> <td><p>WIA_MINIDRV_TRANSFER_DOWNLOAD</p></td> <td><p>Indicates that the transfer is a stream-based download operation (that is, a data transfer from a device to an application).</p> <p>Applications do not set this bit directly. The WIA service sets this bit if the application calls <strong>IWiaTransfer::Download</strong>.</p></td> </tr> <tr class="even"> <td><p>WIA_MINIDRV_TRANSFER_UPLOAD</p></td> <td><p>Indicates that the transfer is a stream-based upload operation (that is, a data transfer from an application to a device).</p> <p>Applications do not set this bit directly. The WIA service sets this bit if the application calls <strong>IWiaTransfer::Upload</strong>.</p></td> </tr> <tr class="odd"> <td><p>WIA_MINIDRV_TRANSFER_ACQUIRE_CHILDREN</p></td> <td><p>Indicates that the driver should perform a folder transfer. If this value is called on a folder item, the application requests to transfer the children of that folder.</p> <p>This value will be set if an application requests a folder transfer by setting the <em>lFlags</em> parameter of <strong>IWiaTransfer::Download</strong> to WIA _TRANSFER_ACQUIRE_CHILDREN <em>and</em> the driver has specified that it can transfer multiple children in one scan. If the driver cannot perform this type of transfer, the WIA service will make multiple calls into the driver and WIA_MINIDRV_TRANSFER_ACQUIRE_CHILDREN will <em>not</em> be set.</p></td> </tr> </tbody> </table> For more information about the **IWiaTransfer** and **IWiaTransferCallback** interfaces, see the Microsoft Windows SDK documentation.
{ "pile_set_name": "Github" }
<?php namespace App\Models; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Session; use Validator; class Customer extends Model implements AuthenticatableContract{ use Authenticatable; protected $table = 'customers'; protected $fillable = array('first_name', 'last_name', 'contact_number', 'email', 'wants_updates'); protected $guarded = array('id', 'created_at', 'updated_at'); /** * Function to add a new customer to the database * * Returns customer id for appointment creation * **/ public static function addCustomer() { // We get appointment information then set up our validator $info = Session::get('appointmentInfo'); $validator = Validator::make( array( 'first_name' => $info['fname'], 'last_name' => $info['lname'], 'email' => $info['email'] ), array( 'first_name' => 'exists:customers,first_name', 'last_name' => 'exists:customers,last_name', 'email' => 'exists:customers,email' ) ); // If the validator fails, that means the user does not exist // If any of those three variables don't exist, we create a new user // This is so that families can use the same e-mail to book, but // We stil create a new user for them in the database. if ($validator->fails()) { // Registering the new user return Customer::create(array( 'first_name' => $info['fname'], 'last_name' => $info['lname'], 'contact_number' => $info['number'], 'email' => $info['email'], 'wants_updates' => Session::get('updates') ))->id; } else { return Customer::where('email', $info['email'])->pluck('id'); } } }
{ "pile_set_name": "Github" }
// DigitalRune Engine - Copyright (C) DigitalRune GmbH // This file is subject to the terms and conditions defined in // file 'LICENSE.TXT', which is part of this source code package. using System.Collections.Generic; using System.Windows.Controls; using System.Windows.Media; using DigitalRune.Windows.Controls; namespace DigitalRune.Editor.About { /// <summary> /// Shows and controls the content of the About dialog. /// </summary> public interface IAboutService { /// <summary> /// Gets or sets the name of the application. /// </summary> /// <value> /// The name of the application. The default value is the same as /// <see cref="IEditorService.ApplicationName"/>. /// </value> string ApplicationName { get; set; } /// <summary> /// Gets or sets the copyright string. /// </summary> /// <value> /// The copyright. Per default, the copyright of the executing assembly is used. /// </value> string Copyright { get; set; } /// <summary> /// Gets or sets the version. /// </summary> /// <value>The version. Per default, the version of the executing assembly is used.</value> string Version { get; set; } /// <summary> /// Gets or sets the additional information. /// </summary> /// <value>Additional information for the About dialog.</value> /// <remarks> /// <para> /// In this property additional information can be set that should also be displayed in the /// about dialog, for example: homepage, contact info, support info, etc. The information /// can be of any type that can be displayed by a WPF <see cref="ContentPresenter"/>. /// </para> /// <para> /// A text representation of this information should be set in /// <see cref="InformationAsString"/>. /// </para> /// </remarks> object Information { get; set; } /// <summary> /// Gets or sets the additional information (as text string). /// </summary> /// <value>Additional information (as text string).</value> /// <remarks> /// This property is not shown in the About dialog. When the about dialog text is copied to /// the clipboard, this string is used instead of <see cref="Information"/>. It is not /// necessary to set this property if <see cref="Information"/> is already of type /// <see cref="string"/>. /// </remarks> string InformationAsString { get; set; } /// <summary> /// Gets or sets the image (<see cref="ImageSource"/> or <see cref="MultiColorGlyph"/>) that /// should be shown in the About dialog. /// </summary> /// <value>The image. Can be <see langword="null"/>.</value> object Icon { get; set; } /// <summary> /// Gets the extension descriptions. /// </summary> /// <value>The extension descriptions.</value> /// <remarks> /// The default dialog contains a list, where information about extensions are displayed. If /// an extension wants to be visible in the About dialog it must add an /// <see cref="EditorExtensionDescription"/> item to this collection. /// </remarks> ICollection<EditorExtensionDescription> ExtensionDescriptions { get; } /// <summary> /// Shows the About dialog. /// </summary> /// <remarks> /// This method opens the About dialog and returns only when the About dialog is closed. /// </remarks> void Show(); /// <summary> /// Copies the About information to the clipboard. /// </summary> /// <returns> /// The About information which has been copied into the clipboard. /// </returns> string CopyInformationToClipboard(); } }
{ "pile_set_name": "Github" }
foo 11 12 13 14 15 16 17 18 19
{ "pile_set_name": "Github" }
# Event 1018 - task_0 ###### Version: 1 ## Description None ## Data Dictionary |Standard Name|Field Name|Type|Description|Sample Value| |---|---|---|---|---| |TBD|PinMask|UInt64|None|`None`| ## Tags * etw_level_Informational * etw_opcode_MaskInterruptsComplete * etw_task_task_0
{ "pile_set_name": "Github" }
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software GmbH & Co. KG, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.main; import org.opencms.i18n.CmsMessageContainer; /** * Describes errors that occur in the context of OpenCms the initialization, this is fatal * and prevents OpenCms from starting.<p> * * If an Exception of this class is thrown, OpenCms is set to an error state and * the system won't try to start up again.<p> * * @since 6.0.0 */ public class CmsInitException extends CmsRuntimeException { /** Serial version UID required for safe serialization. */ private static final long serialVersionUID = 7705928617426913316L; /** Indicates that this exception describes a new error. */ private boolean m_newError; /** * Creates a new localized Exception.<p> * * @param container the localized message container to use */ public CmsInitException(CmsMessageContainer container) { this(container, true); } /** * Creates a new localized Exception.<p> * * @param container the localized message container to use * @param newError indicates that the error is new, and OpenCms should be stopped */ public CmsInitException(CmsMessageContainer container, boolean newError) { super(container); m_newError = newError; if (m_newError) { setErrorCondition(); } } /** * Creates a new localized Exception that also containes a root cause.<p> * * @param container the localized message container to use * @param cause the Exception root cause */ public CmsInitException(CmsMessageContainer container, Throwable cause) { super(container, cause); m_newError = true; setErrorCondition(); } /** * @see org.opencms.main.CmsRuntimeException#createException(org.opencms.i18n.CmsMessageContainer, java.lang.Throwable) */ @Override public CmsRuntimeException createException(CmsMessageContainer container, Throwable cause) { return new CmsInitException(container, cause); } /** * Indicates that this exception describes a new error that was not already logged.<p> * * @return <code>true</code> if this exception describes a new error that was not already logged */ public boolean isNewError() { return m_newError; } /** * Prints an error message to the System.err stream, indicating that OpenCms * is unable to start up.<p> */ private void setErrorCondition() { CmsMessageContainer errorCondition = getMessageContainer(); OpenCmsCore.setErrorCondition(errorCondition); } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>地震点聚集</title> <link rel="stylesheet" href="./css/ol.css"> <script src="./js/ol.js"></script> </head> <body> <div id="map"></div> <script> // 初始化聚集要素的半径 // 可自由定义要素半径的计算规则 let maxFeatureCount; let earthquakeCluster = null; let calculateClusterInfo = (resolution) => { maxFeatureCount = 0; let features = earthquakeCluster.getSource().getFeatures(); let feature, radius; for (let i = features.length - 1; i >= 0; i--) { feature = features[i]; let originalFeatures = feature.get('features'); let extent = ol.extent.createEmpty(); let j = (void 0), jj = (void 0); for (let j = 0, jj = originalFeatures.length; j<jj; ++j) { ol.extent.extend(extent, originalFeatures[j].getGeometry().getExtent()); } maxFeatureCount = Math.max(maxFeatureCount, jj); radius = 0.15 * (ol.extent.getWidth(extent) + ol.extent.getHeight(extent)) / resolution; feature.set('radius', radius); } } // 样式函数,对每个feature返回一个样式 let currentResolution; let styleFunction = (feature, resolution) => { if (resolution != currentResolution) { calculateClusterInfo(resolution); currentResolution = resolution; } let style; let size = feature.get('features').length; if (size > 1) { style = new ol.style.Style({ image: new ol.style.Circle({ radius: feature.get('radius'), fill: new ol.style.Fill({ color: [255, 153, 0] }) }), text: new ol.style.Text({ text: size.toString(), fill: new ol.style.Fill({ color: '#fff' }), stroke: new ol.style.Stroke({ color: 'rgba(0, 0, 0, 0.6)', width: 3 }) }) }) } else { // 每个地震点的默认样式 style = new ol.style.Style({ image: new ol.style.Circle({ radius: 3, fill: new ol.style.Fill({ color: 'rgb(255, 0, 0)' }) }) }); } return style; } // 聚类图层 earthquakeCluster = new ol.layer.Vector({ source: new ol.source.Cluster({ distance: 80, // 聚类阈值,当两点间距离小于20,便聚类为一个点 source: new ol.source.Vector({ format: new ol.format.GeoJSON(), url: 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson' }) }), style: styleFunction }); let map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([118, 36]), zoom: 2 }) }); map.addLayer(earthquakeCluster) </script> </body> </html>
{ "pile_set_name": "Github" }
/* $Id$ */ %#include "pub3prot.h" %#include "okprotext.h" struct xpub_errdoc_t { int status; xpub_fn_t fn; }; struct xpub_errdoc_set_t { xpub_errdoc_t docs<>; }; /* A given service proc, which is indentifier by a service names * and brother-ID. In most cases the brother-ID will be 0 for the * one and only service. -1 means don't care about which, and * >0 specifies a particular service id. */ struct oksvc_proc_t { string name<>; int brother_id; // OR -1 if no ID known/specified int num_brothers; // OR -1 if unknown }; enum ok_set_typ_t { OK_SET_NONE = 0, OK_SET_SOME = 1, OK_SET_ALL = 2 }; union oksvc_procs_t switch (ok_set_typ_t typ) { case OK_SET_SOME: oksvc_proc_t procs<>; default: void; }; struct okctl_send_msg_arg_t { string msg<>; }; union okctl_send_msg_res_t switch (bool ok) { case TRUE: void; case FALSE: string err<>; }; struct oksvc_status_t { oksvc_proc_t proc; int pid; unsigned n_served; unsigned uptime; }; struct oksvc_stats_t { unsigned hyper n_sent; unsigned hyper n_recv; }; struct okctl_stats_t { oksvc_status_t status<>; }; struct ok_custom_data_t { opaque data<>; }; struct ok_custom_arg_t { oksvc_procs_t procs; ok_custom_data_t data; }; union ok_custom_res_union_t switch (ok_xstatus_typ_t status) { case OK_STATUS_OK: ok_custom_data_t dat; default: void; }; struct ok_custom_res_t { oksvc_proc_t proc; ok_custom_res_union_t res; }; struct ok_custom_res_set_t { ok_custom_res_t results<>; }; typedef ok_xstatus_typ_t okctl_sendcon_res_t; struct ssl_ctx_t { string cipher<>; unsigned okd_ordinal; }; typedef opaque okclnt_sin_t<>; struct okctl_timespec_t { unsigned ts_sec; unsigned ts_nsec; }; struct okctl_sendcon_arg2_t { opaque sin<>; unsigned port; ssl_ctx_t *ssl; okctl_timespec_t time_recv; okctl_timespec_t time_sent; unsigned reqno; // >0 for keepalive connections opaque scraps<>; // leftover bytes passed back in keepalive }; struct okssl_sendcon_arg_t { opaque sin<>; ssl_ctx_t ssl; int port; }; typedef string ip_addr_t<16>; struct okmgr_diagnostic_arg_t { oksvc_proc_t proc; ok_diagnostic_domain_t domain; ok_diagnostic_cmd_t cmd; }; struct okctl_diagnostic_arg_t { ok_diagnostic_domain_t domain; ok_diagnostic_cmd_t cmd; }; enum oklog_file_t { OKLOG_NONE = 0, OKLOG_ACCESS = 1, OKLOG_ERROR = 2, OKLOG_SSL = 3 }; struct oklog_fast_arg_t { string access<>; string error<>; string ssl<>; }; struct oklog_entry_t { oklog_file_t file; opaque data<>; }; struct oklog_arg_t { oklog_entry_t entries<>; }; struct oksvc_descriptor_t { oksvc_proc_t proc; int pid; }; struct oksvc_reserve_arg_t { oksvc_proc_t proc; bool lazy; }; struct okws_send_ssl_arg_t { int dummy; }; struct okmgr_send_msg_arg_t { oksvc_procs_t procs; string msg<>; }; struct emergency_kill_arg_t { oksvc_descriptor_t svc; int signal; }; %#define LOG_IP (1 << 0) %#define LOG_UA (1 << 1) %#define LOG_SZ (1 << 2) %#define LOG_REQ (1 << 3) %#define LOG_SVC (1 << 4) %#define LOG_RFR (1 << 5) %#define LOG_UID (1 << 6) namespace RPC { program OKCTL_PROGRAM { version OKCLT_VERS { void OKCTL_NULL (void) = 0; void OKCTL_READY (void) = 1; ok_xstatus_t OKCTL_CUSTOM_1_IN (ok_custom_arg_t) = 7; ok_xstatus_t OKCTL_CUSTOM_1_OUT (ok_custom_data_t) = 8; ok_custom_res_set_t OKCTL_CUSTOM_2_IN (ok_custom_arg_t) = 9; ok_custom_data_t OKCTL_CUSTOM_2_OUT (ok_custom_data_t) = 10; xpub_errdoc_set_t OKCTL_REQ_ERRDOCS_2 (void) = 11; okctl_stats_t OKCTL_GET_STATS(void) = 12; void OKCTL_REENABLE_ACCEPT(void) = 14; oksvc_stats_t OKCTL_GET_STATS_FROM_SVC(void) = 15; ok_xstatus_typ_t OKCTL_DIAGNOSTIC(okctl_diagnostic_arg_t) = 16; okctl_sendcon_res_t OKCTL_SEND_CON2(okctl_sendcon_arg2_t) = 18; okctl_send_msg_res_t OKCTL_SEND_MSG (okctl_send_msg_arg_t) = 19; okctl_sendcon_res_t OKCTL_KEEPALIVE(okctl_sendcon_arg2_t) = 20; void OKCTL_KILL (oksig_t) = 99; } = 1; } = 11279; program OKLOG_PROGRAM { version OKCTL_VERS { void OKLOG_NULL (void) = 0; bool OKLOG_LOG (oklog_arg_t) = 1; bool OKLOG_TURN (void) = 2; unsigned OKLOG_GET_LOGSET (void) = 3; int OKLOG_CLONE (int) = 5; void OKLOG_KILL (ok_killsig_t) = 99; } = 1; } = 11281; program OKMGR_PROGRAM { version OKMGR_VERS { void OKMGR_NULL (void) = 0; ok_xstatus_t OKMGR_RELAUNCH (oksvc_procs_t) = 2; ok_xstatus_t OKMGR_TURNLOG (void) = 3; ok_xstatus_t OKMGR_CUSTOM_1 (ok_custom_arg_t) = 4; ok_custom_res_t OKMGR_CUSTOM_2 (ok_custom_arg_t) = 5; ok_xstatus_t OKMGR_DIAGNOSTIC(okmgr_diagnostic_arg_t) = 7; ok_xstatus_t OKMGR_SEND_MSG(okmgr_send_msg_arg_t) = 9; } = 1; } = 11278; program OKLD_PROGRAM { version OKLD_VERS { void OKLD_NULL(void) = 0; ok_xstatus_typ_t OKLD_NEW_SERVICE(oksvc_descriptor_t) = 1; ok_xstatus_typ_t OKLD_SEND_SSL_SOCKET(okws_send_ssl_arg_t) = 2; ok_xstatus_typ_t OKLD_POKE_LAZY_SERVICE(oksvc_descriptor_t) = 3; ok_xstatus_typ_t OKLD_RESERVE(oksvc_reserve_arg_t) = 4; ok_xstatus_typ_t OKLD_EMERGENCY_KILL(emergency_kill_arg_t) = 5; } = 1; } = 11279; program OKSSL_PROGRAM { version OKSSL_VERS { void OKSSL_NULL(void) = 0; ok_xstatus_typ_t OKSSL_TOGGLE_ACCEPT(bool) = 1; ok_xstatus_typ_t OKSSL_NEW_CONNECTION(okssl_sendcon_arg_t) = 2; } = 1; } = 11280; program NULL_PROGRAM { version NULL_VERS { void NULL_NULL(void) = 0; } = 1; } = 11281; }; /* namespace RPC */
{ "pile_set_name": "Github" }
(* Frama-C journal generated at 16:31 the 05/09/2008 *) (* Running *) let () = Journal.run () let () = Cmdline.ForceValues.set true let () = Cmdline.Files.set ["loop_ok.c"; ] let () = File.init_from_cmdline () let () = !Db.Syntactic_callgraph.dump () (* exception raised on: *) let __ : unit = !Db.Value.compute () (* Finished *) let () = Journal.finished ()
{ "pile_set_name": "Github" }
# Number of days of inactivity before an issue becomes stale daysUntilStale: 60 # Number of days of inactivity before a stale issue is closed daysUntilClose: 14 # Issues with these labels will never be considered stale exemptLabels: - pinned - security # Label to use when marking an issue as stale staleLabel: stale # Comment to post when marking an issue as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale issue. Set to `false` to disable closeComment: false
{ "pile_set_name": "Github" }
<?php /** * This file is part of the LuneticsLocaleBundle package. * * <https://github.com/lunetics/LocaleBundle/> * * For the full copyright and license information, please view the LICENSE * file that is distributed with this source code. */ namespace Lunetics\LocaleBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * This pass remove session dependencies * * @author Asmir Mustafic <[email protected]> * */ class RemoveSessionPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if ($container->hasDefinition('session')) { return; } $container->removeDefinition('lunetics_locale.session_guesser'); $container->removeDefinition('lunetics_locale.locale_session'); } }
{ "pile_set_name": "Github" }
{ "_args": [ [ { "raw": "[email protected]", "scope": null, "escapedName": "concat-map", "name": "concat-map", "rawSpec": "0.0.1", "spec": "0.0.1", "type": "version" }, "/Users/qinliang.ql/Desktop/test/node_modules/brace-expansion" ] ], "_cnpm_publish_time": 1391051195982, "_from": "[email protected]", "_hasShrinkwrap": false, "_id": "[email protected]", "_inCache": true, "_location": "/concat-map", "_npmUser": { "name": "substack", "email": "[email protected]" }, "_npmVersion": "1.3.21", "_phantomChildren": {}, "_requested": { "raw": "[email protected]", "scope": null, "escapedName": "concat-map", "name": "concat-map", "rawSpec": "0.0.1", "spec": "0.0.1", "type": "version" }, "_requiredBy": [ "/brace-expansion" ], "_resolved": "https://registry.npm.taobao.org/concat-map/download/concat-map-0.0.1.tgz", "_shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b", "_shrinkwrap": null, "_spec": "[email protected]", "_where": "/Users/qinliang.ql/Desktop/test/node_modules/brace-expansion", "author": { "name": "James Halliday", "email": "[email protected]", "url": "http://substack.net" }, "bugs": { "url": "https://github.com/substack/node-concat-map/issues" }, "dependencies": {}, "description": "concatenative mapdashery", "devDependencies": { "tape": "~2.4.0" }, "directories": { "example": "example", "test": "test" }, "dist": { "shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b", "tarball": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" }, "homepage": "https://github.com/substack/node-concat-map", "keywords": [ "concat", "concatMap", "map", "functional", "higher-order" ], "license": "MIT", "main": "index.js", "maintainers": [ { "name": "substack", "email": "[email protected]" } ], "name": "concat-map", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git://github.com/substack/node-concat-map.git" }, "scripts": { "test": "tape test/*.js" }, "testling": { "files": "test/*.js", "browsers": { "ie": [ 6, 7, 8, 9 ], "ff": [ 3.5, 10, 15 ], "chrome": [ 10, 22 ], "safari": [ 5.1 ], "opera": [ 12 ] } }, "version": "0.0.1" }
{ "pile_set_name": "Github" }
--- dynflow.gemspec.orig 2019-07-06 19:59:03 UTC +++ dynflow.gemspec @@ -27,7 +27,7 @@ Gem::Specification.new do |s| s.add_runtime_dependency(%q<apipie-params>.freeze, [">= 0"]) s.add_runtime_dependency(%q<algebrick>.freeze, ["~> 0.7.0"]) s.add_runtime_dependency(%q<concurrent-ruby>.freeze, ["~> 1.1.3"]) - s.add_runtime_dependency(%q<concurrent-ruby-edge>.freeze, ["~> 0.4.1"]) + s.add_runtime_dependency(%q<concurrent-ruby-edge>.freeze, ["~> 0.4", ">= 0.4.1"]) s.add_runtime_dependency(%q<sequel>.freeze, [">= 4.0.0"]) s.add_development_dependency(%q<rake>.freeze, [">= 0"]) s.add_development_dependency(%q<rack-test>.freeze, [">= 0"])
{ "pile_set_name": "Github" }
<template> <section> <div class="box box-solid box-clear"> <div class="content"> <div class="row content-centered profile"> <croppa v-model="profileImage" :width="350" :height="350" placeholder="Click here to choose an image." :placeholder-font-size="14" accept=".png,.jpg,.jpeg,.gif" @init="onReady" @image-remove="onImageRemove" @file-type-mismatch="onFileTypeMismatch" @file-size-exceed="onFileSizeExceed" @file-choose="onFileChoose" :prevent-white-space="true" :zoom-speed="5"> <img crossorigin="anonymous" :src="displayUrl" slot="initial"> <img slot="placeholder" src="/static/img/fa-expand.png"> </croppa> </div> <div v-if="fileUploading" class="box box-solid"> <div class="box-header content-centered"> <h3>Uploading...</h3> </div> <div class="box-body"> <div class="progress active"> <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" :aria-valuenow="percentCompleted" aria-valuemin="0" aria-valuemax="100" :style="'width: ' + percentCompleted + '%'"> <span class="sr-only">{{percentCompleted}}% Complete</span> </div> </div> </div> </div> <div v-if="profileloading && percentCompleted >= 100" class="box box-solid"> <div class="box-header content-centered"> <h3>Finalizing...</h3> </div> <div class="box-body content-centered"> <pulse-loader></pulse-loader> </div> </div> <div class="row" v-if="ready"> <div class="content-centered"> <button :disabled="(!profileImage.hasImage() || profileImageUrl.includes('gravatar') || !this.dirty) && !fileChosen" @click="setProfileImage" class="btn btn-primary btn-lg" style="margin-top: 15px;">Set Profile Image</button> <button :disabled="profileImageUrl.includes('gravatar') || profileLoading" @click="removeProfileImage" class="btn btn-danger btn-lg" style="margin-left: 10px; margin-top: 15px;">Remove Profile Image</button> </div> </div> </div> <div v-if="loading" class="overlay"> <i class="fa"> <pulse-loader></pulse-loader> </i> </div> </div> </section> </template> <script> import { userService, fileService } from '../../../services' export default { name: 'ProfileImage', data () { return { ready: false, loading: false, profileloading: false, fileChosen: false, dirty: false, fileUploading: false, percentCompleted: 0, profileImage: null, profileImageName: '', profileImageType: '', profileImageUrl: null } }, computed: { displayUrl () { if (this.profileImageUrl.includes('gravatar')) { return this.profileImageUrl + '&s=256' } else { return this.profileImageUrl } } }, methods: { onReady () { this.loading = false this.ready = true }, onFileChoose (data) { this.dirty = true this.fileChosen = true this.profileImageName = data.name this.profileImageType = data.type }, onImageRemove () { this.fileChosen = false }, onFileTypeMismatch () { this.$snotify.warning('File type must be png, jpg, or gif', 'Warning!') }, onFileSizeExceed () { this.$snotify.warning('Image size must be less than 100kb', 'Warning!') }, setProfileImage () { this.fileUploading = true this.profileloading = true this.profileImage.generateBlob((blob) => { return fileService.uploadProfileImage(this.profileImageName, blob, { onUploadProgress: (progressEvent) => { this.percentCompleted = Math.floor((progressEvent.loaded * 100) / progressEvent.total) console.log(this.percentCompleted) if (this.percentCompleted >= 100) { this.fileUploading = false } } }) .then((response) => { this.profileImageUrl = response.data return userService.updateUserProfile({ profileImageUrl: this.profileImageUrl }) }) .then((response) => { this.profileloading = false this.fileChosen = false this.percentCompleted = 0 // Update the global user object const user = this.$store.state.auth.user user.profileImageUrl = this.profileImageUrl this.$store.commit('auth/SET_USER', user) this.$snotify.success('Profile image updated', 'Success!') }) .catch((error) => { this.loading = false console.error('UserProfile.setProfileImage-error:', error) this.$snotify.error('Update image failed', 'Error!') }) }, this.profileImageType, 1) }, removeProfileImage () { this.loading = true this.profileImageUrl = 'https://www.gravatar.com/avatar/' + this.$store.state.auth.user._id + '?r=PG&d=robohash' return userService.updateUserProfile({ profileImageUrl: this.profileImageUrl }) .then((response) => { this.loading = false // Update the global user object const user = this.$store.state.auth.user user.profileImageUrl = this.profileImageUrl this.$store.commit('auth/SET_USER', user) this.$snotify.success('Profile image removed', 'Success!') }) .catch((error) => { this.loading = false console.error('UserProfile.removeProfileImage-error:', error) this.$snotify.error('Remove image failed', 'Error!') }) } }, created () { this.profileImageUrl = this.$store.state.auth.user.profileImageUrl } } </script> <style lang="scss"> .profile { .croppa-container { border: 2px solid grey; border-radius: 50%; } canvas { border: 2px solid grey; border-radius: 50%; } } </style>
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <!-- File: Clerget9B.xml Author: Aero-Matic v 0.82 Inputs: name: Clerget9B type: piston power: 130 hp augmented? no injected? no the clerget 130hp 9b is as follows: no. of cylinders...........................9 bore..........................................120 mm stroke........................................160 mm weight complete...........................381 lbs compression ratio..........................4:1 normal h.p....................................130 effective h.p.................................135 r.p.m...........................................12 50 oil consumption per h.p. hour............ 0.09 pints petrol consumption per h.p. hour....... 0.74 pints [0.74 pints = 0.0925 gallons; 6.073 pounds per gallon of gasoline = .5617525 pounds per hp hr. In grams per kW hr that is 341.701125 ] the 110 hp 9z is: no. of cylinders..............................9 bore.............................................1 20 mm stroke..........................................16 0 mm weight complete.............................397 lbs compression ratio............................4:1 normal h.p.....................................110 effective h.p..................................115 r.p.m............................................. 1180 oil consumption per h.p. hour............ 0.14 pints petrol consumption per h.p. hour........ 0.75 pints the 140 hp 9bf *is: no. of cylinders ................................9 bore.............................................. .120 mm stroke............................................ .172 mm weight complete...............................381 lbs compression ratio..............................5.3:1 normal h.p.......................................140 effective h.p....................................153 r.p.m............................................. .1250 oil consumption per h.p. hour.............. 0.11 pints petrol consumption per h.p. hour......... 0.59 pints SRC: http://www.theaerodrome.com/forum/2001/10278-clerget-9b-fuel-consumption.html --> <piston_engine name="Clerget9B"> <minmp unit="INHG"> 23.0 </minmp> <maxmp unit="INHG"> 28.5 </maxmp> <displacement unit="IN3"> 993.8 </displacement> <maxhp unit="HP"> 130.00 </maxhp> <cycles> 4.0 </cycles> <idlerpm> 300.0 </idlerpm> <maxrpm> 1250.0 </maxrpm> <maxthrottle> 1.0 </maxthrottle><!-- Deprecated --> <minthrottle> 0.1 </minthrottle><!-- Deprecated --> <sparkfaildrop> 0.17 </sparkfaildrop> <volumetric-efficiency> 0.673 </volumetric-efficiency> <!-- Optional items that affect engine performance --> <!-- Defining <bsfc> over-rides the built-in horsepower calculations --> <bsfc unit="LBS/HP*HR"> 0.54 </bsfc> <!-- 0.5617525 is the calculated amount but the JSBSim manual says that JSBSim incorporates some of this internally so the number may need to be reduced some. 0.353 gives the rated top speed of 116 kts for the Camel at high rpm with unaltered CamelProp.xml. But with the adjusted CamelProp C_THRUST values it is more like .50--> <stroke unit="IN"> 6.2992 </stroke> <bore unit="IN"> 4.72441 </bore> <cylinders> 9.0 </cylinders> <compression-ratio> 4.0 </compression-ratio> </piston_engine>
{ "pile_set_name": "Github" }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google Inc. 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. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "types"; option java_package = "com.google.protobuf"; option java_outer_classname = "StructProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` // might be supported by a native representation. For example, in // scripting languages like JS a struct is represented as an // object. The details of that representation are described together // with the proto support for the language. // // The JSON representation for `Struct` is JSON object. message Struct { // Unordered map of dynamically typed values. map<string, Value> fields = 1; } // `Value` represents a dynamically typed value which can be either // null, a number, a string, a boolean, a recursive struct value, or a // list of values. A producer of value is expected to set one of that // variants, absence of any variant indicates an error. // // The JSON representation for `Value` is JSON value. message Value { // The kind of value. oneof kind { // Represents a null value. NullValue null_value = 1; // Represents a double value. double number_value = 2; // Represents a string value. string string_value = 3; // Represents a boolean value. bool bool_value = 4; // Represents a structured value. Struct struct_value = 5; // Represents a repeated `Value`. ListValue list_value = 6; } } // `NullValue` is a singleton enumeration to represent the null value for the // `Value` type union. // // The JSON representation for `NullValue` is JSON `null`. enum NullValue { // Null value. NULL_VALUE = 0; } // `ListValue` is a wrapper around a repeated field of values. // // The JSON representation for `ListValue` is JSON array. message ListValue { // Repeated field of dynamically typed values. repeated Value values = 1; }
{ "pile_set_name": "Github" }
Aaron Lehmann <[email protected]> Akash Gupta <[email protected]> Akihiro Suda <[email protected]> Andrew Pennebaker <[email protected]> Brandon Philips <[email protected]> Christopher Jones <[email protected]> Daniel, Dao Quang Minh <[email protected]> Derek McGowan <[email protected]> Edward Pilatowicz <[email protected]> Ian Campbell <[email protected]> Justin Cormack <[email protected]> Justin Cummins <[email protected]> Phil Estes <[email protected]> Stephen J Day <[email protected]> Tobias Klauser <[email protected]> Tonis Tiigi <[email protected]>
{ "pile_set_name": "Github" }
/* * Copyright (C) 2008 Apple Inc. 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 Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PluginQuirkSet_h #define PluginQuirkSet_h namespace WebCore { enum PluginQuirk { PluginQuirkWantsMozillaUserAgent = 1 << 0, PluginQuirkDeferFirstSetWindowCall = 1 << 1, PluginQuirkThrottleInvalidate = 1 << 2, PluginQuirkRemoveWindowlessVideoParam = 1 << 3, PluginQuirkThrottleWMUserPlusOneMessages = 1 << 4, PluginQuirkDontUnloadPlugin = 1 << 5, PluginQuirkDontCallWndProcForSameMessageRecursively = 1 << 6, PluginQuirkHasModalMessageLoop = 1 << 7, PluginQuirkFlashURLNotifyBug = 1 << 8, PluginQuirkDontClipToZeroRectWhenScrolling = 1 << 9, PluginQuirkDontSetNullWindowHandleOnDestroy = 1 << 10, PluginQuirkDontAllowMultipleInstances = 1 << 11, PluginQuirkRequiresGtkToolKit = 1 << 12, PluginQuirkRequiresDefaultScreenDepth = 1 << 13, PluginQuirkDontCallSetWindowMoreThanOnce = 1 << 14, PluginQuirkIgnoreRightClickInWindowlessMode = 1 << 15, PluginQuirkWantsChromeUserAgent = 1 << 16 }; class PluginQuirkSet { public: PluginQuirkSet() : m_quirks(0) { } void add(PluginQuirk quirk) { m_quirks |= quirk; } bool contains(PluginQuirk quirk) const { return m_quirks & quirk; } private: unsigned m_quirks; }; } // namespace WebCore #endif // PluginQuirkSet_h
{ "pile_set_name": "Github" }
""" This module stores some ROS parameter names used for passing information between modules in the system. """ CURRENT_RECIPE = "current_recipe" """ Stores the ID of the currently running recipe or "" if no recipe is running """ CURRENT_RECIPE_START = "current_recipe_start" """ Stores the UNIX timestamp at which the current recipe was started or 0 if no recipe is running """ SUPPORTED_RECIPE_FORMATS = "supported_recipe_formats" """ Stores a comma-separated list of all of the recipe formats supported by the running recipe handler module """ CATEGORIES = "categories" """ Stores a list of the currently active module categories """
{ "pile_set_name": "Github" }
import csv import io import os import re import sys from national_voter_file.transformers.base import (DATA_DIR, BasePreparer, BaseTransformer) import usaddress __all__ = ['default_file', 'StatePreparer', 'StateTransformer'] default_file = 'voters.txt' class StatePreparer(BasePreparer): state_path = 'ut' # Two letter code for state state_name = 'Utah' # Name of state with no spaces. Use CamelCase sep = ',' # The character used to delimit records def __init__(self, input_path, *args, **kwargs): super(StatePreparer, self).__init__(input_path, *args, **kwargs) if not self.transformer: self.transformer = StateTransformer() def process(self): fp = open(self.input_path, 'r', encoding='utf-8-sig') reader = self.dict_iterator(fp) for row in reader: yield row class StateTransformer(BaseTransformer): date_format = '%m/%d/%Y' # The format used for dates input_fields = None # This can be a list of column names for the input file. # Use None if the file has headers col_map = { 'TITLE': None, 'FIRST_NAME': 'First Name', 'MIDDLE_NAME': 'Middle Name', 'LAST_NAME': 'Last Name', 'NAME_SUFFIX': 'Name Suffix', 'GENDER': None, 'RACE': None, 'BIRTH_STATE': None, 'LANGUAGE_CHOICE': None, 'EMAIL': None, 'PHONE': 'Phone', 'DO_NOT_CALL_STATUS': None, 'ABSENTEE_TYPE': 'Absentee', 'CONGRESSIONAL_DIST': 'Congressional', 'UPPER_HOUSE_DIST': 'State Senate', 'LOWER_HOUSE_DIST': 'State House', 'SCHOOL_BOARD_DIST': 'State Schoolboard', 'COUNTY_BOARD_DIST': None, 'COUNTYCODE': 'County ID', 'COUNTY_VOTER_REF': None, 'PRECINCT': 'Precinct', 'PRECINCT_SPLIT': None, } ut_party_map = { # Commented values appeared in the data file but couldn't be mapped 'Republican': 'REP', 'Unaffiliated': 'UN', 'Democratic': 'DEM', 'Libertarian': 'LIB', 'Independent American': 'AI', 'Constitution': 'AMC', 'Independent': 'UN', 'Other': 'UN', 'Green': 'GRN', 'Personal Choice': 'PCP', 'Americans Elect': 'AE', 'Reform': 'REF', 'Natural Law': 'NLP', 'Socialist Workers': 'SWP', 'Socialist': 'SP', 'Utah Justice Party': 'UJP', 'U.S. Taxpayers': 'TAX', 'Peace and Freedom': 'PF', 'Independent Patriot Party Of Utah': 'IPU', 'Independent Patriot Party of Utah': 'IPU', 'Desert Greens': 'GPU', #'American': '', #'Populist': '', #'Independents for Economic Recovery': '', } col_type_dict = BaseTransformer.col_type_dict.copy() # File contains some missing First Name values col_type_dict['FIRST_NAME'] = set([str, type(None)]) col_type_dict['PRECINCT_SPLIT'] = set([str, type(None)]) #### Demographics methods ################################################## def extract_birthdate(self, input_columns): """ Inputs: input_columns: name or list of columns Outputs: Dictionary with following keys 'BIRTHDATE' """ dob = None try: dob = self.convert_date(input_columns['DOB']) except ValueError: # Some rows have invalid date values pass return { 'BIRTHDATE': dob, 'BIRTHDATE_IS_ESTIMATE': 'N', } #### Address methods ####################################################### def extract_registration_address(self, input_dict): """ Relies on the usaddress package. Call the self.convert_usaddress_dict() method on the output of usaddress.tag. We provide example code in the method to make this clear. Inputs: input_dict: dictionary of form {colname: value} from raw data Outputs: Dictionary with following keys 'ADDRESS_NUMBER' 'ADDRESS_NUMBER_PREFIX' 'ADDRESS_NUMBER_SUFFIX' 'BUILDING_NAME' 'CORNER_OF' 'INTERSECTION_SEPARATOR' 'LANDMARK_NAME' 'NOT_ADDRESS' 'OCCUPANCY_TYPE' 'OCCUPANCY_IDENTIFIER' 'PLACE_NAME' 'STATE_NAME' 'STREET_NAME' 'STREET_NAME_PRE_DIRECTIONAL' 'STREET_NAME_PRE_MODIFIER' 'STREET_NAME_PRE_TYPE' 'STREET_NAME_POST_DIRECTIONAL' 'STREET_NAME_POST_MODIFIER' 'STREET_NAME_POST_TYPE' 'SUBADDRESS_IDENTIFIER' 'SUBADDRESS_TYPE' 'USPS_BOX_GROUP_ID' 'USPS_BOX_GROUP_TYPE' 'USPS_BOX_ID' 'USPS_BOX_TYPE' 'ZIP_CODE' """ # columns to create address, in order address_components = [ 'House Number', 'House Number Suffix', 'Direction Prefix', 'Street', 'Direction Suffix', 'Street Type', 'Unit Type', 'Unit Number', ] # create address string for usaddress.tag address_str = ' '.join([ input_dict[x] for x in address_components if input_dict[x] is not None ]) raw_dict = { 'RAW_ADDR1': address_str, 'RAW_ADDR2': address_str, 'RAW_CITY': input_dict['City'], 'RAW_ZIP': input_dict['Zip'], } # use the usaddress_tag method to handle errors usaddress_dict, usaddress_type = self.usaddress_tag(address_str) # use the convert_usaddress_dict to get correct column names # and fill in missing values if usaddress_dict: converted = self.convert_usaddress_dict(usaddress_dict) converted['VALIDATION_STATUS'] = '2' # ?? else: converted = self.constructEmptyResidentialAddress() converted['VALIDATION_STATUS'] = '1' converted.update(raw_dict) converted['STATE_NAME'] = 'UT' return converted def extract_mailing_address(self, input_dict): """ Relies on the usaddress package. Inputs: input_dict: dictionary of form {colname: value} from raw data Outputs: Dictionary with following keys 'MAIL_ADDRESS_LINE1' 'MAIL_ADDRESS_LINE2' 'MAIL_CITY' 'MAIL_STATE' 'MAIL_ZIP_CODE' 'MAIL_COUNTRY' """ columns = ['Mailing Address'] mail_str = ' '.join([x for x in columns]) usaddress_dict, usaddress_type = self.usaddress_tag(mail_str) city = state = zipcode = None city_state_zip = input_dict['Mailing city, state zip'] try: if ',' in city_state_zip: city, state_zip = input_dict['Mailing city, state zip'].split(',') state_zip = state_zip.split() if len(state_zip) == 2: state, zipcode = state_zip elif state_zip: state = None zipcode = state_zip[-1] except ValueError: # Some rows have weird values for this field pass return { 'MAIL_ADDRESS_LINE1': self.construct_mail_address_1( usaddress_dict, usaddress_type, ), 'MAIL_ADDRESS_LINE2': self.construct_mail_address_2(usaddress_dict), 'MAIL_CITY': city, 'MAIL_ZIP_CODE': zipcode, 'MAIL_STATE': state, 'MAIL_COUNTRY': 'US', } #### Political methods ##################################################### def extract_state_voter_ref(self, input_dict): return {'STATE_VOTER_REF' : 'UT' + input_dict['Voter ID']} def extract_registration_date(self, input_columns): """ Inputs: input_columns: name or list of columns Outputs: Dictionary with following keys 'REGISTRATION_DATE' """ d = None try: d = self.convert_date(input_columns['Registration Date']) except ValueError: # Some rows have invalid date values pass return {'REGISTRATION_DATE': d} def extract_registration_status(self, input_columns): """ Inputs: input_columns: name or list of columns Outputs: Dictionary with following keys 'REGISTRATION_STATUS' """ return {'REGISTRATION_STATUS': input_columns['Status']} def extract_party(self, input_columns): """ Inputs: input_columns: name or list of columns Outputs: Dictionary with following keys 'PARTY' """ party = input_columns['Party'] return {'PARTY': self.ut_party_map.get(party)}
{ "pile_set_name": "Github" }
// Generated by LiveScript 1.2.0 var string, TABS, unlines, enlines, enslash, reslash, camelize, character, KEYWORDS_SHARED, KEYWORDS_UNUSED, JS_KEYWORDS, LS_KEYWORDS, ID, SYMBOL, SPACE, MULTIDENT, SIMPLESTR, JSTOKEN, BSTOKEN, NUMBER, NUMBER_OMIT, REGEX, HEREGEX_OMIT, LASTDENT, INLINEDENT, NONASCII, OPENERS, CLOSERS, INVERSES, i, o, c, CHAIN, ARG, BLOCK_USERS, slice$ = [].slice; exports.lex = function(code, options){ return clone$(exports).tokenize(code || '', options || {}); }; exports.rewrite = function(it){ var ref$; it || (it = this.tokens); firstPass(it); addImplicitIndentation(it); rewriteBlockless(it); addImplicitParentheses(it); addImplicitBraces(it); expandLiterals(it); if (((ref$ = it[0]) != null ? ref$[0] : void 8) === 'NEWLINE') { it.shift(); } return it; }; exports.tokenize = function(code, o){ var i, c, that; this.inter || (code = code.replace(/[\r\u2028\u2029\uFEFF]/g, '')); code = '\n' + code; this.tokens = [this.last = ['NEWLINE', '\n', 0]]; this.line = ~-o.line; this.dents = []; this.closes = []; this.parens = []; this.flags = []; i = 0; while (c = code.charAt(i)) { switch (c) { case ' ': i += this.doSpace(code, i); break; case '\n': i += this.doLine(code, i); break; case '\\': i += this.doBackslash(code, i); break; case '\'': case '"': i += this.doString(code, i, c); break; case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": i += this.doNumber(code, i); break; case '/': switch (code.charAt(i + 1)) { case '*': i += this.doComment(code, i); break; case '/': i += this.doHeregex(code, i); break; default: i += this.doRegex(code, i) || this.doLiteral(code, i); } break; case '`': if ('`' === code.charAt(i + 1)) { i += this.doJS(code, i); } else { i += this.doLiteral(code, i); } break; default: i += this.doID(code, i) || this.doLiteral(code, i) || this.doSpace(code, i); } } this.dedent(this.dent); if (that = this.closes.pop()) { this.carp("missing `" + that + "`"); } if (this.inter) { this.rest == null && this.carp('unterminated interpolation'); } else { this.last.spaced = true; this.newline(); } o.raw || this.rewrite(); return this.tokens; }; exports.dent = 0; exports.identifiers = {}; exports.hasOwn = Object.prototype.hasOwnProperty; exports.checkConsistency = function(camel, id){ if (this.hasOwn.call(this.identifiers, camel) && this.identifiers[camel] !== id) { throw new ReferenceError("Inconsistent use of " + camel + " as " + id + " on line " + (-~this.line)); } else { return this.identifiers[camel] = id; } }; exports.doID = function(code, index){ var regexMatch, input, id, e, last, ref$, tag, ref1$, that; input = (regexMatch = (ID.lastIndex = index, ID).exec(code))[0]; if (!input) { return 0; } id = camelize(regexMatch[1]); if (/-/.test(regexMatch[1])) { this.checkConsistency(id, regexMatch[1]); } if (NONASCII.test(id)) { try { Function("var " + id); } catch (e$) { e = e$; this.carp("invalid identifier \"" + id + "\""); } } last = this.last; if (regexMatch[2] || last[0] === 'DOT' || this.adi()) { this.token('ID', in$(id, JS_KEYWORDS) ? (ref$ = Object(id), ref$.reserved = true, ref$) : id); if (regexMatch[2]) { this.token(':', ':'); } return input.length; } switch (id) { case 'true': case 'false': case 'on': case 'off': case 'yes': case 'no': case 'null': case 'void': case 'arguments': case 'debugger': tag = 'LITERAL'; break; case 'new': case 'do': case 'typeof': case 'delete': tag = 'UNARY'; break; case 'return': case 'throw': tag = 'HURL'; break; case 'break': case 'continue': tag = 'JUMP'; break; case 'this': case 'eval': case 'super': return this.token('LITERAL', id, true).length; case 'for': id = []; this.fset('for', true); this.fset('to', false); break; case 'then': this.fset('for', false); this.fset('to', false); break; case 'catch': case 'function': id = ''; break; case 'in': case 'of': if (this.fget('for')) { this.fset('for', false); if (id === 'in') { this.fset('by', true); id = ''; if (last[0] === 'ID' && ((ref$ = (ref1$ = this.tokens)[ref1$.length - 2][0]) === ',' || ref$ === ']' || ref$ === '}')) { id = this.tokens.pop()[1]; if ((ref$ = this.tokens)[ref$.length - 1][0] === ',') { this.tokens.pop(); } } } break; } // fallthrough case 'instanceof': if (last[1] === '!') { id = this.tokens.pop()[1] + id; } tag = (ref$ = this.tokens)[ref$.length - 1][0] === '(' ? 'BIOPR' : 'RELATION'; break; case 'not': if (last.alias && last[1] === '===') { return last[1] = '!==', 3; } tag = 'UNARY'; id = '!'; break; case 'and': case 'or': case 'xor': case 'is': case 'isnt': this.unline(); tag = id === 'is' || id === 'isnt' ? 'COMPARE' : 'LOGIC'; if (last[0] === '(') { tag = 'BIOP'; } this.token(tag, (function(){ switch (id) { case 'is': return '==='; case 'isnt': return '!=='; case 'or': return '||'; case 'and': return '&&'; case 'xor': return 'xor'; } }())); this.last.alias = true; return id.length; case 'unless': tag = 'IF'; break; case 'until': tag = 'WHILE'; break; case 'import': if (last[0] === '(') { id = '<<<'; tag = 'BIOP'; } else { if (able(this.tokens)) { id = '<<<'; } else { tag = 'DECL'; } } break; case 'export': case 'const': case 'var': tag = 'DECL'; break; case 'with': tag = (function(){ switch (false) { case !able(this.tokens): return 'CLONEPORT'; case last[0] !== '(': return 'BIOP'; default: return 'WITH'; } }.call(this)); break; case 'when': this.fset('for', false); tag = 'CASE'; // fallthrough case 'case': if (this.doCase()) { return input.length; } break; case 'match': tag = 'SWITCH'; break; case 'loop': this.token('WHILE', id); this.token('LITERAL', 'true'); return input.length; case 'let': case 'own': if (last[0] === 'FOR' && !in$(id, last[1])) { last[1].push(id); return 3; } // fallthrough default: if (in$(id, KEYWORDS_SHARED)) { break; } if (in$(id, KEYWORDS_UNUSED)) { this.carp("reserved word \"" + id + "\""); } if (!last[1] && ((ref$ = last[0]) === 'FUNCTION' || ref$ === 'LABEL')) { last[1] = id; last.spaced = false; return input.length; } tag = 'ID'; switch (id) { case 'otherwise': if ((ref$ = last[0]) === 'CASE' || ref$ === '|') { last[0] = 'DEFAULT'; return id.length; } break; case 'all': if (that = last[1] === '<<<' && '<' || last[1] === 'import' && 'All') { last[1] += that; return 3; } break; case 'from': this.forange() && (tag = 'FROM'); break; case 'to': case 'til': this.forange() && this.tokens.push(['FROM', '', this.line], ['STRNUM', '0', this.line]); if (this.fget('from')) { this.fset('from', false); this.fset('by', true); tag = 'TO'; } else if (!last.callable && last[0] === 'STRNUM' && (ref$ = this.tokens)[ref$.length - 2][0] === '[') { last[0] = 'RANGE'; last.op = id; return id.length; } else if (in$(']', this.closes)) { this.token('TO', id); return id.length; } break; case 'by': if (last[0] === 'STRNUM' && (ref$ = this.tokens)[ref$.length - 2][0] === 'RANGE' && (ref$ = this.tokens)[ref$.length - 3][0] === '[') { tag = 'RANGE_BY'; } else if (in$(']', this.closes)) { tag = 'BY'; } else if (this.fget('by')) { tag = 'BY'; this.fset('by', false); } break; case 'ever': if (last[0] === 'FOR') { this.fset('for', false); last[0] = 'WHILE'; tag = 'LITERAL'; id = 'true'; } } } tag || (tag = regexMatch[1].toUpperCase()); if ((tag === 'COMPARE' || tag === 'LOGIC' || tag === 'RELATION') && last[0] === '(') { tag = tag === 'RELATION' ? 'BIOPR' : 'BIOP'; } if (tag === 'THEN' || tag === 'IF' || tag === 'WHILE') { this.fset('for', false); this.fset('by', false); } if (tag === 'RELATION' || tag === 'THEN' || tag === 'ELSE' || tag === 'CASE' || tag === 'DEFAULT' || tag === 'CATCH' || tag === 'FINALLY' || tag === 'IN' || tag === 'OF' || tag === 'FROM' || tag === 'TO' || tag === 'BY' || tag === 'EXTENDS' || tag === 'IMPLEMENTS' || tag === 'WHERE') { this.unline(); } this.token(tag, id); return input.length; }; exports.doNumber = function(code, lastIndex){ var input, regexMatch, last, radix, num, rnum, bound, ref$; NUMBER.lastIndex = lastIndex; if (!(input = (regexMatch = NUMBER.exec(code))[0])) { return 0; } last = this.last; if (regexMatch[5] && (last[0] === 'DOT' || this.adi())) { this.token('STRNUM', regexMatch[4].replace(NUMBER_OMIT, '')); return regexMatch[4].length; } if (radix = regexMatch[1]) { num = parseInt(rnum = regexMatch[2].replace(NUMBER_OMIT, ''), radix); bound = false; if (radix > 36 || radix < 2) { if (/[0-9]/.exec(rnum)) { this.carp("invalid number base " + radix + " (with number " + rnum + "),base must be from 2 to 36"); } else { bound = true; } } if (isNaN(num) || num === parseInt(rnum.slice(0, -1), radix)) { this.strnum(regexMatch[1]); this.token('DOT', '.~'); this.token('ID', regexMatch[2]); return input.length; } num += ''; } else { num = (regexMatch[3] || input).replace(NUMBER_OMIT, ''); if (regexMatch[3] && num.charAt() === '0' && ((ref$ = num.charAt(1)) !== '' && ref$ !== '.')) { this.carp("deprecated octal literal " + regexMatch[4]); } } if (!last.spaced && last[0] === '+-') { last[0] = 'STRNUM'; last[1] += num; return input.length; } this.strnum(num); return input.length; }; exports.doString = function(code, index, q){ var parts, str; if (q === code.charAt(index + 1)) { return q === code.charAt(index + 2) ? this.doHeredoc(code, index, q) : (this.strnum(q + q), 2); } if (q === '"') { parts = this.interpolate(code, index, q); this.addInterpolated(parts, unlines); return 1 + parts.size; } str = (SIMPLESTR.lastIndex = index, SIMPLESTR).exec(code)[0] || this.carp('unterminated string'); this.strnum(unlines(this.string(q, str.slice(1, -1)))); return this.countLines(str).length; }; exports.doHeredoc = function(code, index, q){ var end, raw, doc, parts, tabs, i$, len$, i, t; if (q === '\'') { ~(end = code.indexOf(q + q + q, index + 3)) || this.carp('unterminated heredoc'); raw = code.slice(index + 3, end); doc = raw.replace(LASTDENT, ''); this.strnum(enlines(this.string(q, lchomp(detab(doc, heretabs(doc)))))); return this.countLines(raw).length + 6; } parts = this.interpolate(code, index, q + q + q); tabs = heretabs(code.slice(index + 3, index + parts.size).replace(LASTDENT, '')); for (i$ = 0, len$ = parts.length; i$ < len$; ++i$) { i = i$; t = parts[i$]; if (t[0] === 'S') { if (i + 1 === parts.length) { t[1] = t[1].replace(LASTDENT, ''); } t[1] = detab(t[1], tabs); if (i === 0) { t[1] = lchomp(t[1]); } } } this.addInterpolated(parts, enlines); return 3 + parts.size; }; exports.doComment = function(code, index){ var comment, end, ref$; comment = ~(end = code.indexOf('*/', index + 2)) ? code.slice(index, end + 2) : code.slice(index) + '*/'; if ((ref$ = this.last[0]) === 'NEWLINE' || ref$ === 'INDENT' || ref$ === 'THEN') { this.token('COMMENT', detab(comment, this.dent)); this.token('NEWLINE', '\n'); } return this.countLines(comment).length; }; exports.doJS = function(code, lastIndex){ var js, ref$; JSTOKEN.lastIndex = lastIndex; js = JSTOKEN.exec(code)[0] || this.carp('unterminated JS literal'); this.token('LITERAL', (ref$ = Object(detab(js.slice(2, -2), this.dent)), ref$.js = true, ref$), true); return this.countLines(js).length; }; exports.doRegex = function(code, index){ var divisible, ref$, input, body, flag; if (divisible = able(this.tokens) || this.last[0] === 'CREMENT') { if (!this.last.spaced || ((ref$ = code.charAt(index + 1)) === ' ' || ref$ === '=')) { return 0; } } ref$ = (REGEX.lastIndex = index, REGEX).exec(code), input = ref$[0], body = ref$[1], flag = ref$[2]; if (input) { this.regex(body, flag); } else if (!divisible && this.last[0] !== '(') { this.carp('unterminated regex'); } return input.length; }; exports.doHeregex = function(code, index){ var tokens, last, parts, rest, flag, i$, i, t, dynaflag, len$, val, one; tokens = this.tokens, last = this.last; parts = this.interpolate(code, index, '//'); rest = code.slice(index + 2 + parts.size); flag = this.validate(/^(?:[gimy]{1,4}|[?$]?)/.exec(rest)[0]); if (parts[1]) { if (flag === '$') { this.adi(); this.token('(', '"'); } else { tokens.push(['ID', 'RegExp', last[2]], ['CALL(', '', last[2]]); if (flag === '?') { for (i$ = parts.length - 1; i$ >= 0; --i$) { i = i$; t = parts[i$]; if (t[0] === 'TOKENS') { dynaflag = parts.splice(i, 1)[0][1]; break; } } } } for (i$ = 0, len$ = parts.length; i$ < len$; ++i$) { i = i$; t = parts[i$]; if (t[0] === 'TOKENS') { tokens.push.apply(tokens, t[1]); } else { val = t[1].replace(HEREGEX_OMIT, ''); if (one && !val) { continue; } one = tokens.push((t[0] = 'STRNUM', t[1] = this.string('\'', enslash(val)), t)); } tokens.push(['+-', '+', tokens[tokens.length - 1][2]]); } --tokens.length; if (dynaflag || flag >= 'g') { this.token(',', ','); if (dynaflag) { tokens.push.apply(tokens, dynaflag); } else { this.token('STRNUM', "'" + flag + "'"); } } this.token(flag === '$' ? ')' : ')CALL', ''); } else { this.regex(reslash(parts[0][1].replace(HEREGEX_OMIT, '')), flag); } return 2 + parts.size + flag.length; }; exports.doBackslash = function(code, lastIndex){ var ref$, input, word; BSTOKEN.lastIndex = lastIndex; ref$ = BSTOKEN.exec(code), input = ref$[0], word = ref$[1]; if (word) { this.strnum(this.string('\'', word)); } else { this.countLines(input); } return input.length; }; exports.doLine = function(code, index){ var ref$, input, tabs, length, last, that, delta, tag, val; ref$ = (MULTIDENT.lastIndex = index, MULTIDENT).exec(code), input = ref$[0], tabs = ref$[1]; length = this.countLines(input).length; last = this.last; last.eol = true; last.spaced = true; if (index + length >= code.length) { return length; } if (that = tabs && (this.emender || (this.emender = RegExp('[^' + tabs.charAt() + ']'))).exec(tabs)) { this.carp("contaminated indent " + escape(that)); } if (0 > (delta = tabs.length - this.dent)) { this.dedent(-delta); this.newline(); } else { tag = last[0], val = last[1]; if (tag === 'ASSIGN' && ((ref$ = val + '') !== '=' && ref$ !== ':=' && ref$ !== '+=') || (tag === '+-' || tag === 'PIPE' || tag === 'BACKPIPE' || tag === 'DOT' || tag === 'LOGIC' || tag === 'MATH' || tag === 'COMPARE' || tag === 'RELATION' || tag === 'SHIFT' || tag === 'IN' || tag === 'OF' || tag === 'TO' || tag === 'BY' || tag === 'FROM' || tag === 'EXTENDS' || tag === 'IMPLEMENTS')) { return length; } if (delta) { this.indent(delta); } else { this.newline(); } } this.fset('for', false); this.fset('by', false); return length; }; exports.doSpace = function(code, lastIndex){ var input; SPACE.lastIndex = lastIndex; if (input = SPACE.exec(code)[0]) { this.last.spaced = true; } return input.length; }; exports.doCase = function(){ var ref$, ref1$; this.seenFor = false; if (((ref$ = this.last[0]) === 'ASSIGN' || ref$ === '->' || ref$ === ':') || (this.last[0] === 'INDENT' && ((ref$ = (ref1$ = this.tokens)[ref1$.length - 2][0]) === 'ASSIGN' || ref$ === '->' || ref$ === ':'))) { this.token('SWITCH', 'switch'); this.line++; return this.token('CASE', 'case'); } }; exports.doLiteral = function(code, index){ var sym, tag, val, ref$, that, up; if (!(sym = (SYMBOL.lastIndex = index, SYMBOL).exec(code)[0])) { return 0; } switch (tag = val = sym) { case '|': tag = 'CASE'; if (this.doCase()) { return sym.length; } break; case '|>': tag = 'PIPE'; break; case '`': tag = 'BACKTICK'; break; case '<<': case '>>': tag = 'COMPOSE'; break; case '<|': tag = 'BACKPIPE'; break; case '+': case '-': tag = '+-'; break; case '&&': case '||': tag = 'LOGIC'; break; case '.&.': case '.|.': case '.^.': tag = 'BITWISE'; break; case '^^': tag = 'CLONE'; break; case '**': case '^': tag = 'POWER'; break; case '?': if (this.last[0] === '(') { this.token('PARAM(', '('); this.token(')PARAM', ')'); this.token('->', '->'); this.token('ID', 'it'); } else { if (this.last.spaced) { tag = 'LOGIC'; } } break; case '/': case '%': case '%%': tag = 'MATH'; break; case '++': case '--': tag = 'CREMENT'; break; case '<<<': case '<<<<': tag = 'IMPORT'; break; case ';': tag = 'NEWLINE'; this.fset('by', false); break; case '..': this.token('LITERAL', '..', true); return 2; case '.': if (this.last[1] === '?') { this.last[0] = '?'; } tag = 'DOT'; break; case ',': switch (this.last[0]) { case ',': case '[': case '(': case 'CALL(': this.token('LITERAL', 'void'); break; case 'FOR': case 'OWN': this.token('ID', ''); } break; case '!=': case '~=': if (!(able(this.tokens) || ((ref$ = this.last[0]) === '(' || ref$ === 'CREMENT'))) { this.tokens.push(val === '!=' ? ['UNARY', '!', this.line] : ['UNARY', '~', this.line], ['ASSIGN', '=', this.line]); return 2; } // fallthrough case '!~=': case '==': val = (function(){ switch (val) { case '~=': return '=='; case '!~=': return '!='; case '==': return '==='; case '!=': return '!=='; } }()); tag = 'COMPARE'; break; case '===': case '!==': val += '='; // fallthrough case '<': case '>': case '<=': case '>=': case '<==': case '>==': case '>>=': case '<<=': tag = 'COMPARE'; break; case '.<<.': case '.>>.': case '.>>>.': case '<?': case '>?': tag = 'SHIFT'; break; case '(': if (!(((ref$ = this.last[0]) === 'FUNCTION' || ref$ === 'LET') || this.able(true) || this.last[1] === '.@')) { this.token('(', '('); this.closes.push(')'); this.parens.push(this.last); return 1; } tag = 'CALL('; this.closes.push(')CALL'); break; case '[': case '{': this.adi(); this.closes.push(']}'.charAt(val === '{')); break; case '}': if (this.inter && val !== (ref$ = this.closes)[ref$.length - 1]) { this.rest = code.slice(index + 1); return 9e9; } // fallthrough case ']': case ')': if (tag === ')' && ((ref$ = this.last[0]) === '+-' || ref$ === 'COMPARE' || ref$ === 'LOGIC' || ref$ === 'MATH' || ref$ === 'POWER' || ref$ === 'SHIFT' || ref$ === 'BITWISE' || ref$ === 'CONCAT' || ref$ === 'COMPOSE' || ref$ === 'RELATION' || ref$ === 'PIPE' || ref$ === 'BACKPIPE' || ref$ === 'IMPORT' || ref$ === 'CLONEPORT' || ref$ === 'ASSIGN')) { (ref$ = this.tokens)[ref$.length - 1][0] = (function(){ switch (this.last[0]) { case 'RELATION': return 'BIOPR'; case 'PIPE': this.parameters(false, -1); return 'BIOPP'; default: return 'BIOP'; } }.call(this)); } if (')' === (tag = val = this.pair(val))) { this.lpar = this.parens.pop(); } break; case '=': case ':': if (val === ':') { switch (this.last[0]) { case 'ID': case 'STRNUM': case ')': break; case '...': this.last[0] = 'STRNUM'; break; default: tag = 'LABEL'; val = ''; } this.token(tag, val); return sym.length; } // fallthrough case ':=': case '+=': case '-=': case '*=': case '/=': case '%=': case '%%=': case '<?=': case '>?=': case '**=': case '^=': case '.&.=': case '.|.=': case '.^.=': case '.<<.=': case '.>>.=': case '.>>>.=': case '++=': if (this.last[1] === '.' || this.last[0] === '?' && this.adi()) { this.last[1] += val; return val.length; } if (this.last[0] === 'LOGIC') { (val = Object(val)).logic = this.tokens.pop()[1]; } else if ((val === '+=' || val === '-=') && !able(this.tokens) && ((ref$ = this.last[0]) !== '+-' && ref$ !== 'UNARY' && ref$ !== 'LABEL')) { this.token('UNARY', val.charAt()); val = '='; } tag = 'ASSIGN'; break; case '::=': this.token('DOT', '.'); this.token('ID', 'prototype'); this.token('IMPORT', '<<'); return sym.length; case '*': if (that = ((ref$ = this.last[0]) === 'NEWLINE' || ref$ === 'INDENT' || ref$ === 'THEN' || ref$ === '=>') && (INLINEDENT.lastIndex = index + 1, INLINEDENT).exec(code)[0].length) { this.tokens.push(['LITERAL', 'void', this.line], ['ASSIGN', '=', this.line]); this.indent(index + that - 1 - this.dent - code.lastIndexOf('\n', index - 1)); return that; } tag = able(this.tokens) || this.last[0] === 'CREMENT' && able(this.tokens, this.tokens.length - 1) || this.last[0] === '(' ? 'MATH' : 'STRNUM'; break; case '@': this.adi(); if (this.last[0] === 'DOT' && this.last[1] === '.' && (ref$ = this.tokens)[ref$.length - 2][0] === 'ID' && (ref$ = this.tokens)[ref$.length - 2][1] === 'constructor') { this.tokens.pop(); this.tokens.pop(); this.token('LITERAL', 'this', true); this.adi(); this.token('ID', 'constructor', true); } else { this.token('LITERAL', 'this', true); } return 1; case '@@': this.adi(); this.token('ID', 'constructor', true); return 2; case '&': this.token('LITERAL', 'arguments'); return 1; case '!': switch (false) { default: if (!this.last.spaced) { if (this.last[1] === 'require') { this.last[0] = 'REQUIRE'; this.last[1] = 'require!'; } else if (able(this.tokens, null, true)) { this.token('CALL(', '!'); this.token(')CALL', ')'); } else if (this.last[1] === 'typeof') { this.last[1] = 'classof'; } else if (this.last[1] === 'delete') { this.last[1] = 'jsdelete'; } else { break; } return 1; } } tag = 'UNARY'; break; case '&': if (!able(this.tokens)) { tag = 'LITERAL'; } break; case '|': tag = 'BITWISE'; break; case '~': if (this.dotcat(val)) { return 1; } tag = 'UNARY'; break; case '->': case '~>': case '-->': case '~~>': case '!->': case '!~>': case '!-->': case '!~~>': up = '->'; // fallthrough case '<-': case '<~': case '<--': case '<~~': this.parameters(tag = up || '<-'); break; case '::': this.adi(); val = 'prototype'; tag = 'ID'; break; case '=>': this.unline(); this.fset('for', false); tag = 'THEN'; break; default: switch (val.charAt(0)) { case '(': this.token('CALL(', '('); tag = ')CALL'; val = ')'; break; case '<': if (val.length < 4) { this.carp('unterminated words'); } this.token('WORDS', val.slice(2, -2), this.adi()); return val.length; } } if ((tag === '+-' || tag === 'COMPARE' || tag === 'LOGIC' || tag === 'MATH' || tag === 'POWER' || tag === 'SHIFT' || tag === 'BITWISE' || tag === 'CONCAT' || tag === 'COMPOSE' || tag === 'RELATION' || tag === 'PIPE' || tag === 'BACKPIPE' || tag === 'IMPORT') && this.last[0] === '(') { tag = tag === 'BACKPIPE' ? 'BIOPBP' : 'BIOP'; } if (tag === ',' || tag === 'CASE' || tag === 'PIPE' || tag === 'BACKPIPE' || tag === 'DOT' || tag === 'LOGIC' || tag === 'COMPARE' || tag === 'MATH' || tag === 'POWER' || tag === 'IMPORT' || tag === 'SHIFT' || tag === 'BITWISE') { this.unline(); } this.token(tag, val); return sym.length; }; exports.token = function(tag, value, callable){ this.tokens.push(this.last = [tag, value, this.line]); if (callable) { this.last.callable = true; } return value; }; exports.indent = function(delta){ this.dent += delta; this.dents.push(this.token('INDENT', delta)); this.closes.push('DEDENT'); }; exports.dedent = function(debt){ var dent; this.dent -= debt; while (debt > 0 && (dent = this.dents.pop())) { if (debt < dent && !this.inter) { this.carp("unmatched dedent (" + debt + " for " + dent + ")"); } this.pair('DEDENT'); debt -= typeof dent === 'number' ? this.token('DEDENT', dent) : dent; } }; exports.newline = function(){ var ref$; this.last[1] === '\n' || this.tokens.push(this.last = (ref$ = ['NEWLINE', '\n', this.line], ref$.spaced = true, ref$)); }; exports.unline = function(){ var ref$; if (!this.tokens[1]) { return; } switch (this.last[0]) { case 'INDENT': (ref$ = this.dents)[ref$.length - 1] += ''; // fallthrough case 'NEWLINE': this.tokens.length--; } }; exports.parameters = function(arrow, offset){ var i$, ref$, i, t, ref1$; if (this.last[0] === ')' && ')' === this.last[1]) { this.lpar[0] = 'PARAM('; this.last[0] = ')PARAM'; return; } if (arrow === '->') { this.token('PARAM(', ''); } else { for (i$ = (ref$ = this.tokens).length - 1; i$ >= 0; --i$) { i = i$; t = ref$[i$]; if ((ref1$ = t[0]) === 'NEWLINE' || ref1$ === 'INDENT' || ref1$ === 'THEN' || ref1$ === '=>' || ref1$ === '(') { break; } } this.tokens.splice(i + 1, 0, ['PARAM(', '', t[2]]); } if (offset) { this.tokens.splice(this.tokens.length + offset, 0, [')PARAM', '', t[2]]); } else { this.token(')PARAM', ''); } }; exports.interpolate = function(str, idx, end){ var parts, end0, pos, i, ch, c1, id, stringified, length, tag, e, delta, nested, clone, ref$; parts = []; end0 = end.charAt(0); pos = 0; i = -1; str = str.slice(idx + end.length); while (ch = str.charAt(++i)) { switch (ch) { case end0: if (end !== str.slice(i, i + end.length)) { continue; } parts.push(['S', this.countLines(str.slice(0, i)), this.line]); return parts.size = pos + i + end.length, parts; case '#': c1 = str.charAt(i + 1); id = in$(c1, ['@']) && c1 || (ID.lastIndex = i + 1, ID).exec(str)[1]; if (!(id || c1 === '{')) { continue; } break; case '\\': ++i; // fallthrough default: continue; } if (i || nested && !stringified) { stringified = parts.push(['S', this.countLines(str.slice(0, i)), this.line]); } if (id) { length = id.length; if (id === '@') { id = 'this'; } if (in$(id, ['this'])) { tag = 'LITERAL'; } else { id = camelize(id); try { Function("'use strict'; var " + id); } catch (e$) { e = e$; this.carp("invalid variable interpolation \"" + id + "\""); } tag = 'ID'; } str = str.slice(delta = i + 1 + length); parts.push(['TOKENS', nested = [[tag, id, this.line]]]); } else { clone = (ref$ = clone$(exports), ref$.inter = true, ref$.emender = this.emender, ref$); nested = clone.tokenize(str.slice(i + 2), { line: this.line, raw: true }); delta = str.length - clone.rest.length; str = clone.rest, this.line = clone.line; while (((ref$ = nested[0]) != null ? ref$[0] : void 8) === 'NEWLINE') { nested.shift(); } if (nested.length) { nested.unshift(['(', '(', nested[0][2]]); nested.push([')', ')', this.line]); parts.push(['TOKENS', nested]); } } pos += delta; i = -1; } this.carp("missing `" + end + "`"); }; exports.addInterpolated = function(parts, nlines){ var tokens, last, ref$, left, right, joint, callable, i$, len$, i, t; if (!parts[1]) { return this.strnum(nlines(this.string('"', parts[0][1]))); } tokens = this.tokens, last = this.last; ref$ = !last.spaced && last[1] === '%' ? (--tokens.length, this.last = last = tokens[tokens.length - 1], ['[', ']', [',', ',']]) : ['(', ')', ['+-', '+']], left = ref$[0], right = ref$[1], joint = ref$[2]; callable = this.adi(); tokens.push([left, '"', last[2]]); for (i$ = 0, len$ = parts.length; i$ < len$; ++i$) { i = i$; t = parts[i$]; if (t[0] === 'TOKENS') { tokens.push.apply(tokens, t[1]); } else { if (i > 1 && !t[1]) { continue; } tokens.push(['STRNUM', nlines(this.string('"', t[1])), t[2]]); } tokens.push(joint.concat(tokens[tokens.length - 1][2])); } --tokens.length; this.token(right, '', callable); }; exports.strnum = function(it){ this.token('STRNUM', it, this.adi() || this.last[0] === 'DOT'); }; exports.regex = function(body, flag){ var e; try { RegExp(body); } catch (e$) { e = e$; this.carp(e.message); } if (flag === '$') { return this.strnum(this.string('\'', enslash(body))); } return this.token('LITERAL', "/" + (body || '(?:)') + "/" + this.validate(flag)); }; exports.adi = function(){ if (this.last.spaced) { return; } if (!able(this.tokens)) { return; } return this.token('DOT', '.'); }; exports.dotcat = function(it){ if (this.last[1] === '.' || this.adi()) { return this.last[1] += it; } }; exports.pair = function(it){ var wanted, ref$; if (!(it === (wanted = (ref$ = this.closes)[ref$.length - 1]) || ')CALL' === wanted && it === ')')) { if ('DEDENT' !== wanted) { this.carp("unmatched `" + it + "`"); } this.dedent((ref$ = this.dents)[ref$.length - 1]); return this.pair(it); } this.unline(); return this.closes.pop(); }; exports.able = function(call){ return !this.last.spaced && able(this.tokens, null, call); }; exports.countLines = function(it){ var pos; while (pos = 1 + it.indexOf('\n', pos)) { ++this.line; } return it; }; exports.forange = function(){ var ref$, ref1$, ref2$; if (((ref$ = (ref1$ = this.tokens)[ref1$.length - 2 - ((ref2$ = this.last[0]) === 'NEWLINE' || ref2$ === 'INDENT')]) != null ? ref$[0] : void 8) === 'FOR' || this.last[0] === 'FOR') { this.fset('for', false); this.fset('from', true); return true; } else { return false; } }; exports.validate = function(flag){ var that; if (that = flag && /(.).*\1/.exec(flag)) { this.carp("duplicate regex flag `" + that[1] + "`"); } return flag; }; exports.fget = function(key){ var ref$; return (ref$ = this.flags[this.closes.length]) != null ? ref$[key] : void 8; }; exports.fset = function(key, val){ var ref$, key$; ((ref$ = this.flags)[key$ = this.closes.length] || (ref$[key$] = {}))[key] = val; }; exports.carp = function(it){ carp(it, this.line); }; exports.string = function(q, body){ return string(q, body, this.line); }; function carp(msg, lno){ throw SyntaxError(msg + " on line " + (-~lno)); } function able(tokens, i, call){ var token, tag; i == null && (i = tokens.length); tag = (token = tokens[i - 1])[0]; return (tag === 'ID' || tag === ']' || tag === '?') || (call ? token.callable || (tag === ')' || tag === ')CALL' || tag === 'BIOPBP') && token[1] : tag === '}' || tag === ')' || tag === ')CALL' || tag === 'STRNUM' || tag === 'LITERAL' || tag === 'WORDS'); } string = (function(re){ return function(q, body, lno){ body = body.replace(re, function(it, oct, xu, rest){ if (it === q || it === '\\') { return '\\' + it; } if (oct) { return '\\x' + (0x100 + parseInt(oct, 8)).toString(16).slice(1); } if (xu) { carp('malformed character escape sequence', lno); } if (!rest || q === rest) { return it; } else { return rest; } }); return q + body + q; }; }.call(this, /['"]|\\(?:([0-3]?[0-7]{2}|[1-7]|0(?=[89]))|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|([xu])|[\\0bfnrtv]|[^\n\S]|([\w\W]))?/g)); function heretabs(doc){ var dent, that, ref$; dent = 0 / 0; while (that = TABS.exec(doc)) { dent <= (ref$ = that[0].length - 1) || (dent = ref$); } return dent; } TABS = /\n(?!$)[^\n\S]*/mg; function detab(str, len){ if (len) { return str.replace(detab[len] || (detab[len] = RegExp('\\n[^\\n\\S]{1,' + len + '}', 'g')), '\n'); } else { return str; } } function replacer(re, to){ return function(it){ return it.replace(re, to); }; } unlines = replacer(/\n[^\n\S]*/g, ''); enlines = replacer(/\n/g, '\\n'); enslash = replacer(/\\/g, '\\\\'); reslash = replacer(/(\\.)|\//g, function(){ return arguments[1] || '\\/'; }); camelize = replacer(/-[a-z]/ig, function(it){ return it.charAt(1).toUpperCase(); }); function lchomp(it){ return it.slice(1 + it.lastIndexOf('\n', 0)); } function decode(val, lno){ if (!isNaN(val)) { return [+val]; } val = val.length > 8 ? 'ng' : Function('return ' + val)(); val.length === 1 || carp('bad string in range', lno); return [val.charCodeAt(), true]; } function uxxxx(it){ return '"\\u' + ('000' + it.toString(16)).slice(-4) + '"'; } character = typeof JSON == 'undefined' || JSON === null ? uxxxx : function(it){ switch (it) { case 0x2028: case 0x2029: return uxxxx(it); default: return JSON.stringify(String.fromCharCode(it)); } }; function firstPass(tokens){ var prev, i, token, tag, val, line, next, ts, parens, i$, j; prev = ['NEWLINE', '\n', 0]; i = 0; while (token = tokens[++i]) { tag = token[0], val = token[1], line = token[2]; switch (false) { case !(tag === 'ASSIGN' && in$(prev[1], LS_KEYWORDS) && tokens[i - 2][0] !== 'DOT'): carp("cannot assign to reserved word \"" + prev[1] + "\"", line); break; case !(tag === 'DOT' && prev[0] === ']' && tokens[i - 2][0] === '[' && tokens[i - 3][0] === 'DOT'): tokens.splice(i - 2, 3); tokens[i - 3][1] = '[]'; break; case !(tag === 'DOT' && prev[0] === '}' && tokens[i - 2][0] === '{' && tokens[i - 3][0] === 'DOT'): tokens.splice(i - 2, 3); tokens[i - 3][1] = '{}'; break; case !(val === '.' && token.spaced && prev.spaced): tokens[i] = ['COMPOSE', '<<', line]; break; case val !== '++': if (!(next = tokens[i + 1])) { break; } ts = ['ID', 'LITERAL', 'STRNUM']; if (prev.spaced && token.spaced || !(prev.spaced || token.spaced) && in$(prev[0], ts) && in$(next[0], ts)) { tokens[i][0] = 'CONCAT'; } if (prev[0] === '(' && next[0] === ')' || prev[0] === '(' && token.spaced || next[0] === ')' && prev.spaced) { tokens[i][0] = 'BIOP'; } break; case !(tag === 'DOT' && val === '.'): next = tokens[i + 1]; if (prev[0] === '(' && next[0] === ')') { tokens[i][0] = 'BIOP'; } else if (prev[0] === '(') { tokens.splice(i, 0, ['PARAM(', '(', line], [')PARAM', ')', line], ['->', '->', line], ['ID', 'it', line]); } else if (next[0] === ')') { tokens.splice(i + 1, 0, ['[', '[', line], ['ID', 'it', line], [']', ']', line]); parens = 1; LOOP: for (i$ = i + 1; i$ >= 0; --i$) { j = i$; switch (tokens[j][0]) { case ')': ++parens; break; case '(': if (--parens === 0) { tokens.splice(j + 1, 0, ['PARAM(', '(', line], ['ID', 'it', line], [')PARAM', ')', line], ['->', '->', line]); break LOOP; } } } } } prev = token; continue; } } function rewriteBlockless(tokens){ var i$, len$, i, token, tag; for (i$ = 0, len$ = tokens.length; i$ < len$; ++i$) { i = i$; token = tokens[i$], tag = token[0]; if (tag === 'IF' || tag === 'CLASS' || tag === 'CATCH') { detectEnd(tokens, i + 1, ok, go); } } function ok(it){ var ref$; return (ref$ = it[0]) === 'NEWLINE' || ref$ === 'INDENT'; } function go(it, i){ var lno; if (tag === 'IF') { if (it[0] !== 'INDENT' || !it[1] && !it.then || in$(tokens[i - 1][0], BLOCK_USERS)) { token[0] = 'POST_IF'; } } else if (it[0] !== 'INDENT') { tokens.splice(i, 0, ['INDENT', 0, lno = tokens[i - 1][2]], ['DEDENT', 0, lno]); } } } function addImplicitIndentation(tokens){ var i, token, tag, next, indent, dedent, ref$, idx; i = 0; while (token = tokens[++i]) { tag = token[0]; if (tag !== '->' && tag !== 'THEN' && tag !== 'ELSE' && tag !== 'DEFAULT' && tag !== 'TRY' && tag !== 'FINALLY' && tag !== 'DECL') { continue; } switch (next = tokens[i + 1][0]) { case 'IF': if (tag === 'ELSE') { continue; } break; case 'INDENT': case 'THEN': if (tag === 'THEN') { tokens.splice(i--, 1); } continue; } indent = ['INDENT', 0, token[2]]; dedent = ['DEDENT', 0]; if (tag === 'THEN') { (tokens[i] = indent).then = true; } else { tokens.splice(++i, 0, indent); } switch (false) { case tag !== 'DECL': break; case next !== 'DOT' && next !== '?' && next !== ',' && next !== 'PIPE' && next !== 'BACKPIPE': --i; // fallthrough case !((next === 'ID' || next === 'STRNUM' || next === 'LITERAL') && ',' === ((ref$ = tokens[i + 2]) != null ? ref$[0] : void 8)): go(0, i += 2); ++i; continue; case !((next === '(' || next === '[' || next === '{') && ',' === ((ref$ = tokens[idx = 1 + indexOfPair(tokens, i + 1)]) != null ? ref$[0] : void 8)): go(0, idx); ++i; continue; } detectEnd(tokens, i + 1, ok, go); } function ok(token, i){ var t0, t; t0 = token[0]; t = tag; if (tag === t0 || tag === 'THEN' && t0 === 'SWITCH') { tag = ''; } switch (t0) { case 'NEWLINE': return token[1] !== ';'; case 'DOT': case '?': case ',': case 'PIPE': case 'BACKPIPE': return tokens[i - 1].eol; case 'ELSE': return t === 'THEN'; case 'CATCH': return t === 'TRY'; case 'FINALLY': return t === 'TRY' || t === 'CATCH' || t === 'THEN'; case 'CASE': case 'DEFAULT': return t === 'CASE' || t === 'THEN'; } } function go(arg$, i){ var prev; prev = tokens[i - 1]; tokens.splice(prev[0] === ',' ? i - 1 : i, 0, (dedent[2] = prev[2], dedent)); } } function addImplicitParentheses(tokens){ var i, brackets, token, endi, ref$, tpair, tag, prev, skipBlock, seenSwitch; i = 0; brackets = []; while (token = tokens[++i]) { if (token[1] === 'do' && tokens[i + 1][0] === 'INDENT') { endi = indexOfPair(tokens, i + 1); if (tokens[endi + 1][0] === 'NEWLINE' && ((ref$ = tokens[endi + 2]) != null ? ref$[0] : void 8) === 'WHILE') { token[0] = 'DO'; tokens[endi + 2].done = true; tokens.splice(endi + 1, 1); } else { (token = tokens[1 + i])[0] = '('; (tpair = tokens[endi])[0] = ')'; token.doblock = true; tokens.splice(i, 1); } } tag = token[0]; prev = tokens[i - 1]; tag === '[' && brackets.push(prev[0] === 'DOT'); if (prev[0] === ']') { if (brackets.pop()) { prev.index = true; } else { continue; } } if (!(((ref$ = prev[0]) === 'FUNCTION' || ref$ === 'LET' || ref$ === 'WHERE') || prev.spaced && able(tokens, i, true))) { continue; } if (token.doblock) { token[0] = 'CALL('; tpair[0] = ')CALL'; continue; } if (!exp(token)) { continue; } if (tag === 'CREMENT') { if (token.spaced || !in$((ref$ = tokens[i + 1]) != null ? ref$[0] : void 8, CHAIN)) { continue; } } skipBlock = seenSwitch = false; tokens.splice(i++, 0, ['CALL(', '', token[2]]); detectEnd(tokens, i, ok, go); } function exp(token){ var tag; tag = token[0]; return in$(tag, ARG) || !token.spaced && (tag === '+-' || tag === 'CLONE'); } function ok(token, i){ var tag, ref$, pre; tag = token[0]; if (tag === 'POST_IF' || tag === 'PIPE' || tag === 'BACKPIPE') { return true; } if (!skipBlock) { if (token.alias && ((ref$ = token[1]) === '&&' || ref$ === '||' || ref$ === 'xor') || (tag === 'TO' || tag === 'BY' || tag === 'IMPLEMENTS')) { return true; } } pre = tokens[i - 1]; switch (tag) { case 'NEWLINE': return pre[0] !== ','; case 'DOT': case '?': return !skipBlock && (pre.spaced || pre[0] === 'DEDENT'); case 'SWITCH': seenSwitch = true; // fallthrough case 'IF': case 'CLASS': case 'FUNCTION': case 'LET': case 'WITH': case 'CATCH': skipBlock = true; break; case 'CASE': if (seenSwitch) { skipBlock = true; } else { return true; } break; case 'INDENT': if (skipBlock) { return skipBlock = false; } return !in$(pre[0], BLOCK_USERS); case 'WHILE': if (token.done) { return false; } // fallthrough case 'FOR': skipBlock = true; return able(tokens, i) || pre[0] === 'CREMENT' || pre[0] === '...' && pre.spaced; } return false; } function go(token, i){ tokens.splice(i, 0, [')CALL', '', tokens[i - 1][2]]); } } function addImplicitBraces(tokens){ var stack, i, token, tag, start, paren, index, pre, ref$, inline; stack = []; i = 0; while (token = tokens[++i]) { if (':' !== (tag = token[0])) { switch (false) { case !in$(tag, CLOSERS): start = stack.pop(); break; case !in$(tag, OPENERS): if (tag === 'INDENT' && tokens[i - 1][0] === '{') { tag = '{'; } stack.push([tag, i]); } continue; } paren = tokens[i - 1][0] === ')'; index = paren ? start[1] : i - 1; pre = tokens[index - 1]; if (!(((ref$ = pre[0]) === ':' || ref$ === 'ASSIGN' || ref$ === 'IMPORT') || ((ref$ = stack[stack.length - 1]) != null ? ref$[0] : void 8) !== '{')) { continue; } stack.push(['{']); inline = !pre.doblock && ((ref$ = pre[0]) !== 'NEWLINE' && ref$ !== 'INDENT'); while (((ref$ = tokens[index - 2]) != null ? ref$[0] : void 8) === 'COMMENT') { index -= 2; } tokens.splice(index, 0, ['{', '{', tokens[index][2]]); detectEnd(tokens, ++i + 1, ok, go); } function ok(token, i){ var tag, t1, ref$; switch (tag = token[0]) { case ',': break; case 'NEWLINE': if (inline) { return true; } break; case 'DEDENT': return true; case 'POST_IF': case 'FOR': case 'WHILE': return inline; default: return false; } t1 = (ref$ = tokens[i + 1]) != null ? ref$[0] : void 8; return t1 !== (tag === ',' ? 'NEWLINE' : 'COMMENT') && ':' !== ((ref$ = tokens[t1 === '(' ? 1 + indexOfPair(tokens, i + 1) : i + 2]) != null ? ref$[0] : void 8); } function go(token, i){ tokens.splice(i, 0, ['}', '', token[2]]); } } function expandLiterals(tokens){ var i, fromNum, token, sig, ref$, lno, char, toNum, tochar, byNum, byp, ts, enc, add, i$, n, len$, word, that; i = 0; while (token = tokens[++i]) { switch (token[0]) { case 'STRNUM': if (~'-+'.indexOf(sig = token[1].charAt(0))) { token[1] = token[1].slice(1); tokens.splice(i++, 0, ['+-', sig, token[2]]); } if (token.callable) { continue; } break; case 'TO': case 'TIL': if (!(tokens[i - 1][0] === '[' && ((tokens[i + 2][0] === ']' && (((ref$ = tokens[i + 1][1].charAt(0)) === '\'' || ref$ === '"') || +tokens[i + 1][1] >= 0)) || (tokens[i + 2][0] === 'BY' && ((ref$ = tokens[i + 3]) != null ? ref$[0] : void 8) === 'STRNUM' && ((ref$ = tokens[i + 4]) != null ? ref$[0] : void 8) === ']')))) { continue; } if (tokens[i + 2][0] === 'BY') { tokens[i + 2][0] = 'RANGE_BY'; } token.op = token[1]; fromNum = 0; // fallthrough case 'RANGE': lno = token[2]; if (fromNum != null || (tokens[i - 1][0] === '[' && tokens[i + 1][0] === 'STRNUM' && ((tokens[i + 2][0] === ']' && (((ref$ = tokens[i + 1][1].charAt(0)) === '\'' || ref$ === '"') || +tokens[i + 1][1] >= 0)) || (tokens[i + 2][0] === 'RANGE_BY' && ((ref$ = tokens[i + 3]) != null ? ref$[0] : void 8) === 'STRNUM' && ((ref$ = tokens[i + 4]) != null ? ref$[0] : void 8) === ']')))) { if (fromNum == null) { ref$ = decode(token[1], lno), fromNum = ref$[0], char = ref$[1]; } ref$ = decode(tokens[i + 1][1], lno), toNum = ref$[0], tochar = ref$[1]; if (toNum == null || char ^ tochar) { carp('bad "to" in range', lno); } byNum = 1; if (byp = ((ref$ = tokens[i + 2]) != null ? ref$[0] : void 8) === 'RANGE_BY') { if (!(byNum = +((ref$ = tokens[i + 3]) != null ? ref$[1] : void 8))) { carp('bad "by" in range', tokens[i + 2][2]); } } else if (fromNum > toNum) { byNum = -1; } ts = []; enc = char ? character : String; add = fn$; if (token.op === 'to') { for (i$ = fromNum; byNum < 0 ? i$ >= toNum : i$ <= toNum; i$ += byNum) { n = i$; add(); } } else { for (i$ = fromNum; byNum < 0 ? i$ > toNum : i$ < toNum; i$ += byNum) { n = i$; add(); } } ts.pop() || carp('empty range', lno); tokens.splice.apply(tokens, [i, 2 + 2 * byp].concat(slice$.call(ts))); i += ts.length - 1; } else { token[0] = 'STRNUM'; if (((ref$ = tokens[i + 2]) != null ? ref$[0] : void 8) === 'RANGE_BY') { tokens.splice(i + 2, 1, ['BY', 'by', lno]); } tokens.splice(i + 1, 0, ['TO', token.op, lno]); } fromNum = null; break; case 'WORDS': ts = [['[', '[', lno = token[2]]]; for (i$ = 0, len$ = (ref$ = token[1].match(/\S+/g) || '').length; i$ < len$; ++i$) { word = ref$[i$]; ts.push(['STRNUM', string('\'', word, lno), lno], [',', ',', lno]); } tokens.splice.apply(tokens, [i, 1].concat(slice$.call(ts), [[']', ']', lno]])); i += ts.length; break; case 'INDENT': if (that = tokens[i - 1]) { if (that[1] === 'new') { tokens.splice(i++, 0, ['PARAM(', '', token[2]], [')PARAM', '', token[2]], ['->', '', token[2]]); } else if ((ref$ = that[0]) === 'FUNCTION' || ref$ === 'LET') { tokens.splice(i, 0, ['CALL(', '', token[2]], [')CALL', '', token[2]]); i += 2; } } continue; case 'LITERAL': case '}': break; case ')': case ')CALL': if (token[1]) { continue; } break; case ']': if (token.index) { continue; } break; case 'CREMENT': if (!able(tokens, i)) { continue; } break; case 'BIOP': if (!token.spaced && ((ref$ = token[1]) === '+' || ref$ === '-') && tokens[i + 1][0] !== ')') { tokens[i][0] = '+-'; } continue; default: continue; } if (token.spaced && in$(tokens[i + 1][0], ARG)) { tokens.splice(++i, 0, [',', ',', token[2]]); } } function fn$(){ if (0x10000 < ts.push(['STRNUM', enc(n), lno], [',', ',', lno])) { carp('range limit exceeded', lno); } } } function detectEnd(tokens, i, ok, go){ var levels, token, tag; levels = 0; for (; token = tokens[i]; ++i) { if (!levels && ok(token, i)) { return go(token, i); } tag = token[0]; if (0 > (levels += in$(tag, OPENERS) || -in$(tag, CLOSERS))) { return go(token, i); } } } function indexOfPair(tokens, i){ var level, end, start, that; level = 1; end = INVERSES[start = tokens[i][0]]; while (that = tokens[++i]) { switch (that[0]) { case start: ++level; break; case end: if (!--level) { return i; } } } return -1; } KEYWORDS_SHARED = ['true', 'false', 'null', 'this', 'void', 'super', 'return', 'throw', 'break', 'continue', 'if', 'else', 'for', 'while', 'switch', 'case', 'default', 'try', 'catch', 'finally', 'function', 'class', 'extends', 'implements', 'new', 'do', 'delete', 'typeof', 'in', 'instanceof', 'let', 'with', 'var', 'const', 'import', 'export', 'debugger']; KEYWORDS_UNUSED = ['enum', 'interface', 'package', 'private', 'protected', 'public', 'static', 'yield']; JS_KEYWORDS = KEYWORDS_SHARED.concat(KEYWORDS_UNUSED); LS_KEYWORDS = ['xor', 'match', 'where']; ID = /((?!\s)[a-z_$\xAA-\uFFDC](?:(?!\s)[\w$\xAA-\uFFDC]|-[a-z])*)([^\n\S]*:(?![:=]))?|/ig; SYMBOL = /[-\/^]=|[%+:*]{1,2}=|\.(?:[&\|\^]|<<|>>>?)\.=?|\.{1,3}|\^\^|!?-->|!?~~>|<--|<~~|([-+&|:])\1|%%|&|\([^\n\S]*\)|!?[-~]>|<[-~]|[!=]==?|!?\~=|@@?|<\[(?:[\s\S]*?\]>)?|<<<<?|<\||[<>]==|<<=|>>=|<<|>>|[<>]\??=?|\|>|\||=>|\*\*|\^|`|[^\s#]?/g; SPACE = /[^\n\S]*(?:#.*)?/g; MULTIDENT = /(?:\s*#.*)*(?:\n([^\n\S]*))*/g; SIMPLESTR = /'[^\\']*(?:\\[\s\S][^\\']*)*'|/g; JSTOKEN = /``[^\\`]*(?:\\[\s\S][^\\`]*)*``|/g; BSTOKEN = /\\(?:(\S[^\s,;)}\]]*)|\s*)/g; NUMBER = /0x[\dA-Fa-f][\dA-Fa-f_]*|(\d*)~([\dA-Za-z]\w*)|((\d[\d_]*)(\.\d[\d_]*)?(?:e[+-]?\d[\d_]*)?)[$\w]*|/g; NUMBER_OMIT = /_+/g; REGEX = /\/([^[\/\n\\]*(?:(?:\\.|\[[^\]\n\\]*(?:\\.[^\]\n\\]*)*\])[^[\/\n\\]*)*)\/([gimy]{1,4}|\$?)|/g; HEREGEX_OMIT = /\s+(?:#.*)?/g; LASTDENT = /\n[^\n\S]*$/; INLINEDENT = /[^\n\S]*[^#\s]?/g; NONASCII = /[\x80-\uFFFF]/; OPENERS = ['(', '[', '{', 'CALL(', 'PARAM(', 'INDENT']; CLOSERS = [')', ']', '}', ')CALL', ')PARAM', 'DEDENT']; INVERSES = import$((function(){ var i$, ref$, len$, results$ = {}; for (i$ = 0, len$ = (ref$ = OPENERS).length; i$ < len$; ++i$) { i = i$; o = ref$[i$]; results$[o] = CLOSERS[i]; } return results$; }()), (function(){ var i$, ref$, len$, results$ = {}; for (i$ = 0, len$ = (ref$ = CLOSERS).length; i$ < len$; ++i$) { i = i$; c = ref$[i$]; results$[c] = OPENERS[i]; } return results$; }())); CHAIN = ['(', '{', '[', 'ID', 'STRNUM', 'LITERAL', 'LET', 'WITH', 'WORDS']; ARG = CHAIN.concat(['...', 'UNARY', 'CREMENT', 'PARAM(', 'FUNCTION', 'IF', 'SWITCH', 'TRY', 'CLASS', 'RANGE', 'LABEL', 'DECL', 'DO', 'BIOPBP']); BLOCK_USERS = [',', ':', '->', 'ELSE', 'ASSIGN', 'IMPORT', 'UNARY', 'DEFAULT', 'TRY', 'FINALLY', 'HURL', 'DECL', 'DO', 'LET', 'FUNCTION']; function clone$(it){ function fun(){} fun.prototype = it; return new fun; } function in$(x, xs){ var i = -1, l = xs.length >>> 0; while (++i < l) if (x === xs[i]) return true; return false; } function import$(obj, src){ var own = {}.hasOwnProperty; for (var key in src) if (own.call(src, key)) obj[key] = src[key]; return obj; }
{ "pile_set_name": "Github" }
&control calculation = 'nscf' prefix = 'sic' wf_collect = .false. pseudo_dir = '../pp/' outdir = './' / &system ibrav = 2 celldm(1) = 8.237 nat = 2 ntyp = 2 ecutwfc = 60 occupations = 'smearing' smearing = 'mp' degauss = 0.02 nbnd = 4 / &electrons diagonalization = 'david' mixing_beta = 0.7 conv_thr = 1.0d-10 / ATOMIC_SPECIES Si 28.0855 Si.pz-vbc.UPF C 12.01078 C.UPF ATOMIC_POSITIONS alat Si 0.00 0.00 0.00 C 0.25 0.25 0.25 K_POINTS crystal 216 0.00000000 0.00000000 0.00000000 4.629630e-03 0.00000000 0.00000000 0.16666667 4.629630e-03 0.00000000 0.00000000 0.33333333 4.629630e-03 0.00000000 0.00000000 0.50000000 4.629630e-03 0.00000000 0.00000000 0.66666667 4.629630e-03 0.00000000 0.00000000 0.83333333 4.629630e-03 0.00000000 0.16666667 0.00000000 4.629630e-03 0.00000000 0.16666667 0.16666667 4.629630e-03 0.00000000 0.16666667 0.33333333 4.629630e-03 0.00000000 0.16666667 0.50000000 4.629630e-03 0.00000000 0.16666667 0.66666667 4.629630e-03 0.00000000 0.16666667 0.83333333 4.629630e-03 0.00000000 0.33333333 0.00000000 4.629630e-03 0.00000000 0.33333333 0.16666667 4.629630e-03 0.00000000 0.33333333 0.33333333 4.629630e-03 0.00000000 0.33333333 0.50000000 4.629630e-03 0.00000000 0.33333333 0.66666667 4.629630e-03 0.00000000 0.33333333 0.83333333 4.629630e-03 0.00000000 0.50000000 0.00000000 4.629630e-03 0.00000000 0.50000000 0.16666667 4.629630e-03 0.00000000 0.50000000 0.33333333 4.629630e-03 0.00000000 0.50000000 0.50000000 4.629630e-03 0.00000000 0.50000000 0.66666667 4.629630e-03 0.00000000 0.50000000 0.83333333 4.629630e-03 0.00000000 0.66666667 0.00000000 4.629630e-03 0.00000000 0.66666667 0.16666667 4.629630e-03 0.00000000 0.66666667 0.33333333 4.629630e-03 0.00000000 0.66666667 0.50000000 4.629630e-03 0.00000000 0.66666667 0.66666667 4.629630e-03 0.00000000 0.66666667 0.83333333 4.629630e-03 0.00000000 0.83333333 0.00000000 4.629630e-03 0.00000000 0.83333333 0.16666667 4.629630e-03 0.00000000 0.83333333 0.33333333 4.629630e-03 0.00000000 0.83333333 0.50000000 4.629630e-03 0.00000000 0.83333333 0.66666667 4.629630e-03 0.00000000 0.83333333 0.83333333 4.629630e-03 0.16666667 0.00000000 0.00000000 4.629630e-03 0.16666667 0.00000000 0.16666667 4.629630e-03 0.16666667 0.00000000 0.33333333 4.629630e-03 0.16666667 0.00000000 0.50000000 4.629630e-03 0.16666667 0.00000000 0.66666667 4.629630e-03 0.16666667 0.00000000 0.83333333 4.629630e-03 0.16666667 0.16666667 0.00000000 4.629630e-03 0.16666667 0.16666667 0.16666667 4.629630e-03 0.16666667 0.16666667 0.33333333 4.629630e-03 0.16666667 0.16666667 0.50000000 4.629630e-03 0.16666667 0.16666667 0.66666667 4.629630e-03 0.16666667 0.16666667 0.83333333 4.629630e-03 0.16666667 0.33333333 0.00000000 4.629630e-03 0.16666667 0.33333333 0.16666667 4.629630e-03 0.16666667 0.33333333 0.33333333 4.629630e-03 0.16666667 0.33333333 0.50000000 4.629630e-03 0.16666667 0.33333333 0.66666667 4.629630e-03 0.16666667 0.33333333 0.83333333 4.629630e-03 0.16666667 0.50000000 0.00000000 4.629630e-03 0.16666667 0.50000000 0.16666667 4.629630e-03 0.16666667 0.50000000 0.33333333 4.629630e-03 0.16666667 0.50000000 0.50000000 4.629630e-03 0.16666667 0.50000000 0.66666667 4.629630e-03 0.16666667 0.50000000 0.83333333 4.629630e-03 0.16666667 0.66666667 0.00000000 4.629630e-03 0.16666667 0.66666667 0.16666667 4.629630e-03 0.16666667 0.66666667 0.33333333 4.629630e-03 0.16666667 0.66666667 0.50000000 4.629630e-03 0.16666667 0.66666667 0.66666667 4.629630e-03 0.16666667 0.66666667 0.83333333 4.629630e-03 0.16666667 0.83333333 0.00000000 4.629630e-03 0.16666667 0.83333333 0.16666667 4.629630e-03 0.16666667 0.83333333 0.33333333 4.629630e-03 0.16666667 0.83333333 0.50000000 4.629630e-03 0.16666667 0.83333333 0.66666667 4.629630e-03 0.16666667 0.83333333 0.83333333 4.629630e-03 0.33333333 0.00000000 0.00000000 4.629630e-03 0.33333333 0.00000000 0.16666667 4.629630e-03 0.33333333 0.00000000 0.33333333 4.629630e-03 0.33333333 0.00000000 0.50000000 4.629630e-03 0.33333333 0.00000000 0.66666667 4.629630e-03 0.33333333 0.00000000 0.83333333 4.629630e-03 0.33333333 0.16666667 0.00000000 4.629630e-03 0.33333333 0.16666667 0.16666667 4.629630e-03 0.33333333 0.16666667 0.33333333 4.629630e-03 0.33333333 0.16666667 0.50000000 4.629630e-03 0.33333333 0.16666667 0.66666667 4.629630e-03 0.33333333 0.16666667 0.83333333 4.629630e-03 0.33333333 0.33333333 0.00000000 4.629630e-03 0.33333333 0.33333333 0.16666667 4.629630e-03 0.33333333 0.33333333 0.33333333 4.629630e-03 0.33333333 0.33333333 0.50000000 4.629630e-03 0.33333333 0.33333333 0.66666667 4.629630e-03 0.33333333 0.33333333 0.83333333 4.629630e-03 0.33333333 0.50000000 0.00000000 4.629630e-03 0.33333333 0.50000000 0.16666667 4.629630e-03 0.33333333 0.50000000 0.33333333 4.629630e-03 0.33333333 0.50000000 0.50000000 4.629630e-03 0.33333333 0.50000000 0.66666667 4.629630e-03 0.33333333 0.50000000 0.83333333 4.629630e-03 0.33333333 0.66666667 0.00000000 4.629630e-03 0.33333333 0.66666667 0.16666667 4.629630e-03 0.33333333 0.66666667 0.33333333 4.629630e-03 0.33333333 0.66666667 0.50000000 4.629630e-03 0.33333333 0.66666667 0.66666667 4.629630e-03 0.33333333 0.66666667 0.83333333 4.629630e-03 0.33333333 0.83333333 0.00000000 4.629630e-03 0.33333333 0.83333333 0.16666667 4.629630e-03 0.33333333 0.83333333 0.33333333 4.629630e-03 0.33333333 0.83333333 0.50000000 4.629630e-03 0.33333333 0.83333333 0.66666667 4.629630e-03 0.33333333 0.83333333 0.83333333 4.629630e-03 0.50000000 0.00000000 0.00000000 4.629630e-03 0.50000000 0.00000000 0.16666667 4.629630e-03 0.50000000 0.00000000 0.33333333 4.629630e-03 0.50000000 0.00000000 0.50000000 4.629630e-03 0.50000000 0.00000000 0.66666667 4.629630e-03 0.50000000 0.00000000 0.83333333 4.629630e-03 0.50000000 0.16666667 0.00000000 4.629630e-03 0.50000000 0.16666667 0.16666667 4.629630e-03 0.50000000 0.16666667 0.33333333 4.629630e-03 0.50000000 0.16666667 0.50000000 4.629630e-03 0.50000000 0.16666667 0.66666667 4.629630e-03 0.50000000 0.16666667 0.83333333 4.629630e-03 0.50000000 0.33333333 0.00000000 4.629630e-03 0.50000000 0.33333333 0.16666667 4.629630e-03 0.50000000 0.33333333 0.33333333 4.629630e-03 0.50000000 0.33333333 0.50000000 4.629630e-03 0.50000000 0.33333333 0.66666667 4.629630e-03 0.50000000 0.33333333 0.83333333 4.629630e-03 0.50000000 0.50000000 0.00000000 4.629630e-03 0.50000000 0.50000000 0.16666667 4.629630e-03 0.50000000 0.50000000 0.33333333 4.629630e-03 0.50000000 0.50000000 0.50000000 4.629630e-03 0.50000000 0.50000000 0.66666667 4.629630e-03 0.50000000 0.50000000 0.83333333 4.629630e-03 0.50000000 0.66666667 0.00000000 4.629630e-03 0.50000000 0.66666667 0.16666667 4.629630e-03 0.50000000 0.66666667 0.33333333 4.629630e-03 0.50000000 0.66666667 0.50000000 4.629630e-03 0.50000000 0.66666667 0.66666667 4.629630e-03 0.50000000 0.66666667 0.83333333 4.629630e-03 0.50000000 0.83333333 0.00000000 4.629630e-03 0.50000000 0.83333333 0.16666667 4.629630e-03 0.50000000 0.83333333 0.33333333 4.629630e-03 0.50000000 0.83333333 0.50000000 4.629630e-03 0.50000000 0.83333333 0.66666667 4.629630e-03 0.50000000 0.83333333 0.83333333 4.629630e-03 0.66666667 0.00000000 0.00000000 4.629630e-03 0.66666667 0.00000000 0.16666667 4.629630e-03 0.66666667 0.00000000 0.33333333 4.629630e-03 0.66666667 0.00000000 0.50000000 4.629630e-03 0.66666667 0.00000000 0.66666667 4.629630e-03 0.66666667 0.00000000 0.83333333 4.629630e-03 0.66666667 0.16666667 0.00000000 4.629630e-03 0.66666667 0.16666667 0.16666667 4.629630e-03 0.66666667 0.16666667 0.33333333 4.629630e-03 0.66666667 0.16666667 0.50000000 4.629630e-03 0.66666667 0.16666667 0.66666667 4.629630e-03 0.66666667 0.16666667 0.83333333 4.629630e-03 0.66666667 0.33333333 0.00000000 4.629630e-03 0.66666667 0.33333333 0.16666667 4.629630e-03 0.66666667 0.33333333 0.33333333 4.629630e-03 0.66666667 0.33333333 0.50000000 4.629630e-03 0.66666667 0.33333333 0.66666667 4.629630e-03 0.66666667 0.33333333 0.83333333 4.629630e-03 0.66666667 0.50000000 0.00000000 4.629630e-03 0.66666667 0.50000000 0.16666667 4.629630e-03 0.66666667 0.50000000 0.33333333 4.629630e-03 0.66666667 0.50000000 0.50000000 4.629630e-03 0.66666667 0.50000000 0.66666667 4.629630e-03 0.66666667 0.50000000 0.83333333 4.629630e-03 0.66666667 0.66666667 0.00000000 4.629630e-03 0.66666667 0.66666667 0.16666667 4.629630e-03 0.66666667 0.66666667 0.33333333 4.629630e-03 0.66666667 0.66666667 0.50000000 4.629630e-03 0.66666667 0.66666667 0.66666667 4.629630e-03 0.66666667 0.66666667 0.83333333 4.629630e-03 0.66666667 0.83333333 0.00000000 4.629630e-03 0.66666667 0.83333333 0.16666667 4.629630e-03 0.66666667 0.83333333 0.33333333 4.629630e-03 0.66666667 0.83333333 0.50000000 4.629630e-03 0.66666667 0.83333333 0.66666667 4.629630e-03 0.66666667 0.83333333 0.83333333 4.629630e-03 0.83333333 0.00000000 0.00000000 4.629630e-03 0.83333333 0.00000000 0.16666667 4.629630e-03 0.83333333 0.00000000 0.33333333 4.629630e-03 0.83333333 0.00000000 0.50000000 4.629630e-03 0.83333333 0.00000000 0.66666667 4.629630e-03 0.83333333 0.00000000 0.83333333 4.629630e-03 0.83333333 0.16666667 0.00000000 4.629630e-03 0.83333333 0.16666667 0.16666667 4.629630e-03 0.83333333 0.16666667 0.33333333 4.629630e-03 0.83333333 0.16666667 0.50000000 4.629630e-03 0.83333333 0.16666667 0.66666667 4.629630e-03 0.83333333 0.16666667 0.83333333 4.629630e-03 0.83333333 0.33333333 0.00000000 4.629630e-03 0.83333333 0.33333333 0.16666667 4.629630e-03 0.83333333 0.33333333 0.33333333 4.629630e-03 0.83333333 0.33333333 0.50000000 4.629630e-03 0.83333333 0.33333333 0.66666667 4.629630e-03 0.83333333 0.33333333 0.83333333 4.629630e-03 0.83333333 0.50000000 0.00000000 4.629630e-03 0.83333333 0.50000000 0.16666667 4.629630e-03 0.83333333 0.50000000 0.33333333 4.629630e-03 0.83333333 0.50000000 0.50000000 4.629630e-03 0.83333333 0.50000000 0.66666667 4.629630e-03 0.83333333 0.50000000 0.83333333 4.629630e-03 0.83333333 0.66666667 0.00000000 4.629630e-03 0.83333333 0.66666667 0.16666667 4.629630e-03 0.83333333 0.66666667 0.33333333 4.629630e-03 0.83333333 0.66666667 0.50000000 4.629630e-03 0.83333333 0.66666667 0.66666667 4.629630e-03 0.83333333 0.66666667 0.83333333 4.629630e-03 0.83333333 0.83333333 0.00000000 4.629630e-03 0.83333333 0.83333333 0.16666667 4.629630e-03 0.83333333 0.83333333 0.33333333 4.629630e-03 0.83333333 0.83333333 0.50000000 4.629630e-03 0.83333333 0.83333333 0.66666667 4.629630e-03 0.83333333 0.83333333 0.83333333 4.629630e-03
{ "pile_set_name": "Github" }
package com.lyq.model; /** * 支付方式 * @author Li Yongqiang */ public enum PaymentWay { NET_BANK{ @Override public String getName() { return "网上银行支付"; } }, ALIPAY{ @Override public String getName() { return "支付宝"; } }, FINISH_PAY{ @Override public String getName() { return "货到付款"; } }, POSTOFFICE_PAY{ @Override public String getName() { return "邮局汇款"; } }; public abstract String getName(); }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.nn.graph.vertex.impl; import org.deeplearning4j.nn.api.Layer; import org.deeplearning4j.nn.api.MaskState; import org.deeplearning4j.nn.gradient.Gradient; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.nn.graph.vertex.BaseGraphVertex; import org.deeplearning4j.nn.graph.vertex.VertexIndices; import org.nd4j.linalg.api.buffer.DataType; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.indexing.INDArrayIndex; import org.nd4j.linalg.indexing.NDArrayIndex; import org.nd4j.common.primitives.Pair; import org.deeplearning4j.nn.workspace.ArrayType; import org.deeplearning4j.nn.workspace.LayerWorkspaceMgr; import java.util.Arrays; /** SubsetVertex is used to select a subset of the activations out of another GraphVertex.<br> * For example, a subset of the activations out of a layer.<br> * Note that this subset is specifying by means of an interval of the original activations. * For example, to get the first 10 activations of a layer (or, first 10 features out of a CNN layer) use * new SubsetVertex(0,9).<br> * In the case of convolutional (4d) activations, this is done along channels. * @author Alex Black */ public class SubsetVertex extends BaseGraphVertex { private int from; private int to; //inclusive private long[] forwardShape; public SubsetVertex(ComputationGraph graph, String name, int vertexIndex, int from, int to, DataType dataType) { this(graph, name, vertexIndex, null, null, from, to, dataType); } public SubsetVertex(ComputationGraph graph, String name, int vertexIndex, VertexIndices[] inputVertices, VertexIndices[] outputVertices, int from, int to, DataType dataType) { super(graph, name, vertexIndex, inputVertices, outputVertices, dataType); this.from = from; this.to = to; } @Override public boolean hasLayer() { return false; } @Override public Layer getLayer() { return null; } @Override public INDArray doForward(boolean training, LayerWorkspaceMgr workspaceMgr) { if (!canDoForward()) throw new IllegalStateException("Cannot do forward pass: input not set"); forwardShape = Arrays.copyOf(inputs[0].shape(), inputs[0].rank()); INDArray out; switch (inputs[0].rank()) { case 2: out = inputs[0].get(NDArrayIndex.all(), NDArrayIndex.interval(from, to, true)); break; case 3: out = inputs[0].get(NDArrayIndex.all(), NDArrayIndex.interval(from, to, true), NDArrayIndex.all()); break; case 4: out = inputs[0].get(NDArrayIndex.all(), NDArrayIndex.interval(from, to, true), NDArrayIndex.all(), NDArrayIndex.all()); break; default: throw new UnsupportedOperationException( "Cannot get subset for activations of rank " + inputs[0].rank()); } return workspaceMgr.dup(ArrayType.ACTIVATIONS, out); } @Override public Pair<Gradient, INDArray[]> doBackward(boolean tbptt, LayerWorkspaceMgr workspaceMgr) { if (!canDoBackward()) throw new IllegalStateException("Cannot do backward pass: error not set"); INDArray out = workspaceMgr.create(ArrayType.ACTIVATION_GRAD, epsilon.dataType(), forwardShape); switch (forwardShape.length) { case 2: out.put(new INDArrayIndex[] {NDArrayIndex.all(), NDArrayIndex.interval(from, to, true)}, epsilon); break; case 3: out.put(new INDArrayIndex[] {NDArrayIndex.all(), NDArrayIndex.interval(from, to, true), NDArrayIndex.all()}, epsilon); break; case 4: out.put(new INDArrayIndex[] {NDArrayIndex.all(), NDArrayIndex.interval(from, to, true), NDArrayIndex.all(), NDArrayIndex.all()}, epsilon); break; default: throw new RuntimeException("Invalid activation rank"); //Should never happen } return new Pair<>(null, new INDArray[] {out}); } @Override public String toString() { return "SubsetVertex(id=" + this.getVertexIndex() + ",name=\"" + this.getVertexName() + "\",fromIdx=" + from + ",toIdx=" + to + ")"; } @Override public void setBackpropGradientsViewArray(INDArray backpropGradientsViewArray) { if (backpropGradientsViewArray != null) throw new RuntimeException("Vertex does not have gradients; gradients view array cannot be set here"); } @Override public Pair<INDArray, MaskState> feedForwardMaskArrays(INDArray[] maskArrays, MaskState currentMaskState, int minibatchSize) { //No op: subset just provides part of the activations for each example (or time step) if (maskArrays == null || maskArrays.length == 0) { return null; } return new Pair<>(maskArrays[0], currentMaskState); } }
{ "pile_set_name": "Github" }
{ "welcome": "Benvenuto" }
{ "pile_set_name": "Github" }
# Manual test Node.js ## Installation In the plugin directory: `npm link` `cd manual_test_nodejs` `npm link serverless-offline` ## Testing signals `node subprocess.js` It should stop after 10 seconds with the proper halting message ## Testing resource proxy `npm start -- --resourceRoutes`
{ "pile_set_name": "Github" }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> int main (int argc, char *argv[]) { int s, len, o, port = 6666; char buf[512]; struct sockaddr_in addr; socklen_t addr_len = sizeof addr; if (argc > 1) port = atoi (argv[1]); s = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP); o = 1; len = 4; setsockopt (3, SOL_SOCKET, SO_REUSEADDR, &o, len); addr.sin_family = AF_INET; addr.sin_port = htons (port); addr.sin_addr.s_addr = INADDR_ANY; /* receive broadcasts */ bind (s, (struct sockaddr *) &addr, sizeof addr); for (;;) { len = recvfrom (s, buf, sizeof buf, 0, (struct sockaddr *) &addr, &addr_len); if (len < 0) break; if (write (1, buf, len) != len) fprintf(stderr, "WARNING: serial characters dropped\n"); } return 0; }
{ "pile_set_name": "Github" }
use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ok() .expect("Failed to read line"); println!("You guessed: {}", guess); }
{ "pile_set_name": "Github" }
// // Header.h // DJISDKSwiftDemo // // Created by DJI on 2019/1/15. // Copyright © 2019 DJI. All rights reserved. // #ifndef Header_h #define Header_h #import "DJIWidget/DJIWidget.h" #import "DJISDK/DJISDK.h" #endif /* Header_h */
{ "pile_set_name": "Github" }
/* * Copyright 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "sdk/android/src/jni/pc/rtp_parameters.h" #include "sdk/android/generated_peerconnection_jni/RtpParameters_jni.h" #include "sdk/android/native_api/jni/java_types.h" #include "sdk/android/src/jni/jni_helpers.h" #include "sdk/android/src/jni/pc/media_stream_track.h" namespace webrtc { namespace jni { namespace { webrtc::DegradationPreference JavaToNativeDegradationPreference( JNIEnv* jni, const JavaRef<jobject>& j_degradation_preference) { std::string enum_name = GetJavaEnumName(jni, j_degradation_preference); if (enum_name == "DISABLED") return webrtc::DegradationPreference::DISABLED; if (enum_name == "MAINTAIN_FRAMERATE") return webrtc::DegradationPreference::MAINTAIN_FRAMERATE; if (enum_name == "MAINTAIN_RESOLUTION") return webrtc::DegradationPreference::MAINTAIN_RESOLUTION; if (enum_name == "BALANCED") return webrtc::DegradationPreference::BALANCED; RTC_CHECK(false) << "Unexpected DegradationPreference enum_name " << enum_name; return webrtc::DegradationPreference::DISABLED; } ScopedJavaLocalRef<jobject> NativeToJavaRtpEncodingParameter( JNIEnv* env, const RtpEncodingParameters& encoding) { return Java_Encoding_Constructor( env, NativeToJavaString(env, encoding.rid), encoding.active, encoding.bitrate_priority, static_cast<int>(encoding.network_priority), NativeToJavaInteger(env, encoding.max_bitrate_bps), NativeToJavaInteger(env, encoding.min_bitrate_bps), NativeToJavaInteger(env, encoding.max_framerate), NativeToJavaInteger(env, encoding.num_temporal_layers), NativeToJavaDouble(env, encoding.scale_resolution_down_by), encoding.ssrc ? NativeToJavaLong(env, *encoding.ssrc) : nullptr); } ScopedJavaLocalRef<jobject> NativeToJavaRtpCodecParameter( JNIEnv* env, const RtpCodecParameters& codec) { return Java_Codec_Constructor(env, codec.payload_type, NativeToJavaString(env, codec.name), NativeToJavaMediaType(env, codec.kind), NativeToJavaInteger(env, codec.clock_rate), NativeToJavaInteger(env, codec.num_channels), NativeToJavaStringMap(env, codec.parameters)); } ScopedJavaLocalRef<jobject> NativeToJavaRtpRtcpParameters( JNIEnv* env, const RtcpParameters& rtcp) { return Java_Rtcp_Constructor(env, NativeToJavaString(env, rtcp.cname), rtcp.reduced_size); } ScopedJavaLocalRef<jobject> NativeToJavaRtpHeaderExtensionParameter( JNIEnv* env, const RtpExtension& extension) { return Java_HeaderExtension_Constructor( env, NativeToJavaString(env, extension.uri), extension.id, extension.encrypt); } } // namespace RtpEncodingParameters JavaToNativeRtpEncodingParameters( JNIEnv* jni, const JavaRef<jobject>& j_encoding_parameters) { RtpEncodingParameters encoding; ScopedJavaLocalRef<jstring> j_rid = Java_Encoding_getRid(jni, j_encoding_parameters); if (!IsNull(jni, j_rid)) { encoding.rid = JavaToNativeString(jni, j_rid); } encoding.active = Java_Encoding_getActive(jni, j_encoding_parameters); ScopedJavaLocalRef<jobject> j_max_bitrate = Java_Encoding_getMaxBitrateBps(jni, j_encoding_parameters); encoding.bitrate_priority = Java_Encoding_getBitratePriority(jni, j_encoding_parameters); encoding.network_priority = static_cast<webrtc::Priority>( Java_Encoding_getNetworkPriority(jni, j_encoding_parameters)); encoding.max_bitrate_bps = JavaToNativeOptionalInt(jni, j_max_bitrate); ScopedJavaLocalRef<jobject> j_min_bitrate = Java_Encoding_getMinBitrateBps(jni, j_encoding_parameters); encoding.min_bitrate_bps = JavaToNativeOptionalInt(jni, j_min_bitrate); ScopedJavaLocalRef<jobject> j_max_framerate = Java_Encoding_getMaxFramerate(jni, j_encoding_parameters); encoding.max_framerate = JavaToNativeOptionalInt(jni, j_max_framerate); ScopedJavaLocalRef<jobject> j_num_temporal_layers = Java_Encoding_getNumTemporalLayers(jni, j_encoding_parameters); encoding.num_temporal_layers = JavaToNativeOptionalInt(jni, j_num_temporal_layers); ScopedJavaLocalRef<jobject> j_scale_resolution_down_by = Java_Encoding_getScaleResolutionDownBy(jni, j_encoding_parameters); encoding.scale_resolution_down_by = JavaToNativeOptionalDouble(jni, j_scale_resolution_down_by); ScopedJavaLocalRef<jobject> j_ssrc = Java_Encoding_getSsrc(jni, j_encoding_parameters); if (!IsNull(jni, j_ssrc)) encoding.ssrc = JavaToNativeLong(jni, j_ssrc); return encoding; } RtpParameters JavaToNativeRtpParameters(JNIEnv* jni, const JavaRef<jobject>& j_parameters) { RtpParameters parameters; ScopedJavaLocalRef<jstring> j_transaction_id = Java_RtpParameters_getTransactionId(jni, j_parameters); parameters.transaction_id = JavaToNativeString(jni, j_transaction_id); ScopedJavaLocalRef<jobject> j_degradation_preference = Java_RtpParameters_getDegradationPreference(jni, j_parameters); if (!IsNull(jni, j_degradation_preference)) { parameters.degradation_preference = JavaToNativeDegradationPreference(jni, j_degradation_preference); } ScopedJavaLocalRef<jobject> j_rtcp = Java_RtpParameters_getRtcp(jni, j_parameters); ScopedJavaLocalRef<jstring> j_rtcp_cname = Java_Rtcp_getCname(jni, j_rtcp); jboolean j_rtcp_reduced_size = Java_Rtcp_getReducedSize(jni, j_rtcp); parameters.rtcp.cname = JavaToNativeString(jni, j_rtcp_cname); parameters.rtcp.reduced_size = j_rtcp_reduced_size; ScopedJavaLocalRef<jobject> j_header_extensions = Java_RtpParameters_getHeaderExtensions(jni, j_parameters); for (const JavaRef<jobject>& j_header_extension : Iterable(jni, j_header_extensions)) { RtpExtension header_extension; header_extension.uri = JavaToStdString( jni, Java_HeaderExtension_getUri(jni, j_header_extension)); header_extension.id = Java_HeaderExtension_getId(jni, j_header_extension); header_extension.encrypt = Java_HeaderExtension_getEncrypted(jni, j_header_extension); parameters.header_extensions.push_back(header_extension); } // Convert encodings. ScopedJavaLocalRef<jobject> j_encodings = Java_RtpParameters_getEncodings(jni, j_parameters); for (const JavaRef<jobject>& j_encoding_parameters : Iterable(jni, j_encodings)) { RtpEncodingParameters encoding = JavaToNativeRtpEncodingParameters(jni, j_encoding_parameters); parameters.encodings.push_back(encoding); } // Convert codecs. ScopedJavaLocalRef<jobject> j_codecs = Java_RtpParameters_getCodecs(jni, j_parameters); for (const JavaRef<jobject>& j_codec : Iterable(jni, j_codecs)) { RtpCodecParameters codec; codec.payload_type = Java_Codec_getPayloadType(jni, j_codec); codec.name = JavaToStdString(jni, Java_Codec_getName(jni, j_codec)); codec.kind = JavaToNativeMediaType(jni, Java_Codec_getKind(jni, j_codec)); codec.clock_rate = JavaToNativeOptionalInt(jni, Java_Codec_getClockRate(jni, j_codec)); codec.num_channels = JavaToNativeOptionalInt(jni, Java_Codec_getNumChannels(jni, j_codec)); auto parameters_map = JavaToNativeStringMap(jni, Java_Codec_getParameters(jni, j_codec)); codec.parameters.insert(parameters_map.begin(), parameters_map.end()); parameters.codecs.push_back(codec); } return parameters; } ScopedJavaLocalRef<jobject> NativeToJavaRtpParameters( JNIEnv* env, const RtpParameters& parameters) { return Java_RtpParameters_Constructor( env, NativeToJavaString(env, parameters.transaction_id), parameters.degradation_preference.has_value() ? Java_DegradationPreference_fromNativeIndex( env, static_cast<int>(*parameters.degradation_preference)) : nullptr, NativeToJavaRtpRtcpParameters(env, parameters.rtcp), NativeToJavaList(env, parameters.header_extensions, &NativeToJavaRtpHeaderExtensionParameter), NativeToJavaList(env, parameters.encodings, &NativeToJavaRtpEncodingParameter), NativeToJavaList(env, parameters.codecs, &NativeToJavaRtpCodecParameter)); } } // namespace jni } // namespace webrtc
{ "pile_set_name": "Github" }
[Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US' $Host.UI.RawUI.WindowTitle = "PowerShell" colortool.exe -c Set-Location c:\
{ "pile_set_name": "Github" }
{% extends '_base.html' %} {% load helpers %} {% load form_helpers %} {% block breadcrumb %}<li class="breadcrumb-item active" aria-current="page">{% block title %}Editing {{ table.rows|length }} {{ object_type_plural|title_with_uppers }}{% endblock %}</li>{% endblock %} {% block content %} <form action="" method="post" class="form form-horizontal"> {% csrf_token %} {% if request.POST.return_url %} <input type="hidden" name="return_url" value="{{ request.POST.return_url }}" /> {% endif %} {% for field in form.hidden_fields %} {{ field }} {% endfor %} <div class="row justify-content-center"> <div class="col-8"> <div class="panel panel-default"> {% include 'utils/responsive_table.html' %} </div> </div> <div class="col-4"> {% if form.non_field_errors %} <div class="card bg-danger text-white my-2"> <div class="card-header"><strong>Errors</strong></div> <div class="card-body"> {{ form.non_field_errors }} </div> </div> {% endif %} <div class="card"> <div class="card-header"><strong>{% block form_title %}Attributes{% endblock %}</strong></div> <div class="card-body"> {% for field in form.visible_fields %} {% if field.name in form.nullable_fields %} {% render_field field bulk_nullable=True %} {% else %} {% render_field field %} {% endif %} {% endfor %} </div> </div> <div class="form-group text-right"> <div class="col-12 mt-2"> <button type="submit" name="_apply" class="btn btn-primary">Apply</button> <a href="{{ return_url }}" class="btn btn-secondary">Cancel</a> </div> </div> </div> </div> </form> {% endblock %}
{ "pile_set_name": "Github" }
# the index exports the most recent version of the engine module.exports = require('./0.9.x')
{ "pile_set_name": "Github" }
package yaml import ( "reflect" "unicode" ) type keyList []reflect.Value func (l keyList) Len() int { return len(l) } func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (l keyList) Less(i, j int) bool { a := l[i] b := l[j] ak := a.Kind() bk := b.Kind() for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { a = a.Elem() ak = a.Kind() } for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { b = b.Elem() bk = b.Kind() } af, aok := keyFloat(a) bf, bok := keyFloat(b) if aok && bok { if af != bf { return af < bf } if ak != bk { return ak < bk } return numLess(a, b) } if ak != reflect.String || bk != reflect.String { return ak < bk } ar, br := []rune(a.String()), []rune(b.String()) for i := 0; i < len(ar) && i < len(br); i++ { if ar[i] == br[i] { continue } al := unicode.IsLetter(ar[i]) bl := unicode.IsLetter(br[i]) if al && bl { return ar[i] < br[i] } if al || bl { return bl } var ai, bi int var an, bn int64 if ar[i] == '0' || br[i] == '0' { for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { if ar[j] != '0' { an = 1 bn = 1 break } } } for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { an = an*10 + int64(ar[ai]-'0') } for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { bn = bn*10 + int64(br[bi]-'0') } if an != bn { return an < bn } if ai != bi { return ai < bi } return ar[i] < br[i] } return len(ar) < len(br) } // keyFloat returns a float value for v if it is a number/bool // and whether it is a number/bool or not. func keyFloat(v reflect.Value) (f float64, ok bool) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return float64(v.Int()), true case reflect.Float32, reflect.Float64: return v.Float(), true case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return float64(v.Uint()), true case reflect.Bool: if v.Bool() { return 1, true } return 0, true } return 0, false } // numLess returns whether a < b. // a and b must necessarily have the same kind. func numLess(a, b reflect.Value) bool { switch a.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return a.Int() < b.Int() case reflect.Float32, reflect.Float64: return a.Float() < b.Float() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return a.Uint() < b.Uint() case reflect.Bool: return !a.Bool() && b.Bool() } panic("not a number") }
{ "pile_set_name": "Github" }
<div class="site-content"> <div class="d-flex flex-md-row flex-items-center stafftools-page-header"> <div class="col-1"> <span class="assignment-icon assignment-icon-group left"> <%= octicon 'organization', height: 22 %> </span> </div> <div class="col-10 col-md-10 d-flex flex-column"> <h2 class="stafftools-heading"> <%= @group.title %> </h2> <p class="assignment-type text-gray"><%= t('views.stafftools.groups.group') %></p> </div> </div> <div class="boxed-group"> <h3>Info</h3> <div class="boxed-group-inner"> <table> <tr> <td class="text-emphasized"><%= t('views.stafftools.groups.id') %></td> <td><%= @group.id %></td> </tr> <tr> <td class="text-emphasized"><%= t('views.stafftools.groups.owner') %></td> <td><%= link_to @group.organization.title, stafftools_organization_path(@group.organization.id) %></td> </tr> <tr> <td class="text-emphasized"><%= t('views.stafftools.groups.grouping') %></td> <td><%= link_to @group.grouping.title, stafftools_grouping_path(@group.grouping.id) %></td> </tr> <tr> <td class="text-emphasized"><%= t('views.stafftools.groups.github_url') %></td> <td><%= link_to @group.github_team.html_url, @group.github_team.html_url %></td> </tr> <tr> <td class="text-emphasized"><%= t('views.stafftools.groups.created_on') %></td> <td><%= local_time(@group.created_at) %></td> </tr> </table> </div> </div> <% if @group.repo_accesses.present? %> <div class="boxed-group"> <h3><%= t('views.stafftools.groups.team_members') %></h3> <div class="boxed-group-inner"> <ul class="boxed-group-list standalone"> <% @group.repo_accesses.each do |repo_access| %> <li class="clearfix"> <%= render partial: 'stafftools/organizations/user', locals: { user: repo_access.user } %> </li> <% end %> </ul> </div> </div> <% end %> <div class="boxed-group dangerzone"> <h3>Dangerzone</h3> <div class="boxed-group-inner"> <p> <a data-remodal-target="delete-group" class="btn btn-danger">Delete this group</a> </p> <div class="remodal text-left" data-remodal-id="delete-group"> <button data-remodal-action="close" class="remodal-close"><%= octicon 'x' %></button> <h2 class="remodal-header">Are you ABSOLUTELY sure?</h2> <div class="remodal-warning"> Unexpected things will happen if you don't read this! </div> <div class="remodal-description"> <p> This action <strong>CANNOT</strong> be undone.<br> Please note this will delete the record on GitHub Classroom and the team on GitHub, but not the repository on GitHub. </p> </div> <%= form_for @group, url: stafftools_group_path(@group.id), html: { "data-name" => @group.id, method: 'delete' } do |f| %> <dl class="form js-normalize-submit"> <dt>Please type the ID (<%= @group.id %>) of the group to confirm</dt> <dd><input type="text" class="js-input-block" autofocus></dd> </dl> <%= f.submit 'Delete this Group', class: 'btn btn-danger btn-block js-submit', disabled: true %> <% end %> </div> </div> </div> </div>
{ "pile_set_name": "Github" }
package com.insightfullogic.slab.classes; import com.insightfullogic.slab.Cursor; public abstract class ClassWithoutInherit implements Cursor { public abstract int getId(); public abstract void setId(int value); }
{ "pile_set_name": "Github" }
<?php namespace Negotiation\Tests; use Negotiation\BaseAccept; class BaseAcceptTest extends TestCase { /** * @dataProvider dataProviderForParseParameters */ public function testParseParameters($value, $expected) { $accept = new DummyAccept($value); $parameters = $accept->getParameters(); // TODO: hack-ish... this is needed because logic in BaseAccept //constructor drops the quality from the parameter set. if (false !== strpos($value, 'q')) { $parameters['q'] = $accept->getQuality(); } $this->assertCount(count($expected), $parameters); foreach ($expected as $key => $value) { $this->assertArrayHasKey($key, $parameters); $this->assertEquals($value, $parameters[$key]); } } public static function dataProviderForParseParameters() { return array( array( 'application/json ;q=1.0; level=2;foo= bar', array( 'q' => 1.0, 'level' => 2, 'foo' => 'bar', ), ), array( 'application/json ;q = 1.0; level = 2; FOO = bAr', array( 'q' => 1.0, 'level' => 2, 'foo' => 'bAr', ), ), array( 'application/json;q=1.0', array( 'q' => 1.0, ), ), array( 'application/json;foo', array(), ), ); } /** * @dataProvider dataProviderBuildParametersString */ public function testBuildParametersString($value, $expected) { $accept = new DummyAccept($value); $this->assertEquals($expected, $accept->getNormalizedValue()); } public static function dataProviderBuildParametersString() { return array( array('media/type; xxx = 1.0;level=2;foo=bar', 'media/type; foo=bar; level=2; xxx=1.0'), ); } } class DummyAccept extends BaseAccept { }
{ "pile_set_name": "Github" }
/* PROJ.4 Cartographic Projection System */ #define MAX_ITER 10 #define DEL_TOL 1e-12 #define PROJ_PARMS__ \ double *en; \ double r0, l, M0; \ double C; #define PJ_LIB__ #include <projects.h> PROJ_HEAD(lcca, "Lambert Conformal Conic Alternative") "\n\tConic, Sph&Ell\n\tlat_0="; static double /* func to compute dr */ fS(double S, double C) { return(S * ( 1. + S * S * C)); } static double /* deriv of fs */ fSp(double S, double C) { return(1. + 3.* S * S * C); } FORWARD(e_forward); /* ellipsoid */ double S, r, dr; S = pj_mlfn(lp.phi, sin(lp.phi), cos(lp.phi), P->en) - P->M0; dr = fS(S, P->C); r = P->r0 - dr; xy.x = P->k0 * (r * sin( lp.lam *= P->l ) ); xy.y = P->k0 * (P->r0 - r * cos(lp.lam) ); return (xy); } INVERSE(e_inverse); /* ellipsoid & spheroid */ double theta, dr, S, dif; int i; xy.x /= P->k0; xy.y /= P->k0; theta = atan2(xy.x , P->r0 - xy.y); dr = xy.y - xy.x * tan(0.5 * theta); lp.lam = theta / P->l; S = dr; for (i = MAX_ITER; i ; --i) { S -= (dif = (fS(S, P->C) - dr) / fSp(S, P->C)); if (fabs(dif) < DEL_TOL) break; } if (!i) I_ERROR lp.phi = pj_inv_mlfn(P->ctx, S + P->M0, P->es, P->en); return (lp); } FREEUP; if (P) { if (P->en) pj_dalloc(P->en); pj_dalloc(P); } } ENTRY0(lcca) double s2p0, N0, R0, tan0; if (!(P->en = pj_enfn(P->es))) E_ERROR_0; if (!pj_param(P->ctx, P->params, "tlat_0").i) E_ERROR(50); if (P->phi0 == 0.) E_ERROR(51); P->l = sin(P->phi0); P->M0 = pj_mlfn(P->phi0, P->l, cos(P->phi0), P->en); s2p0 = P->l * P->l; R0 = 1. / (1. - P->es * s2p0); N0 = sqrt(R0); R0 *= P->one_es * N0; tan0 = tan(P->phi0); P->r0 = N0 / tan0; P->C = 1. / (6. * R0 * N0); P->inv = e_inverse; P->fwd = e_forward; ENDENTRY(P)
{ "pile_set_name": "Github" }
/* arch/arm/mach-msm/generic_gpio.c * * Copyright (C) 2007 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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. * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <asm/gpio.h> #include "gpio_chip.h" #define GPIO_NUM_TO_CHIP_INDEX(gpio) ((gpio)>>5) struct gpio_state { unsigned long flags; int refcount; }; static DEFINE_SPINLOCK(gpio_chips_lock); static LIST_HEAD(gpio_chip_list); static struct gpio_chip **gpio_chip_array; static unsigned long gpio_chip_array_size; int register_gpio_chip(struct gpio_chip *new_gpio_chip) { int err = 0; struct gpio_chip *gpio_chip; int i; unsigned long irq_flags; unsigned int chip_array_start_index, chip_array_end_index; new_gpio_chip->state = kzalloc((new_gpio_chip->end + 1 - new_gpio_chip->start) * sizeof(new_gpio_chip->state[0]), GFP_KERNEL); if (new_gpio_chip->state == NULL) { printk(KERN_ERR "register_gpio_chip: failed to allocate state\n"); return -ENOMEM; } spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip_array_start_index = GPIO_NUM_TO_CHIP_INDEX(new_gpio_chip->start); chip_array_end_index = GPIO_NUM_TO_CHIP_INDEX(new_gpio_chip->end); if (chip_array_end_index >= gpio_chip_array_size) { struct gpio_chip **new_gpio_chip_array; unsigned long new_gpio_chip_array_size = chip_array_end_index + 1; new_gpio_chip_array = kmalloc(new_gpio_chip_array_size * sizeof(new_gpio_chip_array[0]), GFP_ATOMIC); if (new_gpio_chip_array == NULL) { printk(KERN_ERR "register_gpio_chip: failed to allocate array\n"); err = -ENOMEM; goto failed; } for (i = 0; i < gpio_chip_array_size; i++) new_gpio_chip_array[i] = gpio_chip_array[i]; for (i = gpio_chip_array_size; i < new_gpio_chip_array_size; i++) new_gpio_chip_array[i] = NULL; gpio_chip_array = new_gpio_chip_array; gpio_chip_array_size = new_gpio_chip_array_size; } list_for_each_entry(gpio_chip, &gpio_chip_list, list) { if (gpio_chip->start > new_gpio_chip->end) { list_add_tail(&new_gpio_chip->list, &gpio_chip->list); goto added; } if (gpio_chip->end >= new_gpio_chip->start) { printk(KERN_ERR "register_gpio_source %u-%u overlaps with %u-%u\n", new_gpio_chip->start, new_gpio_chip->end, gpio_chip->start, gpio_chip->end); err = -EBUSY; goto failed; } } list_add_tail(&new_gpio_chip->list, &gpio_chip_list); added: for (i = chip_array_start_index; i <= chip_array_end_index; i++) { if (gpio_chip_array[i] == NULL || gpio_chip_array[i]->start > new_gpio_chip->start) gpio_chip_array[i] = new_gpio_chip; } failed: spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); if (err) kfree(new_gpio_chip->state); return err; } static struct gpio_chip *get_gpio_chip_locked(unsigned int gpio) { unsigned long i; struct gpio_chip *chip; i = GPIO_NUM_TO_CHIP_INDEX(gpio); if (i >= gpio_chip_array_size) return NULL; chip = gpio_chip_array[i]; if (chip == NULL) return NULL; list_for_each_entry_from(chip, &gpio_chip_list, list) { if (gpio < chip->start) return NULL; if (gpio <= chip->end) return chip; } return NULL; } static int request_gpio(unsigned int gpio, unsigned long flags) { int err = 0; struct gpio_chip *chip; unsigned long irq_flags; unsigned long chip_index; spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip = get_gpio_chip_locked(gpio); if (chip == NULL) { err = -EINVAL; goto err; } chip_index = gpio - chip->start; if (chip->state[chip_index].refcount == 0) { chip->configure(chip, gpio, flags); chip->state[chip_index].flags = flags; chip->state[chip_index].refcount++; } else if ((flags & IRQF_SHARED) && (chip->state[chip_index].flags & IRQF_SHARED)) chip->state[chip_index].refcount++; else err = -EBUSY; err: spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); return err; } int gpio_request(unsigned gpio, const char *label) { return request_gpio(gpio, 0); } EXPORT_SYMBOL(gpio_request); void gpio_free(unsigned gpio) { struct gpio_chip *chip; unsigned long irq_flags; unsigned long chip_index; spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip = get_gpio_chip_locked(gpio); if (chip) { chip_index = gpio - chip->start; chip->state[chip_index].refcount--; } spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); } EXPORT_SYMBOL(gpio_free); static int gpio_get_irq_num(unsigned int gpio, unsigned int *irqp, unsigned long *irqnumflagsp) { int ret = -ENOTSUPP; struct gpio_chip *chip; unsigned long irq_flags; spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip = get_gpio_chip_locked(gpio); if (chip && chip->get_irq_num) ret = chip->get_irq_num(chip, gpio, irqp, irqnumflagsp); spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); return ret; } int gpio_to_irq(unsigned gpio) { int ret, irq; ret = gpio_get_irq_num(gpio, &irq, NULL); if (ret) return ret; return irq; } EXPORT_SYMBOL(gpio_to_irq); int gpio_configure(unsigned int gpio, unsigned long flags) { int ret = -ENOTSUPP; struct gpio_chip *chip; unsigned long irq_flags; spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip = get_gpio_chip_locked(gpio); if (chip) ret = chip->configure(chip, gpio, flags); spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); return ret; } EXPORT_SYMBOL(gpio_configure); int gpio_direction_input(unsigned gpio) { return gpio_configure(gpio, GPIOF_INPUT); } EXPORT_SYMBOL(gpio_direction_input); int gpio_direction_output(unsigned gpio, int value) { gpio_set_value(gpio, value); return gpio_configure(gpio, GPIOF_DRIVE_OUTPUT); } EXPORT_SYMBOL(gpio_direction_output); int gpio_get_value(unsigned gpio) { int ret = -ENOTSUPP; struct gpio_chip *chip; unsigned long irq_flags; spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip = get_gpio_chip_locked(gpio); if (chip && chip->read) ret = chip->read(chip, gpio); spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); return ret; } EXPORT_SYMBOL(gpio_get_value); void gpio_set_value(unsigned gpio, int on) { int ret = -ENOTSUPP; struct gpio_chip *chip; unsigned long irq_flags; spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip = get_gpio_chip_locked(gpio); if (chip && chip->write) ret = chip->write(chip, gpio, on); spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); } EXPORT_SYMBOL(gpio_set_value); int gpio_read_detect_status(unsigned int gpio) { int ret = -ENOTSUPP; struct gpio_chip *chip; unsigned long irq_flags; spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip = get_gpio_chip_locked(gpio); if (chip && chip->read_detect_status) ret = chip->read_detect_status(chip, gpio); spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); return ret; } EXPORT_SYMBOL(gpio_read_detect_status); int gpio_clear_detect_status(unsigned int gpio) { int ret = -ENOTSUPP; struct gpio_chip *chip; unsigned long irq_flags; spin_lock_irqsave(&gpio_chips_lock, irq_flags); chip = get_gpio_chip_locked(gpio); if (chip && chip->clear_detect_status) ret = chip->clear_detect_status(chip, gpio); spin_unlock_irqrestore(&gpio_chips_lock, irq_flags); return ret; } EXPORT_SYMBOL(gpio_clear_detect_status);
{ "pile_set_name": "Github" }
<?php define('IN_CB', true); include('include/header.php'); registerImageKey('code', 'BCGcode11'); $characters = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'); ?> <div id="validCharacters"> <h3>Valid Characters</h3> <?php foreach ($characters as $character) { echo getButton($character); } ?> </div> <div id="explanation"> <h3>Explanation</h3> <ul> <li>Known also as USD-8.</li> <li>Code 11 was developed in 1977 as a high-density numeric symbology.</li> <li>Used to identify telecommunications equipment.</li> <li>Code 11 is a numeric symbology and its character set consists of 10 digital characters and the dash symbol (-).</li> <li>There is a "C" check digit. If the length of encoded message is greater thant 10, a "K" check digit may be used.</li> </ul> </div> <?php include('include/footer.php'); ?>
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>Motorcar: /home/dave/thesis/motorcar/src/compositor/compositor.h File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Motorcar </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(9)"><span class="SelectionMark">&#160;</span>Macros</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(10)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_9dc369ce777997cdae2eb2324a90015e.html">compositor</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#namespaces">Namespaces</a> </div> <div class="headertitle"> <div class="title">compositor.h File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &lt;<a class="el" href="display_8h_source.html">scenegraph/output/display/display.h</a>&gt;</code><br/> <code>#include &lt;<a class="el" href="seat_8h_source.html">wayland/input/seat.h</a>&gt;</code><br/> <code>#include &lt;<a class="el" href="openglcontext_8h_source.html">gl/openglcontext.h</a>&gt;</code><br/> <code>#include &lt;wayland-server.h&gt;</code><br/> <code>#include &lt;wayland-server-protocol.h&gt;</code><br/> </div><div class="textblock"><div class="dynheader"> Include dependency graph for compositor.h:</div> <div class="dyncontent"> <div class="center"><img src="compositor_8h__incl.png" border="0" usemap="#_2home_2dave_2thesis_2motorcar_2src_2compositor_2compositor_8h" alt=""/></div> <map name="_2home_2dave_2thesis_2motorcar_2src_2compositor_2compositor_8h" id="_2home_2dave_2thesis_2motorcar_2src_2compositor_2compositor_8h"> <area shape="rect" id="node2" href="display_8h.html" title="scenegraph/output/display\l/display.h" alt="" coords="684,97,858,138"/><area shape="rect" id="node24" href="openglcontext_8h.html" title="gl/openglcontext.h" alt="" coords="884,187,1012,213"/><area shape="rect" id="node26" href="seat_8h.html" title="wayland/input/seat.h" alt="" coords="1105,104,1247,131"/><area shape="rect" id="node3" href="viewpoint_8h.html" title="scenegraph/output/viewpoint.h" alt="" coords="89,187,287,213"/><area shape="rect" id="node23" href="physicalnode_8h.html" title="scenegraph/physicalnode.h" alt="" coords="528,187,707,213"/><area shape="rect" id="node4" href="geometry_8h.html" title="geometry.h" alt="" coords="270,411,356,437"/><area shape="rect" id="node10" href="viewport_8h.html" title="gl/viewport.h" alt="" coords="224,261,320,288"/><area shape="rect" id="node12" href="virtualnode_8h.html" title="scenegraph/virtualnode.h" alt="" coords="345,261,511,288"/><area shape="rect" id="node19" href="motorcar-server-protocol_8h.html" title="motorcar&#45;server&#45;protocol.h" alt="" coords="25,261,199,288"/><area shape="rect" id="node13" href="scenegraphnode_8h.html" title="scenegraph/scenegraphnode.h" alt="" coords="450,336,648,363"/><area shape="rect" id="node27" href="waylandsurface_8h.html" title="wayland/output/waylandsurface.h" alt="" coords="1099,187,1315,213"/><area shape="rect" id="node28" href="events_8h.html" title="events/events.h" alt="" coords="1263,261,1378,288"/><area shape="rect" id="node29" href="event_8h.html" title="events/event.h" alt="" coords="1266,485,1374,512"/><area shape="rect" id="node30" href="mouseevent_8h.html" title="events/mouseevent.h" alt="" coords="1247,411,1394,437"/><area shape="rect" id="node31" href="keyboardevent_8h.html" title="events/keyboardevent.h" alt="" coords="1121,336,1282,363"/><area shape="rect" id="node32" href="sixdofevent_8h.html" title="events/sixdofevent.h" alt="" coords="1358,336,1500,363"/></map> </div> </div><div class="textblock"><div class="dynheader"> This graph shows which files directly or indirectly include this file:</div> <div class="dyncontent"> <div class="center"><img src="compositor_8h__dep__incl.png" border="0" usemap="#_2home_2dave_2thesis_2motorcar_2src_2compositor_2compositor_8hdep" alt=""/></div> <map name="_2home_2dave_2thesis_2motorcar_2src_2compositor_2compositor_8hdep" id="_2home_2dave_2thesis_2motorcar_2src_2compositor_2compositor_8hdep"> <area shape="rect" id="node2" href="compositor_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/compositor.cpp" alt="" coords="29,499,234,541"/><area shape="rect" id="node3" href="motorcar_8h.html" title="/home/dave/thesis/motorcar\l/src/compositor/motorcar.h" alt="" coords="417,207,601,249"/><area shape="rect" id="node13" href="sixdofpointingdevice_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/scenegraph\l/input/sixdofpointingdevice.cpp" alt="" coords="852,96,1053,152"/><area shape="rect" id="node14" href="viewpoint_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/scenegraph\l/output/viewpoint.cpp" alt="" coords="1078,96,1262,152"/><area shape="rect" id="node15" href="shell_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/shell.cpp" alt="" coords="625,207,809,249"/><area shape="rect" id="node16" href="windowmanager_8h.html" title="/home/dave/thesis/motorcar\l/src/compositor/windowmanager.h" alt="" coords="606,103,828,145"/><area shape="rect" id="node19" href="sixensecontrollernode_8cpp.html" title="/home/dave/thesis/motorcar\l/src/device/sixensecontrollernode.cpp" alt="" coords="1287,103,1528,145"/><area shape="rect" id="node4" href="qtwaylandmotorcarcompositor_8h.html" title="/home/dave/thesis/motorcar\l/src/compositor/qt/qtwaylandmotorcarcompositor.h" alt="" coords="415,409,730,450"/><area shape="rect" id="node8" href="qtwaylandmotorcarsurface_8h.html" title="/home/dave/thesis/motorcar\l/src/compositor/qt/qtwaylandmotorcarsurface.h" alt="" coords="707,499,1001,541"/><area shape="rect" id="node10" href="qtwaylandmotorcaropenglcontext_8h.html" title="/home/dave/thesis/motorcar\l/src/compositor/qt/qtwaylandmotorcaropenglcontext.h" alt="" coords="50,311,382,353"/><area shape="rect" id="node12" href="main_8cpp.html" title="/home/dave/thesis/motorcar\l/src/examples/compositors\l/rift&#45;hydra&#45;compositor/main.cpp" alt="" coords="408,304,610,360"/><area shape="rect" id="node5" href="qtwaylandmotorcarcompositor_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/qt/qtwaylandmotorcarcompositor.cpp" alt="" coords="278,590,608,631"/><area shape="rect" id="node6" href="qtwaylandmotorcarseat_8h.html" title="/home/dave/thesis/motorcar\l/src/compositor/qt/qtwaylandmotorcarseat.h" alt="" coords="405,499,682,541"/><area shape="rect" id="node7" href="qtwaylandmotorcarseat_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/qt/qtwaylandmotorcarseat.cpp" alt="" coords="633,590,924,631"/><area shape="rect" id="node9" href="qtwaylandmotorcarsurface_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/qt/qtwaylandmotorcarsurface.cpp" alt="" coords="948,590,1256,631"/><area shape="rect" id="node11" href="qtwaylandmotorcaropenglcontext_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/qt/qtwaylandmotorcaropenglcontext.cpp" alt="" coords="44,409,390,450"/><area shape="rect" id="node17" href="scene_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/scenegraph\l/scene.cpp" alt="" coords="833,200,1017,256"/><area shape="rect" id="node18" href="windowmanager_8cpp.html" title="/home/dave/thesis/motorcar\l/src/compositor/windowmanager.cpp" alt="" coords="1041,207,1274,249"/></map> </div> </div> <p><a href="compositor_8h_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classmotorcar_1_1Compositor.html">motorcar::Compositor</a></td></tr> <tr class="memdesc:"><td class="mdescLeft">&#160;</td><td class="mdescRight">This class handles only the invoking the draw calls on the scenegraph needed to display its contents. <a href="classmotorcar_1_1Compositor.html#details">More...</a><br/></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Namespaces</h2></td></tr> <tr class="memitem:namespacemotorcar"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacemotorcar.html">motorcar</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sat Jun 21 2014 17:17:22 for Motorcar by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
{ "pile_set_name": "Github" }
[ { "ref": "context-Downtown_4l", "capacity": 64, "type": "context", "name": "New You Interior", "mods": [ { "town_dir": "", "neighbors": [ "", "context-Downtown_4c", "", "" ], "orientation": 3, "realm": "Downtown", "nitty_bits": 3, "port_dir": LEFT, "depth": 24, "type": "Region" } ] }, { "ref": "item-wall.n9d2.Downtown_4l", "mods": [ { "y": 1, "x": 0, "style": 6, "type": "Wall", "orientation": 172 } ], "type": "item", "name": "Wall", "in": "context-Downtown_4l" }, { "ref": "item-ground.s9j3.Downtown_4l", "mods": [ { "y": 4, "x": 0, "style": 1, "type": "Ground", "orientation": 204 } ], "type": "item", "name": "Ground", "in": "context-Downtown_4l" }, { "ref": "item-head.f901.Downtown_4l", "mods": [ { "y": 0, "x": 0, "style": 32, "type": "Head", "orientation": 56 } ], "type": "item", "name": "Head", "in": "item-vendo_front.0065.Downtown_4l" }, { "ref": "item-head.7d1f.Downtown_4l", "mods": [ { "y": 1, "x": 1, "style": 65, "type": "Head", "orientation": 8 } ], "type": "item", "name": "Head", "in": "item-vendo_front.0065.Downtown_4l" }, { "ref": "item-head.33ac.Downtown_4l", "mods": [ { "style": 87, "orientation": 32, "gr_state": 1, "y": 2, "x": 2, "type": "Head" } ], "type": "item", "name": "Head", "in": "item-vendo_front.0065.Downtown_4l" }, { "ref": "item-head.6fa9.Downtown_4l", "mods": [ { "y": 3, "x": 3, "style": 51, "type": "Head", "orientation": 24 } ], "type": "item", "name": "Head", "in": "item-vendo_front.0065.Downtown_4l" }, { "ref": "item-head.47fe.Downtown_4l", "mods": [ { "y": 4, "x": 4, "style": 41, "type": "Head", "orientation": 8 } ], "type": "item", "name": "Head", "in": "item-vendo_front.0065.Downtown_4l" }, { "ref": "item-head.5a45.Downtown_4l", "mods": [ { "style": 61, "orientation": 40, "gr_state": 1, "y": 5, "x": 5, "type": "Head" } ], "type": "item", "name": "Head", "in": "item-vendo_front.0065.Downtown_4l" }, { "ref": "item-head.n2m9.Downtown_4l", "mods": [ { "style": 89, "orientation": 40, "gr_state": 1, "y": 6, "x": 6, "type": "Head" } ], "type": "item", "name": "Head", "in": "item-vendo_front.0065.Downtown_4l" }, { "ref": "item-vendo_front.0065.Downtown_4l", "mods": [ { "display_item": 7, "orientation": 236, "key_lo": 0, "key_hi": 0, "y": 0, "x": 0, "type": "Vendo_front", "open_flags": 0, "prices": [200, 185, 215, 300, 155, 170, 220, 195], "item_price": 220 } ], "type": "item", "name": "Vendo_front", "in": "item-vendo_inside.55d2.Downtown_4l" }, { "ref": "item-head.f9m2.Downtown_4l", "mods": [ { "style": 80, "orientation": 1, "gr_state": 1, "y": 1, "x": 1, "type": "Head" } ], "type": "item", "name": "Head", "in": "item-vendo_inside.55d2.Downtown_4l" }, { "ref": "item-vendo_inside.55d2.Downtown_4l", "mods": [ { "orientation": 236, "key_lo": 0, "key_hi": 0, "y": 24, "x": 52, "type": "Vendo_inside", "open_flags": 0 } ], "type": "item", "name": "Vendo_inside", "in": "context-Downtown_4l" }, { "ref": "item-short_sign1.a8h1.Downtown_4l", "mods": [ { "orientation": 0, "type": "Short_sign", "gr_state": 1, "y": 104, "x": 60, "ascii": [ 128, 67, 104, 105, 99 ] } ], "type": "item", "name": "Short_sign", "in": "context-Downtown_4l" }, { "ref": "item-short_sign2.n2m8.Downtown_4l", "mods": [ { "orientation": 16, "type": "Short_sign", "gr_state": 0, "y": 78, "x": 4, "ascii": [ 128, 129, 133, 131, 126 ] } ], "type": "item", "name": "Short_sign", "in": "context-Downtown_4l" }, { "ref": "item-pawn_machine.cb51.Downtown_4l", "mods": [ { "y": 138, "x": 144, "type": "Pawn_machine", "orientation": 1 } ], "type": "item", "name": "Pawn_machine", "in": "context-Downtown_4l" } ]
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <ZopeData> <record id="1" aka="AAAAAAAAAAE="> <pickle> <global name="ZopePageTemplate" module="Products.PageTemplates.ZopePageTemplate"/> </pickle> <pickle> <dictionary> <item> <key> <string>_bind_names</string> </key> <value> <object> <klass> <global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/> </klass> <tuple/> <state> <dictionary> <item> <key> <string>_asgns</string> </key> <value> <dictionary> <item> <key> <string>name_subpath</string> </key> <value> <string>traverse_subpath</string> </value> </item> </dictionary> </value> </item> </dictionary> </state> </object> </value> </item> <item> <key> <string>content_type</string> </key> <value> <string>text/html</string> </value> </item> <item> <key> <string>expand</string> </key> <value> <int>0</int> </value> </item> <item> <key> <string>id</string> </key> <value> <string>test_accounting_transaction_input.html</string> </value> </item> <item> <key> <string>output_encoding</string> </key> <value> <string>utf-8</string> </value> </item> <item> <key> <string>title</string> </key> <value> <unicode></unicode> </value> </item> </dictionary> </pickle> </record> </ZopeData>
{ "pile_set_name": "Github" }
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0"; object mut; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -1 0 0 0 0]; internalField uniform 0; boundaryField { front { type mutkWallFunction; value uniform 0; } back { type mutkWallFunction; value uniform 0; } walls { type mutkWallFunction; value uniform 0; } porosityWall { type mutkWallFunction; value uniform 0; } inlet { type calculated; value uniform 0; } outlet { type calculated; value uniform 0; } } // ************************************************************************* //
{ "pile_set_name": "Github" }
#include <algorithm> #include <string> #include <utility> #include <vector> #include "google/protobuf/text_format.h" #include "gtest/gtest.h" #include "caffe/common.hpp" #include "caffe/parallel.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/sgd_solvers.hpp" #include "caffe/util/io.hpp" #include "caffe/test/test_caffe_main.hpp" using std::ostringstream; namespace caffe { template <typename TypeParam> class GradientBasedSolverTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: GradientBasedSolverTest() : seed_(1701), num_(4), channels_(3), height_(10), width_(10), share_(false) { input_file_ = new string( CMAKE_SOURCE_DIR "caffe/test/test_data/solver_data_list.txt" CMAKE_EXT); } ~GradientBasedSolverTest() { delete input_file_; } string snapshot_prefix_; shared_ptr<SGDSolver<Dtype> > solver_; shared_ptr<P2PSync<Dtype> > sync_; int seed_; // Dimensions are determined by generate_sample_data.py // TODO this is brittle and the hdf5 file should be checked instead. int num_, channels_, height_, width_; bool share_; Dtype delta_; // Stability constant for RMSProp, AdaGrad, AdaDelta and Adam // Test data: check out generate_sample_data.py in the same directory. string* input_file_; virtual void InitSolver(const SolverParameter& param) = 0; virtual void InitSolverFromProtoString(const string& proto) { SolverParameter param; CHECK(google::protobuf::TextFormat::ParseFromString(proto, &param)); // Set the solver_mode according to current Caffe::mode. switch (Caffe::mode()) { case Caffe::CPU: param.set_solver_mode(SolverParameter_SolverMode_CPU); break; case Caffe::GPU: param.set_solver_mode(SolverParameter_SolverMode_GPU); break; default: LOG(FATAL) << "Unknown Caffe mode: " << Caffe::mode(); } InitSolver(param); delta_ = param.delta(); } string RunLeastSquaresSolver(const Dtype learning_rate, const Dtype weight_decay, const Dtype momentum, const int num_iters, const int iter_size = 1, const int devices = 1, const bool snapshot = false, const char* from_snapshot = NULL) { ostringstream proto; int device_id = 0; #ifndef CPU_ONLY if (Caffe::mode() == Caffe::GPU) { CUDA_CHECK(cudaGetDevice(&device_id)); } #endif proto << "snapshot_after_train: " << snapshot << " " "max_iter: " << num_iters << " " "base_lr: " << learning_rate << " " "lr_policy: 'fixed' " "iter_size: " << iter_size << " " "device_id: " << device_id << " " "net_param { " " name: 'TestNetwork' " " layer { " " name: 'data' " " type: 'HDF5Data' " " hdf5_data_param { " " source: '" << *(this->input_file_) << "' " " batch_size: " << num_ / iter_size << " " " } " " top: 'data' " " top: 'targets' " " } "; if (share_) { proto << " layer { " " name: 'slice' " " type: 'Slice' " " bottom: 'data' " " top: 'data1' " " top: 'data2' " " slice_param { " " axis: 0 " " } " " } "; } proto << " layer { " " name: 'innerprod' " " type: 'InnerProduct' " " param { name: 'weights' } " " param { name: 'bias' } " " inner_product_param { " " num_output: 1 " " weight_filler { " " type: 'gaussian' " " std: 1.0 " " } " " bias_filler { " " type: 'gaussian' " " std: 1.0 " " } " " } " " bottom: '" << string(share_ ? "data1": "data") << "' " " top: '" << string(share_ ? "innerprod1": "innerprod") << "' " " } "; if (share_) { proto << " layer { " " name: 'innerprod2' " " type: 'InnerProduct' " " param { name: 'weights' } " " param { name: 'bias' } " " inner_product_param { " " num_output: 1 " " weight_filler { " " type: 'gaussian' " " std: 1.0 " " } " " bias_filler { " " type: 'gaussian' " " std: 1.0 " " } " " } " " bottom: 'data2' " " top: 'innerprod2' " " } " " layer { " " name: 'concat' " " type: 'Concat' " " bottom: 'innerprod1' " " bottom: 'innerprod2' " " top: 'innerprod' " " concat_param { " " axis: 0 " " } " " } "; } proto << " layer { " " name: 'loss' " " type: 'EuclideanLoss' " " bottom: 'innerprod' " " bottom: 'targets' " " } " "} "; if (weight_decay != 0) { proto << "weight_decay: " << weight_decay << " "; } if (momentum != 0) { proto << "momentum: " << momentum << " "; } MakeTempDir(&snapshot_prefix_); proto << "snapshot_prefix: '" << snapshot_prefix_ << "/' "; if (snapshot) { proto << "snapshot: " << num_iters << " "; } Caffe::set_random_seed(this->seed_); this->InitSolverFromProtoString(proto.str()); if (from_snapshot != NULL) { this->solver_->Restore(from_snapshot); for (int i = 0; i < this->solver_->iter(); ++i) { this->solver_->net()->Forward(); } } if (devices == 1) { this->solver_->Solve(); } else { LOG(INFO) << "Multi-GPU test on " << devices << " devices"; vector<int> gpus; // put current device at the beginning int device_id = solver_->param().device_id(); gpus.push_back(device_id); for (int i = 0; gpus.size() < devices; ++i) { if (i != device_id) gpus.push_back(i); } Caffe::set_solver_count(gpus.size()); this->sync_.reset(new P2PSync<Dtype>( this->solver_, NULL, this->solver_->param())); this->sync_->Run(gpus); Caffe::set_solver_count(1); } if (snapshot) { ostringstream resume_file; resume_file << snapshot_prefix_ << "/_iter_" << num_iters << ".solverstate"; string resume_filename = resume_file.str(); return resume_filename; } return string(); } // Compute an update value given the current state of the train net, // using the analytical formula for the least squares gradient. // updated_params will store the updated weight and bias results, // using the blobs' diffs to hold the update values themselves. void ComputeLeastSquaresUpdate(const Dtype learning_rate, const Dtype weight_decay, const Dtype momentum, const int num_iters, vector<shared_ptr<Blob<Dtype> > >* updated_params) { const int N = num_; const int D = channels_ * height_ * width_; // Run a forward pass, and manually compute the update values from the // result. Net<Dtype>& net = *this->solver_->net(); net.Forward(); ASSERT_TRUE(net.has_blob("data")); const Blob<Dtype>& data = *net.blob_by_name("data"); ASSERT_TRUE(net.has_blob("targets")); const Blob<Dtype>& targets = *net.blob_by_name("targets"); ASSERT_TRUE(net.has_layer("innerprod")); const vector<shared_ptr<Blob<Dtype> > >& param_blobs = net.layer_by_name("innerprod")->blobs(); const int num_param_blobs = 2; ASSERT_EQ(num_param_blobs, param_blobs.size()); const Blob<Dtype>& weights = *param_blobs[0]; const Blob<Dtype>& bias = *param_blobs[1]; ASSERT_EQ(D * N, data.count()); ASSERT_EQ(N, targets.count()); ASSERT_EQ(D, weights.count()); ASSERT_EQ(1, bias.count()); updated_params->clear(); updated_params->resize(num_param_blobs); for (int i = 0; i < num_param_blobs; ++i) { (*updated_params)[i].reset(new Blob<Dtype>()); } Blob<Dtype>& updated_weights = *(*updated_params)[0]; updated_weights.ReshapeLike(weights); Blob<Dtype>& updated_bias = *(*updated_params)[1]; updated_bias.ReshapeLike(bias); for (int i = 0; i <= D; ++i) { // Compute the derivative with respect to the ith weight (i.e., the ith // element of the gradient). Dtype grad = 0; for (int j = 0; j <= D; ++j) { // Compute element (i, j) of X^T * X. Dtype element = 0; for (int k = 0; k < N; ++k) { // (i, k) in X^T (== (k, i) in X) times (k, j) in X. const Dtype element_i = (i == D) ? 1 : data.cpu_data()[k * D + i]; const Dtype element_j = (j == D) ? 1 : data.cpu_data()[k * D + j]; element += element_i * element_j; } if (j == D) { grad += element * bias.cpu_data()[0]; } else { grad += element * weights.cpu_data()[j]; } } for (int k = 0; k < N; ++k) { const Dtype element_i = (i == D) ? 1 : data.cpu_data()[k * D + i]; grad -= element_i * targets.cpu_data()[k]; } // Scale the gradient over the N samples. grad /= N; // Add the weight decay to the gradient. grad += weight_decay * ((i == D) ? bias.cpu_data()[0] : weights.cpu_data()[i]); // Finally, compute update. const vector<shared_ptr<Blob<Dtype> > >& history = solver_->history(); if (solver_->type() != string("AdaDelta") && solver_->type() != string("Adam")) { ASSERT_EQ(2, history.size()); // 1 blob for weights, 1 for bias } else { ASSERT_EQ(4, history.size()); // additional blobs for update history } Dtype update_value = learning_rate * grad; const Dtype history_value = (i == D) ? history[1]->cpu_data()[0] : history[0]->cpu_data()[i]; const Dtype temp = momentum * history_value; if (solver_->type() == string("SGD")) { update_value += temp; } else if (solver_->type() == string("Nesterov")) { update_value += temp; // step back then over-step update_value = (1 + momentum) * update_value - temp; } else if (solver_->type() == string("AdaGrad")) { update_value /= std::sqrt(history_value + grad * grad) + delta_; } else if (solver_->type() == string("RMSProp")) { const Dtype rms_decay = 0.95; update_value /= std::sqrt(rms_decay*history_value + grad * grad * (1 - rms_decay)) + delta_; } else if (solver_->type() == string("AdaDelta")) { const Dtype update_history_value = (i == D) ? history[1 + num_param_blobs]->cpu_data()[0] : history[0 + num_param_blobs]->cpu_data()[i]; const Dtype weighted_gradient_average = momentum * history_value + (1 - momentum) * (grad * grad); update_value = grad * std::sqrt((update_history_value + delta_) / (weighted_gradient_average + delta_)) * learning_rate; // not actually needed, just here for illustrative purposes // const Dtype weighted_update_average = // momentum * update_history_value + (1 - momentum) * (update_value); } else if (solver_->type() == string("Adam")) { const Dtype momentum2 = 0.999; const Dtype m = history_value; const Dtype v = (i == D) ? history[1 + num_param_blobs]->cpu_data()[0] : history[0 + num_param_blobs]->cpu_data()[i]; const Dtype val_m = (1 - momentum) * grad + momentum * m; const Dtype val_v = (1 - momentum2) * grad * grad + momentum2 * v; Dtype alpha_t = learning_rate * std::sqrt(Dtype(1) - pow(momentum2, num_iters)) / (Dtype(1.) - pow(momentum, num_iters)); update_value = alpha_t * val_m / (std::sqrt(val_v) + delta_); } else { LOG(FATAL) << "Unknown solver type: " << solver_->type(); } if (i == D) { updated_bias.mutable_cpu_diff()[0] = update_value; updated_bias.mutable_cpu_data()[0] = bias.cpu_data()[0] - update_value; } else { updated_weights.mutable_cpu_diff()[i] = update_value; updated_weights.mutable_cpu_data()[i] = weights.cpu_data()[i] - update_value; } } } void CheckLeastSquaresUpdate( const vector<shared_ptr<Blob<Dtype> > >& updated_params) { const int D = channels_ * height_ * width_; const Blob<Dtype>& updated_weights = *updated_params[0]; const Blob<Dtype>& updated_bias = *updated_params[1]; Net<Dtype>& net = *this->solver_->net(); ASSERT_TRUE(net.has_layer("innerprod")); const vector<shared_ptr<Blob<Dtype> > >& param_blobs = net.layer_by_name("innerprod")->blobs(); ASSERT_EQ(2, param_blobs.size()); const Blob<Dtype>& solver_updated_weights = *param_blobs[0]; ASSERT_EQ(D, solver_updated_weights.count()); const double kPrecision = 1e-2; const double kMinPrecision = 1e-7; for (int i = 0; i < D; ++i) { const Dtype expected_updated_weight = updated_weights.cpu_data()[i]; const Dtype solver_updated_weight = solver_updated_weights.cpu_data()[i]; const Dtype error_margin = std::max(kMinPrecision, kPrecision * std::min(fabs(expected_updated_weight), fabs(solver_updated_weight))); EXPECT_NEAR(expected_updated_weight, solver_updated_weight, error_margin); } const Blob<Dtype>& solver_updated_bias_blob = *param_blobs[1]; ASSERT_EQ(1, solver_updated_bias_blob.count()); const Dtype expected_updated_bias = updated_bias.cpu_data()[0]; const Dtype solver_updated_bias = solver_updated_bias_blob.cpu_data()[0]; const Dtype error_margin = std::max(kMinPrecision, kPrecision * std::min(fabs(expected_updated_bias), fabs(solver_updated_bias))); EXPECT_NEAR(expected_updated_bias, solver_updated_bias, error_margin); // Check the solver's history -- should contain the previous update value. if (solver_->type() == string("SGD")) { const vector<shared_ptr<Blob<Dtype> > >& history = solver_->history(); ASSERT_EQ(2, history.size()); for (int i = 0; i < D; ++i) { const Dtype expected_history = updated_weights.cpu_diff()[i]; const Dtype solver_history = history[0]->cpu_data()[i]; const Dtype error_margin_hist = std::max(kMinPrecision, kPrecision * std::min(fabs(expected_history), fabs(solver_history))); EXPECT_NEAR(expected_history, solver_history, error_margin_hist); } const Dtype expected_history = updated_bias.cpu_diff()[0]; const Dtype solver_history = history[1]->cpu_data()[0]; const Dtype error_margin_hist = std::max(kMinPrecision, kPrecision * std::min(fabs(expected_history), fabs(solver_history))); EXPECT_NEAR(expected_history, solver_history, error_margin_hist); } } void CheckAccumulation(const Dtype kLearningRate, const Dtype kWeightDecay, const Dtype kMomentum, const int kNumIters, const int kIterSize) { const double kPrecision = 1e-2; const double kMinPrecision = 1e-7; // Solve without accumulation and save parameters. this->RunLeastSquaresSolver(kLearningRate, kWeightDecay, kMomentum, kNumIters); // Save parameters for comparison. Net<Dtype>& net = *this->solver_->net(); const vector<shared_ptr<Blob<Dtype> > >& param_blobs = net.layer_by_name("innerprod")->blobs(); vector<shared_ptr<Blob<Dtype> > > noaccum_params(param_blobs.size()); for (int i = 0; i < param_blobs.size(); ++i) { noaccum_params[i].reset(new Blob<Dtype>()); noaccum_params[i]->CopyFrom(*param_blobs[i], false, true); } // Solve by equivalent accumulation of gradients over divided batches. this->RunLeastSquaresSolver(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); Net<Dtype>& net_accum = *this->solver_->net(); const vector<shared_ptr<Blob<Dtype> > >& accum_params = net_accum.layer_by_name("innerprod")->blobs(); // Compare accumulated parameters against no accumulation standard. const int D = this->channels_ * this->height_ * this->width_; for (int i = 0; i < D; ++i) { const Dtype expected_param = noaccum_params[0]->cpu_data()[i]; const Dtype accum_param = accum_params[0]->cpu_data()[i]; const Dtype error_margin = std::max(kMinPrecision, kPrecision * std::min(fabs(expected_param), fabs(accum_param))); EXPECT_NEAR(expected_param, accum_param, error_margin); } ASSERT_EQ(1, accum_params[1]->count()); const Dtype expected_bias = noaccum_params[1]->cpu_data()[0]; const Dtype accum_bias = accum_params[1]->cpu_data()[0]; const Dtype error_margin = std::max(kMinPrecision, kPrecision * std::min(fabs(expected_bias), fabs(accum_bias))); EXPECT_NEAR(expected_bias, accum_bias, error_margin); } // Test that the correct update is computed for a regularized least squares // problem: // // E = (1/(2n)) || X w - y ||^2 + (lambda / 2) || w ||^2 // \nabla_w E = (1/n) (X^T X w - X^T y) + lambda * w // // X \in R^{n x (d+1)} (each example is a row, (d+1)th element is always 1) // w \in R^{(d+1) x 1} ((d+1)th element is the bias) // y \in R^{n x 1} // lambda is weight_decay // // TestLeastSquaresUpdate works "inductively", assuming that the solver // correctly updates the net K (= iter_to_check) times, then given the history // from the Kth update, we compute the (K+1)th update and check that it // matches the solver's (K+1)th update. void TestLeastSquaresUpdate(const Dtype learning_rate = 1.0, const Dtype weight_decay = 0.0, const Dtype momentum = 0.0, const int iter_to_check = 0) { const int kNum = num_; const int kIterSize = 1; // Test over all numbers of devices. int available_devices = 1; #ifndef CPU_ONLY if (Caffe::mode() == Caffe::GPU) { CUDA_CHECK(cudaGetDeviceCount(&available_devices)); } #endif for (int devices = 1; devices <= available_devices; ++devices) { // Configure batch size for single / multi device equivalence. // Constant data is needed for multi device as for accumulation. num_ = kNum * devices; // Initialize the solver and run K (= iter_to_check) solver iterations // (on single device). RunLeastSquaresSolver(learning_rate, weight_decay, momentum, iter_to_check, kIterSize, 1); // Compute the (K+1)th update using the analytic least squares gradient. vector<shared_ptr<Blob<Dtype> > > updated_params; ComputeLeastSquaresUpdate(learning_rate, weight_decay, momentum, iter_to_check + 1, &updated_params); // Reinitialize the solver and run K+1 solver iterations. num_ = kNum; RunLeastSquaresSolver(learning_rate, weight_decay, momentum, iter_to_check + 1, kIterSize, devices); // Check that the solver's solution matches ours. CheckLeastSquaresUpdate(updated_params); } } void TestSnapshot(const Dtype learning_rate = 1.0, const Dtype weight_decay = 0.0, const Dtype momentum = 0.0, const int num_iters = 1) { // Run the solver for num_iters * 2 iterations. const int total_num_iters = num_iters * 2; bool snapshot = false; const int kIterSize = 1; const int kDevices = 1; RunLeastSquaresSolver(learning_rate, weight_decay, momentum, total_num_iters, kIterSize, kDevices, snapshot); // Save the resulting param values. vector<shared_ptr<Blob<Dtype> > > param_copies; const vector<Blob<Dtype>*>& orig_params = solver_->net()->learnable_params(); param_copies.resize(orig_params.size()); for (int i = 0; i < orig_params.size(); ++i) { param_copies[i].reset(new Blob<Dtype>()); const bool kReshape = true; for (int copy_diff = false; copy_diff <= true; ++copy_diff) { param_copies[i]->CopyFrom(*orig_params[i], copy_diff, kReshape); } } // Save the solver history vector<shared_ptr<Blob<Dtype> > > history_copies; const vector<shared_ptr<Blob<Dtype> > >& orig_history = solver_->history(); history_copies.resize(orig_history.size()); for (int i = 0; i < orig_history.size(); ++i) { history_copies[i].reset(new Blob<Dtype>()); const bool kReshape = true; for (int copy_diff = false; copy_diff <= true; ++copy_diff) { history_copies[i]->CopyFrom(*orig_history[i], copy_diff, kReshape); } } // Run the solver for num_iters iterations and snapshot. snapshot = true; string snapshot_name = RunLeastSquaresSolver(learning_rate, weight_decay, momentum, num_iters, kIterSize, kDevices, snapshot); // Reinitialize the solver and run for num_iters more iterations. snapshot = false; RunLeastSquaresSolver(learning_rate, weight_decay, momentum, total_num_iters, kIterSize, kDevices, snapshot, snapshot_name.c_str()); // Check that params now match. const vector<Blob<Dtype>*>& params = solver_->net()->learnable_params(); for (int i = 0; i < params.size(); ++i) { for (int j = 0; j < params[i]->count(); ++j) { EXPECT_EQ(param_copies[i]->cpu_data()[j], params[i]->cpu_data()[j]) << "param " << i << " data differed at dim " << j; EXPECT_EQ(param_copies[i]->cpu_diff()[j], params[i]->cpu_diff()[j]) << "param " << i << " diff differed at dim " << j; } } // Check that history now matches. const vector<shared_ptr<Blob<Dtype> > >& history = solver_->history(); for (int i = 0; i < history.size(); ++i) { for (int j = 0; j < history[i]->count(); ++j) { EXPECT_EQ(history_copies[i]->cpu_data()[j], history[i]->cpu_data()[j]) << "history blob " << i << " data differed at dim " << j; EXPECT_EQ(history_copies[i]->cpu_diff()[j], history[i]->cpu_diff()[j]) << "history blob " << i << " diff differed at dim " << j; } } } }; template <typename TypeParam> class SGDSolverTest : public GradientBasedSolverTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: virtual void InitSolver(const SolverParameter& param) { this->solver_.reset(new SGDSolver<Dtype>(param)); } }; TYPED_TEST_CASE(SGDSolverTest, TestDtypesAndDevices); TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdate) { this->TestLeastSquaresUpdate(); } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateLROneHundredth) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; this->TestLeastSquaresUpdate(kLearningRate); } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateWithWeightDecay) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 1; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateWithWeightDecayMultiIter) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateWithMomentum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0; const Dtype kMomentum = 0.5; const int kNumIters = 1; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateWithMomentumMultiIter) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0; const Dtype kMomentum = 0.5; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateWithEverything) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.5; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateWithEverythingShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.5; const int kNumIters = 4; this->share_ = true; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateWithEverythingAccum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; const int kIterSize = 2; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(SGDSolverTest, TestLeastSquaresUpdateWithEverythingAccumShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; const int kIterSize = 2; this->share_ = true; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(SGDSolverTest, TestSnapshot) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(SGDSolverTest, TestSnapshotShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; this->share_ = true; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } template <typename TypeParam> class AdaGradSolverTest : public GradientBasedSolverTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: virtual void InitSolver(const SolverParameter& param) { this->solver_.reset(new AdaGradSolver<Dtype>(param)); } }; TYPED_TEST_CASE(AdaGradSolverTest, TestDtypesAndDevices); TYPED_TEST(AdaGradSolverTest, TestAdaGradLeastSquaresUpdate) { this->TestLeastSquaresUpdate(); } TYPED_TEST(AdaGradSolverTest, TestAdaGradLeastSquaresUpdateLROneHundredth) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; this->TestLeastSquaresUpdate(kLearningRate); } TYPED_TEST(AdaGradSolverTest, TestAdaGradLeastSquaresUpdateWithWeightDecay) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay); } TYPED_TEST(AdaGradSolverTest, TestAdaGradLeastSquaresUpdateWithEverything) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdaGradSolverTest, TestAdaGradLeastSquaresUpdateWithEverythingShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; this->share_ = true; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdaGradSolverTest, TestLeastSquaresUpdateWithEverythingAccum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; const int kIterSize = 2; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(AdaGradSolverTest, TestLeastSquaresUpdateWithEverythingAccumShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; const int kIterSize = 2; this->share_ = true; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(AdaGradSolverTest, TestSnapshot) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdaGradSolverTest, TestSnapshotShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; this->share_ = true; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } template <typename TypeParam> class NesterovSolverTest : public GradientBasedSolverTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: virtual void InitSolver(const SolverParameter& param) { this->solver_.reset(new NesterovSolver<Dtype>(param)); } }; TYPED_TEST_CASE(NesterovSolverTest, TestDtypesAndDevices); TYPED_TEST(NesterovSolverTest, TestNesterovLeastSquaresUpdate) { this->TestLeastSquaresUpdate(); } TYPED_TEST(NesterovSolverTest, TestNesterovLeastSquaresUpdateLROneHundredth) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; this->TestLeastSquaresUpdate(kLearningRate); } TYPED_TEST(NesterovSolverTest, TestNesterovLeastSquaresUpdateWithWeightDecay) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay); } TYPED_TEST(NesterovSolverTest, TestNesterovLeastSquaresUpdateWithWeightDecayMultiIter) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(NesterovSolverTest, TestNesterovLeastSquaresUpdateWithMomentum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0; const Dtype kMomentum = 0.5; const int kNumIters = 1; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(NesterovSolverTest, TestLeastSquaresUpdateWithMomentumMultiIter) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0; const Dtype kMomentum = 0.5; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(NesterovSolverTest, TestNesterovLeastSquaresUpdateWithEverything) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(NesterovSolverTest, TestNesterovLeastSquaresUpdateWithEverythingShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; this->share_ = true; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(NesterovSolverTest, TestLeastSquaresUpdateWithEverythingAccum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; const int kIterSize = 2; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(NesterovSolverTest, TestLeastSquaresUpdateWithEverythingAccumShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; const int kIterSize = 2; this->share_ = true; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(NesterovSolverTest, TestSnapshot) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(NesterovSolverTest, TestSnapshotShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; this->share_ = true; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } template <typename TypeParam> class AdaDeltaSolverTest : public GradientBasedSolverTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: virtual void InitSolver(const SolverParameter& param) { this->solver_.reset(new AdaDeltaSolver<Dtype>(param)); } }; TYPED_TEST_CASE(AdaDeltaSolverTest, TestDtypesAndDevices); TYPED_TEST(AdaDeltaSolverTest, TestAdaDeltaLeastSquaresUpdate) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; this->TestLeastSquaresUpdate(kLearningRate); } TYPED_TEST(AdaDeltaSolverTest, TestAdaDeltaLeastSquaresUpdateWithWeightDecay) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.95; this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum); } TYPED_TEST(AdaDeltaSolverTest, TestAdaDeltaLeastSquaresUpdateWithHalfMomentum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.0; const Dtype kMomentum = 0.5; const int kNumIters = 1; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum); } } TYPED_TEST(AdaDeltaSolverTest, TestAdaDeltaLeastSquaresUpdateWithMomentum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.0; const Dtype kMomentum = 0.95; const int kNumIters = 1; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum); } } TYPED_TEST(AdaDeltaSolverTest, TestLeastSquaresUpdateWithMomentumMultiIter) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.0; const Dtype kMomentum = 0.95; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdaDeltaSolverTest, TestAdaDeltaLeastSquaresUpdateWithEverything) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.1; const Dtype kMomentum = 0.95; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdaDeltaSolverTest, TestAdaDeltaLeastSquaresUpdateWithEverythingShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.1; const Dtype kMomentum = 0.95; const int kNumIters = 4; this->share_ = true; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdaDeltaSolverTest, TestLeastSquaresUpdateWithEverythingAccum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.1; const Dtype kMomentum = 0.95; const int kNumIters = 4; const int kIterSize = 2; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(AdaDeltaSolverTest, TestLeastSquaresUpdateWithEverythingAccumShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.1; const Dtype kMomentum = 0.95; const int kNumIters = 4; const int kIterSize = 2; this->share_ = true; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(AdaDeltaSolverTest, TestSnapshot) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.1; const Dtype kMomentum = 0.95; const int kNumIters = 4; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdaDeltaSolverTest, TestSnapshotShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.1; const Dtype kWeightDecay = 0.1; const Dtype kMomentum = 0.95; const int kNumIters = 4; this->share_ = true; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } template <typename TypeParam> class AdamSolverTest : public GradientBasedSolverTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: virtual void InitSolver(const SolverParameter& param) { SolverParameter new_param = param; const Dtype momentum = 0.9; new_param.set_momentum(momentum); const Dtype momentum2 = 0.999; new_param.set_momentum2(momentum2); this->solver_.reset(new AdamSolver<Dtype>(new_param)); } }; TYPED_TEST_CASE(AdamSolverTest, TestDtypesAndDevices); TYPED_TEST(AdamSolverTest, TestAdamLeastSquaresUpdate) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0; const Dtype kMomentum = 0.9; this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum); } TYPED_TEST(AdamSolverTest, TestAdamLeastSquaresUpdateWithWeightDecay) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum); } TYPED_TEST(AdamSolverTest, TestAdamLeastSquaresUpdateWithEverything) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdamSolverTest, TestAdamLeastSquaresUpdateWithEverythingShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; this->share_ = true; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdamSolverTest, TestLeastSquaresUpdateWithEverythingAccum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; const int kIterSize = 2; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(AdamSolverTest, TestLeastSquaresUpdateWithEverythingAccumShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; const int kIterSize = 2; this->share_ = true; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(AdamSolverTest, TestSnapshot) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(AdamSolverTest, TestSnapshotShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.9; const int kNumIters = 4; this->share_ = true; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } template <typename TypeParam> class RMSPropSolverTest : public GradientBasedSolverTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: virtual void InitSolver(const SolverParameter& param) { const Dtype rms_decay = 0.95; SolverParameter new_param = param; new_param.set_rms_decay(rms_decay); this->solver_.reset(new RMSPropSolver<Dtype>(new_param)); } }; TYPED_TEST_CASE(RMSPropSolverTest, TestDtypesAndDevices); TYPED_TEST(RMSPropSolverTest, TestRMSPropLeastSquaresUpdateWithWeightDecay) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 1.0; const Dtype kWeightDecay = 0.5; this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay); } TYPED_TEST(RMSPropSolverTest, TestRMSPropLeastSquaresUpdateWithRmsDecay) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.0; const Dtype kMomentum = 0.0; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(RMSPropSolverTest, TestRMSPropLeastSquaresUpdateWithEverything) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.0; const int kNumIters = 4; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(RMSPropSolverTest, TestRMSPropLeastSquaresUpdateWithEverythingShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.0; const int kNumIters = 4; this->share_ = true; for (int i = 0; i <= kNumIters; ++i) { this->TestLeastSquaresUpdate(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(RMSPropSolverTest, TestLeastSquaresUpdateWithEverythingAccum) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.0; const int kNumIters = 4; const int kIterSize = 2; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(RMSPropSolverTest, TestLeastSquaresUpdateWithEverythingAccumShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0.0; const int kNumIters = 4; const int kIterSize = 2; this->share_ = true; this->CheckAccumulation(kLearningRate, kWeightDecay, kMomentum, kNumIters, kIterSize); } TYPED_TEST(RMSPropSolverTest, TestSnapshot) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } TYPED_TEST(RMSPropSolverTest, TestSnapshotShare) { typedef typename TypeParam::Dtype Dtype; const Dtype kLearningRate = 0.01; const Dtype kWeightDecay = 0.5; const Dtype kMomentum = 0; const int kNumIters = 4; this->share_ = true; for (int i = 1; i <= kNumIters; ++i) { this->TestSnapshot(kLearningRate, kWeightDecay, kMomentum, i); } } } // namespace caffe
{ "pile_set_name": "Github" }
using System; using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.ReactiveUI; namespace BindingDemo { public class App : Application { public override void Initialize() { AvaloniaXamlLoader.Load(this); } private static void Main() { AppBuilder.Configure<App>() .UsePlatformDetect() .UseReactiveUI() .LogToDebug() .Start<MainWindow>(); } } }
{ "pile_set_name": "Github" }
// typedef typedef unsigned long ULongArrayTypedef[10]; ULongArrayTypedef ULongArrayVar; typedef long double*& RefTypedef; long double* LongDoublePtrVar = 0; RefTypedef RefVar = LongDoublePtrVar; typedef long long (*FuncPtrTypedef)(int&, unsigned char**, short[], const double, volatile bool); FuncPtrTypedef FuncVar; typedef char (*VarArgsFuncTypedef)(void*, long, unsigned short, unsigned int, ...); VarArgsFuncTypedef VarArgsFuncVar; typedef float (*VarArgsFuncTypedefA)(...); VarArgsFuncTypedefA VarArgsFuncVarA; // unscoped enum enum Enum { RED, GREEN, BLUE }; Enum EnumVar; enum EnumConst { LOW, NORMAL = 10, HIGH }; EnumConst EnumConstVar; enum EnumEmpty {}; EnumEmpty EnumEmptyVar; enum EnumUChar : unsigned char { ON, OFF, AUTO }; EnumUChar EnumCharVar; // scoped enum enum class EnumClass { YES, NO, DEFAULT }; EnumClass EnumClassVar; enum struct EnumStruct { red, blue, black }; EnumStruct EnumStructVar; typedef signed char SCharTypedef; SCharTypedef SCVar; typedef char16_t WChar16Typedef; WChar16Typedef WC16Var; typedef char32_t WChar32Typedef; WChar32Typedef WC32Var; typedef wchar_t WCharTypedef; WCharTypedef WCVar; int main() { return 0; }
{ "pile_set_name": "Github" }
# # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. # # Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved. # # The contents of this file are subject to the terms of either the GNU # General Public License Version 2 only ("GPL") or the Common Development # and Distribution License("CDDL") (collectively, the "License"). You # may not use this file except in compliance with the License. You can # obtain a copy of the License at # https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html # or packager/legal/LICENSE.txt. See the License for the specific # language governing permissions and limitations under the License. # # When distributing the software, include this License Header Notice in each # file and include the License file at packager/legal/LICENSE.txt. # # GPL Classpath Exception: # Oracle designates this particular file as subject to the "Classpath" # exception as provided by Oracle in the GPL Version 2 section of the License # file that accompanied this code. # # Modifications: # If applicable, add the following below the License Header, with the fields # enclosed by brackets [] replaced by your own identifying information: # "Portions Copyright [year] [name of copyright owner]" # # Contributor(s): # If you wish your version of this file to be governed by only the CDDL or # only the GPL Version 2, indicate your decision by adding "[Contributor] # elects to include this software in this distribution under the [CDDL or GPL # Version 2] license." If you don't indicate a single choice of license, a # recipient has the option to distribute your version of this file under # either the CDDL, the GPL Version 2 or to extend the choice of license to # its licensees as provided above. However, if you add GPL Version 2 code # and therefore, elected the GPL Version 2 license, then the option applies # only if the new code is made subject to such option by the copyright # holder. # -exportcontents: \ org.glassfish.admin.mejb;\ version=${project.osgi.version}
{ "pile_set_name": "Github" }
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.tools.jib.api; import com.google.cloud.tools.jib.Command; import com.google.cloud.tools.jib.registry.LocalRegistry; import com.google.cloud.tools.jib.registry.ManifestPullerIntegrationTest; import com.google.common.io.Resources; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** Integration tests for {@link Jib}. */ public class JibIntegrationTest { @ClassRule public static final LocalRegistry localRegistry = new LocalRegistry(5000, "username", "password"); @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); /** * Pulls a built image and attempts to run it. * * @param imageReference the image reference of the built image * @return the container output * @throws IOException if an I/O exception occurs * @throws InterruptedException if the process was interrupted */ private static String pullAndRunBuiltImage(String imageReference) throws IOException, InterruptedException { localRegistry.pull(imageReference); return new Command("docker", "run", "--rm", imageReference).run(); } private static Containerizer getLocalRegistryContainerizer(ImageReference targetImageReference) { return Containerizer.to( RegistryImage.named(targetImageReference) .addCredentialRetriever(() -> Optional.of(Credential.from("username", "password")))) .setAllowInsecureRegistries(true); } @Before public void setUp() { System.setProperty("sendCredentialsOverHttp", "true"); } @After public void tearDown() { System.clearProperty("sendCredentialsOverHttp"); } @Test public void testBasic_helloWorld() throws InvalidImageReferenceException, InterruptedException, CacheDirectoryCreationException, IOException, RegistryException, ExecutionException { ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "basic-helloworld"); JibContainer jibContainer = Jib.from("busybox") .setEntrypoint("echo", "Hello World") .containerize(getLocalRegistryContainerizer(targetImageReference)); Assert.assertEquals("Hello World\n", pullAndRunBuiltImage(targetImageReference.toString())); Assert.assertEquals( "Hello World\n", pullAndRunBuiltImage( targetImageReference.withQualifier(jibContainer.getDigest().toString()).toString())); } @Test public void testBasic_dockerDaemonBaseImage() throws IOException, InterruptedException, InvalidImageReferenceException, ExecutionException, RegistryException, CacheDirectoryCreationException { localRegistry.pull("busybox"); ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "basic-helloworld-dockerdaemon"); JibContainer jibContainer = Jib.from("docker://busybox") .setEntrypoint("echo", "Hello World") .containerize(getLocalRegistryContainerizer(targetImageReference)); Assert.assertEquals("Hello World\n", pullAndRunBuiltImage(targetImageReference.toString())); Assert.assertEquals( "Hello World\n", pullAndRunBuiltImage( targetImageReference.withQualifier(jibContainer.getDigest().toString()).toString())); } @Test public void testBasic_dockerDaemonBaseImageToDockerDaemon() throws IOException, InterruptedException, InvalidImageReferenceException, ExecutionException, RegistryException, CacheDirectoryCreationException { localRegistry.pull("busybox"); ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "basic-helloworld-dockerdaemon"); Jib.from(DockerDaemonImage.named("busybox")) .setEntrypoint("echo", "Hello World") .containerize(Containerizer.to(DockerDaemonImage.named(targetImageReference))); String output = new Command("docker", "run", "--rm", targetImageReference.toString()).run(); Assert.assertEquals("Hello World\n", output); } @Test public void testBasic_tarBaseImage_dockerSavedCommand() throws IOException, InterruptedException, InvalidImageReferenceException, ExecutionException, RegistryException, CacheDirectoryCreationException { localRegistry.pull("busybox"); Path path = temporaryFolder.getRoot().toPath().resolve("docker-save"); new Command("docker", "save", "busybox", "-o", path.toString()).run(); ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "basic-helloworld-dockersavedtar"); JibContainer jibContainer = Jib.from("tar://" + path) .setEntrypoint("echo", "Hello World") .containerize(getLocalRegistryContainerizer(targetImageReference)); Assert.assertEquals("Hello World\n", pullAndRunBuiltImage(targetImageReference.toString())); Assert.assertEquals( "Hello World\n", pullAndRunBuiltImage( targetImageReference.withQualifier(jibContainer.getDigest().toString()).toString())); } @Test public void testBasic_tarBaseImage_dockerSavedFile() throws IOException, InterruptedException, InvalidImageReferenceException, ExecutionException, RegistryException, CacheDirectoryCreationException, URISyntaxException { // tar saved with 'docker save busybox -o busybox.tar' Path path = Paths.get(Resources.getResource("core/busybox-docker.tar").toURI()); ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "basic-helloworld-dockersavedtar"); JibContainer jibContainer = Jib.from(TarImage.at(path).named("ignored")) .setEntrypoint("echo", "Hello World") .containerize(getLocalRegistryContainerizer(targetImageReference)); Assert.assertEquals("Hello World\n", pullAndRunBuiltImage(targetImageReference.toString())); Assert.assertEquals( "Hello World\n", pullAndRunBuiltImage( targetImageReference.withQualifier(jibContainer.getDigest().toString()).toString())); } @Test public void testBasic_tarBaseImage_jibImage() throws InvalidImageReferenceException, InterruptedException, ExecutionException, RegistryException, CacheDirectoryCreationException, IOException, URISyntaxException { ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "jib-base-image"); Path outputPath = temporaryFolder.getRoot().toPath().resolve("jib-image.tar"); Jib.from("busybox") .addLayer( Collections.singletonList(Paths.get(Resources.getResource("core/hello").toURI())), "/") .containerize( Containerizer.to(TarImage.at(outputPath).named(targetImageReference)) .setAllowInsecureRegistries(true)); targetImageReference = ImageReference.of("localhost:5000", "jib-core", "jib-helloworld-jibtar"); JibContainer jibContainer = Jib.from(TarImage.at(outputPath).named("ignored")) .setEntrypoint("cat", "/hello") .containerize(getLocalRegistryContainerizer(targetImageReference)); Assert.assertEquals("Hello World\n", pullAndRunBuiltImage(targetImageReference.toString())); Assert.assertEquals( "Hello World\n", pullAndRunBuiltImage( targetImageReference.withQualifier(jibContainer.getDigest().toString()).toString())); } @Test public void testBasic_tarBaseImage_jibImageToDockerDaemon() throws InvalidImageReferenceException, InterruptedException, ExecutionException, RegistryException, CacheDirectoryCreationException, IOException, URISyntaxException { // tar saved with Jib.from("busybox").addLayer(...("core/hello")).containerize(TarImage.at...) Path path = Paths.get(Resources.getResource("core/busybox-jib.tar").toURI()); ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "basic-helloworld-jibtar"); JibContainer jibContainer = Jib.from(TarImage.at(path).named("ignored")) .setEntrypoint("cat", "/hello") .containerize(getLocalRegistryContainerizer(targetImageReference)); Assert.assertEquals("Hello World\n", pullAndRunBuiltImage(targetImageReference.toString())); Assert.assertEquals( "Hello World\n", pullAndRunBuiltImage( targetImageReference.withQualifier(jibContainer.getDigest().toString()).toString())); } @Test public void testScratch() throws IOException, InterruptedException, ExecutionException, RegistryException, CacheDirectoryCreationException { ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "basic-scratch"); Jib.fromScratch().containerize(getLocalRegistryContainerizer(targetImageReference)); // Check that resulting image has no layers localRegistry.pull(targetImageReference.toString()); String inspectOutput = new Command("docker", "inspect", targetImageReference.toString()).run(); Assert.assertFalse( "docker inspect output contained layers: " + inspectOutput, inspectOutput.contains("\"Layers\": [")); } @Test public void testOffline() throws IOException, InterruptedException, InvalidImageReferenceException, ExecutionException, RegistryException, CacheDirectoryCreationException { LocalRegistry tempRegistry = new LocalRegistry(5001); tempRegistry.start(); tempRegistry.pullAndPushToLocal("busybox", "busybox"); Path cacheDirectory = temporaryFolder.getRoot().toPath(); ImageReference targetImageReferenceOnline = ImageReference.of("localhost:5001", "jib-core", "basic-online"); ImageReference targetImageReferenceOffline = ImageReference.of("localhost:5001", "jib-core", "basic-offline"); JibContainerBuilder jibContainerBuilder = Jib.from("localhost:5001/busybox").setEntrypoint("echo", "Hello World"); // Should fail since Jib can't build to registry offline try { jibContainerBuilder.containerize( Containerizer.to(RegistryImage.named(targetImageReferenceOffline)).setOfflineMode(true)); Assert.fail(); } catch (IllegalStateException ex) { Assert.assertEquals("Cannot build to a container registry in offline mode", ex.getMessage()); } // Should fail since Jib hasn't cached the base image yet try { jibContainerBuilder.containerize( Containerizer.to(DockerDaemonImage.named(targetImageReferenceOffline)) .setBaseImageLayersCache(cacheDirectory) .setOfflineMode(true)); Assert.fail(); } catch (ExecutionException ex) { Assert.assertEquals( "Cannot run Jib in offline mode; localhost:5001/busybox not found in local Jib cache", ex.getCause().getMessage()); } // Run online to cache the base image jibContainerBuilder.containerize( Containerizer.to(DockerDaemonImage.named(targetImageReferenceOnline)) .setBaseImageLayersCache(cacheDirectory) .setAllowInsecureRegistries(true)); // Run again in offline mode, should succeed this time tempRegistry.stop(); jibContainerBuilder.containerize( Containerizer.to(DockerDaemonImage.named(targetImageReferenceOffline)) .setBaseImageLayersCache(cacheDirectory) .setOfflineMode(true)); // Verify output Assert.assertEquals( "Hello World\n", new Command("docker", "run", "--rm", targetImageReferenceOffline.toString()).run()); } /** Ensure that a provided executor is not disposed. */ @Test public void testProvidedExecutorNotDisposed() throws InvalidImageReferenceException, InterruptedException, CacheDirectoryCreationException, IOException, RegistryException, ExecutionException { ImageReference targetImageReference = ImageReference.of("localhost:5000", "jib-core", "basic-helloworld"); Containerizer containerizer = getLocalRegistryContainerizer(targetImageReference); ExecutorService executorService = Executors.newCachedThreadPool(); try { containerizer.setExecutorService(executorService); Jib.from("busybox").setEntrypoint("echo", "Hello World").containerize(containerizer); Assert.assertFalse(executorService.isShutdown()); } finally { executorService.shutdown(); } } @Test public void testManifestListReferenceByShaDoesNotFail() throws InvalidImageReferenceException, IOException, InterruptedException, ExecutionException, RegistryException, CacheDirectoryCreationException { ImageReference sourceImageReferenceAsManifestList = ImageReference.parse("openjdk@" + ManifestPullerIntegrationTest.KNOWN_MANIFEST_LIST_SHA); Containerizer containerizer = Containerizer.to( TarImage.at(temporaryFolder.newFolder("goose").toPath().resolve("moose")) .named("whatever")); Jib.from(sourceImageReferenceAsManifestList).containerize(containerizer); // pass, no exceptions thrown } }
{ "pile_set_name": "Github" }
/** * Project: zebra-client * * File Created at 2011-6-19 * $Id$ * * Copyright 2010 dianping.com. * All rights reserved. * * This software is the confidential and proprietary information of * Dianping Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with dianping.com. */ package com.dianping.zebra.group.jdbc.param; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Calendar; /** * TODO Comment of DateParamContext * * @author Leo Liang */ public class DateParamContext extends ParamContext { private static final long serialVersionUID = -135291105713694295L; /** * @param index * @param values */ public DateParamContext(int index, Object[] values) { super(index, values); } /* * (non-Javadoc) * * @see com.dianping.zebra.jdbc.param.ParamContext#setParam(java.sql. PreparedStatement) */ @Override public void setParam(PreparedStatement stmt) throws SQLException { if (values.length == 1) { stmt.setDate(index, (Date) values[0]); } else if (values.length == 2) { stmt.setDate(index, (Date) values[0], (Calendar) values[1]); } } }
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1 import ( "context" "time" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) // PersistentVolumeClaimsGetter has a method to return a PersistentVolumeClaimInterface. // A group's client should implement this interface. type PersistentVolumeClaimsGetter interface { PersistentVolumeClaims(namespace string) PersistentVolumeClaimInterface } // PersistentVolumeClaimInterface has methods to work with PersistentVolumeClaim resources. type PersistentVolumeClaimInterface interface { Create(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.CreateOptions) (*v1.PersistentVolumeClaim, error) Update(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.UpdateOptions) (*v1.PersistentVolumeClaim, error) UpdateStatus(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.UpdateOptions) (*v1.PersistentVolumeClaim, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.PersistentVolumeClaim, error) List(ctx context.Context, opts metav1.ListOptions) (*v1.PersistentVolumeClaimList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PersistentVolumeClaim, err error) PersistentVolumeClaimExpansion } // persistentVolumeClaims implements PersistentVolumeClaimInterface type persistentVolumeClaims struct { client rest.Interface ns string } // newPersistentVolumeClaims returns a PersistentVolumeClaims func newPersistentVolumeClaims(c *CoreV1Client, namespace string) *persistentVolumeClaims { return &persistentVolumeClaims{ client: c.RESTClient(), ns: namespace, } } // Get takes name of the persistentVolumeClaim, and returns the corresponding persistentVolumeClaim object, and an error if there is any. func (c *persistentVolumeClaims) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PersistentVolumeClaim, err error) { result = &v1.PersistentVolumeClaim{} err = c.client.Get(). Namespace(c.ns). Resource("persistentvolumeclaims"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // List takes label and field selectors, and returns the list of PersistentVolumeClaims that match those selectors. func (c *persistentVolumeClaims) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PersistentVolumeClaimList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1.PersistentVolumeClaimList{} err = c.client.Get(). Namespace(c.ns). Resource("persistentvolumeclaims"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } // Watch returns a watch.Interface that watches the requested persistentVolumeClaims. func (c *persistentVolumeClaims) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("persistentvolumeclaims"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } // Create takes the representation of a persistentVolumeClaim and creates it. Returns the server's representation of the persistentVolumeClaim, and an error, if there is any. func (c *persistentVolumeClaims) Create(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.CreateOptions) (result *v1.PersistentVolumeClaim, err error) { result = &v1.PersistentVolumeClaim{} err = c.client.Post(). Namespace(c.ns). Resource("persistentvolumeclaims"). VersionedParams(&opts, scheme.ParameterCodec). Body(persistentVolumeClaim). Do(ctx). Into(result) return } // Update takes the representation of a persistentVolumeClaim and updates it. Returns the server's representation of the persistentVolumeClaim, and an error, if there is any. func (c *persistentVolumeClaims) Update(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.UpdateOptions) (result *v1.PersistentVolumeClaim, err error) { result = &v1.PersistentVolumeClaim{} err = c.client.Put(). Namespace(c.ns). Resource("persistentvolumeclaims"). Name(persistentVolumeClaim.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(persistentVolumeClaim). Do(ctx). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *persistentVolumeClaims) UpdateStatus(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.UpdateOptions) (result *v1.PersistentVolumeClaim, err error) { result = &v1.PersistentVolumeClaim{} err = c.client.Put(). Namespace(c.ns). Resource("persistentvolumeclaims"). Name(persistentVolumeClaim.Name). SubResource("status"). VersionedParams(&opts, scheme.ParameterCodec). Body(persistentVolumeClaim). Do(ctx). Into(result) return } // Delete takes name of the persistentVolumeClaim and deletes it. Returns an error if one occurs. func (c *persistentVolumeClaims) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("persistentvolumeclaims"). Name(name). Body(&opts). Do(ctx). Error() } // DeleteCollection deletes a collection of objects. func (c *persistentVolumeClaims) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second } return c.client.Delete(). Namespace(c.ns). Resource("persistentvolumeclaims"). VersionedParams(&listOpts, scheme.ParameterCodec). Timeout(timeout). Body(&opts). Do(ctx). Error() } // Patch applies the patch and returns the patched persistentVolumeClaim. func (c *persistentVolumeClaims) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PersistentVolumeClaim, err error) { result = &v1.PersistentVolumeClaim{} err = c.client.Patch(pt). Namespace(c.ns). Resource("persistentvolumeclaims"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
{ "pile_set_name": "Github" }
/* * Copyright 2012 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Ben Skeggs */ #include "priv.h" void nv44_mc_init(struct nvkm_mc *mc) { struct nvkm_device *device = mc->subdev.device; u32 tmp = nvkm_rd32(device, 0x10020c); nvkm_wr32(device, 0x000200, 0xffffffff); /* everything enabled */ nvkm_wr32(device, 0x001700, tmp); nvkm_wr32(device, 0x001704, 0); nvkm_wr32(device, 0x001708, 0); nvkm_wr32(device, 0x00170c, tmp); } static const struct nvkm_mc_func nv44_mc = { .init = nv44_mc_init, .intr = nv17_mc_intr, .intr_unarm = nv04_mc_intr_unarm, .intr_rearm = nv04_mc_intr_rearm, .intr_stat = nv04_mc_intr_stat, .reset = nv17_mc_reset, }; int nv44_mc_new(struct nvkm_device *device, int index, struct nvkm_mc **pmc) { return nvkm_mc_new_(&nv44_mc, device, index, pmc); }
{ "pile_set_name": "Github" }
--- layout: base title: 'Statistics of iobj in UD_Basque-BDT' udver: '2' --- ## Treebank Statistics: UD_Basque-BDT: Relations: `iobj` This relation is universal. 1022 nodes (1%) are attached to their parents as `iobj`. 689 instances of `iobj` (67%) are right-to-left (child precedes parent). Average distance between parent and child is 2.73287671232877. The following 17 pairs of parts of speech are connected with `iobj`: <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt>-<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> (668; 65% instances), <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt>-<tt><a href="eu_bdt-pos-PROPN.html">PROPN</a></tt> (225; 22% instances), <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt>-<tt><a href="eu_bdt-pos-DET.html">DET</a></tt> (32; 3% instances), <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt>-<tt><a href="eu_bdt-pos-PRON.html">PRON</a></tt> (30; 3% instances), <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt>-<tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt> (19; 2% instances), <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt>-<tt><a href="eu_bdt-pos-ADJ.html">ADJ</a></tt> (13; 1% instances), <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt>-<tt><a href="eu_bdt-pos-NUM.html">NUM</a></tt> (9; 1% instances), <tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt>-<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> (6; 1% instances), <tt><a href="eu_bdt-pos-PUNCT.html">PUNCT</a></tt>-<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> (5; 0% instances), <tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt>-<tt><a href="eu_bdt-pos-PROPN.html">PROPN</a></tt> (4; 0% instances), <tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt>-<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> (3; 0% instances), <tt><a href="eu_bdt-pos-PUNCT.html">PUNCT</a></tt>-<tt><a href="eu_bdt-pos-PROPN.html">PROPN</a></tt> (2; 0% instances), <tt><a href="eu_bdt-pos-X.html">X</a></tt>-<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> (2; 0% instances), <tt><a href="eu_bdt-pos-ADV.html">ADV</a></tt>-<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> (1; 0% instances), <tt><a href="eu_bdt-pos-AUX.html">AUX</a></tt>-<tt><a href="eu_bdt-pos-PROPN.html">PROPN</a></tt> (1; 0% instances), <tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt>-<tt><a href="eu_bdt-pos-PROPN.html">PROPN</a></tt> (1; 0% instances), <tt><a href="eu_bdt-pos-PUNCT.html">PUNCT</a></tt>-<tt><a href="eu_bdt-pos-NUM.html">NUM</a></tt> (1; 0% instances). ~~~ conllu # visual-style 1 bgColor:blue # visual-style 1 fgColor:white # visual-style 2 bgColor:blue # visual-style 2 fgColor:white # visual-style 2 1 iobj color:blue 1 Aurkariari aurkari NOUN _ Case=Dat|Definite=Def|Number=Sing 2 iobj _ _ 2 dagokionez egon VERB _ Aspect=Prog|Mood=Ind|Number[abs]=Sing|Number[dat]=Sing|Person[abs]=3|Person[dat]=3 6 advcl _ SpaceAfter=No 3 , , PUNCT _ _ 6 punct _ _ 4 Feyenoord Feyenoord PROPN _ _ 6 nsubj _ _ 5 ez ez PART _ Polarity=Neg 6 advmod _ _ 6 dago egon VERB _ Aspect=Prog|Mood=Ind|Number[abs]=Sing|Person[abs]=3 0 root _ _ 7 bere bera DET _ Case=Gen|Number=Sing 8 nmod _ _ 8 garairik garai ADJ _ Case=Par|Definite=Ind 6 obl _ _ 9 onenean on ADJ _ Case=Ine|Definite=Def|Degree=Sup|Number=Sing 8 amod _ SpaceAfter=No 10 . . PUNCT _ _ 6 punct _ _ ~~~ ~~~ conllu # visual-style 1 bgColor:blue # visual-style 1 fgColor:white # visual-style 7 bgColor:blue # visual-style 7 fgColor:white # visual-style 7 1 iobj color:blue 1 Susanari Susana PROPN _ Case=Dat|Definite=Def|Number=Sing 7 iobj _ _ 2 ere ere CCONJ _ _ 4 advmod _ _ 3 ez ez PART _ Polarity=Neg 4 advmod _ _ 4 zirudien iruditu VERB _ Aspect=Prog|Mood=Ind|Number[abs]=Sing|Number[erg]=Sing|Person[abs]=3|Person[erg]=3 0 root _ _ 5 asko asko ADV _ _ 7 advmod _ _ 6 axola axola NOUN _ Case=Abs|Definite=Ind 7 compound _ _ 7 zitzaionik izan VERB _ _ 4 ccomp _ SpaceAfter=No 8 : : PUNCT _ _ 4 punct _ _ ~~~ ~~~ conllu # visual-style 1 bgColor:blue # visual-style 1 fgColor:white # visual-style 2 bgColor:blue # visual-style 2 fgColor:white # visual-style 2 1 iobj color:blue 1 Besteei beste DET _ Case=Dat|Definite=Def|Number=Plur 2 iobj _ _ 2 esan esan VERB _ Aspect=Perf|VerbForm=Part 0 root _ _ 3 zien *edun AUX _ Mood=Ind|Number[abs]=Sing|Number[dat]=Plur|Number[erg]=Sing|Person[abs]=3|Person[dat]=3|Person[erg]=3 2 aux _ SpaceAfter=No 4 : : PUNCT _ _ 2 punct _ _ ~~~
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 人臉辨識 - 臉部偵測、對齊 & 裁剪\n", "人臉辨識大致可分成四個主要的步驟:\n", "1. 人臉偵測\n", "2. 人臉轉換、對齊與裁剪\n", "3. 人臉特徵擷取\n", "4. 人臉特徵比對\n", "\n", "在這篇文章中主要是介紹:\n", "1. 使用MTCNN來進行人臉偵測 -> Detect\n", "2. 然後進行簡單的裁剪 -> Tranform & Crop\n", "\n", "![openface](https://raw.githubusercontent.com/cmusatyalab/openface/master/images/summary.jpg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## face-recognition 專案說明\n", "\n", "[face-recognition](https://github.com/erhwenkuo/face-recognition)包含了使用MTCNN與FaceNet來進行人臉辨識。\n", "\n", "### 安裝\n", "\n", "```bash\n", "git clone https://github.com/erhwenkuo/face-recognition.git\n", "cd face-recognition\n", "...\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 資料集說明\n", "\n", "LFW資料集是一個常見的人臉資料集,歷史非常悠久。LFW資料集中收錄了5749位公眾人物的人臉影像,總共有超過一萬三千多張影像檔案。但大部份公眾人物的影像都只有一張,只有1680位有超過一張照片,而極少數有超過10張照片。\n", "\n", "資料集的網站: http://vis-www.cs.umass.edu/lfw" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 專案的檔案路徑佈局\n", "\n", "1. 使用Git從[erhwenkuo/face-recognition]https://github.com/erhwenkuo/face-recognition.git)下載整個專案源碼\n", "2. 在`face-recognition`的目錄裡產生二個子目錄`data`與`model`\n", "3. 從[Labeled Faces in the Wild資料集官網]點撃[All images as gzipped tar file](http://vis-www.cs.umass.edu/lfw/lfw.tgz)來下 載`lfw.tgz`。\n", "4. 解壓縮`lfw.tgz`到`face-recognition/data/`的目錄下\n", "\n", "最後你的目錄結構看起來像這樣: (這裡只列出來在這個範例會用到的相關檔案與目錄)\n", "```\n", "face-recognition/\n", "├── xxxx.ipynb\n", "├── detect_face.py\n", "├── facenet.py\n", "├── model/\n", "│ └── mtcnn/\n", "│ ├── det1.npy\n", "│ ├── det2.npy\n", "│ └── det3.npy\n", "└── data/\n", " └── lfw/\n", " ├── Aaron_Eckhart/ \n", " │ └── Aaron_Eckhart_0001.jpg\n", " ├── ...\n", " └── Zydrunas_Ilgauskas/\n", " └── Zydrunas_Ilgauskas_0001.jpg\n", " \n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### STEP 1. 載入相關函式庫" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 屏蔽Jupyter的warning訊息\n", "import warnings\n", "warnings.filterwarnings('ignore')\n", "\n", "# Utilities相關函式庫\n", "from scipy import misc\n", "import sys\n", "import os\n", "import random\n", "from tqdm import tqdm\n", "\n", "# 多維向量處理相關函式庫\n", "import numpy as np\n", "\n", "# 圖像處理相關函式庫\n", "import cv2\n", "\n", "# 深度學習相關函式庫\n", "import tensorflow as tf\n", "\n", "# 專案相關函式庫\n", "import facenet\n", "import detect_face" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### STEP 2. 設定相關設定與參數" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 專案的根目錄路徑\n", "ROOT_DIR = os.getcwd()\n", "\n", "# 訓練/驗證用的資料目錄\n", "DATA_PATH = os.path.join(ROOT_DIR, \"data\")\n", "\n", "# 模型的資料目錄\n", "MODEL_PATH = os.path.join(ROOT_DIR, \"model\")\n", "\n", "# MTCNN的模型\n", "MTCNN_MODEL_PATH = os.path.join(MODEL_PATH, \"mtcnn\")\n", "\n", "# 訓練/驗證用的圖像資料目錄\n", "IMG_IN_PATH = os.path.join(DATA_PATH, \"lfw\")\n", "\n", "# 訓練/驗證用的圖像資料目錄\n", "IMG_OUT_PATH = os.path.join(DATA_PATH, \"lfw_crops\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### STEP 3. 取得儲存在檔案系統裡的人臉圖像資料集的圖像路徑與人臉的identity\n", "```\n", "參數:\n", " paths (string): 圖像資料集的檔案路徑\n", " has_class_directories (bool): 是否使用子目錄名作為人臉的identity (預設為True)\n", " path_expanduser (bool): 是否把path中包含的\"~\"和\"~user\"轉換成在作業系統下的用戶根目錄 (預設為False)\n", "回傳:\n", " dataset (list[ImageClass]): 人臉類別(ImageClass)的列表與圖像路徑\n", "```" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 檢查要儲放裁剪結果的目錄\n", "if not os.path.exists(IMG_OUT_PATH):\n", " os.makedirs(IMG_OUT_PATH)\n", "\n", "\n", "# 臉類別(ImageClass)的列表與圖像路徑\n", "dataset = facenet.get_dataset(IMG_IN_PATH)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total face identities: 5749\n" ] } ], "source": [ "# 打印看有多少人臉的身份\n", "print(\"Total face identities: \", len(dataset))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### STEP 4. 構建MTCNN的模型來偵測人臉位置\n", "詳細說明: [人臉偵測 - MTCNN (Multi-task Cascaded Convolutional Networks)](https://github.com/erhwenkuo/deep-learning-with-keras-notebooks/blob/master/7.1-mtcnn-face-detection.ipynb)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating networks and loading parameters\n" ] } ], "source": [ "print('Creating networks and loading parameters')\n", "with tf.Graph().as_default():\n", " gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)\n", " sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n", " with sess.as_default():\n", " pnet, rnet, onet = detect_face.create_mtcnn(sess, MTCNN_MODEL_PATH)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 設定人臉偵測模型所需的相關參數" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "minsize = 20 # 最小的臉部的大小\n", "threshold = [0.6, 0.7, 0.7] # 三個網絡(P-Net, R-Net, O-Net)的閥值\n", "factor = 0.709 # scale factor\n", "\n", "margin = 44 # 在裁剪人臉時的邊框margin\n", "image_size = 182 # 160 + 22" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 將一個隨機key添加到圖像檔名以允許使用多個進程進行人臉對齊\n", "random_key = np.random.randint(0, high=99999)\n", "bounding_boxes_filename = os.path.join(IMG_OUT_PATH, 'bounding_boxes_%05d.txt' % random_key)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### STEP 5. 人臉圖像處理\n", "\n", "對每一張人臉圖像進行偵測並找出靠近圖像中心點的人臉邊界框來進行裁剪及調整大小。\n", "\n", "ImageClass類別\n", "```\n", "儲存某特定人臉(Identity)的名稱與相關的人臉圖像的路徑列表的類別\n", " \n", " 屬性:\n", " name (string): 人臉的Identity\n", " image_paths (List<string>): 人臉圖像路徑的列表\n", " \n", " 方法:\n", " str(ImageClass): 取得人臉的Identity\n", " len(ImageClass): 取得人臉的Identity有多少圖像 \n", "```" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████████████████████████████████| 5749/5749 [39:27<00:00, 2.43it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Total number of images: 13233\n", "Number of successfully aligned images: 13233\n" ] } ], "source": [ "# 使用Tensorflow來運行MTCNN\n", "with open(bounding_boxes_filename, \"w\") as text_file:\n", " nrof_images_total = 0 # 處理過的圖像總數\n", " nrof_successfully_aligned = 0 # 人臉圖像align的總數\n", " \n", " # 迭代每一個人臉身份(ImageClass)\n", " for cls in tqdm(dataset):\n", " output_class_dir = os.path.join(IMG_OUT_PATH, cls.name) # 裁剪後的圖像目錄\n", " if not os.path.exists(output_class_dir):\n", " os.makedirs(output_class_dir)\n", " \n", " # 迭代每一個人臉身份的圖像的路徑 (ImageClass.image_paths)\n", " for image_path in cls.image_paths:\n", " nrof_images_total += 1\n", " filename = os.path.splitext(os.path.split(image_path)[1])[0] # 取得圖像檔名\n", " output_filename = os.path.join(output_class_dir, filename + '.png') # 設定輸出的圖像檔名 \n", " # print(image_path)\n", " \n", " if not os.path.exists(output_filename):\n", " try:\n", " img = misc.imread(image_path) # 讀進圖檔\n", " # print('read data dimension: ', img.ndim) \n", " except (IOError, ValueError, IndexError) as e:\n", " errorMessage = '{}: {}'.format(image_path, e)\n", " # print(errorMessage)\n", " else:\n", " # 將圖檔轉換成numpy array (height, widith, color_channels)\n", " if img.ndim < 2:\n", " print('Unable to align \"%s\"' % image_path)\n", " text_file.write('%s\\n' % (output_filename))\n", " continue\n", " if img.ndim == 2:\n", " img = facenet.to_rgb(img)\n", " print('to_rgb data dimension: ', img.ndim)\n", " img = img[:, :, 0:3]\n", " # print('after data dimension: ', img.ndim)\n", " \n", " # 使用MTCNN來偵測人臉在圖像中的位置\n", " bounding_boxes, _ = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n", " nrof_faces = bounding_boxes.shape[0] # 偵測到的人臉總數\n", " # print('detected_face: %d' % nrof_faces)\n", " if nrof_faces > 0:\n", " # 當有偵測到多個人臉的時候, 我們希望從中找到主要置中位置的人臉\n", " det = bounding_boxes[:, 0:4]\n", " img_size = np.asarray(img.shape)[0:2]\n", " if nrof_faces > 1:\n", " bounding_box_size = (det[:, 2] - det[:, 0]) * (det[:, 3] - det[:, 1])\n", " img_center = img_size / 2\n", " offsets = np.vstack([(det[:, 0] + det[:, 2]) / 2 - img_center[1],\n", " (det[:, 1] + det[:, 3]) / 2 - img_center[0]])\n", " offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)\n", " index = np.argmax(bounding_box_size - offset_dist_squared * 2.0) # some extra weight on the centering\n", " det = det[index, :]\n", " det = np.squeeze(det)\n", " bb_temp = np.zeros(4, dtype=np.int32)\n", " # 取得人臉的左上角與右下角座標\n", " bb_temp[0] = det[0]\n", " bb_temp[1] = det[1]\n", " bb_temp[2] = det[2]\n", " bb_temp[3] = det[3]\n", " \n", " # 進行裁剪以及大小的轉換\n", " cropped_temp = img[bb_temp[1]:bb_temp[3], bb_temp[0]:bb_temp[2], :]\n", " scaled_temp = misc.imresize(cropped_temp, (image_size, image_size), interp='bilinear')\n", "\n", " nrof_successfully_aligned += 1\n", " misc.imsave(output_filename, scaled_temp) # 儲存處理過的圖像\n", " text_file.write('%s %d %d %d %d\\n' % (output_filename, bb_temp[0], bb_temp[1], bb_temp[2], bb_temp[3]))\n", " else:\n", " # print('Unable to align \"%s\"' % image_path)\n", " text_file.write('%s\\n' % (output_filename))\n", "\n", "print('Total number of images: %d' % nrof_images_total)\n", "print('Number of successfully aligned images: %d' % nrof_successfully_aligned)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### STEP 6. 檢查人臉圖像處理結果" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "face_identity = 'Bill_Clinton'\n", "origin_face_image = os.path.join(IMG_IN_PATH, face_identity, 'Bill_Clinton_0009.jpg')\n", "aligned_face_image = os.path.join(IMG_OUT_PATH, face_identity, 'Bill_Clinton_0009.png')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 使用OpenCV讀入測試圖像\n", "# 注意: OpenCV讀進來的圖像所產生的Numpy Ndaary格式是BGR (B:Blue, G: Green, R: Red) \n", "# 跟使用PIL或skimage的格式RGB (R: Red, G: Green, B:Blue)在色階(channel)的順序上有所不同\n", "bgr_image = cv2.imread(origin_face_image)\n", "rgb_image = bgr_image[:,:,::-1] # 把BGR轉換成RGB\n", "\n", "# 偵測人臉\n", "bounding_boxes, _ = detect_face.detect_face(rgb_image, minsize, pnet, rnet, onet, threshold, factor)\n", "\n", "# 複製原圖像\n", "draw = bgr_image.copy()\n", "\n", "# 被偵測到的臉部總數\n", "faces_detected = len(bounding_boxes)\n", "\n", "print('Total faces detected :{}'.format(faces_detected))\n", "\n", "# 每一個 bounding_box包括了(x1,y1,x2,y2,confidence score):\n", "#   左上角座標 (x1,y1)\n", "# 右下角座標 (x2,y2)\n", "# 信心分數 confidence score\n", "\n", "# 迭代每一個偵測出來的邊界框\n", "for face_position in bounding_boxes:\n", " # 把資料由float轉成int\n", " face_position=face_position.astype(int)\n", " \n", " # 取出左上角座標 (x1,y1)與右下角座標 (x2,y2)\n", " # 由於有可能預測出來的臉在圖像的圖邊而導致座標值為負值\n", " # 因此進行的負值的偵測與修正\n", " x1 = face_position[0] if face_position[0] > 0 else 0\n", " y1 = face_position[1] if face_position[1] > 0 else 0\n", " x2 = face_position[2] if face_position[2] > 0 else 0\n", " y2 = face_position[3] if face_position[3] > 0 else 0\n", " \n", " # 在原圖像上畫上這些邊界框 \n", " cv2.rectangle(draw, (x1, y1), (x2, y2), (0, 255, 0), 2)\n", "\n", "# 設定展示的大小\n", "plt.figure(figsize=(10,5))\n", "\n", "# 展示偵測出來的結果\n", "plt.imshow(draw[:,:,::-1]) # 轉換成RGB來給matplotlib展示\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "以上的人臉圖像裡頭有兩個人臉被找出來,因此在圖像處理中要找到離圖像中心點比較接近的那一個來當成主要的人臉圖像並進行其它的前處理。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bgr_image = cv2.imread(aligned_face_image)\n", "rgb_image = bgr_image[:,:,::-1] # 把BGR轉換成RGB\n", "\n", "# 設定展示的大小\n", "plt.figure(figsize=(8,3))\n", "\n", "# 展示偵測出來的結果\n", "plt.imshow(rgb_image) # 轉換成RGB來給matplotlib展示\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### 參考\n", "* [Multi-task Cascaded Convolutional Networks論文](https://arxiv.org/abs/1604.02878v1)\n", "* [OpenFace](https://github.com/cmusatyalab/openface)\n", "* Facenet 專案 [davidsandberg](https://github.com/davidsandberg/facenet)\n", "* [bearsprogrammer](https://github.com/bearsprogrammer/real-time-deep-face-recognition)\n", "* [shanren7](https://github.com/shanren7/real_time_face_recognition)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "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.5.3" } }, "nbformat": 4, "nbformat_minor": 2 }
{ "pile_set_name": "Github" }
<?php namespace Watson\Active; use Illuminate\Routing\Router; use Illuminate\Support\Str; class Route { /** * Illuminate Router instance. * * @var \Illuminate\Routing\Router */ protected $router; /** * Construct the class. * * @param \Illuminate\Routing\Router $router * @return void */ public function __construct(Router $router) { $this->router = $router; } /** * Get the controller name, separated as necessary and with or without namespaces. * * @param string $separator * @param bool $includeNamespace * @param string $trimNamespace * @return string|null */ public function controller($separator = null, $includeNamespace = true, $trimNamespace = 'App\Http\Controllers\\') { if ($action = $this->router->currentRouteAction()) { $separator = is_null($separator) ? ' ' : $separator; $controller = head(Str::parseCallback($action, null)); // If the controller contains the given namespace, remove it. if (substr($controller, 0, strlen($trimNamespace)) === $trimNamespace) { $controller = substr($controller, strlen($trimNamespace)); } // If the controller contains 'Controller' at the end, remove it. if (substr($controller, - strlen('Controller')) === 'Controller') { $controller = substr($controller, 0, - strlen('Controller')); } // Separate out nested controller resources. $controller = str_replace('_', $separator, Str::snake($controller)); // Either separate out the namespaces or remove them. $controller = $includeNamespace ? str_replace('\\', null, $controller) : substr(strrchr($controller, '\\'), 1); return trim($controller); } return null; } /** * Get the current controller action name. * * @param bool $removeHttpMethod * @return string|null */ public function action($removeHttpMethod = true) { if ($action = $this->router->currentRouteAction()) { $action = last(Str::parseCallback($action, null)); if ($removeHttpMethod) { $action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', $action); } return Str::snake($action, '-'); } return null; } }
{ "pile_set_name": "Github" }
endian big
{ "pile_set_name": "Github" }
{ "name": "Visit OSLO AS", "displayName": "Visit OSLO", "properties": [ "visitoslo.com" ] }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2005 - 2013 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2013 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2006 - 2013 ScriptDev2 <http://www.scriptdev2.com/> * * Copyright (C) 2010 - 2013 ProjectSkyfire <http://www.projectskyfire.org/> * * Copyright (C) 2011 - 2013 ArkCORE <http://www.arkania.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 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef DEF_RAMPARTS_H #define DEF_RAMPARTS_H #define MAX_ENCOUNTER 2 enum eTypes { TYPE_VAZRUDEN = 1, TYPE_NAZAN = 2 }; #endif
{ "pile_set_name": "Github" }
/* * Copyright © 2012 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "mtypes.h" #include "context.h" #include "glformats.h" #include "macros.h" #include "enums.h" #include "fbobject.h" #include "formatquery.h" #include "teximage.h" #include "texparam.h" #include "texobj.h" #include "get.h" #include "genmipmap.h" #include "shaderimage.h" #include "texcompress.h" #include "textureview.h" static bool _is_renderable(struct gl_context *ctx, GLenum internalformat) { /* Section 4.4.4 on page 212 of the GLES 3.0.4 spec says: * * "An internal format is color-renderable if it is one of the * formats from table 3.13 noted as color-renderable or if it * is unsized format RGBA or RGB." * * Therefore, we must accept GL_RGB and GL_RGBA here. */ if (internalformat != GL_RGB && internalformat != GL_RGBA && _mesa_base_fbo_format(ctx, internalformat) == 0) return false; return true; } /* Handles the cases where either ARB_internalformat_query or * ARB_internalformat_query2 have to return an error. */ static bool _legal_parameters(struct gl_context *ctx, GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params) { bool query2 = _mesa_has_ARB_internalformat_query2(ctx); /* The ARB_internalformat_query2 spec says: * * "The INVALID_ENUM error is generated if the <target> parameter to * GetInternalformati*v is not one of the targets listed in Table 6.xx. */ switch(target){ case GL_TEXTURE_1D: case GL_TEXTURE_1D_ARRAY: case GL_TEXTURE_2D: case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_3D: case GL_TEXTURE_CUBE_MAP: case GL_TEXTURE_CUBE_MAP_ARRAY: case GL_TEXTURE_RECTANGLE: case GL_TEXTURE_BUFFER: if (!query2) { /* The ARB_internalformat_query spec says: * * "If the <target> parameter to GetInternalformativ is not one of * TEXTURE_2D_MULTISAMPLE, TEXTURE_2D_MULTISAMPLE_ARRAY * or RENDERBUFFER then an INVALID_ENUM error is generated. */ _mesa_error(ctx, GL_INVALID_ENUM, "glGetInternalformativ(target=%s)", _mesa_enum_to_string(target)); return false; } break; case GL_RENDERBUFFER: break; case GL_TEXTURE_2D_MULTISAMPLE: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: /* The non-existence of ARB_texture_multisample is treated in * ARB_internalformat_query implementation like an error. */ if (!query2 && !(_mesa_has_ARB_texture_multisample(ctx) || _mesa_is_gles31(ctx))) { _mesa_error(ctx, GL_INVALID_ENUM, "glGetInternalformativ(target=%s)", _mesa_enum_to_string(target)); return false; } break; default: _mesa_error(ctx, GL_INVALID_ENUM, "glGetInternalformativ(target=%s)", _mesa_enum_to_string(target)); return false; } /* The ARB_internalformat_query2 spec says: * * "The INVALID_ENUM error is generated if the <pname> parameter is * not one of the listed possibilities. */ switch(pname){ case GL_SAMPLES: case GL_NUM_SAMPLE_COUNTS: break; case GL_SRGB_DECODE_ARB: /* The ARB_internalformat_query2 spec says: * * "If ARB_texture_sRGB_decode or EXT_texture_sRGB_decode or * equivalent functionality is not supported, queries for the * SRGB_DECODE_ARB <pname> set the INVALID_ENUM error. */ if (!_mesa_has_EXT_texture_sRGB_decode(ctx)) { _mesa_error(ctx, GL_INVALID_ENUM, "glGetInternalformativ(pname=%s)", _mesa_enum_to_string(pname)); return false; } /* fallthrough */ case GL_INTERNALFORMAT_SUPPORTED: case GL_INTERNALFORMAT_PREFERRED: case GL_INTERNALFORMAT_RED_SIZE: case GL_INTERNALFORMAT_GREEN_SIZE: case GL_INTERNALFORMAT_BLUE_SIZE: case GL_INTERNALFORMAT_ALPHA_SIZE: case GL_INTERNALFORMAT_DEPTH_SIZE: case GL_INTERNALFORMAT_STENCIL_SIZE: case GL_INTERNALFORMAT_SHARED_SIZE: case GL_INTERNALFORMAT_RED_TYPE: case GL_INTERNALFORMAT_GREEN_TYPE: case GL_INTERNALFORMAT_BLUE_TYPE: case GL_INTERNALFORMAT_ALPHA_TYPE: case GL_INTERNALFORMAT_DEPTH_TYPE: case GL_INTERNALFORMAT_STENCIL_TYPE: case GL_MAX_WIDTH: case GL_MAX_HEIGHT: case GL_MAX_DEPTH: case GL_MAX_LAYERS: case GL_MAX_COMBINED_DIMENSIONS: case GL_COLOR_COMPONENTS: case GL_DEPTH_COMPONENTS: case GL_STENCIL_COMPONENTS: case GL_COLOR_RENDERABLE: case GL_DEPTH_RENDERABLE: case GL_STENCIL_RENDERABLE: case GL_FRAMEBUFFER_RENDERABLE: case GL_FRAMEBUFFER_RENDERABLE_LAYERED: case GL_FRAMEBUFFER_BLEND: case GL_READ_PIXELS: case GL_READ_PIXELS_FORMAT: case GL_READ_PIXELS_TYPE: case GL_TEXTURE_IMAGE_FORMAT: case GL_TEXTURE_IMAGE_TYPE: case GL_GET_TEXTURE_IMAGE_FORMAT: case GL_GET_TEXTURE_IMAGE_TYPE: case GL_MIPMAP: case GL_MANUAL_GENERATE_MIPMAP: case GL_AUTO_GENERATE_MIPMAP: case GL_COLOR_ENCODING: case GL_SRGB_READ: case GL_SRGB_WRITE: case GL_FILTER: case GL_VERTEX_TEXTURE: case GL_TESS_CONTROL_TEXTURE: case GL_TESS_EVALUATION_TEXTURE: case GL_GEOMETRY_TEXTURE: case GL_FRAGMENT_TEXTURE: case GL_COMPUTE_TEXTURE: case GL_TEXTURE_SHADOW: case GL_TEXTURE_GATHER: case GL_TEXTURE_GATHER_SHADOW: case GL_SHADER_IMAGE_LOAD: case GL_SHADER_IMAGE_STORE: case GL_SHADER_IMAGE_ATOMIC: case GL_IMAGE_TEXEL_SIZE: case GL_IMAGE_COMPATIBILITY_CLASS: case GL_IMAGE_PIXEL_FORMAT: case GL_IMAGE_PIXEL_TYPE: case GL_IMAGE_FORMAT_COMPATIBILITY_TYPE: case GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST: case GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST: case GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE: case GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE: case GL_TEXTURE_COMPRESSED: case GL_TEXTURE_COMPRESSED_BLOCK_WIDTH: case GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT: case GL_TEXTURE_COMPRESSED_BLOCK_SIZE: case GL_CLEAR_BUFFER: case GL_TEXTURE_VIEW: case GL_VIEW_COMPATIBILITY_CLASS: case GL_NUM_TILING_TYPES_EXT: case GL_TILING_TYPES_EXT: /* The ARB_internalformat_query spec says: * * "If the <pname> parameter to GetInternalformativ is not SAMPLES * or NUM_SAMPLE_COUNTS, then an INVALID_ENUM error is generated." */ if (!query2) { _mesa_error(ctx, GL_INVALID_ENUM, "glGetInternalformativ(pname=%s)", _mesa_enum_to_string(pname)); return false; } break; default: _mesa_error(ctx, GL_INVALID_ENUM, "glGetInternalformativ(pname=%s)", _mesa_enum_to_string(pname)); return false; } /* The ARB_internalformat_query spec says: * * "If the <bufSize> parameter to GetInternalformativ is negative, then * an INVALID_VALUE error is generated." * * Nothing is said in ARB_internalformat_query2 but we assume the same. */ if (bufSize < 0) { _mesa_error(ctx, GL_INVALID_VALUE, "glGetInternalformativ(target=%s)", _mesa_enum_to_string(target)); return false; } /* The ARB_internalformat_query spec says: * * "If the <internalformat> parameter to GetInternalformativ is not * color-, depth- or stencil-renderable, then an INVALID_ENUM error is * generated." */ if (!query2 && !_is_renderable(ctx, internalformat)) { _mesa_error(ctx, GL_INVALID_ENUM, "glGetInternalformativ(internalformat=%s)", _mesa_enum_to_string(internalformat)); return false; } return true; } /* Sets the appropriate "unsupported" response as defined by the * ARB_internalformat_query2 spec for each each <pname>. */ static void _set_default_response(GLenum pname, GLint buffer[16]) { /* The ARB_internalformat_query2 defines which is the reponse best * representing "not supported" or "not applicable" for each <pname>. * * " In general: * - size- or count-based queries will return zero, * - support-, format- or type-based queries will return NONE, * - boolean-based queries will return FALSE, and * - list-based queries return no entries." */ switch(pname) { case GL_SAMPLES: case GL_TILING_TYPES_EXT: break; case GL_MAX_COMBINED_DIMENSIONS: /* This value can be a 64-bit value. As the default is the 32-bit query, * we pack 2 32-bit integers. So we need to clean both */ buffer[0] = 0; buffer[1] = 0; break; case GL_NUM_SAMPLE_COUNTS: case GL_INTERNALFORMAT_RED_SIZE: case GL_INTERNALFORMAT_GREEN_SIZE: case GL_INTERNALFORMAT_BLUE_SIZE: case GL_INTERNALFORMAT_ALPHA_SIZE: case GL_INTERNALFORMAT_DEPTH_SIZE: case GL_INTERNALFORMAT_STENCIL_SIZE: case GL_INTERNALFORMAT_SHARED_SIZE: case GL_MAX_WIDTH: case GL_MAX_HEIGHT: case GL_MAX_DEPTH: case GL_MAX_LAYERS: case GL_IMAGE_TEXEL_SIZE: case GL_TEXTURE_COMPRESSED_BLOCK_WIDTH: case GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT: case GL_TEXTURE_COMPRESSED_BLOCK_SIZE: case GL_NUM_TILING_TYPES_EXT: buffer[0] = 0; break; case GL_INTERNALFORMAT_PREFERRED: case GL_INTERNALFORMAT_RED_TYPE: case GL_INTERNALFORMAT_GREEN_TYPE: case GL_INTERNALFORMAT_BLUE_TYPE: case GL_INTERNALFORMAT_ALPHA_TYPE: case GL_INTERNALFORMAT_DEPTH_TYPE: case GL_INTERNALFORMAT_STENCIL_TYPE: case GL_FRAMEBUFFER_RENDERABLE: case GL_FRAMEBUFFER_RENDERABLE_LAYERED: case GL_FRAMEBUFFER_BLEND: case GL_READ_PIXELS: case GL_READ_PIXELS_FORMAT: case GL_READ_PIXELS_TYPE: case GL_TEXTURE_IMAGE_FORMAT: case GL_TEXTURE_IMAGE_TYPE: case GL_GET_TEXTURE_IMAGE_FORMAT: case GL_GET_TEXTURE_IMAGE_TYPE: case GL_MANUAL_GENERATE_MIPMAP: case GL_AUTO_GENERATE_MIPMAP: case GL_COLOR_ENCODING: case GL_SRGB_READ: case GL_SRGB_WRITE: case GL_SRGB_DECODE_ARB: case GL_FILTER: case GL_VERTEX_TEXTURE: case GL_TESS_CONTROL_TEXTURE: case GL_TESS_EVALUATION_TEXTURE: case GL_GEOMETRY_TEXTURE: case GL_FRAGMENT_TEXTURE: case GL_COMPUTE_TEXTURE: case GL_TEXTURE_SHADOW: case GL_TEXTURE_GATHER: case GL_TEXTURE_GATHER_SHADOW: case GL_SHADER_IMAGE_LOAD: case GL_SHADER_IMAGE_STORE: case GL_SHADER_IMAGE_ATOMIC: case GL_IMAGE_COMPATIBILITY_CLASS: case GL_IMAGE_PIXEL_FORMAT: case GL_IMAGE_PIXEL_TYPE: case GL_IMAGE_FORMAT_COMPATIBILITY_TYPE: case GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST: case GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST: case GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE: case GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE: case GL_CLEAR_BUFFER: case GL_TEXTURE_VIEW: case GL_VIEW_COMPATIBILITY_CLASS: buffer[0] = GL_NONE; break; case GL_INTERNALFORMAT_SUPPORTED: case GL_COLOR_COMPONENTS: case GL_DEPTH_COMPONENTS: case GL_STENCIL_COMPONENTS: case GL_COLOR_RENDERABLE: case GL_DEPTH_RENDERABLE: case GL_STENCIL_RENDERABLE: case GL_MIPMAP: case GL_TEXTURE_COMPRESSED: buffer[0] = GL_FALSE; break; default: unreachable("invalid 'pname'"); } } static bool _is_target_supported(struct gl_context *ctx, GLenum target) { /* The ARB_internalformat_query2 spec says: * * "if a particular type of <target> is not supported by the * implementation the "unsupported" answer should be given. * This is not an error." * * Note that legality of targets has already been verified. */ switch(target){ case GL_TEXTURE_1D: case GL_TEXTURE_2D: case GL_TEXTURE_3D: break; case GL_TEXTURE_1D_ARRAY: if (!_mesa_has_EXT_texture_array(ctx)) return false; break; case GL_TEXTURE_2D_ARRAY: if (!_mesa_has_EXT_texture_array(ctx)) return false; break; case GL_TEXTURE_CUBE_MAP: if (ctx->API != API_OPENGL_CORE && !_mesa_has_ARB_texture_cube_map(ctx)) return false; break; case GL_TEXTURE_CUBE_MAP_ARRAY: if (!_mesa_has_ARB_texture_cube_map_array(ctx)) return false; break; case GL_TEXTURE_RECTANGLE: if (!_mesa_has_ARB_texture_rectangle(ctx)) return false; break; case GL_TEXTURE_BUFFER: if (!_mesa_has_ARB_texture_buffer_object(ctx)) return false; break; case GL_RENDERBUFFER: if (!(_mesa_has_ARB_framebuffer_object(ctx) || _mesa_is_gles3(ctx))) return false; break; case GL_TEXTURE_2D_MULTISAMPLE: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: if (!(_mesa_has_ARB_texture_multisample(ctx) || _mesa_is_gles31(ctx))) return false; break; default: unreachable("invalid target"); } return true; } static bool _is_resource_supported(struct gl_context *ctx, GLenum target, GLenum internalformat, GLenum pname) { /* From the ARB_internalformat_query2 spec: * * In the following descriptions, the term /resource/ is used to generically * refer to an object of the appropriate type that has been created with * <internalformat> and <target>. If the particular <target> and * <internalformat> combination do not make sense, ... the "unsupported" * answer should be given. This is not an error. */ /* In the ARB_internalformat_query2 spec wording, some <pnames> do not care * about the /resource/ being supported or not, we return 'true' for those. */ switch (pname) { case GL_INTERNALFORMAT_SUPPORTED: case GL_INTERNALFORMAT_PREFERRED: case GL_COLOR_COMPONENTS: case GL_DEPTH_COMPONENTS: case GL_STENCIL_COMPONENTS: case GL_COLOR_RENDERABLE: case GL_DEPTH_RENDERABLE: case GL_STENCIL_RENDERABLE: return true; default: break; } switch(target){ case GL_TEXTURE_1D: case GL_TEXTURE_1D_ARRAY: case GL_TEXTURE_2D: case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_3D: case GL_TEXTURE_CUBE_MAP: case GL_TEXTURE_CUBE_MAP_ARRAY: case GL_TEXTURE_RECTANGLE: /* Based on what Mesa does for glTexImage1D/2D/3D and * glCompressedTexImage1D/2D/3D functions. */ if (_mesa_base_tex_format(ctx, internalformat) < 0) return false; /* additional checks for depth textures */ if (!_mesa_legal_texture_base_format_for_target(ctx, target, internalformat)) return false; /* additional checks for compressed textures */ if (_mesa_is_compressed_format(ctx, internalformat) && (!_mesa_target_can_be_compressed(ctx, target, internalformat, NULL) || _mesa_format_no_online_compression(internalformat))) return false; break; case GL_TEXTURE_2D_MULTISAMPLE: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: /* Based on what Mesa does for glTexImage2D/3DMultisample, * glTexStorage2D/3DMultisample and * glTextureStorage2D/3DMultisample functions. */ if (!_mesa_is_renderable_texture_format(ctx, internalformat)) return false; break; case GL_TEXTURE_BUFFER: /* Based on what Mesa does for the glTexBuffer function. */ if (_mesa_validate_texbuffer_format(ctx, internalformat) == MESA_FORMAT_NONE) return false; break; case GL_RENDERBUFFER: /* Based on what Mesa does for glRenderbufferStorage(Multisample) and * glNamedRenderbufferStorage functions. */ if (!_mesa_base_fbo_format(ctx, internalformat)) return false; break; default: unreachable("bad target"); } return true; } static bool _is_internalformat_supported(struct gl_context *ctx, GLenum target, GLenum internalformat) { /* From the ARB_internalformat_query2 specification: * * "- INTERNALFORMAT_SUPPORTED: If <internalformat> is an internal format * that is supported by the implementation in at least some subset of * possible operations, TRUE is written to <params>. If <internalformat> * if not a valid token for any internal format usage, FALSE is returned. * * <internalformats> that must be supported (in GL 4.2 or later) include * the following: * - "sized internal formats" from Table 3.12, 3.13, and 3.15, * - any specific "compressed internal format" from Table 3.14, * - any "image unit format" from Table 3.21. * - any generic "compressed internal format" from Table 3.14, if the * implementation accepts it for any texture specification commands, and * - unsized or base internal format, if the implementation accepts * it for texture or image specification. * * But also: * "If the particualar <target> and <internalformat> combination do not make * sense, or if a particular type of <target> is not supported by the * implementation the "unsupported" answer should be given. This is not an * error. */ GLint buffer[1]; if (target == GL_RENDERBUFFER) { if (_mesa_base_fbo_format(ctx, internalformat) == 0) { return false; } } else if (target == GL_TEXTURE_BUFFER) { if (_mesa_validate_texbuffer_format(ctx, internalformat) == MESA_FORMAT_NONE) { return false; } } else { if (_mesa_base_tex_format(ctx, internalformat) < 0) { return false; } } /* Let the driver have the final word */ ctx->Driver.QueryInternalFormat(ctx, target, internalformat, GL_INTERNALFORMAT_SUPPORTED, buffer); return (buffer[0] == GL_TRUE); } static bool _legal_target_for_framebuffer_texture_layer(struct gl_context *ctx, GLenum target) { switch (target) { case GL_TEXTURE_3D: case GL_TEXTURE_1D_ARRAY: case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_CUBE_MAP_ARRAY: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: case GL_TEXTURE_CUBE_MAP: return true; default: return false; } } static GLenum _mesa_generic_type_for_internal_format(GLenum internalFormat) { if (_mesa_is_enum_format_unsigned_int(internalFormat)) return GL_UNSIGNED_BYTE; else if (_mesa_is_enum_format_signed_int(internalFormat)) return GL_BYTE; else return GL_FLOAT; } /* default implementation of QueryInternalFormat driverfunc, for * drivers not implementing ARB_internalformat_query2. */ void _mesa_query_internal_format_default(struct gl_context *ctx, GLenum target, GLenum internalFormat, GLenum pname, GLint *params) { (void) target; switch (pname) { case GL_SAMPLES: case GL_NUM_SAMPLE_COUNTS: params[0] = 1; break; case GL_INTERNALFORMAT_SUPPORTED: params[0] = GL_TRUE; break; case GL_INTERNALFORMAT_PREFERRED: params[0] = internalFormat; break; case GL_READ_PIXELS_FORMAT: { GLenum base_format = _mesa_base_tex_format(ctx, internalFormat); switch (base_format) { case GL_STENCIL_INDEX: case GL_DEPTH_COMPONENT: case GL_DEPTH_STENCIL: case GL_RED: case GL_RGB: case GL_BGR: case GL_RGBA: case GL_BGRA: params[0] = base_format; break; default: params[0] = GL_NONE; break; } break; } case GL_READ_PIXELS_TYPE: case GL_TEXTURE_IMAGE_TYPE: case GL_GET_TEXTURE_IMAGE_TYPE: { GLenum base_format = _mesa_base_tex_format(ctx, internalFormat); if (base_format > 0) params[0] = _mesa_generic_type_for_internal_format(internalFormat); else params[0] = GL_NONE; break; } case GL_TEXTURE_IMAGE_FORMAT: case GL_GET_TEXTURE_IMAGE_FORMAT: { GLenum format = GL_NONE; GLenum base_format = _mesa_base_tex_format(ctx, internalFormat); if (base_format > 0) { if (_mesa_is_enum_format_integer(internalFormat)) format = _mesa_base_format_to_integer_format(base_format); else format = base_format; } params[0] = format; break; } case GL_MANUAL_GENERATE_MIPMAP: case GL_AUTO_GENERATE_MIPMAP: case GL_SRGB_READ: case GL_SRGB_WRITE: case GL_SRGB_DECODE_ARB: case GL_VERTEX_TEXTURE: case GL_TESS_CONTROL_TEXTURE: case GL_TESS_EVALUATION_TEXTURE: case GL_GEOMETRY_TEXTURE: case GL_FRAGMENT_TEXTURE: case GL_COMPUTE_TEXTURE: case GL_SHADER_IMAGE_LOAD: case GL_SHADER_IMAGE_STORE: case GL_SHADER_IMAGE_ATOMIC: case GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST: case GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST: case GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE: case GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE: case GL_CLEAR_BUFFER: case GL_TEXTURE_VIEW: case GL_TEXTURE_SHADOW: case GL_TEXTURE_GATHER: case GL_TEXTURE_GATHER_SHADOW: case GL_FRAMEBUFFER_RENDERABLE: case GL_FRAMEBUFFER_RENDERABLE_LAYERED: case GL_FRAMEBUFFER_BLEND: case GL_FILTER: /* * TODO seems a tad optimistic just saying yes to everything here. * Even for combinations which make no sense... * And things like TESS_CONTROL_TEXTURE should definitely default to * NONE if the driver doesn't even support tessellation... */ params[0] = GL_FULL_SUPPORT; break; case GL_NUM_TILING_TYPES_EXT: params[0] = 2; break; case GL_TILING_TYPES_EXT: params[0] = GL_OPTIMAL_TILING_EXT; params[1] = GL_LINEAR_TILING_EXT; break; default: _set_default_response(pname, params); break; } } /* * For MAX_WIDTH/MAX_HEIGHT/MAX_DEPTH it returns the equivalent GetInteger * pname for a Getinternalformat pname/target combination. target/pname * combinations that would return 0 due dimension number or unsupported status * should be already filtered out * * Note that this means that the returned value would be independent of the * internalformat. This possibility is already mentioned at the Issue 7 of the * arb_internalformat_query2 spec. */ static GLenum _equivalent_size_pname(GLenum target, GLenum pname) { switch (target) { case GL_TEXTURE_1D: case GL_TEXTURE_2D: case GL_TEXTURE_2D_MULTISAMPLE: return GL_MAX_TEXTURE_SIZE; case GL_TEXTURE_3D: return GL_MAX_3D_TEXTURE_SIZE; case GL_TEXTURE_CUBE_MAP: return GL_MAX_CUBE_MAP_TEXTURE_SIZE; case GL_TEXTURE_RECTANGLE: return GL_MAX_RECTANGLE_TEXTURE_SIZE; case GL_RENDERBUFFER: return GL_MAX_RENDERBUFFER_SIZE; case GL_TEXTURE_1D_ARRAY: if (pname == GL_MAX_HEIGHT) return GL_MAX_ARRAY_TEXTURE_LAYERS; else return GL_MAX_TEXTURE_SIZE; case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: if (pname == GL_MAX_DEPTH) return GL_MAX_ARRAY_TEXTURE_LAYERS; else return GL_MAX_TEXTURE_SIZE; case GL_TEXTURE_CUBE_MAP_ARRAY: if (pname == GL_MAX_DEPTH) return GL_MAX_ARRAY_TEXTURE_LAYERS; else return GL_MAX_CUBE_MAP_TEXTURE_SIZE; case GL_TEXTURE_BUFFER: return GL_MAX_TEXTURE_BUFFER_SIZE; default: return 0; } } /* * Returns the dimensions associated to a target. GL_TEXTURE_BUFFER and * GL_RENDERBUFFER have associated a dimension, but they are not textures * per-se, so we can't just call _mesa_get_texture_dimension directly. */ static GLint _get_target_dimensions(GLenum target) { switch(target) { case GL_TEXTURE_BUFFER: return 1; case GL_RENDERBUFFER: return 2; default: return _mesa_get_texture_dimensions(target); } } /* * Returns the minimum amount of dimensions associated to a pname. So for * example, if querying GL_MAX_HEIGHT, it is assumed that your target would * have as minimum 2 dimensions. * * Useful to handle sentences like this from query2 spec: * * "MAX_HEIGHT: * <skip> * If the resource does not have at least two dimensions * <skip>." */ static GLint _get_min_dimensions(GLenum pname) { switch(pname) { case GL_MAX_WIDTH: return 1; case GL_MAX_HEIGHT: return 2; case GL_MAX_DEPTH: return 3; default: return 0; } } /* * Similar to teximage.c:check_multisample_target, but independent of the * dimensions. */ static bool _is_multisample_target(GLenum target) { switch(target) { case GL_TEXTURE_2D_MULTISAMPLE: case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: return true; default: return false; } } void GLAPIENTRY _mesa_GetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params) { GLint buffer[16]; GET_CURRENT_CONTEXT(ctx); ASSERT_OUTSIDE_BEGIN_END(ctx); /* ARB_internalformat_query is also mandatory for ARB_internalformat_query2 */ if (!(_mesa_has_ARB_internalformat_query(ctx) || _mesa_is_gles3(ctx))) { _mesa_error(ctx, GL_INVALID_OPERATION, "glGetInternalformativ"); return; } assert(ctx->Driver.QueryInternalFormat != NULL); if (!_legal_parameters(ctx, target, internalformat, pname, bufSize, params)) return; /* initialize the contents of the temporary buffer */ memcpy(buffer, params, MIN2(bufSize, 16) * sizeof(GLint)); /* Use the 'unsupported' response defined by the spec for every pname * as the default answer. */ _set_default_response(pname, buffer); if (!_is_target_supported(ctx, target) || !_is_internalformat_supported(ctx, target, internalformat) || !_is_resource_supported(ctx, target, internalformat, pname)) goto end; switch (pname) { case GL_SAMPLES: /* fall-through */ case GL_NUM_SAMPLE_COUNTS: /* The ARB_internalformat_query2 sets the response as 'unsupported' for * SAMPLES and NUM_SAMPLE_COUNTS: * * "If <internalformat> is not color-renderable, depth-renderable, or * stencil-renderable (as defined in section 4.4.4), or if <target> * does not support multiple samples (ie other than * TEXTURE_2D_MULTISAMPLE, TEXTURE_2D_MULTISAMPLE_ARRAY, * or RENDERBUFFER)." */ if ((target != GL_RENDERBUFFER && target != GL_TEXTURE_2D_MULTISAMPLE && target != GL_TEXTURE_2D_MULTISAMPLE_ARRAY) || !_is_renderable(ctx, internalformat)) goto end; /* The GL ES 3.0 specification, section 6.1.15 page 236 says: * * "Since multisampling is not supported for signed and unsigned * integer internal formats, the value of NUM_SAMPLE_COUNTS will be * zero for such formats. * * Since OpenGL ES 3.1 adds support for multisampled integer formats, we * have to check the version for 30 exactly. */ if (pname == GL_NUM_SAMPLE_COUNTS && ctx->API == API_OPENGLES2 && ctx->Version == 30 && _mesa_is_enum_format_integer(internalformat)) { goto end; } ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_INTERNALFORMAT_SUPPORTED: /* Having a supported <internalformat> is implemented as a prerequisite * for all the <pnames>. Thus, if we reach this point, the internalformat is * supported. */ buffer[0] = GL_TRUE; break; case GL_INTERNALFORMAT_PREFERRED: /* The ARB_internalformat_query2 spec says: * * "- INTERNALFORMAT_PREFERRED: The implementation-preferred internal * format for representing resources of the specified <internalformat> is * returned in <params>. * * Therefore, we let the driver answer. Note that if we reach this * point, it means that the internalformat is supported, so the driver * is called just to try to get a preferred format. If not supported, * GL_NONE was already returned and the driver is not called. */ ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_INTERNALFORMAT_RED_SIZE: case GL_INTERNALFORMAT_GREEN_SIZE: case GL_INTERNALFORMAT_BLUE_SIZE: case GL_INTERNALFORMAT_ALPHA_SIZE: case GL_INTERNALFORMAT_DEPTH_SIZE: case GL_INTERNALFORMAT_STENCIL_SIZE: case GL_INTERNALFORMAT_SHARED_SIZE: case GL_INTERNALFORMAT_RED_TYPE: case GL_INTERNALFORMAT_GREEN_TYPE: case GL_INTERNALFORMAT_BLUE_TYPE: case GL_INTERNALFORMAT_ALPHA_TYPE: case GL_INTERNALFORMAT_DEPTH_TYPE: case GL_INTERNALFORMAT_STENCIL_TYPE: { GLint baseformat; mesa_format texformat; if (target != GL_RENDERBUFFER) { baseformat = _mesa_base_tex_format(ctx, internalformat); } else { baseformat = _mesa_base_fbo_format(ctx, internalformat); } /* Let the driver choose the texture format. * * Disclaimer: I am considering that drivers use for renderbuffers the * same format-choice logic as for textures. */ texformat = ctx->Driver.ChooseTextureFormat(ctx, target, internalformat, GL_NONE /*format */, GL_NONE /* type */); if (texformat == MESA_FORMAT_NONE || baseformat <= 0) goto end; /* Implementation based on what Mesa does for glGetTexLevelParameteriv * and glGetRenderbufferParameteriv functions. */ if (pname == GL_INTERNALFORMAT_SHARED_SIZE) { if (texformat == MESA_FORMAT_R9G9B9E5_FLOAT) { buffer[0] = 5; } goto end; } if (!_mesa_base_format_has_channel(baseformat, pname)) goto end; switch (pname) { case GL_INTERNALFORMAT_DEPTH_SIZE: if (ctx->API != API_OPENGL_CORE && !_mesa_has_ARB_depth_texture(ctx) && target != GL_RENDERBUFFER && target != GL_TEXTURE_BUFFER) goto end; /* fallthrough */ case GL_INTERNALFORMAT_RED_SIZE: case GL_INTERNALFORMAT_GREEN_SIZE: case GL_INTERNALFORMAT_BLUE_SIZE: case GL_INTERNALFORMAT_ALPHA_SIZE: case GL_INTERNALFORMAT_STENCIL_SIZE: buffer[0] = _mesa_get_format_bits(texformat, pname); break; case GL_INTERNALFORMAT_DEPTH_TYPE: if (!_mesa_has_ARB_texture_float(ctx)) goto end; /* fallthrough */ case GL_INTERNALFORMAT_RED_TYPE: case GL_INTERNALFORMAT_GREEN_TYPE: case GL_INTERNALFORMAT_BLUE_TYPE: case GL_INTERNALFORMAT_ALPHA_TYPE: case GL_INTERNALFORMAT_STENCIL_TYPE: buffer[0] = _mesa_get_format_datatype(texformat); break; default: break; } break; } /* For WIDTH/HEIGHT/DEPTH/LAYERS there is no reason to think that the * returned values should be different to the values returned by * GetInteger with MAX_TEXTURE_SIZE, MAX_3D_TEXTURE_SIZE, etc.*/ case GL_MAX_WIDTH: case GL_MAX_HEIGHT: case GL_MAX_DEPTH: { GLenum get_pname; GLint dimensions; GLint min_dimensions; /* From query2:MAX_HEIGHT spec (as example): * * "If the resource does not have at least two dimensions, or if the * resource is unsupported, zero is returned." */ dimensions = _get_target_dimensions(target); min_dimensions = _get_min_dimensions(pname); if (dimensions < min_dimensions) goto end; get_pname = _equivalent_size_pname(target, pname); if (get_pname == 0) goto end; _mesa_GetIntegerv(get_pname, buffer); break; } case GL_MAX_LAYERS: if (!_mesa_has_EXT_texture_array(ctx)) goto end; if (!_mesa_is_array_texture(target)) goto end; _mesa_GetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, buffer); break; case GL_MAX_COMBINED_DIMENSIONS:{ GLint64 combined_value = 1; GLenum max_dimensions_pnames[] = { GL_MAX_WIDTH, GL_MAX_HEIGHT, GL_MAX_DEPTH, GL_SAMPLES }; unsigned i; GLint current_value; /* Combining the dimensions. Note that for array targets, this would * automatically include the value of MAX_LAYERS, as that value is * returned as MAX_HEIGHT or MAX_DEPTH */ for (i = 0; i < 4; i++) { if (max_dimensions_pnames[i] == GL_SAMPLES && !_is_multisample_target(target)) continue; _mesa_GetInternalformativ(target, internalformat, max_dimensions_pnames[i], 1, &current_value); if (current_value != 0) combined_value *= current_value; } if (_mesa_is_cube_map_texture(target)) combined_value *= 6; /* We pack the 64-bit value on two 32-bit values. Calling the 32-bit * query, this would work as far as the value can be hold on a 32-bit * signed integer. For the 64-bit query, the wrapper around the 32-bit * query will unpack the value */ memcpy(buffer, &combined_value, sizeof(GLint64)); break; } case GL_COLOR_COMPONENTS: /* The ARB_internalformat_query2 spec says: * * "- COLOR_COMPONENTS: If the internal format contains any color * components (R, G, B, or A), TRUE is returned in <params>. * If the internal format is unsupported or contains no color * components, FALSE is returned." */ if (_mesa_is_color_format(internalformat)) buffer[0] = GL_TRUE; break; case GL_DEPTH_COMPONENTS: /* The ARB_internalformat_query2 spec says: * * "- DEPTH_COMPONENTS: If the internal format contains a depth * component (D), TRUE is returned in <params>. If the internal format * is unsupported or contains no depth component, FALSE is returned." */ if (_mesa_is_depth_format(internalformat) || _mesa_is_depthstencil_format(internalformat)) buffer[0] = GL_TRUE; break; case GL_STENCIL_COMPONENTS: /* The ARB_internalformat_query2 spec says: * * "- STENCIL_COMPONENTS: If the internal format contains a stencil * component (S), TRUE is returned in <params>. If the internal format * is unsupported or contains no stencil component, FALSE is returned. */ if (_mesa_is_stencil_format(internalformat) || _mesa_is_depthstencil_format(internalformat)) buffer[0] = GL_TRUE; break; case GL_COLOR_RENDERABLE: case GL_DEPTH_RENDERABLE: case GL_STENCIL_RENDERABLE: if (!_is_renderable(ctx, internalformat)) goto end; if (pname == GL_COLOR_RENDERABLE) { if (!_mesa_is_color_format(internalformat)) goto end; } else { GLenum baseFormat = _mesa_base_fbo_format(ctx, internalformat); if (baseFormat != GL_DEPTH_STENCIL && ((pname == GL_DEPTH_RENDERABLE && baseFormat != GL_DEPTH_COMPONENT) || (pname == GL_STENCIL_RENDERABLE && baseFormat != GL_STENCIL_INDEX))) goto end; } buffer[0] = GL_TRUE; break; case GL_FRAMEBUFFER_RENDERABLE_LAYERED: if (!_mesa_has_EXT_texture_array(ctx) || _legal_target_for_framebuffer_texture_layer(ctx, target)) goto end; /* fallthrough */ case GL_FRAMEBUFFER_RENDERABLE: case GL_FRAMEBUFFER_BLEND: if (!_mesa_has_ARB_framebuffer_object(ctx)) goto end; if (target == GL_TEXTURE_BUFFER || !_is_renderable(ctx, internalformat)) goto end; ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_READ_PIXELS: case GL_READ_PIXELS_FORMAT: case GL_READ_PIXELS_TYPE: ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_TEXTURE_IMAGE_FORMAT: case GL_GET_TEXTURE_IMAGE_FORMAT: case GL_TEXTURE_IMAGE_TYPE: case GL_GET_TEXTURE_IMAGE_TYPE: ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_MIPMAP: case GL_MANUAL_GENERATE_MIPMAP: case GL_AUTO_GENERATE_MIPMAP: if (!_mesa_is_valid_generate_texture_mipmap_target(ctx, target) || !_mesa_is_valid_generate_texture_mipmap_internalformat(ctx, internalformat)) { goto end; } if (pname == GL_MIPMAP) { buffer[0] = GL_TRUE; goto end; } else if (pname == GL_MANUAL_GENERATE_MIPMAP) { if (!_mesa_has_ARB_framebuffer_object(ctx)) goto end; } else { /* From ARB_internalformat_query2: * "Dependencies on OpenGL 3.2 (Core Profile) * In core profiles for OpenGL 3.2 and later versions, queries * for the AUTO_GENERATE_MIPMAP <pname> return the appropriate * unsupported response." */ if (_mesa_is_desktop_gl(ctx) && ctx->Version >= 32) goto end; } ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_COLOR_ENCODING: if (!_mesa_is_color_format(internalformat)) goto end; if (_mesa_is_srgb_format(internalformat)) buffer[0] = GL_SRGB; else buffer[0] = GL_LINEAR; break; case GL_SRGB_READ: if (!_mesa_has_EXT_texture_sRGB(ctx) || !_mesa_is_srgb_format(internalformat)) { goto end; } ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_SRGB_WRITE: if (!_mesa_has_EXT_framebuffer_sRGB(ctx) || !_mesa_is_color_format(internalformat)) { goto end; } ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_SRGB_DECODE_ARB: /* Presence of EXT_texture_sRGB_decode was already verified */ if (!_mesa_has_EXT_texture_sRGB(ctx) || target == GL_RENDERBUFFER || !_mesa_is_srgb_format(internalformat)) { goto end; } ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_FILTER: /* If it doesn't allow to set sampler parameters then it would not allow * to set a filter different to GL_NEAREST. In practice, this method * only filters out MULTISAMPLE/MULTISAMPLE_ARRAY */ if (!_mesa_target_allows_setting_sampler_parameters(target)) goto end; if (_mesa_is_enum_format_integer(internalformat)) goto end; if (target == GL_TEXTURE_BUFFER) goto end; /* At this point we know that multi-texel filtering is supported. We * need to call the driver to know if it is CAVEAT_SUPPORT or * FULL_SUPPORT. */ ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_VERTEX_TEXTURE: case GL_TESS_CONTROL_TEXTURE: case GL_TESS_EVALUATION_TEXTURE: case GL_GEOMETRY_TEXTURE: case GL_FRAGMENT_TEXTURE: case GL_COMPUTE_TEXTURE: if (target == GL_RENDERBUFFER) goto end; if ((pname == GL_TESS_CONTROL_TEXTURE || pname == GL_TESS_EVALUATION_TEXTURE) && !_mesa_has_tessellation(ctx)) goto end; if (pname == GL_GEOMETRY_TEXTURE && !_mesa_has_geometry_shaders(ctx)) goto end; if (pname == GL_COMPUTE_TEXTURE && !_mesa_has_compute_shaders(ctx)) goto end; ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_TEXTURE_GATHER: case GL_TEXTURE_GATHER_SHADOW: if (!_mesa_has_ARB_texture_gather(ctx)) goto end; /* fallthrough */ case GL_TEXTURE_SHADOW: /* Only depth or depth-stencil image formats make sense in shadow samplers */ if (pname != GL_TEXTURE_GATHER && !_mesa_is_depth_format(internalformat) && !_mesa_is_depthstencil_format(internalformat)) goto end; /* Validate the target for shadow and gather operations */ switch (target) { case GL_TEXTURE_2D: case GL_TEXTURE_2D_ARRAY: case GL_TEXTURE_CUBE_MAP: case GL_TEXTURE_CUBE_MAP_ARRAY: case GL_TEXTURE_RECTANGLE: break; case GL_TEXTURE_1D: case GL_TEXTURE_1D_ARRAY: /* 1D and 1DArray textures are not admitted in gather operations */ if (pname != GL_TEXTURE_SHADOW) goto end; break; default: goto end; } ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_SHADER_IMAGE_LOAD: case GL_SHADER_IMAGE_STORE: if (!_mesa_has_ARB_shader_image_load_store(ctx)) goto end; /* We call to _mesa_is_shader_image_format_supported * using "internalformat" as parameter, because the * the ARB_internalformat_query2 spec says: * "In this case the <internalformat> is the value of the <format> * parameter that is passed to BindImageTexture." */ if (target == GL_RENDERBUFFER || !_mesa_is_shader_image_format_supported(ctx, internalformat)) goto end; ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_SHADER_IMAGE_ATOMIC: if (!_mesa_has_ARB_shader_image_load_store(ctx)) goto end; ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_IMAGE_TEXEL_SIZE: { mesa_format image_format; if (!_mesa_has_ARB_shader_image_load_store(ctx) || target == GL_RENDERBUFFER) goto end; image_format = _mesa_get_shader_image_format(internalformat); if (image_format == MESA_FORMAT_NONE) goto end; /* We return bits */ buffer[0] = (_mesa_get_format_bytes(image_format) * 8); break; } case GL_IMAGE_COMPATIBILITY_CLASS: if (!_mesa_has_ARB_shader_image_load_store(ctx) || target == GL_RENDERBUFFER) goto end; buffer[0] = _mesa_get_image_format_class(internalformat); break; case GL_IMAGE_PIXEL_FORMAT: { GLint base_format; if (!_mesa_has_ARB_shader_image_load_store(ctx) || target == GL_RENDERBUFFER || !_mesa_is_shader_image_format_supported(ctx, internalformat)) goto end; base_format = _mesa_base_tex_format(ctx, internalformat); if (base_format == -1) goto end; if (_mesa_is_enum_format_integer(internalformat)) buffer[0] = _mesa_base_format_to_integer_format(base_format); else buffer[0] = base_format; break; } case GL_IMAGE_PIXEL_TYPE: { mesa_format image_format; GLenum datatype; GLuint comps; if (!_mesa_has_ARB_shader_image_load_store(ctx) || target == GL_RENDERBUFFER) goto end; image_format = _mesa_get_shader_image_format(internalformat); if (image_format == MESA_FORMAT_NONE) goto end; _mesa_uncompressed_format_to_type_and_comps(image_format, &datatype, &comps); if (!datatype) goto end; buffer[0] = datatype; break; } case GL_IMAGE_FORMAT_COMPATIBILITY_TYPE: { if (!_mesa_has_ARB_shader_image_load_store(ctx)) goto end; /* As pointed by the spec quote below, this pname query should return * the same value that GetTexParameter. So if the target is not valid * for GetTexParameter we return the unsupported value. The check below * is the same target check used by GetTexParameter. */ int targetIndex = _mesa_tex_target_to_index(ctx, target); if (targetIndex < 0 || targetIndex == TEXTURE_BUFFER_INDEX) goto end; /* From spec: "Equivalent to calling GetTexParameter with <value> set * to IMAGE_FORMAT_COMPATIBILITY_TYPE." * * GetTexParameter just returns * tex_obj->ImageFormatCompatibilityType. We create a fake tex_obj * just with the purpose of getting the value. */ struct gl_texture_object *tex_obj = _mesa_new_texture_object(ctx, 0, target); buffer[0] = tex_obj->ImageFormatCompatibilityType; _mesa_delete_texture_object(ctx, tex_obj); break; } case GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST: case GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST: case GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE: case GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE: if (target == GL_RENDERBUFFER) goto end; if (!_mesa_is_depthstencil_format(internalformat)) { if (((pname == GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST || pname == GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE) && !_mesa_is_depth_format(internalformat)) || ((pname == GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST || pname == GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE) && !_mesa_is_stencil_format(internalformat))) goto end; } ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_TEXTURE_COMPRESSED: buffer[0] = _mesa_is_compressed_format(ctx, internalformat); break; case GL_TEXTURE_COMPRESSED_BLOCK_WIDTH: case GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT: case GL_TEXTURE_COMPRESSED_BLOCK_SIZE: { mesa_format mesaformat; GLint block_size; mesaformat = _mesa_glenum_to_compressed_format(internalformat); if (mesaformat == MESA_FORMAT_NONE) goto end; block_size = _mesa_get_format_bytes(mesaformat); assert(block_size > 0); if (pname == GL_TEXTURE_COMPRESSED_BLOCK_SIZE) { buffer[0] = block_size; } else { GLuint bwidth, bheight; /* Returns the width and height in pixels. We return bytes */ _mesa_get_format_block_size(mesaformat, &bwidth, &bheight); assert(bwidth > 0 && bheight > 0); if (pname == GL_TEXTURE_COMPRESSED_BLOCK_WIDTH) buffer[0] = block_size / bheight; else buffer[0] = block_size / bwidth; } break; } case GL_CLEAR_BUFFER: if (target != GL_TEXTURE_BUFFER) goto end; ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; case GL_TEXTURE_VIEW: case GL_VIEW_COMPATIBILITY_CLASS: if (!_mesa_has_ARB_texture_view(ctx) || target == GL_TEXTURE_BUFFER || target == GL_RENDERBUFFER) goto end; if (pname == GL_TEXTURE_VIEW) { ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); } else { GLenum view_class = _mesa_texture_view_lookup_view_class(ctx, internalformat); if (view_class == GL_FALSE) goto end; buffer[0] = view_class; } break; case GL_NUM_TILING_TYPES_EXT: case GL_TILING_TYPES_EXT: ctx->Driver.QueryInternalFormat(ctx, target, internalformat, pname, buffer); break; default: unreachable("bad param"); } end: if (bufSize != 0 && params == NULL) { /* Emit a warning to aid application debugging, but go ahead and do the * memcpy (and probably crash) anyway. */ _mesa_warning(ctx, "glGetInternalformativ(bufSize = %d, but params = NULL)", bufSize); } /* Copy the data from the temporary buffer to the buffer supplied by the * application. Clamp the size of the copy to the size supplied by the * application. */ memcpy(params, buffer, MIN2(bufSize, 16) * sizeof(GLint)); return; } void GLAPIENTRY _mesa_GetInternalformati64v(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params) { GLint params32[16]; unsigned i; GLsizei realSize = MIN2(bufSize, 16); GLsizei callSize; GET_CURRENT_CONTEXT(ctx); ASSERT_OUTSIDE_BEGIN_END(ctx); if (!_mesa_has_ARB_internalformat_query2(ctx)) { _mesa_error(ctx, GL_INVALID_OPERATION, "glGetInternalformati64v"); return; } /* For SAMPLES there are cases where params needs to remain unmodified. As * no pname can return a negative value, we fill params32 with negative * values as reference values, that can be used to know what copy-back to * params */ for (i = 0; i < realSize; i++) params32[i] = -1; /* For GL_MAX_COMBINED_DIMENSIONS we need to get back 2 32-bit integers, * and at the same time we only need 2. So for that pname, we call the * 32-bit query with bufSize 2, except on the case of bufSize 0, that is * basically like asking to not get the value, but that is a caller * problem. */ if (pname == GL_MAX_COMBINED_DIMENSIONS && bufSize > 0) callSize = 2; else callSize = bufSize; _mesa_GetInternalformativ(target, internalformat, pname, callSize, params32); if (pname == GL_MAX_COMBINED_DIMENSIONS) { memcpy(params, params32, sizeof(GLint64)); } else { for (i = 0; i < realSize; i++) { /* We only copy back the values that changed */ if (params32[i] < 0) break; params[i] = (GLint64) params32[i]; } } }
{ "pile_set_name": "Github" }
syntax = "proto2"; package etcdserverpb; import "gogoproto/gogo.proto"; option (gogoproto.marshaler_all) = true; option (gogoproto.sizer_all) = true; option (gogoproto.unmarshaler_all) = true; option (gogoproto.goproto_getters_all) = false; message Request { optional uint64 ID = 1 [(gogoproto.nullable) = false]; optional string Method = 2 [(gogoproto.nullable) = false]; optional string Path = 3 [(gogoproto.nullable) = false]; optional string Val = 4 [(gogoproto.nullable) = false]; optional bool Dir = 5 [(gogoproto.nullable) = false]; optional string PrevValue = 6 [(gogoproto.nullable) = false]; optional uint64 PrevIndex = 7 [(gogoproto.nullable) = false]; optional bool PrevExist = 8 [(gogoproto.nullable) = true]; optional int64 Expiration = 9 [(gogoproto.nullable) = false]; optional bool Wait = 10 [(gogoproto.nullable) = false]; optional uint64 Since = 11 [(gogoproto.nullable) = false]; optional bool Recursive = 12 [(gogoproto.nullable) = false]; optional bool Sorted = 13 [(gogoproto.nullable) = false]; optional bool Quorum = 14 [(gogoproto.nullable) = false]; optional int64 Time = 15 [(gogoproto.nullable) = false]; optional bool Stream = 16 [(gogoproto.nullable) = false]; optional bool Refresh = 17 [(gogoproto.nullable) = true]; } message Metadata { optional uint64 NodeID = 1 [(gogoproto.nullable) = false]; optional uint64 ClusterID = 2 [(gogoproto.nullable) = false]; }
{ "pile_set_name": "Github" }
package oss import ( "github.com/denverdino/aliyungo/util" //"log" "net/http" "net/url" "sort" "strings" ) const HeaderOSSPrefix = "x-oss-" var ossParamsToSign = map[string]bool{ "acl": true, "delete": true, "location": true, "logging": true, "notification": true, "partNumber": true, "policy": true, "requestPayment": true, "torrent": true, "uploadId": true, "uploads": true, "versionId": true, "versioning": true, "versions": true, "response-content-type": true, "response-content-language": true, "response-expires": true, "response-cache-control": true, "response-content-disposition": true, "response-content-encoding": true, "bucketInfo": true, } func (client *Client) signRequest(request *request) { query := request.params urlSignature := query.Get("OSSAccessKeyId") != "" headers := request.headers contentMd5 := headers.Get("Content-Md5") contentType := headers.Get("Content-Type") date := "" if urlSignature { date = query.Get("Expires") } else { date = headers.Get("Date") } resource := request.path if request.bucket != "" { resource = "/" + request.bucket + request.path } params := make(url.Values) for k, v := range query { if ossParamsToSign[k] { params[k] = v } } if len(params) > 0 { resource = resource + "?" + util.Encode(params) } canonicalizedResource := resource _, canonicalizedHeader := canonicalizeHeader(headers) stringToSign := request.method + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedHeader + canonicalizedResource //log.Println("stringToSign: ", stringToSign) signature := util.CreateSignature(stringToSign, client.AccessKeySecret) if query.Get("OSSAccessKeyId") != "" { query.Set("Signature", signature) } else { headers.Set("Authorization", "OSS "+client.AccessKeyId+":"+signature) } } //Have to break the abstraction to append keys with lower case. func canonicalizeHeader(headers http.Header) (newHeaders http.Header, result string) { var canonicalizedHeaders []string newHeaders = http.Header{} for k, v := range headers { if lower := strings.ToLower(k); strings.HasPrefix(lower, HeaderOSSPrefix) { newHeaders[lower] = v canonicalizedHeaders = append(canonicalizedHeaders, lower) } else { newHeaders[k] = v } } sort.Strings(canonicalizedHeaders) var canonicalizedHeader string for _, k := range canonicalizedHeaders { canonicalizedHeader += k + ":" + headers.Get(k) + "\n" } return newHeaders, canonicalizedHeader }
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.8"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="functions_b.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">载入中...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">搜索中...</div> <div class="SRStatus" id="NoMatches">未找到</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
{ "pile_set_name": "Github" }
import AbstractPlugin from 'shared/AbstractPlugin'; const onInitialize = Symbol('onInitialize'); const onDestroy = Symbol('onDestroy'); /** * Focusable default options * @property {Object} defaultOptions * @type {Object} */ const defaultOptions = {}; /** * Focusable plugin * @class Focusable * @module Focusable * @extends AbstractPlugin */ export default class Focusable extends AbstractPlugin { /** * Focusable constructor. * @constructs Focusable * @param {Draggable} draggable - Draggable instance */ constructor(draggable) { super(draggable); /** * Focusable options * @property {Object} options * @type {Object} */ this.options = { ...defaultOptions, ...this.getOptions(), }; this[onInitialize] = this[onInitialize].bind(this); this[onDestroy] = this[onDestroy].bind(this); } /** * Attaches listeners to draggable */ attach() { this.draggable.on('draggable:initialize', this[onInitialize]).on('draggable:destroy', this[onDestroy]); } /** * Detaches listeners from draggable */ detach() { this.draggable.off('draggable:initialize', this[onInitialize]).off('draggable:destroy', this[onDestroy]); // Remove modified elements when detach this[onDestroy](); } /** * Returns options passed through draggable * @return {Object} */ getOptions() { return this.draggable.options.focusable || {}; } /** * Returns draggable containers and elements * @return {HTMLElement[]} */ getElements() { return [...this.draggable.containers, ...this.draggable.getDraggableElements()]; } /** * Intialize handler * @private */ [onInitialize]() { // Can wait until the next best frame is available requestAnimationFrame(() => { this.getElements().forEach((element) => decorateElement(element)); }); } /** * Destroy handler * @private */ [onDestroy]() { // Can wait until the next best frame is available requestAnimationFrame(() => { this.getElements().forEach((element) => stripElement(element)); }); } } /** * Keeps track of all the elements that are missing tabindex attributes * so they can be reset when draggable gets destroyed * @const {HTMLElement[]} elementsWithMissingTabIndex */ const elementsWithMissingTabIndex = []; /** * Decorates element with tabindex attributes * @param {HTMLElement} element * @return {Object} * @private */ function decorateElement(element) { const hasMissingTabIndex = Boolean(!element.getAttribute('tabindex') && element.tabIndex === -1); if (hasMissingTabIndex) { elementsWithMissingTabIndex.push(element); element.tabIndex = 0; } } /** * Removes elements tabindex attributes * @param {HTMLElement} element * @private */ function stripElement(element) { const tabIndexElementPosition = elementsWithMissingTabIndex.indexOf(element); if (tabIndexElementPosition !== -1) { element.tabIndex = -1; elementsWithMissingTabIndex.splice(tabIndexElementPosition, 1); } }
{ "pile_set_name": "Github" }
name: simple_auth_flutter_example description: A new Flutter project. dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 simple_auth: simple_auth_flutter: dev_dependencies: simple_auth_generator: build_runner: flutter_test: sdk: flutter dependency_overrides: simple_auth: path: ../simple_auth simple_auth_flutter: path: ../simple_auth_flutter simple_auth_generator: path: ../simple_auth_generator # For information on the generic Dart part of this file, see the # following page: https://www.dartlang.org/tools/pub/pubspec # The following section is specific to Flutter. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.io/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.io/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.io/custom-fonts/#from-packages
{ "pile_set_name": "Github" }
############################################################################# # Tables adapted from the Xotl FACTION ASSIGNMENT & RARITY TABLES # # Original tables can be found here: # # http://www.classicbattletech.com/forums/index.php/topic,1219.0.html # # As noted in the original files, these are fan works and should not be # # taken as official in any way. # # # # Adaptation performed by Deric Page (aka Netzilla on # # http://www.classicbattletech.com/forums/) # # If any discrepancies are found between these files and the original # # Xotl tables, please contact me by PM on the forums or via email: # # [email protected]. # # # # Notes on adaptation: # # * The original Xotl tables use a d1,000 to randomly determine the unit. # # For the adaptation I simply use the frequency of the entry as the # # MegaMek RAT Weight value. So, a unit that appears on rolls 101-200 # # receives a base Weight of 100. # ############################################################################# Liao 3028 Medium Mechs D @Davion 3028 Medium Mechs D,50 @Marik 3028 Medium Mechs D,50 Clint CLNT-2-4T,5 Cicada CDA-2B,5 Vulcan VL-2T,19 Cicada CDA-2A,18 Clint CLNT-1-2R,5 Clint CLNT-2-3T,10 Cicada CDA-3C,5 Vulcan VL-5T,5 Centurion CN9-A,10 Blackjack BJ-1,71 Vindicator VND-1AA 'Avenging Angel',10 Whitworth WTH-1,14 Trebuchet TBT-5S,5 Wyvern WVE-6N,10 Vindicator VND-1X,5 Scorpion SCP-1N,19 Vindicator VND-1R,238 Phoenix Hawk PXH-1,143 Hunchback HBK-4G,48 Shadow Hawk SHD-2H,71 Hunchback HBK-4H,5 Hunchback HBK-4N,5 Wolverine WVR-6R,71 Hunchback HBK-4P,5 Crab CRB-20,10 Hunchback HBK-4J,5 Dervish DV-6M,19 Trebuchet TBT-5N,33 Griffin GRF-1N,31
{ "pile_set_name": "Github" }
Forbidden request
{ "pile_set_name": "Github" }
// @flow import * as React from 'react' import { withReduxForm } from './ReduxFormContext' import type { ReactContext } from './types' export type Props = { +children: (props: { form: string, sectionPrefix: ?string }) => React.Node } type PropsWithContext = ReactContext & Props const FormName = ({ children, _reduxForm }: PropsWithContext): React.Node => children({ form: _reduxForm && _reduxForm.form, sectionPrefix: _reduxForm && _reduxForm.sectionPrefix }) export default withReduxForm(FormName)
{ "pile_set_name": "Github" }
# # This file is part of JQLibrary # # Library introduce: https://github.com/188080501/JQLibrary # # Copyright: Jason # # Contact email: [email protected] # # GitHub: https://github.com/188080501/ # INCLUDEPATH *= \ $$PWD/include/JQQRCodeWriter/ # 定义JQQRCodeWriter的版本 JQQRCODEWRITER_VERSIONSTRING = 1.6 # 判断Qt版本,小于等于5.6就报错 lessThan( QT_MAJOR_VERSION, 5 ) | lessThan( QT_MINOR_VERSION, 7 ) { error( JQQRCodeWriter request minimum Qt version is 5.7.0 ) } # 准备bin库目录 JQQRCODEWRITER_BIN_NO1_DIR = JQQRCodeWriter$$JQQRCODEWRITER_VERSIONSTRING/Qt$$[QT_VERSION] JQQRCODEWRITER_BIN_NO2_DIR = $$QT_ARCH JQQRCODEWRITER_BIN_NO3_DIR = $$[QMAKE_XSPEC] JQQRCODEWRITER_BIN_NO3_DIR ~= s/g\+\+/gcc # 根据编译参数,追加static名称 contains( CONFIG, static ) { JQQRCODEWRITER_BIN_NO3_DIR = $$JQQRCODEWRITER_BIN_NO3_DIR-static } JQQRCODEWRITER_BIN_DIR = $$PWD/bin/$$JQQRCODEWRITER_BIN_NO1_DIR/$$JQQRCODEWRITER_BIN_NO2_DIR/$$JQQRCODEWRITER_BIN_NO3_DIR #message($$JQQRCODEWRITER_BIN_DIR) # 若bin目录不存在则创建 !exists( $$JQQRCODEWRITER_BIN_DIR ) { mkpath( $$JQQRCODEWRITER_BIN_DIR ) } # 根据不同系统,选择合适的名字 unix | linux | mingw { CONFIG( debug, debug | release ) { JQQRCODEWRITER_LIB_FILENAME = libJQQRCodeWriterd.a } CONFIG( release, debug | release ) { JQQRCODEWRITER_LIB_FILENAME = libJQQRCodeWriter.a } } else: msvc { CONFIG( debug, debug | release ) { JQQRCODEWRITER_LIB_FILENAME = JQQRCodeWriterd.lib } CONFIG( release, debug | release ) { JQQRCODEWRITER_LIB_FILENAME = JQQRCodeWriter.lib } } else { error( unknow platfrom ) } # 生成bin路径 JQQRCODEWRITER_LIB_FILEPATH = $$JQQRCODEWRITER_BIN_DIR/$$JQQRCODEWRITER_LIB_FILENAME # 如果未指定编译模式,并且本地存在bin文件,那么使用bin文件 !equals(JQQRCODEWRITER_COMPILE_MODE, SRC) { exists($$JQQRCODEWRITER_LIB_FILEPATH) { JQQRCODEWRITER_COMPILE_MODE = LIB } else { JQQRCODEWRITER_COMPILE_MODE = SRC } } equals(JQQRCODEWRITER_COMPILE_MODE,SRC) { HEADERS *= \ $$PWD/src/JQQRCodeWriter/qrencode/qrencode.h \ $$PWD/src/JQQRCodeWriter/qrencode/bitstream.h \ $$PWD/src/JQQRCodeWriter/qrencode/mask.h \ $$PWD/src/JQQRCodeWriter/qrencode/mmask.h \ $$PWD/src/JQQRCodeWriter/qrencode/mqrspec.h \ $$PWD/src/JQQRCodeWriter/qrencode/qrencode_inner.h \ $$PWD/src/JQQRCodeWriter/qrencode/qrinput.h \ $$PWD/src/JQQRCodeWriter/qrencode/qrspec.h \ $$PWD/src/JQQRCodeWriter/qrencode/rscode.h \ $$PWD/src/JQQRCodeWriter/qrencode/split.h \ $$PWD/src/JQQRCodeWriter/qrencode/config.h \ $$PWD/include/JQQRCodeWriter/JQQRCodeWriter.h SOURCES *= \ $$PWD/src/JQQRCodeWriter/qrencode/qrencode.c \ $$PWD/src/JQQRCodeWriter/qrencode/bitstream.c \ $$PWD/src/JQQRCodeWriter/qrencode/mask.c \ $$PWD/src/JQQRCodeWriter/qrencode/mmask.c \ $$PWD/src/JQQRCodeWriter/qrencode/mqrspec.c \ $$PWD/src/JQQRCodeWriter/qrencode/qrinput.c \ $$PWD/src/JQQRCodeWriter/qrencode/qrspec.c \ $$PWD/src/JQQRCodeWriter/qrencode/rscode.c \ $$PWD/src/JQQRCodeWriter/qrencode/split.c \ $$PWD/src/JQQRCodeWriter/JQQRCodeWriter.cpp } else : equals(JQQRCODEWRITER_COMPILE_MODE,LIB) { LIBS *= $$JQQRCODEWRITER_LIB_FILEPATH } else { error(unknow JQQRCODEWRITER_COMPILE_MODE: $$JQQRCODEWRITER_COMPILE_MODE) } DEFINES *= JQQRCODEWRITER_COMPILE_MODE_STRING=\\\"$$JQQRCODEWRITER_COMPILE_MODE\\\" DEFINES *= JQQRCODEWRITER_VERSIONSTRING=\\\"$$JQQRCODEWRITER_VERSIONSTRING\\\"
{ "pile_set_name": "Github" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix import ( "runtime" "sync" "syscall" "unsafe" ) var ( Stdin = 0 Stdout = 1 Stderr = 2 ) const ( darwin64Bit = runtime.GOOS == "darwin" && sizeofPtr == 8 dragonfly64Bit = runtime.GOOS == "dragonfly" && sizeofPtr == 8 netbsd32Bit = runtime.GOOS == "netbsd" && sizeofPtr == 4 solaris64Bit = runtime.GOOS == "solaris" && sizeofPtr == 8 ) // Do the interface allocations only once for common // Errno values. var ( errEAGAIN error = syscall.EAGAIN errEINVAL error = syscall.EINVAL errENOENT error = syscall.ENOENT ) // errnoErr returns common boxed Errno values, to prevent // allocations at runtime. func errnoErr(e syscall.Errno) error { switch e { case 0: return nil case EAGAIN: return errEAGAIN case EINVAL: return errEINVAL case ENOENT: return errENOENT } return e } // clen returns the index of the first NULL byte in n or len(n) if n contains no NULL byte. func clen(n []byte) int { for i := 0; i < len(n); i++ { if n[i] == 0 { return i } } return len(n) } // Mmap manager, for use by operating system-specific implementations. type mmapper struct { sync.Mutex active map[*byte][]byte // active mappings; key is last byte in mapping mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error) munmap func(addr uintptr, length uintptr) error } func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { if length <= 0 { return nil, EINVAL } // Map the requested memory. addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset) if errno != nil { return nil, errno } // Slice memory layout var sl = struct { addr uintptr len int cap int }{addr, length, length} // Use unsafe to turn sl into a []byte. b := *(*[]byte)(unsafe.Pointer(&sl)) // Register mapping in m and return it. p := &b[cap(b)-1] m.Lock() defer m.Unlock() m.active[p] = b return b, nil } func (m *mmapper) Munmap(data []byte) (err error) { if len(data) == 0 || len(data) != cap(data) { return EINVAL } // Find the base of the mapping. p := &data[cap(data)-1] m.Lock() defer m.Unlock() b := m.active[p] if b == nil || &b[0] != &data[0] { return EINVAL } // Unmap the memory and update m. if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil { return errno } delete(m.active, p) return nil } func Read(fd int, p []byte) (n int, err error) { n, err = read(fd, p) if raceenabled { if n > 0 { raceWriteRange(unsafe.Pointer(&p[0]), n) } if err == nil { raceAcquire(unsafe.Pointer(&ioSync)) } } return } func Write(fd int, p []byte) (n int, err error) { if raceenabled { raceReleaseMerge(unsafe.Pointer(&ioSync)) } n, err = write(fd, p) if raceenabled && n > 0 { raceReadRange(unsafe.Pointer(&p[0]), n) } return } // For testing: clients can set this flag to force // creation of IPv6 sockets to return EAFNOSUPPORT. var SocketDisableIPv6 bool // Sockaddr represents a socket address. type Sockaddr interface { sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs } // SockaddrInet4 implements the Sockaddr interface for AF_INET type sockets. type SockaddrInet4 struct { Port int Addr [4]byte raw RawSockaddrInet4 } // SockaddrInet6 implements the Sockaddr interface for AF_INET6 type sockets. type SockaddrInet6 struct { Port int ZoneId uint32 Addr [16]byte raw RawSockaddrInet6 } // SockaddrUnix implements the Sockaddr interface for AF_UNIX type sockets. type SockaddrUnix struct { Name string raw RawSockaddrUnix } func Bind(fd int, sa Sockaddr) (err error) { ptr, n, err := sa.sockaddr() if err != nil { return err } return bind(fd, ptr, n) } func Connect(fd int, sa Sockaddr) (err error) { ptr, n, err := sa.sockaddr() if err != nil { return err } return connect(fd, ptr, n) } func Getpeername(fd int) (sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny if err = getpeername(fd, &rsa, &len); err != nil { return } return anyToSockaddr(&rsa) } func GetsockoptInt(fd, level, opt int) (value int, err error) { var n int32 vallen := _Socklen(4) err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) return int(n), err } func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny if n, err = recvfrom(fd, p, flags, &rsa, &len); err != nil { return } if rsa.Addr.Family != AF_UNSPEC { from, err = anyToSockaddr(&rsa) } return } func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) { ptr, n, err := to.sockaddr() if err != nil { return err } return sendto(fd, p, flags, ptr, n) } func SetsockoptByte(fd, level, opt int, value byte) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(&value), 1) } func SetsockoptInt(fd, level, opt int, value int) (err error) { var n = int32(value) return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4) } func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(&value[0]), 4) } func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPMreq) } func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPv6Mreq) } func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error { return setsockopt(fd, level, opt, unsafe.Pointer(filter), SizeofICMPv6Filter) } func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(l), SizeofLinger) } func SetsockoptString(fd, level, opt int, s string) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(&[]byte(s)[0]), uintptr(len(s))) } func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(tv), unsafe.Sizeof(*tv)) } func Socket(domain, typ, proto int) (fd int, err error) { if domain == AF_INET6 && SocketDisableIPv6 { return -1, EAFNOSUPPORT } fd, err = socket(domain, typ, proto) return } func Socketpair(domain, typ, proto int) (fd [2]int, err error) { var fdx [2]int32 err = socketpair(domain, typ, proto, &fdx) if err == nil { fd[0] = int(fdx[0]) fd[1] = int(fdx[1]) } return } func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { if raceenabled { raceReleaseMerge(unsafe.Pointer(&ioSync)) } return sendfile(outfd, infd, offset, count) } var ioSync int64 func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) } func SetNonblock(fd int, nonblocking bool) (err error) { flag, err := fcntl(fd, F_GETFL, 0) if err != nil { return err } if nonblocking { flag |= O_NONBLOCK } else { flag &= ^O_NONBLOCK } _, err = fcntl(fd, F_SETFL, flag) return err }
{ "pile_set_name": "Github" }
package org.assetloader.example { import org.assetloader.AssetLoader; import org.assetloader.core.IAssetLoader; import org.assetloader.signals.LoaderSignal; import org.assetloader.utils.ALLogger; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.MouseEvent; import flash.filters.BevelFilter; import flash.filters.DropShadowFilter; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFieldType; import flash.text.TextFormat; /** * @author Matan Uberstein */ public class ALLoggerExample extends Sprite { // --- Controls ---// protected var _btns : Array = []; // ----------------// protected var _assetloader : IAssetLoader; protected var _field : TextField; protected var _logger : ALLogger; public function ALLoggerExample() { stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; initControls(); initConsole(); _assetloader = new AssetLoader("pr-group"); // AssetLoader Logger, will output trace statements. _logger = new ALLogger(); _logger.onLog.add(append); // Sample swapping out of indent char. _logger.indentChar = "--> "; } // --------------------------------------------------------------------------------------------------------------------------------// // HANDLERS // --------------------------------------------------------------------------------------------------------------------------------// protected function load_click_handler(event : MouseEvent) : void { append("//------------------------------------------------------------------------------//"); append("USER COMMAND: Load Config"); _assetloader.onConfigLoaded.addOnce(onConfigLoaded_handler); _assetloader.addConfig("complex-queue-config.xml"); } protected function start_click_handler(event : MouseEvent) : void { append("//------------------------------------------------------------------------------//"); append("USER COMMAND: Start Loading"); append("//------------------------------------------------------------------------------//"); _assetloader.start(); } protected function attach_click_handler(event : MouseEvent) : void { var field : TextField = event.currentTarget.getChildByName("field"); var verbosity : int = int(TextField(getChildByName("attVInput")).text); var recursion : int = int(TextField(getChildByName("attRInput")).text); append("//------------------------------------------------------------------------------//"); if(field.text == "Attach Logger ") { field.text = "Detach Logger"; _logger.attach(_assetloader, verbosity, recursion); append("USER COMMAND: Attach Logger | verbosity=" + verbosity + " | recursion=" + recursion); } else { field.text = "Attach Logger "; _logger.detach(_assetloader, verbosity, recursion); append("USER COMMAND: Detach Logger | verbosity=" + verbosity + " | recursion=" + recursion); } append("//------------------------------------------------------------------------------//"); } protected function explode_click_handler(event : MouseEvent) : void { var verbosity : int = int(TextField(getChildByName("expVInput")).text); var recursion : int = int(TextField(getChildByName("expRInput")).text); append("//------------------------------------------------------------------------------//"); append("USER COMMAND: Explode | verbosity=" + verbosity + " | recursion=" + recursion); append("//------------------------------------------------------------------------------//"); _logger.explode(_assetloader, verbosity, recursion); } protected function expStats_click_handler(event : MouseEvent) : void { var recursion : int = int(TextField(getChildByName("stsRInput")).text); append("//------------------------------------------------------------------------------//"); append("USER COMMAND: Explode | recursion=" + recursion); append("//------------------------------------------------------------------------------//"); _logger.explodeStats(_assetloader, recursion); } protected function clear_click_handler(event:MouseEvent) : void { _field.text = ""; } protected function onConfigLoaded_handler(signal : LoaderSignal) : void { append("... Config Loaded"); append("//------------------------------------------------------------------------------//"); } // --------------------------------------------------------------------------------------------------------------------------------// // CONTROLS // --------------------------------------------------------------------------------------------------------------------------------// protected function initControls() : void { addButton("Load Config", load_click_handler); addButton("Start Loading", start_click_handler); addButton("Attach Logger ", attach_click_handler); addInputs("att", 0, -1); addButton("Explode", explode_click_handler); addInputs("exp", 0, -1); addButton("Explode Stats", expStats_click_handler); addInputs("sts", 0, -1); addButton("Clear Console", clear_click_handler); removeChild(getChildByName("stsVInput")); } protected function addButton(label : String, clickHandler : Function) : Sprite { var field : TextField = new TextField(); field.defaultTextFormat = new TextFormat("Arial", 12, 0xFFFFFF, true); field.autoSize = TextFieldAutoSize.LEFT; field.x = 4; field.y = 4; field.name = "field"; field.mouseEnabled = false; field.text = label; var btn : Sprite = new Sprite(); var pBtn : Sprite = _btns[_btns.length - 1]; if(pBtn) btn.x = pBtn.x + pBtn.width + 6; with(btn.graphics) { beginFill(0x333333); drawRoundRect(0, 0, field.width + 8, field.height + 8, 3); } btn.buttonMode = true; btn.filters = [new BevelFilter(2, 45, 0xFFFFFF, .6, 0, .2, 5, 5, 1, 3), new DropShadowFilter(2, 45, 0, .3, 5, 5, 1, 3)]; btn.addEventListener(MouseEvent.CLICK, clickHandler); btn.addChild(field); _btns.push(btn); addChild(btn); return btn; } protected function addInputs(prefix : String, valueV : int, valueR : int) : void { var btn : Sprite = _btns[_btns.length - 1]; if(btn) { createInput(prefix + "V", valueV, btn.x, (btn.width / 2) - 4); createInput(prefix + "R", valueR, btn.x + (btn.width / 2) + 2, (btn.width / 2) - 4); } } protected function createInput(prefix : String, value : int, x : Number, width : Number) : void { var input : TextField = new TextField(); input.defaultTextFormat = new TextFormat("Courier New", 12, null, null, null, null, null, null, "center"); input.border = true; input.type = TextFieldType.INPUT; input.x = x; input.y = 32; input.width = width; input.height = 18; input.restrict = "\-0-4"; input.maxChars = 2; input.name = prefix + "Input"; input.text = String(value); addChild(input); } // --------------------------------------------------------------------------------------------------------------------------------// // CONSOLE // --------------------------------------------------------------------------------------------------------------------------------// protected function initConsole() : void { _field = new TextField(); _field.defaultTextFormat = new TextFormat("Courier New", 12); _field.multiline = true; _field.selectable = true; _field.wordWrap = false; _field.y = 60; _field.width = stage.stageWidth; _field.height = stage.stageHeight - 60; stage.addEventListener(Event.RESIZE, resize_handler); addChild(_field); } protected function append(text : String) : void { _field.appendText(text + "\n"); } protected function resize_handler(event : Event) : void { _field.width = stage.stageWidth; _field.height = stage.stageHeight - 60; } } }
{ "pile_set_name": "Github" }
# From http://www.harding.motd.ca/autossh/autossh-1.4d.cksums md5 89c09b50aa2d57814f808d727e937d0f autossh-1.4d.tgz sha1 27da23c357f8d263aba6ecf3e8792a3552d90e50 autossh-1.4d.tgz sha256 00008fe458bde4c94e98bfa96e1e6e18c4107a1f9fc8a538556b82e91ddedc16 autossh-1.4d.tgz
{ "pile_set_name": "Github" }
using NPBehave; using UnityEngine; using XNode; using Node = XNode.Node; namespace CabinIcarus.IcSkillSystem.Nodes.Runtime { public abstract class ClockNode:ANPNode<Clock> { } }
{ "pile_set_name": "Github" }
@echo off setlocal cd "%~p0" call bin/_initdemos.bat :: G3dOGL data/mechpart.recon.m -st data/mechpart.s3d -imagename data/mechpart.image.bmp -picture %G3DARGS% -geometry 800x800+100+0 G3dOGL data/mechpart.recon.m -st data/mechpart.s3d -offscreen data/mechpart.image.bmp -noinfo 1 %G3DARGS% -geometry 800x800+100+0 echo File data/mechpart.image.bmp is now created; it can be viewed using view_rendered_mechpart_image.bat
{ "pile_set_name": "Github" }
/* Copyright 2020 The Rook 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 osd import ( "testing" "github.com/pkg/errors" "github.com/rook/rook/pkg/clusterd" exectest "github.com/rook/rook/pkg/util/exec/test" "github.com/stretchr/testify/assert" ) func TestCloseEncryptedDevice(t *testing.T) { executor := &exectest.MockExecutor{} executor.MockExecuteCommandWithCombinedOutput = func(command string, args ...string) (string, error) { logger.Infof("%s %v", command, args) if command == "cryptsetup" && args[0] == "--verbose" && args[1] == "luksClose" { return "success", nil } return "", errors.Errorf("unknown command %s %s", command, args) } context := &clusterd.Context{Executor: executor} err := closeEncryptedDevice(context, "/dev/mapper/ceph-43e9efed-0676-4731-b75a-a4c42ece1bb1-xvdbr-block-dmcrypt") assert.NoError(t, err) }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <!-- Copyright 2007-2016, Kaazing Corporation. 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. --> <gateway-config xmlns="http://xmlns.kaazing.org/2014/09/gateway"> <service> <name>echo</name> <accept>ws://localhost:8001</accept> <type>echo</type> </service> </gateway-config>
{ "pile_set_name": "Github" }
import requests from parsel import Selector with open('urls.txt','r') as fp: for line in fp: url = line.strip() #url = 'http://sh.xiaozhu.com/fangzi/99382335701.html' headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': '_uab_collina=155350740949073319393702; gr_user_id=4844e1fa-126f-43d0-909f-5af5f96866e6; 59a81cc7d8c04307ba183d331c373ef6_gr_last_sent_cs1=N%2FA; grwng_uid=a409c431-1140-4e26-95e7-2e69a55e5a31; xz_guid_4se=03459fce-2235-4d5b-9e84-a36ee4184660; _uab_collina=155358561150539202408096; abtest_ABTest4SearchDate=b; 59a81cc7d8c04307ba183d331c373ef6_gr_session_id=9be3fa82-3c61-425d-9c1a-e156d4ed47e4; 59a81cc7d8c04307ba183d331c373ef6_gr_session_id_9be3fa82-3c61-425d-9c1a-e156d4ed47e4=true; TY_SESSION_ID=78d7cca8-a26c-42a8-8ea3-a74c4d20d992; SPIDER_AVOID_TOKEN_calendar=25315d7e8e32b1441d08e0663d3e3187', 'Host': 'sh.xiaozhu.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36', } response = requests.get(url, headers=headers) selector = Selector(text=response.text) # 性别 sex = selector.xpath('//span[contains(@class,"member")]/@class').extract_first() if 'girl' in sex: sex = '女' elif 'boy' in sex: sex = '男' # 房子描述 selectors = selector.xpath('//div[@class="intro_item_content"]') for sele in selectors: # data = sele.xpath('.//br/text()').getall() # 个性描述 gexing = selector.xpath('//*[@id="introducePart"]/div[1]/div[2]/div[1]/p//text()').getall() # 内部情况 qingkuang = selector.xpath('//*[@id="introducePart"]/div[2]/div[2]/div[1]/p//text()').getall() # 交通情况 jiaotong = selector.xpath('//*[@id="introducePart"]/div[3]/div[2]/div[1]/p//text()').getall() # 周边情况 zhoubian = selector.xpath('//*[@id="introducePart"]/div[4]/div[2]/div[1]/p//text()').getall() # 配套设施 sheshi = selector.xpath('//*[@id="introducePart"]/div[5]/div[2]/div[1]/ul/li//text()').getall() # 入住须知 xuzhi = selector.xpath('//*[@id="introducePart"]/div[6]/div[2]/div/ul/li//text()').getall() data = f'{gexing},{qingkuang},{jiaotong},{zhoubian},{sheshi},{xuzhi}' print(data) with open('content.csv','a', encoding='utf-8') as fp: fp.write(data+'\n')
{ "pile_set_name": "Github" }
**This airport has been automatically generated** We have no information about GE30[*] 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" }
from lib.utils.container import Services output = Services.get("output") request = Services.get("request_factory") if request.redirect == True: output.info("For better waf detection we recommend you to run with --no-redirect")
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-or-later /* -*- mode: c; c-basic-offset: 8; -*- * vim: noexpandtab sw=8 ts=8 sts=0: * * sysfile.c * * Initialize, read, write, etc. system files. * * Copyright (C) 2002, 2004 Oracle. All rights reserved. */ #include <linux/fs.h> #include <linux/types.h> #include <linux/highmem.h> #include <cluster/masklog.h> #include "ocfs2.h" #include "alloc.h" #include "dir.h" #include "inode.h" #include "journal.h" #include "sysfile.h" #include "buffer_head_io.h" static struct inode * _ocfs2_get_system_file_inode(struct ocfs2_super *osb, int type, u32 slot); #ifdef CONFIG_DEBUG_LOCK_ALLOC static struct lock_class_key ocfs2_sysfile_cluster_lock_key[NUM_SYSTEM_INODES]; #endif static inline int is_global_system_inode(int type) { return type >= OCFS2_FIRST_ONLINE_SYSTEM_INODE && type <= OCFS2_LAST_GLOBAL_SYSTEM_INODE; } static struct inode **get_local_system_inode(struct ocfs2_super *osb, int type, u32 slot) { int index; struct inode **local_system_inodes, **free = NULL; BUG_ON(slot == OCFS2_INVALID_SLOT); BUG_ON(type < OCFS2_FIRST_LOCAL_SYSTEM_INODE || type > OCFS2_LAST_LOCAL_SYSTEM_INODE); spin_lock(&osb->osb_lock); local_system_inodes = osb->local_system_inodes; spin_unlock(&osb->osb_lock); if (unlikely(!local_system_inodes)) { local_system_inodes = kzalloc(array3_size(sizeof(struct inode *), NUM_LOCAL_SYSTEM_INODES, osb->max_slots), GFP_NOFS); if (!local_system_inodes) { mlog_errno(-ENOMEM); /* * return NULL here so that ocfs2_get_sytem_file_inodes * will try to create an inode and use it. We will try * to initialize local_system_inodes next time. */ return NULL; } spin_lock(&osb->osb_lock); if (osb->local_system_inodes) { /* Someone has initialized it for us. */ free = local_system_inodes; local_system_inodes = osb->local_system_inodes; } else osb->local_system_inodes = local_system_inodes; spin_unlock(&osb->osb_lock); kfree(free); } index = (slot * NUM_LOCAL_SYSTEM_INODES) + (type - OCFS2_FIRST_LOCAL_SYSTEM_INODE); return &local_system_inodes[index]; } struct inode *ocfs2_get_system_file_inode(struct ocfs2_super *osb, int type, u32 slot) { struct inode *inode = NULL; struct inode **arr = NULL; /* avoid the lookup if cached in local system file array */ if (is_global_system_inode(type)) { arr = &(osb->global_system_inodes[type]); } else arr = get_local_system_inode(osb, type, slot); mutex_lock(&osb->system_file_mutex); if (arr && ((inode = *arr) != NULL)) { /* get a ref in addition to the array ref */ inode = igrab(inode); mutex_unlock(&osb->system_file_mutex); BUG_ON(!inode); return inode; } /* this gets one ref thru iget */ inode = _ocfs2_get_system_file_inode(osb, type, slot); /* add one more if putting into array for first time */ if (arr && inode) { *arr = igrab(inode); BUG_ON(!*arr); } mutex_unlock(&osb->system_file_mutex); return inode; } static struct inode * _ocfs2_get_system_file_inode(struct ocfs2_super *osb, int type, u32 slot) { char namebuf[40]; struct inode *inode = NULL; u64 blkno; int status = 0; ocfs2_sprintf_system_inode_name(namebuf, sizeof(namebuf), type, slot); status = ocfs2_lookup_ino_from_name(osb->sys_root_inode, namebuf, strlen(namebuf), &blkno); if (status < 0) { goto bail; } inode = ocfs2_iget(osb, blkno, OCFS2_FI_FLAG_SYSFILE, type); if (IS_ERR(inode)) { mlog_errno(PTR_ERR(inode)); inode = NULL; goto bail; } #ifdef CONFIG_DEBUG_LOCK_ALLOC if (type == LOCAL_USER_QUOTA_SYSTEM_INODE || type == LOCAL_GROUP_QUOTA_SYSTEM_INODE || type == JOURNAL_SYSTEM_INODE) { /* Ignore inode lock on these inodes as the lock does not * really belong to any process and lockdep cannot handle * that */ OCFS2_I(inode)->ip_inode_lockres.l_lockdep_map.key = NULL; } else { lockdep_init_map(&OCFS2_I(inode)->ip_inode_lockres. l_lockdep_map, ocfs2_system_inodes[type].si_name, &ocfs2_sysfile_cluster_lock_key[type], 0); } #endif bail: return inode; }
{ "pile_set_name": "Github" }
/* $Id: openssl-compat.h,v 1.31 2014/08/29 18:18:29 djm Exp $ */ /* * Copyright (c) 2005 Darren Tucker <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _OPENSSL_COMPAT_H #define _OPENSSL_COMPAT_H #include "includes.h" #ifdef WITH_OPENSSL #include <openssl/opensslv.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/dsa.h> int ssh_compatible_openssl(long, long); #if (OPENSSL_VERSION_NUMBER <= 0x0090805fL) # error OpenSSL 0.9.8f or greater is required #endif #if OPENSSL_VERSION_NUMBER < 0x10000001L # define LIBCRYPTO_EVP_INL_TYPE unsigned int #else # define LIBCRYPTO_EVP_INL_TYPE size_t #endif #ifndef OPENSSL_RSA_MAX_MODULUS_BITS # define OPENSSL_RSA_MAX_MODULUS_BITS 16384 #endif #ifndef OPENSSL_DSA_MAX_MODULUS_BITS # define OPENSSL_DSA_MAX_MODULUS_BITS 10000 #endif #ifndef OPENSSL_HAVE_EVPCTR # define EVP_aes_128_ctr evp_aes_128_ctr # define EVP_aes_192_ctr evp_aes_128_ctr # define EVP_aes_256_ctr evp_aes_128_ctr const EVP_CIPHER *evp_aes_128_ctr(void); void ssh_aes_ctr_iv(EVP_CIPHER_CTX *, int, u_char *, size_t); #endif /* Avoid some #ifdef. Code that uses these is unreachable without GCM */ #if !defined(OPENSSL_HAVE_EVPGCM) && !defined(EVP_CTRL_GCM_SET_IV_FIXED) # define EVP_CTRL_GCM_SET_IV_FIXED -1 # define EVP_CTRL_GCM_IV_GEN -1 # define EVP_CTRL_GCM_SET_TAG -1 # define EVP_CTRL_GCM_GET_TAG -1 #endif /* Replace missing EVP_CIPHER_CTX_ctrl() with something that returns failure */ #ifndef HAVE_EVP_CIPHER_CTX_CTRL # ifdef OPENSSL_HAVE_EVPGCM # error AES-GCM enabled without EVP_CIPHER_CTX_ctrl /* shouldn't happen */ # else # define EVP_CIPHER_CTX_ctrl(a,b,c,d) (0) # endif #endif /* * We overload some of the OpenSSL crypto functions with ssh_* equivalents * to automatically handle OpenSSL engine initialisation. * * In order for the compat library to call the real functions, it must * define SSH_DONT_OVERLOAD_OPENSSL_FUNCS before including this file and * implement the ssh_* equivalents. */ #ifndef SSH_DONT_OVERLOAD_OPENSSL_FUNCS # ifdef USE_OPENSSL_ENGINE # ifdef OpenSSL_add_all_algorithms # undef OpenSSL_add_all_algorithms # endif # define OpenSSL_add_all_algorithms() ssh_OpenSSL_add_all_algorithms() # endif void ssh_OpenSSL_add_all_algorithms(void); #endif /* SSH_DONT_OVERLOAD_OPENSSL_FUNCS */ #endif /* WITH_OPENSSL */ #endif /* _OPENSSL_COMPAT_H */
{ "pile_set_name": "Github" }
; RUN: llc < %s -march=arm -mcpu=cortex-a8 | FileCheck %s define <8 x i8> @vmuli8(<8 x i8>* %A, <8 x i8>* %B) nounwind { ;CHECK: vmuli8: ;CHECK: vmul.i8 %tmp1 = load <8 x i8>* %A %tmp2 = load <8 x i8>* %B %tmp3 = mul <8 x i8> %tmp1, %tmp2 ret <8 x i8> %tmp3 } define <4 x i16> @vmuli16(<4 x i16>* %A, <4 x i16>* %B) nounwind { ;CHECK: vmuli16: ;CHECK: vmul.i16 %tmp1 = load <4 x i16>* %A %tmp2 = load <4 x i16>* %B %tmp3 = mul <4 x i16> %tmp1, %tmp2 ret <4 x i16> %tmp3 } define <2 x i32> @vmuli32(<2 x i32>* %A, <2 x i32>* %B) nounwind { ;CHECK: vmuli32: ;CHECK: vmul.i32 %tmp1 = load <2 x i32>* %A %tmp2 = load <2 x i32>* %B %tmp3 = mul <2 x i32> %tmp1, %tmp2 ret <2 x i32> %tmp3 } define <2 x float> @vmulf32(<2 x float>* %A, <2 x float>* %B) nounwind { ;CHECK: vmulf32: ;CHECK: vmul.f32 %tmp1 = load <2 x float>* %A %tmp2 = load <2 x float>* %B %tmp3 = fmul <2 x float> %tmp1, %tmp2 ret <2 x float> %tmp3 } define <8 x i8> @vmulp8(<8 x i8>* %A, <8 x i8>* %B) nounwind { ;CHECK: vmulp8: ;CHECK: vmul.p8 %tmp1 = load <8 x i8>* %A %tmp2 = load <8 x i8>* %B %tmp3 = call <8 x i8> @llvm.arm.neon.vmulp.v8i8(<8 x i8> %tmp1, <8 x i8> %tmp2) ret <8 x i8> %tmp3 } define <16 x i8> @vmulQi8(<16 x i8>* %A, <16 x i8>* %B) nounwind { ;CHECK: vmulQi8: ;CHECK: vmul.i8 %tmp1 = load <16 x i8>* %A %tmp2 = load <16 x i8>* %B %tmp3 = mul <16 x i8> %tmp1, %tmp2 ret <16 x i8> %tmp3 } define <8 x i16> @vmulQi16(<8 x i16>* %A, <8 x i16>* %B) nounwind { ;CHECK: vmulQi16: ;CHECK: vmul.i16 %tmp1 = load <8 x i16>* %A %tmp2 = load <8 x i16>* %B %tmp3 = mul <8 x i16> %tmp1, %tmp2 ret <8 x i16> %tmp3 } define <4 x i32> @vmulQi32(<4 x i32>* %A, <4 x i32>* %B) nounwind { ;CHECK: vmulQi32: ;CHECK: vmul.i32 %tmp1 = load <4 x i32>* %A %tmp2 = load <4 x i32>* %B %tmp3 = mul <4 x i32> %tmp1, %tmp2 ret <4 x i32> %tmp3 } define <4 x float> @vmulQf32(<4 x float>* %A, <4 x float>* %B) nounwind { ;CHECK: vmulQf32: ;CHECK: vmul.f32 %tmp1 = load <4 x float>* %A %tmp2 = load <4 x float>* %B %tmp3 = fmul <4 x float> %tmp1, %tmp2 ret <4 x float> %tmp3 } define <16 x i8> @vmulQp8(<16 x i8>* %A, <16 x i8>* %B) nounwind { ;CHECK: vmulQp8: ;CHECK: vmul.p8 %tmp1 = load <16 x i8>* %A %tmp2 = load <16 x i8>* %B %tmp3 = call <16 x i8> @llvm.arm.neon.vmulp.v16i8(<16 x i8> %tmp1, <16 x i8> %tmp2) ret <16 x i8> %tmp3 } declare <8 x i8> @llvm.arm.neon.vmulp.v8i8(<8 x i8>, <8 x i8>) nounwind readnone declare <16 x i8> @llvm.arm.neon.vmulp.v16i8(<16 x i8>, <16 x i8>) nounwind readnone define arm_aapcs_vfpcc <2 x float> @test_vmul_lanef32(<2 x float> %arg0_float32x2_t, <2 x float> %arg1_float32x2_t) nounwind readnone { entry: ; CHECK: test_vmul_lanef32: ; CHECK: vmul.f32 d0, d0, d1[0] %0 = shufflevector <2 x float> %arg1_float32x2_t, <2 x float> undef, <2 x i32> zeroinitializer ; <<2 x float>> [#uses=1] %1 = fmul <2 x float> %0, %arg0_float32x2_t ; <<2 x float>> [#uses=1] ret <2 x float> %1 } define arm_aapcs_vfpcc <4 x i16> @test_vmul_lanes16(<4 x i16> %arg0_int16x4_t, <4 x i16> %arg1_int16x4_t) nounwind readnone { entry: ; CHECK: test_vmul_lanes16: ; CHECK: vmul.i16 d0, d0, d1[1] %0 = shufflevector <4 x i16> %arg1_int16x4_t, <4 x i16> undef, <4 x i32> <i32 1, i32 1, i32 1, i32 1> ; <<4 x i16>> [#uses$ %1 = mul <4 x i16> %0, %arg0_int16x4_t ; <<4 x i16>> [#uses=1] ret <4 x i16> %1 } define arm_aapcs_vfpcc <2 x i32> @test_vmul_lanes32(<2 x i32> %arg0_int32x2_t, <2 x i32> %arg1_int32x2_t) nounwind readnone { entry: ; CHECK: test_vmul_lanes32: ; CHECK: vmul.i32 d0, d0, d1[1] %0 = shufflevector <2 x i32> %arg1_int32x2_t, <2 x i32> undef, <2 x i32> <i32 1, i32 1> ; <<2 x i32>> [#uses=1] %1 = mul <2 x i32> %0, %arg0_int32x2_t ; <<2 x i32>> [#uses=1] ret <2 x i32> %1 } define arm_aapcs_vfpcc <4 x float> @test_vmulQ_lanef32(<4 x float> %arg0_float32x4_t, <2 x float> %arg1_float32x2_t) nounwind readnone { entry: ; CHECK: test_vmulQ_lanef32: ; CHECK: vmul.f32 q0, q0, d2[1] %0 = shufflevector <2 x float> %arg1_float32x2_t, <2 x float> undef, <4 x i32> <i32 1, i32 1, i32 1, i32 1> ; <<4 x float>$ %1 = fmul <4 x float> %0, %arg0_float32x4_t ; <<4 x float>> [#uses=1] ret <4 x float> %1 } define arm_aapcs_vfpcc <8 x i16> @test_vmulQ_lanes16(<8 x i16> %arg0_int16x8_t, <4 x i16> %arg1_int16x4_t) nounwind readnone { entry: ; CHECK: test_vmulQ_lanes16: ; CHECK: vmul.i16 q0, q0, d2[1] %0 = shufflevector <4 x i16> %arg1_int16x4_t, <4 x i16> undef, <8 x i32> <i32 1, i32 1, i32 1, i32 1, i32 1, i32 1, i32 1, i32 1> %1 = mul <8 x i16> %0, %arg0_int16x8_t ; <<8 x i16>> [#uses=1] ret <8 x i16> %1 } define arm_aapcs_vfpcc <4 x i32> @test_vmulQ_lanes32(<4 x i32> %arg0_int32x4_t, <2 x i32> %arg1_int32x2_t) nounwind readnone { entry: ; CHECK: test_vmulQ_lanes32: ; CHECK: vmul.i32 q0, q0, d2[1] %0 = shufflevector <2 x i32> %arg1_int32x2_t, <2 x i32> undef, <4 x i32> <i32 1, i32 1, i32 1, i32 1> ; <<4 x i32>> [#uses$ %1 = mul <4 x i32> %0, %arg0_int32x4_t ; <<4 x i32>> [#uses=1] ret <4 x i32> %1 } define <8 x i16> @vmulls8(<8 x i8>* %A, <8 x i8>* %B) nounwind { ;CHECK: vmulls8: ;CHECK: vmull.s8 %tmp1 = load <8 x i8>* %A %tmp2 = load <8 x i8>* %B %tmp3 = sext <8 x i8> %tmp1 to <8 x i16> %tmp4 = sext <8 x i8> %tmp2 to <8 x i16> %tmp5 = mul <8 x i16> %tmp3, %tmp4 ret <8 x i16> %tmp5 } define <8 x i16> @vmulls8_int(<8 x i8>* %A, <8 x i8>* %B) nounwind { ;CHECK: vmulls8_int: ;CHECK: vmull.s8 %tmp1 = load <8 x i8>* %A %tmp2 = load <8 x i8>* %B %tmp3 = call <8 x i16> @llvm.arm.neon.vmulls.v8i16(<8 x i8> %tmp1, <8 x i8> %tmp2) ret <8 x i16> %tmp3 } define <4 x i32> @vmulls16(<4 x i16>* %A, <4 x i16>* %B) nounwind { ;CHECK: vmulls16: ;CHECK: vmull.s16 %tmp1 = load <4 x i16>* %A %tmp2 = load <4 x i16>* %B %tmp3 = sext <4 x i16> %tmp1 to <4 x i32> %tmp4 = sext <4 x i16> %tmp2 to <4 x i32> %tmp5 = mul <4 x i32> %tmp3, %tmp4 ret <4 x i32> %tmp5 } define <4 x i32> @vmulls16_int(<4 x i16>* %A, <4 x i16>* %B) nounwind { ;CHECK: vmulls16_int: ;CHECK: vmull.s16 %tmp1 = load <4 x i16>* %A %tmp2 = load <4 x i16>* %B %tmp3 = call <4 x i32> @llvm.arm.neon.vmulls.v4i32(<4 x i16> %tmp1, <4 x i16> %tmp2) ret <4 x i32> %tmp3 } define <2 x i64> @vmulls32(<2 x i32>* %A, <2 x i32>* %B) nounwind { ;CHECK: vmulls32: ;CHECK: vmull.s32 %tmp1 = load <2 x i32>* %A %tmp2 = load <2 x i32>* %B %tmp3 = sext <2 x i32> %tmp1 to <2 x i64> %tmp4 = sext <2 x i32> %tmp2 to <2 x i64> %tmp5 = mul <2 x i64> %tmp3, %tmp4 ret <2 x i64> %tmp5 } define <2 x i64> @vmulls32_int(<2 x i32>* %A, <2 x i32>* %B) nounwind { ;CHECK: vmulls32_int: ;CHECK: vmull.s32 %tmp1 = load <2 x i32>* %A %tmp2 = load <2 x i32>* %B %tmp3 = call <2 x i64> @llvm.arm.neon.vmulls.v2i64(<2 x i32> %tmp1, <2 x i32> %tmp2) ret <2 x i64> %tmp3 } define <8 x i16> @vmullu8(<8 x i8>* %A, <8 x i8>* %B) nounwind { ;CHECK: vmullu8: ;CHECK: vmull.u8 %tmp1 = load <8 x i8>* %A %tmp2 = load <8 x i8>* %B %tmp3 = zext <8 x i8> %tmp1 to <8 x i16> %tmp4 = zext <8 x i8> %tmp2 to <8 x i16> %tmp5 = mul <8 x i16> %tmp3, %tmp4 ret <8 x i16> %tmp5 } define <8 x i16> @vmullu8_int(<8 x i8>* %A, <8 x i8>* %B) nounwind { ;CHECK: vmullu8_int: ;CHECK: vmull.u8 %tmp1 = load <8 x i8>* %A %tmp2 = load <8 x i8>* %B %tmp3 = call <8 x i16> @llvm.arm.neon.vmullu.v8i16(<8 x i8> %tmp1, <8 x i8> %tmp2) ret <8 x i16> %tmp3 } define <4 x i32> @vmullu16(<4 x i16>* %A, <4 x i16>* %B) nounwind { ;CHECK: vmullu16: ;CHECK: vmull.u16 %tmp1 = load <4 x i16>* %A %tmp2 = load <4 x i16>* %B %tmp3 = zext <4 x i16> %tmp1 to <4 x i32> %tmp4 = zext <4 x i16> %tmp2 to <4 x i32> %tmp5 = mul <4 x i32> %tmp3, %tmp4 ret <4 x i32> %tmp5 } define <4 x i32> @vmullu16_int(<4 x i16>* %A, <4 x i16>* %B) nounwind { ;CHECK: vmullu16_int: ;CHECK: vmull.u16 %tmp1 = load <4 x i16>* %A %tmp2 = load <4 x i16>* %B %tmp3 = call <4 x i32> @llvm.arm.neon.vmullu.v4i32(<4 x i16> %tmp1, <4 x i16> %tmp2) ret <4 x i32> %tmp3 } define <2 x i64> @vmullu32(<2 x i32>* %A, <2 x i32>* %B) nounwind { ;CHECK: vmullu32: ;CHECK: vmull.u32 %tmp1 = load <2 x i32>* %A %tmp2 = load <2 x i32>* %B %tmp3 = zext <2 x i32> %tmp1 to <2 x i64> %tmp4 = zext <2 x i32> %tmp2 to <2 x i64> %tmp5 = mul <2 x i64> %tmp3, %tmp4 ret <2 x i64> %tmp5 } define <2 x i64> @vmullu32_int(<2 x i32>* %A, <2 x i32>* %B) nounwind { ;CHECK: vmullu32_int: ;CHECK: vmull.u32 %tmp1 = load <2 x i32>* %A %tmp2 = load <2 x i32>* %B %tmp3 = call <2 x i64> @llvm.arm.neon.vmullu.v2i64(<2 x i32> %tmp1, <2 x i32> %tmp2) ret <2 x i64> %tmp3 } define <8 x i16> @vmullp8(<8 x i8>* %A, <8 x i8>* %B) nounwind { ;CHECK: vmullp8: ;CHECK: vmull.p8 %tmp1 = load <8 x i8>* %A %tmp2 = load <8 x i8>* %B %tmp3 = call <8 x i16> @llvm.arm.neon.vmullp.v8i16(<8 x i8> %tmp1, <8 x i8> %tmp2) ret <8 x i16> %tmp3 } define arm_aapcs_vfpcc <4 x i32> @test_vmull_lanes16(<4 x i16> %arg0_int16x4_t, <4 x i16> %arg1_int16x4_t) nounwind readnone { entry: ; CHECK: test_vmull_lanes16 ; CHECK: vmull.s16 q0, d0, d1[1] %0 = shufflevector <4 x i16> %arg1_int16x4_t, <4 x i16> undef, <4 x i32> <i32 1, i32 1, i32 1, i32 1> ; <<4 x i16>> [#uses=1] %1 = sext <4 x i16> %arg0_int16x4_t to <4 x i32> %2 = sext <4 x i16> %0 to <4 x i32> %3 = mul <4 x i32> %1, %2 ret <4 x i32> %3 } define arm_aapcs_vfpcc <4 x i32> @test_vmull_lanes16_int(<4 x i16> %arg0_int16x4_t, <4 x i16> %arg1_int16x4_t) nounwind readnone { entry: ; CHECK: test_vmull_lanes16_int ; CHECK: vmull.s16 q0, d0, d1[1] %0 = shufflevector <4 x i16> %arg1_int16x4_t, <4 x i16> undef, <4 x i32> <i32 1, i32 1, i32 1, i32 1> ; <<4 x i16>> [#uses=1] %1 = tail call <4 x i32> @llvm.arm.neon.vmulls.v4i32(<4 x i16> %arg0_int16x4_t, <4 x i16> %0) ; <<4 x i32>> [#uses=1] ret <4 x i32> %1 } define arm_aapcs_vfpcc <2 x i64> @test_vmull_lanes32(<2 x i32> %arg0_int32x2_t, <2 x i32> %arg1_int32x2_t) nounwind readnone { entry: ; CHECK: test_vmull_lanes32 ; CHECK: vmull.s32 q0, d0, d1[1] %0 = shufflevector <2 x i32> %arg1_int32x2_t, <2 x i32> undef, <2 x i32> <i32 1, i32 1> ; <<2 x i32>> [#uses=1] %1 = sext <2 x i32> %arg0_int32x2_t to <2 x i64> %2 = sext <2 x i32> %0 to <2 x i64> %3 = mul <2 x i64> %1, %2 ret <2 x i64> %3 } define arm_aapcs_vfpcc <2 x i64> @test_vmull_lanes32_int(<2 x i32> %arg0_int32x2_t, <2 x i32> %arg1_int32x2_t) nounwind readnone { entry: ; CHECK: test_vmull_lanes32_int ; CHECK: vmull.s32 q0, d0, d1[1] %0 = shufflevector <2 x i32> %arg1_int32x2_t, <2 x i32> undef, <2 x i32> <i32 1, i32 1> ; <<2 x i32>> [#uses=1] %1 = tail call <2 x i64> @llvm.arm.neon.vmulls.v2i64(<2 x i32> %arg0_int32x2_t, <2 x i32> %0) ; <<2 x i64>> [#uses=1] ret <2 x i64> %1 } define arm_aapcs_vfpcc <4 x i32> @test_vmull_laneu16(<4 x i16> %arg0_uint16x4_t, <4 x i16> %arg1_uint16x4_t) nounwind readnone { entry: ; CHECK: test_vmull_laneu16 ; CHECK: vmull.u16 q0, d0, d1[1] %0 = shufflevector <4 x i16> %arg1_uint16x4_t, <4 x i16> undef, <4 x i32> <i32 1, i32 1, i32 1, i32 1> ; <<4 x i16>> [#uses=1] %1 = zext <4 x i16> %arg0_uint16x4_t to <4 x i32> %2 = zext <4 x i16> %0 to <4 x i32> %3 = mul <4 x i32> %1, %2 ret <4 x i32> %3 } define arm_aapcs_vfpcc <4 x i32> @test_vmull_laneu16_int(<4 x i16> %arg0_uint16x4_t, <4 x i16> %arg1_uint16x4_t) nounwind readnone { entry: ; CHECK: test_vmull_laneu16_int ; CHECK: vmull.u16 q0, d0, d1[1] %0 = shufflevector <4 x i16> %arg1_uint16x4_t, <4 x i16> undef, <4 x i32> <i32 1, i32 1, i32 1, i32 1> ; <<4 x i16>> [#uses=1] %1 = tail call <4 x i32> @llvm.arm.neon.vmullu.v4i32(<4 x i16> %arg0_uint16x4_t, <4 x i16> %0) ; <<4 x i32>> [#uses=1] ret <4 x i32> %1 } define arm_aapcs_vfpcc <2 x i64> @test_vmull_laneu32(<2 x i32> %arg0_uint32x2_t, <2 x i32> %arg1_uint32x2_t) nounwind readnone { entry: ; CHECK: test_vmull_laneu32 ; CHECK: vmull.u32 q0, d0, d1[1] %0 = shufflevector <2 x i32> %arg1_uint32x2_t, <2 x i32> undef, <2 x i32> <i32 1, i32 1> ; <<2 x i32>> [#uses=1] %1 = zext <2 x i32> %arg0_uint32x2_t to <2 x i64> %2 = zext <2 x i32> %0 to <2 x i64> %3 = mul <2 x i64> %1, %2 ret <2 x i64> %3 } define arm_aapcs_vfpcc <2 x i64> @test_vmull_laneu32_int(<2 x i32> %arg0_uint32x2_t, <2 x i32> %arg1_uint32x2_t) nounwind readnone { entry: ; CHECK: test_vmull_laneu32_int ; CHECK: vmull.u32 q0, d0, d1[1] %0 = shufflevector <2 x i32> %arg1_uint32x2_t, <2 x i32> undef, <2 x i32> <i32 1, i32 1> ; <<2 x i32>> [#uses=1] %1 = tail call <2 x i64> @llvm.arm.neon.vmullu.v2i64(<2 x i32> %arg0_uint32x2_t, <2 x i32> %0) ; <<2 x i64>> [#uses=1] ret <2 x i64> %1 } declare <8 x i16> @llvm.arm.neon.vmulls.v8i16(<8 x i8>, <8 x i8>) nounwind readnone declare <4 x i32> @llvm.arm.neon.vmulls.v4i32(<4 x i16>, <4 x i16>) nounwind readnone declare <2 x i64> @llvm.arm.neon.vmulls.v2i64(<2 x i32>, <2 x i32>) nounwind readnone declare <8 x i16> @llvm.arm.neon.vmullu.v8i16(<8 x i8>, <8 x i8>) nounwind readnone declare <4 x i32> @llvm.arm.neon.vmullu.v4i32(<4 x i16>, <4 x i16>) nounwind readnone declare <2 x i64> @llvm.arm.neon.vmullu.v2i64(<2 x i32>, <2 x i32>) nounwind readnone declare <8 x i16> @llvm.arm.neon.vmullp.v8i16(<8 x i8>, <8 x i8>) nounwind readnone ; Radar 8687140 ; VMULL needs to recognize BUILD_VECTORs with sign/zero-extended elements. define <8 x i16> @vmull_extvec_s8(<8 x i8> %arg) nounwind { ; CHECK: vmull_extvec_s8 ; CHECK: vmull.s8 %tmp3 = sext <8 x i8> %arg to <8 x i16> %tmp4 = mul <8 x i16> %tmp3, <i16 -12, i16 -12, i16 -12, i16 -12, i16 -12, i16 -12, i16 -12, i16 -12> ret <8 x i16> %tmp4 } define <8 x i16> @vmull_extvec_u8(<8 x i8> %arg) nounwind { ; CHECK: vmull_extvec_u8 ; CHECK: vmull.u8 %tmp3 = zext <8 x i8> %arg to <8 x i16> %tmp4 = mul <8 x i16> %tmp3, <i16 12, i16 12, i16 12, i16 12, i16 12, i16 12, i16 12, i16 12> ret <8 x i16> %tmp4 } define <8 x i16> @vmull_noextvec_s8(<8 x i8> %arg) nounwind { ; Do not use VMULL if the BUILD_VECTOR element values are too big. ; CHECK: vmull_noextvec_s8 ; CHECK: vmovl.s8 ; CHECK: vmul.i16 %tmp3 = sext <8 x i8> %arg to <8 x i16> %tmp4 = mul <8 x i16> %tmp3, <i16 -999, i16 -999, i16 -999, i16 -999, i16 -999, i16 -999, i16 -999, i16 -999> ret <8 x i16> %tmp4 } define <8 x i16> @vmull_noextvec_u8(<8 x i8> %arg) nounwind { ; Do not use VMULL if the BUILD_VECTOR element values are too big. ; CHECK: vmull_noextvec_u8 ; CHECK: vmovl.u8 ; CHECK: vmul.i16 %tmp3 = zext <8 x i8> %arg to <8 x i16> %tmp4 = mul <8 x i16> %tmp3, <i16 999, i16 999, i16 999, i16 999, i16 999, i16 999, i16 999, i16 999> ret <8 x i16> %tmp4 } define <4 x i32> @vmull_extvec_s16(<4 x i16> %arg) nounwind { ; CHECK: vmull_extvec_s16 ; CHECK: vmull.s16 %tmp3 = sext <4 x i16> %arg to <4 x i32> %tmp4 = mul <4 x i32> %tmp3, <i32 -12, i32 -12, i32 -12, i32 -12> ret <4 x i32> %tmp4 } define <4 x i32> @vmull_extvec_u16(<4 x i16> %arg) nounwind { ; CHECK: vmull_extvec_u16 ; CHECK: vmull.u16 %tmp3 = zext <4 x i16> %arg to <4 x i32> %tmp4 = mul <4 x i32> %tmp3, <i32 1234, i32 1234, i32 1234, i32 1234> ret <4 x i32> %tmp4 } define <2 x i64> @vmull_extvec_s32(<2 x i32> %arg) nounwind { ; CHECK: vmull_extvec_s32 ; CHECK: vmull.s32 %tmp3 = sext <2 x i32> %arg to <2 x i64> %tmp4 = mul <2 x i64> %tmp3, <i64 -1234, i64 -1234> ret <2 x i64> %tmp4 } define <2 x i64> @vmull_extvec_u32(<2 x i32> %arg) nounwind { ; CHECK: vmull_extvec_u32 ; CHECK: vmull.u32 %tmp3 = zext <2 x i32> %arg to <2 x i64> %tmp4 = mul <2 x i64> %tmp3, <i64 1234, i64 1234> ret <2 x i64> %tmp4 } ; rdar://9197392 define void @distribute(i16* %dst, i8* %src, i32 %mul) nounwind { entry: ; CHECK: distribute: ; CHECK: vmull.u8 [[REG1:(q[0-9]+)]], d{{.*}}, [[REG2:(d[0-9]+)]] ; CHECK: vmlal.u8 [[REG1]], d{{.*}}, [[REG2]] %0 = trunc i32 %mul to i8 %1 = insertelement <8 x i8> undef, i8 %0, i32 0 %2 = shufflevector <8 x i8> %1, <8 x i8> undef, <8 x i32> zeroinitializer %3 = tail call <16 x i8> @llvm.arm.neon.vld1.v16i8(i8* %src, i32 1) %4 = bitcast <16 x i8> %3 to <2 x double> %5 = extractelement <2 x double> %4, i32 1 %6 = bitcast double %5 to <8 x i8> %7 = zext <8 x i8> %6 to <8 x i16> %8 = zext <8 x i8> %2 to <8 x i16> %9 = extractelement <2 x double> %4, i32 0 %10 = bitcast double %9 to <8 x i8> %11 = zext <8 x i8> %10 to <8 x i16> %12 = add <8 x i16> %7, %11 %13 = mul <8 x i16> %12, %8 %14 = bitcast i16* %dst to i8* tail call void @llvm.arm.neon.vst1.v8i16(i8* %14, <8 x i16> %13, i32 2) ret void } declare <16 x i8> @llvm.arm.neon.vld1.v16i8(i8*, i32) nounwind readonly declare void @llvm.arm.neon.vst1.v8i16(i8*, <8 x i16>, i32) nounwind ; Take advantage of the Cortex-A8 multiplier accumulator forward. %struct.uint8x8_t = type { <8 x i8> } define void @distribute2(%struct.uint8x8_t* nocapture %dst, i8* %src, i32 %mul) nounwind { entry: ; CHECK: distribute2 ; CHECK-NOT: vadd.i8 ; CHECK: vmul.i8 ; CHECK: vmla.i8 %0 = trunc i32 %mul to i8 %1 = insertelement <8 x i8> undef, i8 %0, i32 0 %2 = shufflevector <8 x i8> %1, <8 x i8> undef, <8 x i32> zeroinitializer %3 = tail call <16 x i8> @llvm.arm.neon.vld1.v16i8(i8* %src, i32 1) %4 = bitcast <16 x i8> %3 to <2 x double> %5 = extractelement <2 x double> %4, i32 1 %6 = bitcast double %5 to <8 x i8> %7 = extractelement <2 x double> %4, i32 0 %8 = bitcast double %7 to <8 x i8> %9 = add <8 x i8> %6, %8 %10 = mul <8 x i8> %9, %2 %11 = getelementptr inbounds %struct.uint8x8_t* %dst, i32 0, i32 0 store <8 x i8> %10, <8 x i8>* %11, align 8 ret void } define void @distribute2_commutative(%struct.uint8x8_t* nocapture %dst, i8* %src, i32 %mul) nounwind { entry: ; CHECK: distribute2_commutative ; CHECK-NOT: vadd.i8 ; CHECK: vmul.i8 ; CHECK: vmla.i8 %0 = trunc i32 %mul to i8 %1 = insertelement <8 x i8> undef, i8 %0, i32 0 %2 = shufflevector <8 x i8> %1, <8 x i8> undef, <8 x i32> zeroinitializer %3 = tail call <16 x i8> @llvm.arm.neon.vld1.v16i8(i8* %src, i32 1) %4 = bitcast <16 x i8> %3 to <2 x double> %5 = extractelement <2 x double> %4, i32 1 %6 = bitcast double %5 to <8 x i8> %7 = extractelement <2 x double> %4, i32 0 %8 = bitcast double %7 to <8 x i8> %9 = add <8 x i8> %6, %8 %10 = mul <8 x i8> %2, %9 %11 = getelementptr inbounds %struct.uint8x8_t* %dst, i32 0, i32 0 store <8 x i8> %10, <8 x i8>* %11, align 8 ret void } ; If one operand has a zero-extend and the other a sign-extend, vmull ; cannot be used. define i16 @vmullWithInconsistentExtensions(<8 x i8> %vec) { ; CHECK: vmullWithInconsistentExtensions ; CHECK-NOT: vmull.s8 %1 = sext <8 x i8> %vec to <8 x i16> %2 = mul <8 x i16> %1, <i16 255, i16 255, i16 255, i16 255, i16 255, i16 255, i16 255, i16 255> %3 = extractelement <8 x i16> %2, i32 0 ret i16 %3 } ; A constant build_vector created for a vmull with half-width elements must ; not introduce illegal types. <rdar://problem/11324364> define void @vmull_buildvector() nounwind optsize ssp align 2 { ; CHECK: vmull_buildvector entry: br i1 undef, label %for.end179, label %for.body.lr.ph for.body.lr.ph: ; preds = %entry br label %for.body for.cond.loopexit: ; preds = %for.body33, %for.body br i1 undef, label %for.end179, label %for.body for.body: ; preds = %for.cond.loopexit, %for.body.lr.ph br i1 undef, label %for.cond.loopexit, label %for.body33.lr.ph for.body33.lr.ph: ; preds = %for.body %.sub = select i1 undef, i32 0, i32 undef br label %for.body33 for.body33: ; preds = %for.body33, %for.body33.lr.ph %add45 = add i32 undef, undef %vld155 = tail call <16 x i8> @llvm.arm.neon.vld1.v16i8(i8* undef, i32 1) %0 = load i32** undef, align 4 %shuffle.i250 = shufflevector <2 x i64> undef, <2 x i64> undef, <1 x i32> zeroinitializer %1 = bitcast <1 x i64> %shuffle.i250 to <8 x i8> %vmovl.i249 = zext <8 x i8> %1 to <8 x i16> %shuffle.i246 = shufflevector <2 x i64> undef, <2 x i64> undef, <1 x i32> zeroinitializer %shuffle.i240 = shufflevector <2 x i64> undef, <2 x i64> undef, <1 x i32> <i32 1> %2 = bitcast <1 x i64> %shuffle.i240 to <8 x i8> %3 = bitcast <16 x i8> undef to <2 x i64> %vmovl.i237 = zext <8 x i8> undef to <8 x i16> %shuffle.i234 = shufflevector <2 x i64> undef, <2 x i64> undef, <1 x i32> zeroinitializer %shuffle.i226 = shufflevector <2 x i64> undef, <2 x i64> undef, <1 x i32> zeroinitializer %vmovl.i225 = zext <8 x i8> undef to <8 x i16> %mul.i223 = mul <8 x i16> %vmovl.i249, %vmovl.i249 %vshl_n = shl <8 x i16> %mul.i223, <i16 2, i16 2, i16 2, i16 2, i16 2, i16 2, i16 2, i16 2> %vqsub2.i216 = tail call <8 x i16> @llvm.arm.neon.vqsubu.v8i16(<8 x i16> <i16 256, i16 256, i16 256, i16 256, i16 256, i16 256, i16 256, i16 256>, <8 x i16> %vshl_n) nounwind %mul.i209 = mul <8 x i16> undef, <i16 80, i16 80, i16 80, i16 80, i16 80, i16 80, i16 80, i16 80> %vshr_n130 = lshr <8 x i16> undef, <i16 8, i16 8, i16 8, i16 8, i16 8, i16 8, i16 8, i16 8> %vshr_n134 = lshr <8 x i16> %mul.i209, <i16 8, i16 8, i16 8, i16 8, i16 8, i16 8, i16 8, i16 8> %sub.i205 = sub <8 x i16> <i16 80, i16 80, i16 80, i16 80, i16 80, i16 80, i16 80, i16 80>, %vshr_n130 %sub.i203 = sub <8 x i16> <i16 80, i16 80, i16 80, i16 80, i16 80, i16 80, i16 80, i16 80>, %vshr_n134 %add.i200 = add <8 x i16> %sub.i205, <i16 96, i16 96, i16 96, i16 96, i16 96, i16 96, i16 96, i16 96> %add.i198 = add <8 x i16> %add.i200, %sub.i203 %mul.i194 = mul <8 x i16> %add.i198, %vmovl.i237 %mul.i191 = mul <8 x i16> %vshr_n130, undef %add.i192 = add <8 x i16> %mul.i191, %mul.i194 %mul.i187 = mul <8 x i16> %vshr_n134, undef %add.i188 = add <8 x i16> %mul.i187, %add.i192 %mul.i185 = mul <8 x i16> undef, undef %add.i186 = add <8 x i16> %mul.i185, undef %vrshr_n160 = tail call <8 x i16> @llvm.arm.neon.vrshiftu.v8i16(<8 x i16> %add.i188, <8 x i16> <i16 -8, i16 -8, i16 -8, i16 -8, i16 -8, i16 -8, i16 -8, i16 -8>) %vrshr_n163 = tail call <8 x i16> @llvm.arm.neon.vrshiftu.v8i16(<8 x i16> %add.i186, <8 x i16> <i16 -8, i16 -8, i16 -8, i16 -8, i16 -8, i16 -8, i16 -8, i16 -8>) %mul.i184 = mul <8 x i16> undef, %vrshr_n160 %mul.i181 = mul <8 x i16> undef, %vmovl.i225 %add.i182 = add <8 x i16> %mul.i181, %mul.i184 %vrshr_n170 = tail call <8 x i16> @llvm.arm.neon.vrshiftu.v8i16(<8 x i16> %add.i182, <8 x i16> <i16 -7, i16 -7, i16 -7, i16 -7, i16 -7, i16 -7, i16 -7, i16 -7>) %vqmovn1.i180 = tail call <8 x i8> @llvm.arm.neon.vqmovnu.v8i8(<8 x i16> %vrshr_n170) nounwind %4 = bitcast <8 x i8> %vqmovn1.i180 to <1 x i64> %shuffle.i = shufflevector <1 x i64> %4, <1 x i64> undef, <2 x i32> <i32 0, i32 1> %5 = bitcast <2 x i64> %shuffle.i to <16 x i8> store <16 x i8> %5, <16 x i8>* undef, align 16 %add177 = add nsw i32 undef, 16 br i1 undef, label %for.body33, label %for.cond.loopexit for.end179: ; preds = %for.cond.loopexit, %entry ret void } declare <8 x i16> @llvm.arm.neon.vrshiftu.v8i16(<8 x i16>, <8 x i16>) nounwind readnone declare <8 x i16> @llvm.arm.neon.vqsubu.v8i16(<8 x i16>, <8 x i16>) nounwind readnone declare <8 x i8> @llvm.arm.neon.vqmovnu.v8i8(<8 x i16>) nounwind readnone
{ "pile_set_name": "Github" }
#include "pch_script.h" #include "game_sv_mp_script.h" #include "xrServer_script_macroses.h" #include "xrServer.h" #include "xrServer_Objects_ALife_Monsters.h" #include "Level.h" #include "ai_space.h" #include "xrScriptEngine/script_engine.hpp" void game_sv_mp_script::SetHitParams(NET_Packet* P, float impulse, float power) { u32 PowRPos = 16; u32 ImpRPos = 34; u32 bk = P->B.count; P->B.count = PowRPos; P->w_float(power); P->B.count = ImpRPos; P->w_float(impulse); P->B.count = bk; } float game_sv_mp_script::GetHitParamsPower(NET_Packet* P) { u32 PowRPos = 16; u32 bk = P->r_pos; P->r_pos = PowRPos; float res = P->r_float(); P->r_pos = bk; return res; } float game_sv_mp_script::GetHitParamsImpulse(NET_Packet* P) { u32 ImpRPos = 34; u32 bk = P->r_pos; P->r_pos = ImpRPos; float res = P->r_float(); P->r_pos = bk; return res; } void game_sv_mp_script::Create(shared_str& options) { inherited::Create(options); LPCSTR lpcstr_options = options.c_str(); Create(lpcstr_options); } void game_sv_mp_script::SpawnPlayer(ClientID id, LPCSTR N, LPCSTR SkinName, RPoint rp) { xrClientData* CL = m_server->ID_to_client(id); game_PlayerState* ps_who = CL->ps; ps_who->setFlag(GAME_PLAYER_FLAG_VERY_VERY_DEAD); CSE_Abstract* pOldOwner = CL->owner; if (pOldOwner && pOldOwner->owner == CL) { CSE_ALifeCreatureActor* pOldActor = smart_cast<CSE_ALifeCreatureActor*>(pOldOwner); CSE_Spectator* pOldSpectator = smart_cast<CSE_Spectator*>(pOldOwner); if (pOldActor) { AllowDeadBodyRemove(id, pOldActor->ID); m_CorpseList.push_back(pOldOwner->ID); }; if (pOldSpectator) { pOldSpectator->owner = (xrClientData*)m_server->GetServerClient(); NET_Packet P; u_EventGen(P, GE_DESTROY, pOldSpectator->ID); Level().Send(P, net_flags(TRUE, TRUE)); }; } // Spawn CSE_Abstract* E = spawn_begin(N); // create SE E->set_name_replace(get_name_id(id)); // name E->s_flags.assign(M_SPAWN_OBJECT_LOCAL | M_SPAWN_OBJECT_ASPLAYER); // flags CSE_ALifeCreatureActor* pA = smart_cast<CSE_ALifeCreatureActor*>(E); CSE_Spectator* pS = smart_cast<CSE_Spectator*>(E); R_ASSERT2(pA || pS, "Respawned Client is not Actor nor Spectator"); if (pA) { pA->s_team = u8(ps_who->team); if (xr_strlen(SkinName) != 0) pA->set_visual(SkinName); ps_who->resetFlag(GAME_PLAYER_FLAG_VERY_VERY_DEAD); ps_who->RespawnTime = Device.dwTimeGlobal; E->o_Position.set(rp.P); E->o_Angle.set(rp.A); } else if (pS) { Fvector Pos, Angle; /// ps_who->setFlag(GAME_PLAYER_FLAG_CS_SPECTATOR); if (!GetPosAngleFromActor(id, Pos, Angle)) assign_RP(E, ps_who); else { E->o_Angle.set(Angle); E->o_Position.set(Pos); } }; Msg("* %s respawned as %s", get_name_id(id), (0 == pA) ? "spectator" : "actor"); spawn_end(E, id); ps_who->SetGameID(CL->owner->ID); CL->owner->owner = CL; signal_Syncronize(); } void game_sv_mp_script::switch_Phase(u32 new_phase) { inherited::switch_Phase(new_phase); } void game_sv_mp_script::net_Export_State(NET_Packet& P, ClientID id_to) { inherited::net_Export_State(P, id_to); }; void game_sv_mp_script::OnEvent(NET_Packet& P, u16 type, u32 time, ClientID sender) { inherited::OnEvent(P, type, time, sender); }; void game_sv_mp_script::OnPlayerConnect(ClientID id_who) { inherited::OnPlayerConnect(id_who); }; void game_sv_mp_script::OnPlayerDisconnect(ClientID id_who, LPSTR Name, u16 GameID) { inherited::OnPlayerDisconnect(id_who, Name, GameID); }; #pragma warning(push) #pragma warning(disable : 4709) using namespace luabind; using namespace luabind::policy; template <typename T> struct CWrapperBase : public T, public luabind::wrap_base { typedef T inherited; typedef CWrapperBase<T> self_type; DEFINE_LUA_WRAPPER_CONST_METHOD_0(type_name, LPCSTR) DEFINE_LUA_WRAPPER_METHOD_V0(Update) DEFINE_LUA_WRAPPER_METHOD_R2P1_V4(OnEvent, NET_Packet, u16, u32, ClientID) DEFINE_LUA_WRAPPER_METHOD_V1(Create, LPCSTR) DEFINE_LUA_WRAPPER_METHOD_R2P1_V2(net_Export_State, NET_Packet, ClientID) DEFINE_LUA_WRAPPER_METHOD_V0(OnRoundStart) // DEFINE_LUA_WRAPPER_METHOD_V1(OnDelayedRoundEnd, ERoundEnd_Result) DEFINE_LUA_WRAPPER_METHOD_V0(OnRoundEnd) game_PlayerState* createPlayerState() override { return call_member<game_PlayerState*>(this, "createPlayerState"); // XXX: investigate //return call_member<game_PlayerState*>(this, "createPlayerState")[adopt<0>()]; } static game_PlayerState* createPlayerState_static(inherited* ptr) { return ptr->self_type::inherited::createPlayerState(); } DEFINE_LUA_WRAPPER_METHOD_R2P3_V3(OnPlayerHitPlayer, u16, u16, NET_Packet) }; #pragma warning(pop) #pragma optimize("s", on) void game_sv_mp_script_register(lua_State* luaState) { module(luaState) [ class_<game_sv_mp, game_sv_GameState>("game_sv_mp") .def(constructor<>()) //.def("SpawnWeaponForActor", &game_sv_mp::SpawnWeaponForActor) .def("KillPlayer", &game_sv_mp::KillPlayer) .def("SendPlayerKilledMessage", &game_sv_mp::SendPlayerKilledMessage) .def("signal_Syncronize", &game_sv_GameState::signal_Syncronize) ]; } void game_sv_mp_script_script_register(lua_State* luaState) { using WrapType = CWrapperBase<game_sv_mp_script>; using BaseType = game_sv_mp_script; module(luaState) [ class_<game_sv_mp_script, game_sv_mp, default_holder, WrapType>("game_sv_mp_script") .def(constructor<>()) .def("GetTeamData", &game_sv_mp_script::GetTeamData) .def("SpawnPlayer", &game_sv_mp_script::SpawnPlayer) .def("switch_Phase", &game_sv_mp_script::switch_Phase) .def("SetHitParams", &BaseType::SetHitParams) .def("GetHitParamsPower", &BaseType::GetHitParamsPower) .def("GetHitParamsImpulse", &BaseType::GetHitParamsImpulse) .def("type_name", &BaseType::type_name, &WrapType::type_name_static) .def("Update", &BaseType::Update, &WrapType::Update_static) .def("OnEvent", &BaseType::OnEvent, &WrapType::OnEvent_static) .def("Create", (void (BaseType::*)(LPCSTR))(&BaseType::Create), &WrapType::Create_static) .def("OnPlayerHitPlayer", &BaseType::OnPlayerHitPlayer, &WrapType::OnPlayerHitPlayer_static) .def("OnRoundStart", &BaseType::OnRoundStart, &WrapType::OnRoundStart_static) //.def("OnDelayedRoundEnd", &BaseType::OnDelayedRoundEnd, &WrapType::OnDelayedRoundEnd_static) .def("OnRoundEnd", &BaseType::OnRoundEnd, &WrapType::OnRoundEnd_static) .def("net_Export_State", &BaseType::net_Export_State, &WrapType::net_Export_State_static) .def("createPlayerState", &BaseType::createPlayerState, &WrapType::createPlayerState_static, adopt<0>()) ]; } SCRIPT_EXPORT_FUNC(game_sv_mp, (game_sv_GameState), game_sv_mp_script_register); SCRIPT_EXPORT_FUNC(game_sv_mp_script, (game_sv_mp), game_sv_mp_script_script_register);
{ "pile_set_name": "Github" }
import React, { Component } from 'react'; import * as PropTypes from 'prop-types'; import { compose, propOr } from 'ramda'; import { withRouter } from 'react-router-dom'; import { withStyles } from '@material-ui/core/styles'; import { QueryRenderer } from '../../../relay/environment'; import { buildViewParamsFromUrlAndStorage, saveViewParameters, } from '../../../utils/ListParameters'; import inject18n from '../../../components/i18n'; import ListLines from '../../../components/list_lines/ListLines'; import UsersLines, { usersLinesQuery } from './users/UsersLines'; import UserCreation from './users/UserCreation'; import AccessesMenu from './AccessesMenu'; const styles = () => ({ container: { margin: 0, padding: '0 200px 0 0', }, }); class Users extends Component { constructor(props) { super(props); const params = buildViewParamsFromUrlAndStorage( props.history, props.location, 'Users-view', ); this.state = { sortBy: propOr('name', 'sortBy', params), orderAsc: propOr(true, 'orderAsc', params), searchTerm: propOr('', 'searchTerm', params), view: propOr('lines', 'view', params), }; } saveView() { saveViewParameters( this.props.history, this.props.location, 'Users-view', this.state, ); } handleSearch(value) { this.setState({ searchTerm: value }, () => this.saveView()); } handleSort(field, orderAsc) { this.setState({ sortBy: field, orderAsc }, () => this.saveView()); } renderLines(paginationOptions) { const { sortBy, orderAsc, searchTerm } = this.state; const dataColumns = { name: { label: 'Name', width: '20%', isSortable: true, }, user_email: { label: 'Email', width: '30%', isSortable: true, }, firstname: { label: 'Firstname', width: '15%', isSortable: true, }, lastname: { label: 'Lastname', width: '15%', isSortable: true, }, created_at: { label: 'Creation date', width: '15%', isSortable: true, }, }; return ( <ListLines sortBy={sortBy} orderAsc={orderAsc} dataColumns={dataColumns} handleSort={this.handleSort.bind(this)} handleSearch={this.handleSearch.bind(this)} displayImport={false} secondaryAction={true} keyword={searchTerm} > <QueryRenderer query={usersLinesQuery} variables={{ count: 25, ...paginationOptions }} render={({ props }) => ( <UsersLines data={props} paginationOptions={paginationOptions} dataColumns={dataColumns} initialLoading={props === null} /> )} /> </ListLines> ); } render() { const { view, sortBy, orderAsc, searchTerm, } = this.state; const { classes } = this.props; const paginationOptions = { search: searchTerm, orderBy: sortBy, orderMode: orderAsc ? 'asc' : 'desc', }; return ( <div className={classes.container}> <AccessesMenu /> {view === 'lines' ? this.renderLines(paginationOptions) : ''} <UserCreation paginationOptions={paginationOptions} /> </div> ); } } Users.propTypes = { t: PropTypes.func, classes: PropTypes.object, history: PropTypes.object, location: PropTypes.object, }; export default compose(inject18n, withRouter, withStyles(styles))(Users);
{ "pile_set_name": "Github" }
const {globalShortcut, BrowserWindow} = require('electron'); function Shortcuts(){ this.toggle = (toggle) => { if (toggle){ var showdevtools = function(){ var win = BrowserWindow.getFocusedWindow(); if (!win.isDevToolsOpened()){ win.openDevTools() } else { win.closeDevTools(); } } globalShortcut.register('CommandOrControl+Shift+I', showdevtools); globalShortcut.register('F12', showdevtools); globalShortcut.register('CommandOrControl+W', () => { BrowserWindow.getFocusedWindow().close() }); } else { globalShortcut.unregisterAll(); } } } module.exports = new Shortcuts();
{ "pile_set_name": "Github" }
Please visit http://www.breezejs.com/documentation/start-nuget to learn more.
{ "pile_set_name": "Github" }
/* * Copyright (C) 2008 The Android Open Source Project * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _SYS_SYSMACROS_H_ #define _SYS_SYSMACROS_H_ /* some rogue code includes this file directly :-( */ #ifndef _SYS_TYPES_H_ # include <sys/types.h> #endif static __inline__ int major(dev_t _dev) { return (_dev >> 8) & 0xfff; } static __inline__ int minor(dev_t _dev) { return (_dev & 0xff) | ((_dev >> 12) & 0xfff00); } static __inline__ dev_t makedev(int __ma, int __mi) { return ((__ma & 0xfff) << 8) | (__mi & 0xff) | ((__mi & 0xfff00) << 12); } #endif /* _SYS_SYSMACROS_H_ */
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{46e8f605-7ab1-4b13-b6e1-de496d8b6431}</UniqueIdentifier> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{5cd02ae4-3641-4b51-a04c-0de9f7c89b3b}</UniqueIdentifier> </Filter> </ItemGroup> <ItemGroup> <ClCompile Include="src\Array.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\Binary.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\Connection.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\Cursor.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\Database.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\DeleteRequest.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\Document.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\Element.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\GetMoreRequest.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\InsertRequest.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\JavaScriptCode.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\KillCursorsRequest.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\Message.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\MessageHeader.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\ObjectId.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\QueryRequest.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\RegularExpression.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\ReplicaSet.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\RequestMessage.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\ResponseMessage.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="src\UpdateRequest.cpp"> <Filter>Source Files</Filter> </ClCompile> </ItemGroup> <ItemGroup> <ClInclude Include="include\Poco\MongoDB\Array.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\Binary.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\BSONReader.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\BSONWriter.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\Connection.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\Cursor.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\Database.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\DeleteRequest.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\Document.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\Element.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\GetMoreRequest.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\InsertRequest.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\JavaScriptCode.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\KillCursorsRequest.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\Message.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\MessageHeader.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\MongoDB.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\ObjectId.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\PoolableConnectionFactory.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\QueryRequest.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\RegularExpression.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\ReplicaSet.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\RequestMessage.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\ResponseMessage.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="include\Poco\MongoDB\UpdateRequest.h"> <Filter>Header Files</Filter> </ClInclude> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>JMessage PC SDK: 类成员</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">JMessage PC SDK &#160;<span id="projectnumber">1.2.3</span> </div> <div id="projectbrief">JMessage PC SDK</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- 制作者 Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'搜索'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','搜索'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('functions_n.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">这里列出了所有类成员,并附带类的详细说明:</div> <h3><a id="index_n"></a>- n -</h3><ul> <li>needReceipt : <a class="el" href="class_jmcpp_1_1_message.html#af489c598d3cb2d66bff384585eb5ea7d">Jmcpp::Message</a> , <a class="el" href="struct_jmcpp_1_1_message_settings.html#ac46d10992b0c708930c2f13905f8b4c3">Jmcpp::MessageSettings</a> </li> <li>newOwner : <a class="el" href="struct_jmcpp_1_1_group_owner_changed_event.html#ae685d574bead247ddef936c50abb581c">Jmcpp::GroupOwnerChangedEvent</a> , <a class="el" href="struct_jmcpp_1_1_leaved_group_event.html#ac9167ac239501fa3ad259e34d1fa15c4">Jmcpp::LeavedGroupEvent</a> , <a class="el" href="struct_jmcpp_1_1_removed_from_group_event.html#ad956c3e008191f1bc0263ad733a0830e">Jmcpp::RemovedFromGroupEvent</a> </li> <li>nickname : <a class="el" href="struct_jmcpp_1_1_group_member.html#a2c9d990904ad6aa559767d53a6065e7f">Jmcpp::GroupMember</a> , <a class="el" href="struct_jmcpp_1_1_user_info.html#a9396a3563396b9c1a939130adaf4e332">Jmcpp::UserInfo</a> , <a class="el" href="struct_jmcpp_1_1_user_info_lite.html#ae843d002e4d8b956590b7ca6fab08942">Jmcpp::UserInfoLite</a> , <a class="el" href="struct_jmcpp_1_1_user_info_param.html#a73dde79e95a9d93baf176efe4d6e8975">Jmcpp::UserInfoParam</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">制作者 <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2002-2020 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j 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.neo4j.cypher.internal case class PeriodicCommitInfo(size: Option[Long]) { def batchRowCount: Long = size.getOrElse(/* defaultSize */ 1000L) }
{ "pile_set_name": "Github" }
// Copyright 2013 Yangqing Jia // // This is a simple script that allows one to quickly test a network whose // structure is specified by text format protocol buffers, and whose parameter // are loaded from a pre-trained network. // Usage: // test_net net_proto pretrained_net_proto iterations [CPU/GPU] #include <cuda_runtime.h> #include <cstring> #include <cstdlib> #include <vector> #include "caffe/caffe.hpp" using namespace caffe; // NOLINT(build/namespaces) int main(int argc, char** argv) { if (argc < 4) { LOG(ERROR) << "test_net net_proto pretrained_net_proto iterations " << "[CPU/GPU]"; return 0; } cudaSetDevice(0); Caffe::set_phase(Caffe::TEST); if (argc == 5 && strcmp(argv[4], "GPU") == 0) { LOG(ERROR) << "Using GPU"; Caffe::set_mode(Caffe::GPU); } else { LOG(ERROR) << "Using CPU"; Caffe::set_mode(Caffe::CPU); } NetParameter test_net_param; ReadProtoFromTextFile(argv[1], &test_net_param); Net<float> caffe_test_net(test_net_param); NetParameter trained_net_param; ReadProtoFromBinaryFile(argv[2], &trained_net_param); caffe_test_net.CopyTrainedLayersFrom(trained_net_param); int total_iter = atoi(argv[3]); LOG(ERROR) << "Running " << total_iter << "Iterations."; double test_accuracy = 0; vector<Blob<float>*> dummy_blob_input_vec; for (int i = 0; i < total_iter; ++i) { const vector<Blob<float>*>& result = caffe_test_net.Forward(dummy_blob_input_vec); test_accuracy += result[0]->cpu_data()[0]; LOG(ERROR) << "Batch " << i << ", accuracy: " << result[0]->cpu_data()[0]; } test_accuracy /= total_iter; LOG(ERROR) << "Test accuracy:" << test_accuracy; return 0; }
{ "pile_set_name": "Github" }
rule k3e9_15e108d61ee31132 { meta: copyright="Copyright (c) 2014-2018 Support Intelligence Inc, All Rights Reserved." engine="saphire/1.3.1 divinorum/0.998 icewater/0.4" viz_url="http://icewater.io/en/cluster/query?h64=k3e9.15e108d61ee31132" cluster="k3e9.15e108d61ee31132" cluster_size="14" filetype = "application/x-dosexec" tlp = "amber" version = "icewater snowflake" author = "Rick Wesson (@wessorh) [email protected]" date = "20171123" license = "RIL-1.0 [Rick's Internet License] " family="virut virtob virux" md5_hashes="['40e4b4757cecf380c4405b8a183528e8','576c2070427509db0205388f7bb7c0e5','ee3e03763319ada713e6dfcbfd570911']" strings: $hex_string = { 8082ccc87777777800867c687044447800867f7870ccc4780087f7b8b0bcc478008fffc8bb0000780087f7bbfbb7777800087f22bb8888880008f76bb2b22220 } condition: filesize > 16384 and filesize < 65536 and $hex_string }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <title>SVG img as flex item</title> <link rel="author" title="David Grogan" href="mailto:[email protected]"> <link rel="help" href="https://drafts.csswg.org/css-flexbox/#algo-main-item" title="Part E"> <link rel="match" href="../reference/ref-filled-green-100px-square-only.html"> <meta name="assert" content="SVG's specified intrinsic width is honored when used as a flex base size and no intrinsic height is specified." /> <p>Test passes if there is a filled green square.</p> <div style="display: flex; width: 100px;"> <img src="data:image/svg+xml,%3Csvg viewBox='0 0 200 400' width='50px' xmlns='http://www.w3.org/2000/svg' %3E%3Crect width='100%' height='100%' fill='green' /%3E%3C/svg%3E" style="border-left: 50px solid green; min-width: 0px;"> </div>
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0+ /* * Compaq Hot Plug Controller Driver * * Copyright (C) 1995,2001 Compaq Computer Corporation * Copyright (C) 2001,2003 Greg Kroah-Hartman ([email protected]) * Copyright (C) 2001 IBM Corp. * * All rights reserved. * * Send feedback to <[email protected]> * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/proc_fs.h> #include <linux/workqueue.h> #include <linux/pci.h> #include <linux/pci_hotplug.h> #include <linux/mutex.h> #include <linux/debugfs.h> #include "cpqphp.h" static DEFINE_MUTEX(cpqphp_mutex); static int show_ctrl(struct controller *ctrl, char *buf) { char *out = buf; int index; struct pci_resource *res; out += sprintf(buf, "Free resources: memory\n"); index = 11; res = ctrl->mem_head; while (res && index--) { out += sprintf(out, "start = %8.8x, length = %8.8x\n", res->base, res->length); res = res->next; } out += sprintf(out, "Free resources: prefetchable memory\n"); index = 11; res = ctrl->p_mem_head; while (res && index--) { out += sprintf(out, "start = %8.8x, length = %8.8x\n", res->base, res->length); res = res->next; } out += sprintf(out, "Free resources: IO\n"); index = 11; res = ctrl->io_head; while (res && index--) { out += sprintf(out, "start = %8.8x, length = %8.8x\n", res->base, res->length); res = res->next; } out += sprintf(out, "Free resources: bus numbers\n"); index = 11; res = ctrl->bus_head; while (res && index--) { out += sprintf(out, "start = %8.8x, length = %8.8x\n", res->base, res->length); res = res->next; } return out - buf; } static int show_dev(struct controller *ctrl, char *buf) { char *out = buf; int index; struct pci_resource *res; struct pci_func *new_slot; struct slot *slot; slot = ctrl->slot; while (slot) { new_slot = cpqhp_slot_find(slot->bus, slot->device, 0); if (!new_slot) break; out += sprintf(out, "assigned resources: memory\n"); index = 11; res = new_slot->mem_head; while (res && index--) { out += sprintf(out, "start = %8.8x, length = %8.8x\n", res->base, res->length); res = res->next; } out += sprintf(out, "assigned resources: prefetchable memory\n"); index = 11; res = new_slot->p_mem_head; while (res && index--) { out += sprintf(out, "start = %8.8x, length = %8.8x\n", res->base, res->length); res = res->next; } out += sprintf(out, "assigned resources: IO\n"); index = 11; res = new_slot->io_head; while (res && index--) { out += sprintf(out, "start = %8.8x, length = %8.8x\n", res->base, res->length); res = res->next; } out += sprintf(out, "assigned resources: bus numbers\n"); index = 11; res = new_slot->bus_head; while (res && index--) { out += sprintf(out, "start = %8.8x, length = %8.8x\n", res->base, res->length); res = res->next; } slot = slot->next; } return out - buf; } static int spew_debug_info(struct controller *ctrl, char *data, int size) { int used; used = size - show_ctrl(ctrl, data); used = (size - used) - show_dev(ctrl, &data[used]); return used; } struct ctrl_dbg { int size; char *data; struct controller *ctrl; }; #define MAX_OUTPUT (4*PAGE_SIZE) static int open(struct inode *inode, struct file *file) { struct controller *ctrl = inode->i_private; struct ctrl_dbg *dbg; int retval = -ENOMEM; mutex_lock(&cpqphp_mutex); dbg = kmalloc(sizeof(*dbg), GFP_KERNEL); if (!dbg) goto exit; dbg->data = kmalloc(MAX_OUTPUT, GFP_KERNEL); if (!dbg->data) { kfree(dbg); goto exit; } dbg->size = spew_debug_info(ctrl, dbg->data, MAX_OUTPUT); file->private_data = dbg; retval = 0; exit: mutex_unlock(&cpqphp_mutex); return retval; } static loff_t lseek(struct file *file, loff_t off, int whence) { struct ctrl_dbg *dbg = file->private_data; return fixed_size_llseek(file, off, whence, dbg->size); } static ssize_t read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { struct ctrl_dbg *dbg = file->private_data; return simple_read_from_buffer(buf, nbytes, ppos, dbg->data, dbg->size); } static int release(struct inode *inode, struct file *file) { struct ctrl_dbg *dbg = file->private_data; kfree(dbg->data); kfree(dbg); return 0; } static const struct file_operations debug_ops = { .owner = THIS_MODULE, .open = open, .llseek = lseek, .read = read, .release = release, }; static struct dentry *root; void cpqhp_initialize_debugfs(void) { if (!root) root = debugfs_create_dir("cpqhp", NULL); } void cpqhp_shutdown_debugfs(void) { debugfs_remove(root); } void cpqhp_create_debugfs_files(struct controller *ctrl) { ctrl->dentry = debugfs_create_file(dev_name(&ctrl->pci_dev->dev), S_IRUGO, root, ctrl, &debug_ops); } void cpqhp_remove_debugfs_files(struct controller *ctrl) { debugfs_remove(ctrl->dentry); ctrl->dentry = NULL; }
{ "pile_set_name": "Github" }
// Package imager handles image, video, etc. upload requests and processing package imager import ( "bytes" "context" "crypto" "crypto/md5" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "errors" "fmt" "image" "image/jpeg" "io" "mime/multipart" "net" "net/http" "strconv" "strings" "time" "unicode/utf8" "github.com/bakape/meguca/auth" "github.com/bakape/meguca/common" "github.com/bakape/meguca/config" "github.com/bakape/meguca/db" "github.com/bakape/meguca/websockets" "github.com/bakape/thumbnailer/v2" "github.com/chai2010/webp" "github.com/go-playground/log" "github.com/jackc/pgx/v4" uuid "github.com/satori/go.uuid" ) var ( // Map of MIME types to the constants used internally mimeTypes = map[string]common.FileType{ "image/jpeg": common.JPEG, "image/png": common.PNG, "image/gif": common.GIF, "image/webp": common.WEBP, mimePDF: common.PDF, "video/webm": common.WEBM, "application/ogg": common.OGG, "video/mp4": common.MP4, "video/quicktime": common.MP4, "audio/mpeg": common.MP3, mime7Zip: common.SevenZip, mimeTarGZ: common.TGZ, mimeTarXZ: common.TXZ, mimeZip: common.ZIP, "audio/x-flac": common.FLAC, mimeText: common.TXT, "application/x-rar-compressed": common.RAR, "application/vnd.comicbook+zip": common.CBZ, "application/vnd.comicbook-rar": common.CBR, } pubKeyCache = common.NewCacheMap() // MIME types from thumbnailer to accept allowedMimeTypes map[string]bool errTooLarge = common.StatusError{ Err: errors.New("file too large"), Code: 400, } errNoCandidatePost = common.StatusError{ Err: errors.New("no post found for image insertion"), Code: 404, } errNotProcessed = common.StatusError{ Err: errors.New("hash not in database"), Code: 404, } ) func init() { allowedMimeTypes = make(map[string]bool, len(mimeTypes)) for t := range mimeTypes { allowedMimeTypes[t] = true } } // Request to insert an image into the client's open post type insertionRequest struct { spoiler bool post, pubKey uint64 name string ctx context.Context } // Handles the clients' image (or other file) upload request func NewImageUpload(w http.ResponseWriter, r *http.Request) { handleError(w, r, func() (err error) { var req insertionRequest req.ctx = r.Context() req.pubKey, err = validateUploader(w, r) if err != nil { return } can, err := db.CanInsertImage(r.Context(), req.pubKey) if err != nil { return } if !can { return errNoCandidatePost } // Limit data received to the maximum uploaded file size limit max := config.Get().MaxSize<<20 + 1<<10 r.Body = http.MaxBytesReader(w, r.Body, int64(max)) length, err := strconv.ParseUint(r.Header.Get("Content-Length"), 10, 64) if err != nil { return common.StatusError{ Err: err, Code: 413, } } if uint(length) > max { return errTooLarge } err = r.ParseMultipartForm(0) if err != nil { return common.StatusError{ Err: err, Code: 400, } } file, head, err := r.FormFile("image") if err != nil { return common.StatusError{ Err: err, Code: 400, } } if uint(head.Size) > max { return errTooLarge } err = req.extract(r, head.Filename) if err != nil { return } select { case err = <-requestThumbnailing(thumbnailingRequest{ insertionRequest: req, file: file, size: int(head.Size), }): case <-req.ctx.Done(): return } if err == io.EOF { err = common.StatusError{ Err: err, Code: 400, } } return }) } // Apply security restrictions to uploader func validateUploader(w http.ResponseWriter, r *http.Request) ( pubKeyID uint64, err error, ) { type keyStore struct { id uint64 key *rsa.PublicKey } var ( nonce [32]byte signature [512]byte pubID uuid.UUID ) err = common.WrapError(400, func() (err error) { pubID, err = uuid.FromString(r.Header.Get("X-Public-Key-ID")) if err != nil { return } decode := func(dst []byte, key string) (err error) { n, err := base64.StdEncoding.Decode( dst, []byte(r.Header.Get(key)), ) if err != nil { return } if n != len(dst) { return fmt.Errorf("invalid %s length: %d", key, n) } return } err = decode(nonce[:], "X-Nonce") if err != nil { return } return decode(signature[:], "X-Signature") }) if err != nil { return } store_, err := pubKeyCache.GetOrGen( pubID, func() (val interface{}, err error) { id, der, err := db.GetPubKey(pubID) switch err { case nil: case pgx.ErrNoRows: err = common.ErrAccessDenied("unknown public key ID") return default: return } pubKey, err := x509.ParsePKCS1PublicKey(der) if err != nil { err = common.StatusError{ Err: err, Code: 400, } return } val = keyStore{ id: id, key: pubKey, } return }, ) if err != nil { return } store := store_.(keyStore) pubKeyID = store.id h := sha256.New() _, err = h.Write(pubID[:]) if err != nil { return } _, err = h.Write(nonce[:]) if err != nil { return } digest := h.Sum(nil) err = rsa.VerifyPKCS1v15(store.key, crypto.SHA256, digest, signature[:]) if err != nil { err = common.StatusError{ Err: err, Code: 403, } } return } // Extract and validate common request data from request func (req *insertionRequest) extract(r *http.Request, name string) (err error) { req.spoiler = r.FormValue("spoiler") == "true" req.name = name errStr := func() string { if len(req.name) > 200 { return "image name too long" } req.name = strings.TrimSpace(req.name) if i := strings.LastIndexByte(req.name, '.'); i != -1 { req.name = req.name[:i] if strings.HasSuffix(req.name, ".tar") { req.name = req.name[:len(req.name)-4] } } if !utf8.ValidString(req.name) { // Need to replace invalid UTF-8 with a valid UTF-8 marker req.name = strings.ToValidUTF8(req.name, "?") } if len(req.name) == 0 { return "no image name" } req.post, err = strconv.ParseUint(r.FormValue("post"), 10, 64) if err != nil { return "invalid post number" } return "" }() if errStr != "" { return common.StatusError{ Err: errors.New(errStr), Code: 400, } } return nil } // UploadImageHash attempts to skip image upload, if the file has already // been thumbnailed and is stored on the server. The client sends an SHA1 hash // of the file it wants to upload. The server looks up, if such a file is // thumbnailed. If yes, generates and sends a new image allocation token to // the client. func UploadImageHash(w http.ResponseWriter, r *http.Request) { handleError(w, r, func() (err error) { var req struct { insertionRequest id common.SHA1Hash } req.ctx = r.Context() req.pubKey, err = validateUploader(w, r) if err != nil { return } r.Body = http.MaxBytesReader(w, r.Body, 1<<10) err = r.ParseForm() if err != nil { return common.StatusError{ Err: err, Code: 400, } } err = req.id.UnmarshalText([]byte(r.FormValue("id"))) if err != nil { return common.StatusError{ Err: err, Code: 400, } } err = req.extract(r, r.FormValue("name")) if err != nil { return } return tryInsertExisting(req.insertionRequest, req.id) }) } // Try finding and inserting an already processed image into the post func tryInsertExisting(req insertionRequest, id common.SHA1Hash, ) error { return db.InTransaction(req.ctx, func(tx pgx.Tx) (err error) { img, err := db.GetImage(req.ctx, tx, id) switch err { case nil: return insertImage(tx, req, img) case pgx.ErrNoRows: return errNotProcessed default: return } }) } // Try inserting an image into the post func insertImage(tx pgx.Tx, req insertionRequest, img common.ImageCommon, ) (err error) { var thread uint64 thread, err = db.InsertImage( req.ctx, tx, req.post, req.pubKey, img.SHA1, req.name, req.spoiler, ) switch err { case nil: return websockets.InsertImage( thread, req.post, req.pubKey, common.Image{ ImageCommon: img, Spoilered: req.spoiler, Name: req.name, }, ) case pgx.ErrNoRows: return errNoCandidatePost default: return } } // handleError sends the client file upload errors and logs them server-side func handleError(w http.ResponseWriter, r *http.Request, f func() error) { err := f() if err == nil { return } code := 500 if err, ok := err.(common.StatusError); ok { code = err.Code } http.Error(w, err.Error(), code) if common.IsTest || common.CanIgnoreClientError(err) { return } ip, ipErr := auth.GetIP(r) if ipErr != nil { ip = net.IPv4zero } log.Errorf("upload error: by %s: %s: %#v", ip, err, err) } // Create a new thumbnail, commit its resources to the DB and filesystem, // insert it into an open post and send insertion even to listening clients func insertNewThumbnail(req thumbnailingRequest, id common.SHA1Hash) (err error) { var img common.ImageCommon img.SHA1 = id conf := config.Get() thumb, err := processFile(req.file, &img, thumbnailer.Options{ MaxSourceDims: thumbnailer.Dims{ Width: uint(conf.MaxWidth), Height: uint(conf.MaxHeight), }, ThumbDims: thumbnailer.Dims{ Width: 150, Height: 150, }, AcceptedMimeTypes: allowedMimeTypes, }) defer func() { if thumb != nil { putThumbBuffer(thumb) } }() if err != nil { switch err.(type) { case thumbnailer.ErrUnsupportedMIME, thumbnailer.ErrInvalidImage: err = common.StatusError{ Err: err, Code: 400, } } return } // Being done in one transaction prevents the image DB record from getting // garbage-collected between the calls err = db.InTransaction(req.ctx, func(tx pgx.Tx) (err error) { var thumbR io.ReadSeeker if thumb != nil { thumbR = bytes.NewReader(thumb) } err = db.AllocateImage(req.ctx, tx, img, req.file, thumbR) if err != nil { return } return insertImage(tx, req.insertionRequest, img) }) return } // Separate function for easier testability func processFile( f multipart.File, img *common.ImageCommon, opts thumbnailer.Options, ) ( thumb []byte, err error, ) { src, thumbImage, err := thumbnailer.Process(f, opts) defer func() { // Add image internal buffer to pool. // Only image type used in thumbnailer by default. img, ok := thumbImage.(*image.RGBA) if ok { putThumbBuffer(img.Pix) } }() switch err { case nil: if config.Get().JPEGThumbnails { img.ThumbType = common.JPEG } else { img.ThumbType = common.WEBP } case thumbnailer.ErrCantThumbnail: err = nil img.ThumbType = common.NoFile default: return } img.FileType = mimeTypes[src.Mime] img.Audio = src.HasAudio img.Video = src.HasVideo img.Duration = uint32(src.Length / time.Second) // Some media has retardedly long meta strings. Just truncate them, instead // of rejecting. if len(src.Artist) > 100 { src.Artist = src.Artist[:100] } if len(src.Title) > 200 { src.Title = src.Title[:200] } if src.Artist != "" { img.Artist = &src.Artist } if src.Title != "" { img.Title = &src.Title } img.Width = uint16(src.Width) img.Height = uint16(src.Height) if thumbImage != nil { b := thumbImage.Bounds() img.ThumbWidth = uint16(b.Dx()) img.ThumbHeight = uint16(b.Dy()) } n, err := hashFile(img.MD5[:], f, md5.New()) if err != nil { return } img.Size = uint64(n) if thumbImage != nil { w := bytes.NewBuffer(getThumbBuffer()) switch img.ThumbType { case common.JPEG: err = jpeg.Encode(w, thumbImage, &jpeg.Options{ Quality: 90, }) case common.WEBP: err = webp.Encode(w, thumbImage, &webp.Options{ Lossless: false, Quality: 90, }) } if err != nil { return } thumb = w.Bytes() } return }
{ "pile_set_name": "Github" }
using System.IO; namespace Outracks.IO { public static class FilePath { /// <exception cref="System.IO.IOException" /> public static AbsoluteFilePath CreateTempFile() { return AbsoluteFilePath.Parse(Path.GetTempFileName()); } public static AbsoluteFilePath ParseAndMakeAbsolute(string path) { return ParseAndMakeAbsolute(path, DirectoryPath.GetCurrentDirectory()); } public static AbsoluteFilePath ParseAndMakeAbsolute(IFilePath path, AbsoluteDirectoryPath root) { return path as AbsoluteFilePath ?? ParseAndMakeAbsolute(((RelativeFilePath) path).NativeRelativePath, root); } public static AbsoluteFilePath ParseAndMakeAbsolute(string path, AbsoluteDirectoryPath root) { var filePath = FilePath.Parse(path); return filePath.MatchWith( (AbsoluteFilePath absolutePath) => absolutePath, (RelativeFilePath relativePath) => root / relativePath); } public static IFilePath Parse(string relativeOrAbsolutePath) { return Path.IsPathRooted(relativeOrAbsolutePath) ? (IFilePath) AbsoluteFilePath.Parse(relativeOrAbsolutePath) : (IFilePath) RelativeFilePath.Parse(relativeOrAbsolutePath); } } }
{ "pile_set_name": "Github" }
package test fun a() = "aa"
{ "pile_set_name": "Github" }