max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
988
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.db.sql.editor; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.api.db.explorer.DatabaseConnection; import org.netbeans.modules.db.api.sql.execute.SQLExecuteCookie; import org.netbeans.modules.db.spi.sql.editor.SQLEditorProvider; import org.openide.cookies.OpenCookie; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.util.Exceptions; import org.openide.util.NbBundle; /** * * @author <NAME> */ @org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.db.spi.sql.editor.SQLEditorProvider.class) public class SQLEditorProviderImpl implements SQLEditorProvider { // TODO: should ensure that the number of the generated temporary file // is greater than any of the numbers of the existing files private static final String CMD_FOLDER = "Databases/SQLCommands"; // NOI18N @Override public void openSQLEditor(DatabaseConnection dbconn, String sql, boolean execute) { FileObject tmpFo = FileUtil.getConfigFile(CMD_FOLDER); if (tmpFo == null) { try { tmpFo = FileUtil.createFolder(FileUtil.getConfigRoot(), CMD_FOLDER ); } catch (IOException e) { Logger.getLogger(SQLEditorProviderImpl.class.getName()).log(Level.INFO, e.getLocalizedMessage(), e); } } FileObject sqlFo = null; int i = 1; for (;;) { String nameFmt = NbBundle.getMessage(SQLEditorProviderImpl.class, "LBL_SQLCommandFileName"); String name = MessageFormat.format(nameFmt, new Object[] { Integer.valueOf(i) }); try { sqlFo = tmpFo.createData(name); } catch (IOException e) { i++; continue; } break; } try { FileLock lock = sqlFo.lock(); try { OutputStream stream = sqlFo.getOutputStream(lock); try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8)); try { writer.write(sql); } finally { writer.close(); } } finally { stream.close(); } } finally { lock.releaseLock(); } } catch (IOException e) { Exceptions.printStackTrace(e); } DataObject sqlDo; try { sqlDo = DataObject.find(sqlFo); } catch (DataObjectNotFoundException e) { Logger.getLogger(SQLEditorProviderImpl.class.getName()).log(Level.INFO, e.getLocalizedMessage(), e); return; } OpenCookie openCookie = sqlDo.getCookie (OpenCookie.class); openCookie.open(); SQLExecuteCookie sqlCookie = sqlDo.getCookie (SQLExecuteCookie.class); if (sqlCookie != null) { sqlCookie.setDatabaseConnection(dbconn); if (execute) { sqlCookie.execute(); } } else { Logger.getLogger(SQLEditorProviderImpl.class.getName()).log(Level.INFO, "No SQLExecuteCookie found for " + sqlDo); } } }
1,976
539
/** * Copyright 2022 The Magma Authors. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <chrono> #include <gtest/gtest.h> #include <cstdint> #include <thread> #include <mutex> #include <condition_variable> #include <stdio.h> #include "lte/gateway/c/core/oai/tasks/mme_app/mme_app_state_manager.hpp" #include "lte/gateway/c/core/oai/test/mme_app_task/mme_app_test_util.h" #include "lte/gateway/c/core/oai/test/mme_app_task/mme_procedure_test_fixture.h" namespace magma { namespace lte { TEST_F(MmeAppProcedureTest, TestImsiAttachExpiredNasTimers) { mme_app_desc_t* mme_state_p = magma::lte::MmeNasStateManager::getInstance().get_state(false); std::condition_variable cv; std::mutex mx; std::unique_lock<std::mutex> lock(mx); nas_config_timer_reinit(&mme_config.nas_config, MME_APP_TIMER_TO_MSEC); MME_APP_EXPECT_CALLS(15, 1, 1, 1, 1, 1, 1, 1, 0, 1, 2); // Constructing and sending Initial Attach Request to mme_app mimicing S1AP send_mme_app_initial_ue_msg(nas_msg_imsi_attach_req, sizeof(nas_msg_imsi_attach_req), plmn, guti, 1); // Sending AIA to mme_app mimicing successful S6A response for AIR send_authentication_info_resp(imsi, true); // Wait for DL NAS Transport up to retransmission limit for (int i = 0; i < NAS_RETX_LIMIT; ++i) { cv.wait_for(lock, std::chrono::milliseconds(STATE_MAX_WAIT_MS)); } // Constructing and sending Authentication Response to mme_app mimicing S1AP send_mme_app_uplink_data_ind(nas_msg_auth_resp, sizeof(nas_msg_auth_resp), plmn); // Wait for DL NAS Transport up to retransmission limit for (int i = 0; i < NAS_RETX_LIMIT; ++i) { cv.wait_for(lock, std::chrono::milliseconds(STATE_MAX_WAIT_MS)); } // Constructing and sending SMC Response to mme_app mimicing S1AP send_mme_app_uplink_data_ind(nas_msg_smc_resp, sizeof(nas_msg_smc_resp), plmn); // Sending ULA to mme_app mimicing successful S6A response for ULR send_s6a_ula(imsi, true); // Constructing and sending Create Session Response to mme_app mimicing SPGW send_create_session_resp(REQUEST_ACCEPTED, DEFAULT_LBI); // Wait for ICS request to be sent cv.wait_for(lock, std::chrono::milliseconds(STATE_MAX_WAIT_MS)); // Constructing and sending ICS Response to mme_app mimicing S1AP send_ics_response(); // Constructing UE Capability Indication message to mme_app // mimicing S1AP with dummy radio capabilities send_ue_capabilities_ind(); // Wait for DL NAS Transport up to retransmission limit. // The first Attach Accept was piggybacked on ICS Request. for (int i = 1; i < NAS_RETX_LIMIT; ++i) { cv.wait_for(lock, std::chrono::milliseconds(STATE_MAX_WAIT_MS)); } // Constructing and sending Attach Complete to mme_app // mimicing S1AP send_mme_app_uplink_data_ind(nas_msg_attach_comp, sizeof(nas_msg_attach_comp), plmn); // Wait for DL NAS Transport for EMM Information cv.wait_for(lock, std::chrono::milliseconds(STATE_MAX_WAIT_MS)); // Constructing and sending Modify Bearer Response to mme_app // mimicing SPGW std::vector<int> b_modify = {5}; std::vector<int> b_rm = {}; send_modify_bearer_resp(b_modify, b_rm); // Check MME state after Modify Bearer Response send_activate_message_to_mme_app(); cv.wait_for(lock, std::chrono::milliseconds(STATE_MAX_WAIT_MS)); EXPECT_EQ(mme_state_p->nb_ue_attached, 1); EXPECT_EQ(mme_state_p->nb_ue_connected, 1); EXPECT_EQ(mme_state_p->nb_default_eps_bearers, 1); EXPECT_EQ(mme_state_p->nb_ue_idle, 0); detach_ue(cv, lock, mme_state_p, guti, false); } } // namespace lte } // namespace magma
1,614
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.autoupdate.ui; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import javax.swing.table.JTableHeader; import org.netbeans.api.autoupdate.InstallSupport; import org.netbeans.api.autoupdate.OperationContainer; import org.netbeans.api.autoupdate.UpdateUnit; import org.openide.util.NbBundle; /** * * @author <NAME>, <NAME> */ public class LocallyDownloadedTableModel extends UnitCategoryTableModel { private OperationContainer<InstallSupport> availableNbmsContainer = Containers.forAvailableNbms(); private OperationContainer<InstallSupport> updateNbmsContainer = Containers.forUpdateNbms(); private LocalDownloadSupport localDownloadSupport = null; List<UpdateUnit> cachedUnits; /** Creates a new instance of InstalledTableModel */ public LocallyDownloadedTableModel (LocalDownloadSupport localDownloadSupport) { this.localDownloadSupport = localDownloadSupport; } @Override public final void setUnits(final List<UpdateUnit> unused) { getLocalDownloadSupport ().removeInstalledUnit (); Collection<UpdateUnit> units = getLocalDownloadSupport().getUpdateUnits(); //do not compute if not necessary if (cachedUnits == null || !units.containsAll (cachedUnits) || !cachedUnits.containsAll (units)) { setData(makeCategories (new LinkedList<UpdateUnit> (units))); cachedUnits = new ArrayList<UpdateUnit>(units); } } void removeInstalledUnits () { getLocalDownloadSupport ().removeInstalledUnit (); cachedUnits = null; setUnits (null); } private List<UnitCategory> makeCategories(List<UpdateUnit> units) { final List<UnitCategory> categories = new ArrayList<UnitCategory>(); categories.addAll(Utilities.makeAvailableCategories(units, true)); categories.addAll(Utilities.makeUpdateCategories(units, true)); return categories; } LocalDownloadSupport getLocalDownloadSupport() { return localDownloadSupport; } @Override public void setValueAt(Object anValue, int row, int col) { super.setValueAt(anValue, row, col); if (anValue == null) { return ; } if (! (anValue instanceof Boolean)) { return ; } Unit u = getUnitAtRow(row); if (u != null) { assert anValue instanceof Boolean : anValue + " must be instanceof Boolean."; boolean beforeMarked = u.isMarked(); u.setMarked(!beforeMarked); if (u.isMarked() != beforeMarked) { fireButtonsChange(); if (u.isMarked ()) { getLocalDownloadSupport ().checkUnit (u.updateUnit); } else { getLocalDownloadSupport ().uncheckUnit (u.updateUnit); } } else { assert false : u.getDisplayName(); } } } @Override public Object getValueAt(int row, int col) { Object res = null; Unit u = getUnitAtRow(row); if (u != null) { boolean isAvailable = (u instanceof Unit.Available); switch (col) { case 0 : res = u.isMarked() ? Boolean.TRUE : Boolean.FALSE; break; case 1 : res = u.getDisplayName(); break; case 2 : res = u.getCategoryName(); break; case 3 : if (isAvailable) { res = ((Unit.Available)u).getAvailableVersion(); } else { res = ((Unit.Update)u).getAvailableVersion(); } break; case 4 : if (isAvailable) { res = ((Unit.Available)u).getSize(); } else { res = ((Unit.Update)u).getSize(); } break; } } return res; } @Override public int getColumnCount() { return 2; } @Override public Class getColumnClass(int c) { Class res = null; switch (c) { case 0 : res = Boolean.class; break; case 1 : res = String.class; break; case 2 : res = String.class; break; case 3 : res = String.class; break; case 4 : res = String.class; break; } return res; } @Override public String getColumnName(int column) { switch (column) { case 0 : return getBundle ("LocallyDownloadedTableModel_Columns_Install"); case 1 : return getBundle ("LocallyDownloadedTableModel_Columns_Name"); case 2 : return getBundle ("InstalledTableModel_Columns_Category"); case 3 : return getBundle ("LocallyDownloadedTableModel_Columns_Version"); case 4 : return getBundle ("LocallyDownloadedTableModel_Columns_Size"); } assert false; return super.getColumnName( column ); } @Override public int getPreferredWidth(JTableHeader header, int col) { switch (col) { case 1: return super.getMinWidth(header, col)*4; case 2: return super.getMinWidth(header, col)*2; } return super.getMinWidth(header, col); } @Override public Type getType () { return UnitCategoryTableModel.Type.LOCAL; } public class DisplayName { public DisplayName (String name) { } } @Override public boolean isSortAllowed(Object columnIdentifier) { boolean isInstall = getColumnName(0).equals(columnIdentifier); boolean isSize = getColumnName(4).equals(columnIdentifier); return isInstall || isSize ? false : true; } @Override protected Comparator<Unit> getDefaultComparator () { return new Comparator<Unit> () { @Override public int compare (Unit o1, Unit o2) { return Unit.compareDisplayNames(o1, o2); } }; } @Override protected Comparator<Unit> getComparator(final Object columnIdentifier, final boolean sortAscending) { return new Comparator<Unit>(){ @Override public int compare(Unit o1, Unit o2) { Unit unit1 = sortAscending ? o1 : o2; Unit unit2 = sortAscending ? o2 : o1; if (getColumnName(0).equals(columnIdentifier)) { assert false : columnIdentifier.toString(); } else if (getColumnName(1).equals(columnIdentifier)) { return Unit.compareDisplayNames(unit1, unit2); } else if (getColumnName(2).equals(columnIdentifier)) { return Unit.compareCategories(unit1, unit2); } else if (getColumnName(3).equals(columnIdentifier)) { return Unit.compareDisplayVersions(unit1, unit2); } else if (getColumnName(4).equals(columnIdentifier)) { assert false : columnIdentifier.toString(); } return 0; } }; } @Override public int getDownloadSize () { // no need to download anything in Locally Downloaded tab return 0; } private String getBundle (String key) { return NbBundle.getMessage (this.getClass (), key); } @Override public String getTabTitle() { return NbBundle.getMessage (PluginManagerUI.class, "PluginManagerUI_UnitTab_Local_Title");//NOI18N } @Override public int getTabIndex() { return PluginManagerUI.INDEX_OF_DOWNLOAD_TAB; } @Override public boolean canBePrimaryTab() { return false; } @Override public boolean needsRestart () { return false; } }
4,168
409
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2018, <NAME>, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: <NAME> <[email protected]> // Author: <NAME> <[email protected]> // ========================================================================== #ifndef SEQAN_INCLUDE_SEQAN_UCSC_RECORD_H_ #define SEQAN_INCLUDE_SEQAN_UCSC_RECORD_H_ namespace seqan { // ============================================================================ // Tags, Classes, Enums // ============================================================================ // ---------------------------------------------------------------------------- // Class UcscRecord // ---------------------------------------------------------------------------- /*! * @class UcscRecord * @implements FormattedFileRecordConcept * @headerfile <seqan/ucsc_io.h> * @brief Represent the information for one UCSC gene annotation record. * * @signature class UcscRecord; * * The UCSC genome browser server allows the download of a set of the known genes and isoforms used in the browser. * These files can be downloaded from the UCSC FTP's <tt>goldenPath</tt> folder, e.g. the one for <a * href="http://hgdownload.cse.ucsc.edu/goldenpath/hg19/">hg19</a>. * * To load the annotations, you need to download both the <tt>knownGenes.txt.gz</tt> and the * <tt>knownIsoforms.txt.gz</tt> files from the UCSC <tt>goldenPath</tt> database. These files can then be read record * by record into a <tt>UcscRecord</tt>. This record type is capable of representing records from either file type. */ class UcscRecord { public: /*! * @var CharString UcscRecord::transName * @brief Name of the transcript. */ CharString transName; /*! * @var CharString UcscRecord::contigName * @brief Name of the contig of the genomic location. */ CharString contigName; /*! * @var int32_t UcscRecord::cdsBegin * @brief Start of the coding region (<tt>0</tt>-based position, defaults to <tt>-1</tt>). */ int32_t cdsBegin; /*! * @var int32_t UcscRecord::cdsEnd * @brief End of the coding region, defaults to <tt>-1</tt>. */ int32_t cdsEnd; /*! * @var CharString UcscRecord::exonBegin * @brief Start of the exon (<tt>0</tt>-based position, defaults to <tt>-1</tt>). */ String<int32_t> exonBegin; /*! * @var CharString UcscRecord::exonEnds * @brief End of the exon, defaults to <tt>-1</tt>. */ String<int32_t> exonEnds; /*! * @var CharString UcscRecord::proteinName * @brief Name of the coded protein. */ CharString proteinName; /*! * @var uint32_t UcscRecord::annotationBeginPos * @brief Start of the annotation (<tt>0</tt>-based, defaults to <tt>-1</tt>). */ uint32_t annotationBeginPos; /*! * @var CharString UcscRecord::annotationEndPos * @brief End position of the annotation, defaults to <tt>-1</tt>. */ uint32_t annotationEndPos; UcscRecord() : cdsBegin(0), cdsEnd(0), annotationBeginPos(0), annotationEndPos(0) {} }; // ============================================================================ // Functions // ============================================================================ // ---------------------------------------------------------------------------- // Function clear() // ---------------------------------------------------------------------------- /*! * @fn UcscRecord#clear * @brief Clear UcscRecord. * * @signature void clear(record); * * @param record The UcscRecord to clear. * * Clears all strings and resets it to default initialization state. */ inline void clear(UcscRecord & record) { clear(record.transName); clear(record.contigName); record.cdsBegin = -1; record.cdsEnd = -1; clear(record.exonBegin); clear(record.exonEnds); clear(record.proteinName); record.annotationBeginPos = -1; record.annotationEndPos = -1; } } // namespace seqan #endif // #ifndef SEQAN_INCLUDE_SEQAN_BAM_IO_BAM_RECORD_H_
1,856
979
<reponame>smeualex/cmake-examples #include <iostream> #include "calculator-shared-export/calculator.h" int main(int argc, char** argv) { std::cout << calc_pow(5, 5) << "\n"; return 0; }
90
1,574
//======================================================================= // Copyright <NAME> 2013-2018. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include "tlib/dns.hpp" #include "tlib/malloc.hpp" #include "tlib/system.hpp" #include "tlib/errors.hpp" #include "tlib/print.hpp" namespace { bool is_digit(char c){ return c >= '0' && c <= '9'; } } // end of anonymous namespace bool tlib::dns::is_ip(const std::string& value){ auto ip_parts = std::split(value, '.'); if(ip_parts.size() != 4){ return false; } for(auto& part : ip_parts){ if(part.empty() || part.size() > 3){ return false; } for(size_t i = 0; i < part.size(); ++i){ if(!is_digit(part[i])){ return false; } } } return true; } std::string tlib::dns::decode_domain(char* payload, size_t& offset) { std::string domain; offset = 0; while (true) { auto label_size = static_cast<uint8_t>(*(payload + offset)); ++offset; if (!label_size) { break; } if (!domain.empty()) { domain += '.'; } for (size_t i = 0; i < label_size; ++i) { domain += *(payload + offset); ++offset; } } return domain; } tlib::ip::address tlib::dns::gateway_address(){ uint64_t ret; asm volatile("mov rax, 0xB15; int 50; mov %[code], rax" : [code] "=m"(ret) : : "rax"); return {uint32_t(ret)}; } std::expected<void> tlib::dns::send_request(tlib::socket& sock, const std::string& domain, uint16_t rr_type, uint16_t rr_class){ auto parts = std::split(domain, '.'); size_t characters = domain.size() - (parts.size() - 1); // The dots are not included size_t labels = parts.size(); tlib::dns::packet_descriptor desc; desc.payload_size = labels + characters + 1 + 2 * 2; desc.identification = 0x666; desc.query = true; auto packet = sock.prepare_packet(&desc); if (!sock) { return std::make_unexpected<void>(sock.error()); } auto* payload = reinterpret_cast<char*>(packet.payload + packet.index); size_t i = 0; for (auto& part : parts) { payload[i++] = part.size(); for (size_t j = 0; j < part.size(); ++j) { payload[i++] = part[j]; } } payload[i++] = 0; auto* q_type = reinterpret_cast<uint16_t*>(packet.payload + packet.index + i); *q_type = tlib::switch_endian_16(rr_type); auto* q_class = reinterpret_cast<uint16_t*>(packet.payload + packet.index + i + 2); *q_class = tlib::switch_endian_16(rr_class); sock.finalize_packet(packet); if (!sock) { return std::make_unexpected<void>(sock.error()); } return {}; } std::expected<tlib::ip::address> tlib::dns::resolve(const std::string& domain, size_t timeout_ms, size_t retries){ tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::DGRAM, tlib::socket_protocol::DNS); sock.client_bind(gateway_address()); sock.listen(true); if (!sock) { return std::make_unexpected<tlib::ip::address>(sock.error()); } size_t tries = 0; auto sr = send_request(sock, domain, 0x1, 0x1); if(!sr){ return std::make_unexpected<tlib::ip::address>(sr.error()); } auto before = tlib::ms_time(); auto after = before; while (true) { // Make sure we don't wait for more than the timeout if (after > before + timeout_ms) { break; } auto remaining = timeout_ms - (after - before); auto p = sock.wait_for_packet(remaining); if (!sock) { return std::make_unexpected<tlib::ip::address>(sock.error()); } else { auto* dns_header = reinterpret_cast<tlib::dns::header*>(p.payload + p.index); auto identification = tlib::switch_endian_16(dns_header->identification); // Only handle packet with the correct identification if (identification == 0x666) { auto questions = tlib::switch_endian_16(dns_header->questions); auto answers = tlib::switch_endian_16(dns_header->answers); auto flags = tlib::switch_endian_16(dns_header->flags); auto qr = flags >> 15; // Only handle Response if (qr) { auto rcode = flags & 0xF; if (rcode == 0x0 && answers > 0) { auto* payload = p.payload + p.index + sizeof(tlib::dns::header); // Decode the questions (simply wrap around it) for (size_t i = 0; i < questions; ++i) { size_t length; tlib::dns::decode_domain(payload, length); payload += length; payload += 4; } for (size_t i = 0; i < answers; ++i) { auto label = static_cast<uint8_t>(*payload); if (label > 64) { // This is a pointer auto pointer = tlib::switch_endian_16(*reinterpret_cast<uint16_t*>(payload)); auto offset = pointer & (0xFFFF >> 2); payload += 2; size_t ignored; tlib::dns::decode_domain(p.payload + p.index + offset, ignored); } else { return std::make_unexpected<tlib::ip::address>(std::ERROR_UNSUPPORTED); } auto rr_type = tlib::switch_endian_16(*reinterpret_cast<uint16_t*>(payload)); payload += 2; auto rr_class = tlib::switch_endian_16(*reinterpret_cast<uint16_t*>(payload)); payload += 2; payload += 4; // TTL auto rd_length = tlib::switch_endian_16(*reinterpret_cast<uint16_t*>(payload)); payload += 2; if(rr_class == 1){ // IN (Internet) class if (rr_type == 0x1) { // A record auto ip = reinterpret_cast<uint8_t*>(payload); auto result = tlib::ip::make_address(ip[3], ip[2], ip[1], ip[0]); return std::make_expected<tlib::ip::address>(result); } } payload += rd_length; } break; } else { // There was an error, retry if(++tries == retries || !send_request(sock, domain)){ return std::make_unexpected<tlib::ip::address>(std::ERROR_SOCKET_TIMEOUT); } } } } } after = tlib::ms_time(); } return std::make_unexpected<tlib::ip::address>(std::ERROR_SOCKET_TIMEOUT); } std::expected<std::string> tlib::dns::resolve_str(const std::string& domain, size_t timeout_ms, size_t retries){ auto result = resolve(domain, timeout_ms, retries); if(result){ auto& ip = *result; auto result = sprintf("%u.%u.%u.%u", ip(3), ip(2), ip(1), ip(0)); return std::make_expected<std::string>(result); } return std::make_unexpected<std::string>(result.error()); }
4,123
416
// // CNContactViewController.h // ContactsUI // // Copyright (c) 2015 Apple, Inc. All rights reserved. // #import <UIKit/UIKit.h> #import <Contacts/Contacts.h> NS_ASSUME_NONNULL_BEGIN @protocol CNContactViewControllerDelegate; /*! * @abstract The CNContactViewController is used to display a contact. * @discussion This class can display a new contact, unknown contact or existing contact. You must use one of the designated initializers. */ NS_CLASS_AVAILABLE_IOS(9_0) @interface CNContactViewController : UIViewController /*! * @abstract Descriptor for all keys that must be fetched on your contact before setting it on the view controller. * @discussion Pass this descriptor to the keysToFetch of the CNContactFetchRequest if you want to display the contact in a CNContactViewController. */ + (id<CNKeyDescriptor>)descriptorForRequiredKeys; /*! * @abstract Designated initializers. * @discussion These initializers customize the behavior and appearance of CNContactViewController. * @note All keys of the given contact must be fetched */ + (instancetype)viewControllerForContact:(CNContact *)contact; + (instancetype)viewControllerForUnknownContact:(CNContact *)contact; + (instancetype)viewControllerForNewContact:(nullable CNContact *)contact; /*! * @abstract The contact being displayed. */ @property (nonatomic, strong, readonly) CNContact *contact; /*! * @abstract The CNContact property keys to display. * @discussion If not set all properties are displayed. * @note All properties are visible when editing the contact. */ @property (nonatomic, copy, nullable) NSArray *displayedPropertyKeys; /*! * @abstract The delegate to be notified. */ @property (nonatomic, weak, nullable) id <CNContactViewControllerDelegate> delegate; /*! * @abstract The CNContactStore where the contact was fetched from or will be saved to. * @discussion If not set adding the contact to the user's contacts is disabled. */ @property (nonatomic, strong, nullable) CNContactStore *contactStore; /*! * @abstract A CNGroup where the new contact will be assigned membership. * @discussion If not set the contact is added only to the default CNContainer with no group membership. * @note When set to a group not in the default container, the container property must also be set to the container of parentGroup. */ @property (nonatomic, strong, nullable) CNGroup *parentGroup; /*! * @abstract A CNContainer where the new contact will be created. * @discussion If not set the contact is added to the default container. */ @property (nonatomic, strong, nullable) CNContainer *parentContainer; /*! * @abstract The name to use if the contact has no display name. */ @property (nonatomic, copy, nullable) NSString *alternateName; /*! * @abstract The message to display under the name. */ @property (nonatomic, copy, nullable) NSString *message; /*! * @abstract Customization of the card. */ @property (nonatomic, assign) BOOL allowsEditing; // YES by default @property (nonatomic, assign) BOOL allowsActions; // YES by default @property (nonatomic, assign) BOOL shouldShowLinkedContacts; // NO by default /*! * @abstract Highlight a property. * @discussion Indicates whether to highlight a certain property value for the contact. * If a single value property key is specified, identifier will be ignored. */ - (void)highlightPropertyWithKey:(NSString *)key identifier:(nullable NSString *)identifier; @end NS_AVAILABLE_IOS(9_0) @protocol CNContactViewControllerDelegate <NSObject> @optional /*! * @abstract Called when the user selects a single property. * @discussion Return NO if you do not want anything to be done or if you are handling the actions yourself. * Return YES if you want the default action performed for the property otherwise return NO. */ - (BOOL)contactViewController:(CNContactViewController *)viewController shouldPerformDefaultActionForContactProperty:(CNContactProperty *)property; /*! * @abstract Called when the view has completed. * @discussion If creating a new contact, the new contact added to the contacts list will be passed. * If adding to an existing contact, the existing contact will be passed. * @note It is up to the delegate to dismiss the view controller. */ - (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(nullable CNContact *)contact; @end NS_ASSUME_NONNULL_END
1,197
532
/* This sample program computes a canonical polygonal schema of a closed manifodl * with genus g, which is basically a map to a regular polygon with 4g sides. For * more details refer to: * * Obtaining a Canonical Polygonal Schema from a * Greedy Homotopy Basis with Minimal Mesh Refinement * <NAME> * IEEE Transactions on Visualization and Computer Graphics, 2020 * * and * * Globally Optimal Surface Mapping for Surfaces with Arbitrary Topology * <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME> * IEEE Transactions on Visualization and Computer Graphics, 2008 * * Enjoy! */ #include <QApplication> #include <QHBoxLayout> #include <cinolib/gui/qt/qt_gui_tools.h> #include <cinolib/meshes/meshes.h> #include <cinolib/homotopy_basis.h> #include <cinolib/canonical_polygonal_schema.h> #include <cinolib/polycube.h> //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: int main(int argc, char **argv) { using namespace cinolib; QApplication app(argc, argv); std::string s = (argc==2) ? std::string(argv[1]) : std::string(DATA_PATH) + "/torus.obj"; DrawableTrimesh<> m_xyz(s.c_str()); HomotopyBasisData data; data.globally_shortest = false; data.root = 152; // best for torus data.detach_loops = true; data.split_strategy = EDGE_SPLIT_STRATEGY; homotopy_basis(m_xyz, data); std::cout << data << std::endl; DrawableTrimesh<> m_uvw; canonical_polygonal_schema(m_xyz, data, m_uvw); // set UV coordinates auto xyz = m_xyz.vector_verts(); m_xyz.vector_verts() = m_uvw.vector_verts(); m_xyz.copy_xyz_to_uvw(UV_param); m_uvw.copy_xyz_to_uvw(UV_param); m_xyz.vector_verts() = xyz; QWidget window; GLcanvas gui_xyz; GLcanvas gui_uvw; QHBoxLayout layout; layout.addWidget(&gui_xyz); layout.addWidget(&gui_uvw); window.setLayout(&layout); m_xyz.show_wireframe(false); m_xyz.edge_mark_boundaries(); m_xyz.show_texture2D(TEXTURE_2D_CHECKERBOARD, 1); m_xyz.updateGL(); gui_xyz.push_obj(&m_xyz); m_uvw.show_wireframe(false); m_uvw.edge_mark_boundaries(); m_uvw.show_texture2D(TEXTURE_2D_CHECKERBOARD, 1); m_uvw.updateGL(); gui_uvw.push_obj(&m_uvw); window.resize(800,600); window.show(); //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: SurfaceMeshControlPanel<DrawableTrimesh<>> panel_xyz(&m_xyz, &gui_xyz); SurfaceMeshControlPanel<DrawableTrimesh<>> panel_uvw(&m_uvw, &gui_uvw); QApplication::connect(new QShortcut(QKeySequence(Qt::CTRL+Qt::Key_1), &gui_xyz), &QShortcut::activated, [&](){panel_xyz.show();}); QApplication::connect(new QShortcut(QKeySequence(Qt::CTRL+Qt::Key_2), &gui_uvw), &QShortcut::activated, [&](){panel_uvw.show();}); return app.exec(); }
1,146
577
// Copyright (c) Corporation for National Research Initiatives package org.python.core; /** * A deprecated interface that can be used if a java class want control over * the class dict initialization. * * @deprecated This class is deprecated. See ClassDictInit for a replacement. * @see ClassDictInit */ @Deprecated public interface InitModule { public abstract void initModule(PyObject dict); }
105
1,605
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.tools; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.StringReader; import org.apache.pdfbox.pdmodel.PDDocument; import org.junit.jupiter.api.Test; /** * Test suite for TextToPDF. */ class TestTextToPdf { /** * This test ensures that a PDF created from an empty String is still readable by Adobe Reader */ @Test void testCreateEmptyPdf() throws Exception { TextToPDF pdfCreator = new TextToPDF(); PDDocument pdfDoc; try (StringReader reader = new StringReader("")) { pdfDoc = pdfCreator.createPDFFromText(reader); } // In order for the PDF document to be openable by Adobe Reader, it needs // to have some pages in it. So we'll check that. int pageCount = pdfDoc.getNumberOfPages(); assertTrue(pageCount > 0, "All Pages was unexpectedly zero."); assertEquals(1, pageCount, "Wrong number of pages."); pdfDoc.close(); } }
652
1,398
#ifndef CONFLUO_TEST_FILTER_TEST_H_ #define CONFLUO_TEST_FILTER_TEST_H_ #include "filter.h" #include "gtest/gtest.h" #include <thread> using namespace ::confluo::monitor; using namespace ::confluo::monolog; using namespace ::confluo; // Stateless filter inline bool filter1(const record_t &r) { return r.timestamp() % 10000 == 0; } class FilterTest : public testing::Test { public: static const uint32_t kMaxEntries = 100000; static const uint64_t kTimeBlock = static_cast<const uint64_t>(1e3); static const uint64_t kMillisecs = static_cast<const uint64_t>(1e6); struct data_point { int64_t ts; int64_t val; data_point(uint64_t _ts, int64_t _val) : ts(_ts), val(_val) { } }__attribute__((packed)); void fill(filter &f) { ASSERT_TRUE(thread_manager::register_thread() != -1); for (size_t i = 0; i < kMaxEntries; i++) { data_point p(i * kTimeBlock, static_cast<int64_t>(i)); record_t r(i, reinterpret_cast<uint8_t *>(&p), sizeof(data_point)); r.push_back(field_t(0, primitive_types::LONG_TYPE(), r.data(), false, 0, 0.0)); r.push_back(field_t(1, primitive_types::LONG_TYPE(), reinterpret_cast<char *>(r.data()) + sizeof(int64_t), false, 0, 0.0)); f.update(r); } ASSERT_TRUE(thread_manager::deregister_thread() != -1); } void fill_mt(filter &f, uint32_t num_threads) { std::vector<std::thread> workers; for (size_t i = 1; i <= num_threads; i++) { workers.push_back( std::thread( [i, &f] { ASSERT_TRUE(thread_manager::register_thread() != -1); size_t begin = (i - 1) * kMaxEntries, end = i * kMaxEntries; for (size_t j = begin; j < end; j++) { data_point p((j - begin) * kTimeBlock, static_cast<int64_t>(j)); record_t r(j, reinterpret_cast<uint8_t *>(&p), sizeof(data_point)); r.push_back(field_t(0, primitive_types::LONG_TYPE(), r.data(), false, 0, 0.0)); r.push_back(field_t(1, primitive_types::LONG_TYPE(), reinterpret_cast<char *>(r.data()) + sizeof(int64_t), false, 0, 0.0)); f.update(r); } ASSERT_TRUE(thread_manager::deregister_thread() != -1); })); } for (std::thread &worker : workers) { worker.join(); } } static compiled_expression get_expr(std::string &expr) { schema_builder builder; builder.add_column(primitive_types::LONG_TYPE(), "value"); schema_t schema(builder.get_columns()); auto t = parser::parse_expression(expr); return parser::compile_expression(t, schema); } }; TEST_F(FilterTest, FilterFunctionTest) { filter f(filter1); fill(f); size_t accum = 0; for (size_t t = 0; t < 100; t++) { reflog const *s = f.lookup(t); size_t size = s->size(); ASSERT_EQ(static_cast<size_t>(100), size); for (uint32_t i = static_cast<uint32_t>(accum); i < accum + size; i++) { ASSERT_EQ(i * 10, s->at(i - accum)); } accum += size; } auto res = f.lookup_range(0, 3); size_t count = res.count(); ASSERT_EQ(static_cast<size_t>(4 * 100), count); size_t i = 0; for (const uint64_t &r : res) { ASSERT_EQ(i * 10, r); i++; } for (size_t num_threads = 1; num_threads <= 4; num_threads++) { filter f1(filter1); fill_mt(f1, static_cast<uint32_t>(num_threads)); uint64_t n_filtered_entries = (kMaxEntries * num_threads) / 10; std::vector<size_t> counts(n_filtered_entries, 0); for (size_t t = 0; t < 100; t++) { reflog const *s = f1.lookup(t); size_t size = s->size(); ASSERT_EQ(100 * num_threads, size); for (i = 0; i < size; i++) { uint64_t val = s->at(i); ASSERT_TRUE(val % 10 == 0); ASSERT_TRUE(val / 10 < n_filtered_entries); counts[val / 10]++; } } for (size_t c : counts) { ASSERT_EQ(static_cast<size_t>(1), c); } } } TEST_F(FilterTest, FilterExpressionTest) { std::string expr("value >= 50000"); auto cexpr = get_expr(expr); filter f(cexpr); fill(f); for (size_t t = 0; t < 50; t++) { ASSERT_EQ(nullptr, f.lookup(t)); } size_t accum = 50000; for (size_t t = 50; t < 100; t++) { reflog const *s = f.lookup(t); size_t size = s->size(); ASSERT_EQ(static_cast<size_t>(1000), size); for (uint32_t i = static_cast<uint32_t>(accum); i < accum + size; i++) { ASSERT_EQ(i, s->at(i - accum)); } accum += size; } auto res = f.lookup_range(48, 52); size_t count = res.count(); ASSERT_EQ(static_cast<size_t>(3 * 1000), count); size_t i = 50000; for (const uint64_t &r : res) { ASSERT_EQ(i, r); i++; } } TEST_F(FilterTest, AggregateTest) { std::string expr("value >= 50000"); auto cexpr = get_expr(expr); filter f(cexpr); aggregate_info *a = new aggregate_info( "agg1", aggregate_manager::get_aggregator("max"), 0); size_t aid = f.add_aggregate(a); ASSERT_EQ(0, aid); fill(f); uint64_t version = kMaxEntries + sizeof(data_point); for (size_t t = 50; t < 100; t++) { const aggregated_reflog *ar = f.lookup(t); int64_t expected = static_cast<int64_t>(((t + 1) * kTimeBlock - 1) * 1000); ASSERT_TRUE(numeric(expected) == ar->get_aggregate(aid, version)); } } TEST_F(FilterTest, MultiThreadedAggregateTest) { std::string expr("value >= 50000"); auto cexpr = get_expr(expr); filter f(cexpr); aggregate_info *a = new aggregate_info( "agg1", aggregate_manager::get_aggregator("max"), 0); size_t aid = f.add_aggregate(a); ASSERT_EQ(0, aid); fill_mt(f, 4); uint64_t version = 4 * kMaxEntries + sizeof(data_point); for (size_t t = 50; t < 100; t++) { const aggregated_reflog *ar = f.lookup(t); int64_t expected = static_cast<int64_t>(((t + 1) * kTimeBlock - 1) * 1000); ASSERT_TRUE(numeric(expected) == ar->get_aggregate(aid, version)); } } #endif // CONFLUO_TEST_FILTER_TEST_H_
3,028
460
/* * Copyright 2018 Red Hat, Inc, and individual contributors. * * 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 org.wildfly.swarm.microprofile.restclient.ft; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.inject.Inject; import javax.ws.rs.WebApplicationException; import org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException; import org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException; import org.eclipse.microprofile.rest.client.RestClientBuilder; import org.eclipse.microprofile.rest.client.RestClientDefinitionException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.swarm.microprofile.restclient.Counter; import org.wildfly.swarm.microprofile.restclient.HelloResource; import org.wildfly.swarm.microprofile.restclient.Latch; import org.wildfly.swarm.microprofile.restclient.Timer; /** * * @author <NAME> */ @RunWith(Arquillian.class) public class FaultToleranceTest { static final int BULKHEAD = 2; @Inject Counter counter; @Inject Timer timer; @Inject Latch latch; @ArquillianResource URL url; @Deployment public static WebArchive createTestArchive() { return ShrinkWrap.create(WebArchive.class).addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addPackage(HelloResource.class.getPackage()) .addPackage(FaultToleranceTest.class.getPackage()); } @Test public void testRetry() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException { counter.reset(3); timer.reset(0); HelloClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).build(HelloClient.class); assertEquals("OK3", helloClient.helloRetry()); } @Test public void testFallback() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException { HelloClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).build(HelloClient.class); timer.reset(0); counter.reset(3); assertEquals("fallback", helloClient.helloFallback()); assertEquals("defaultFallback", helloClient.helloFallbackDefaultMethod()); } @Test public void testCircuitBreaker() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException { HelloClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).build(HelloClient.class); counter.reset(3); timer.reset(0); try { helloClient.helloCircuitBreaker(); fail(); } catch (WebApplicationException expected) { } try { helloClient.helloCircuitBreaker(); fail(); } catch (WebApplicationException expected) { } try { helloClient.helloCircuitBreaker(); fail(); } catch (CircuitBreakerOpenException expected) { } } @Test public void testCircuitBreakerClassLevel() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException { HelloClientClassLevelCircuitBreaker client = RestClientBuilder.newBuilder().baseUrl(url).build(HelloClientClassLevelCircuitBreaker.class); counter.reset(3); timer.reset(0); try { client.helloCircuitBreaker(); fail(); } catch (WebApplicationException expected) { } try { client.helloCircuitBreaker(); fail(); } catch (WebApplicationException expected) { } try { client.helloCircuitBreaker(); fail(); } catch (CircuitBreakerOpenException expected) { } } @Test public void testTimeout() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException { HelloClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).build(HelloClient.class); counter.reset(1); timer.reset(400); latch.reset(1); try { helloClient.helloTimeout(); fail(); } catch (TimeoutException expected) { } latch.await(); } @Test public void testBulkhead() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException, ExecutionException { int pool = BULKHEAD; // Start latch latch.reset(pool); // End latch latch.add("end", 1); ExecutorService executor = Executors.newFixedThreadPool(pool); try { HelloClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).property("resteasy.connectionPoolSize", pool * 2).build(HelloClient.class); List<Future<String>> results = new ArrayList<>(); for (int i = 0; i < pool; i++) { results.add(executor.submit(() -> helloClient.helloBulkhead(true))); } // Wait until all requests are being processed if(!latch.await()) { fail(); } // Next invocation should return fallback due to BulkheadException assertEquals("bulkheadFallback", helloClient.helloBulkhead(false)); latch.countDown("end"); for (Future<String> future : results) { assertEquals("OK", future.get()); } } finally { executor.shutdown(); } } }
2,498
364
<gh_stars>100-1000 /* Dwarf Therapist Copyright (c) 2009 <NAME> (chmod) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ROTATED_HEADER_H #define ROTATED_HEADER_H #include <QHeaderView> #include "dwarfmodelproxy.h" class RotatedHeader : public QHeaderView { Q_OBJECT public: RotatedHeader(Qt::Orientation orientation, QWidget *parent = 0); void paintSection(QPainter *p, const QRect &rect, int idx) const; void column_hover(int col); void set_last_sorted_idx(int idx){m_last_sorted_idx = idx;} QSize sizeHint() const; public slots: void read_settings(); void resizeSection(int logicalIndex, int size ); void set_header_height(QString max_title); void set_index_as_spacer(int idx); void clear_spacers(); void contextMenuEvent(QContextMenuEvent *); protected: void leaveEvent(QEvent *e); void mouseMoveEvent(QMouseEvent *e); void mousePressEvent(QMouseEvent *e); signals: void section_right_clicked(int idx); void sort(int, DwarfModelProxy::DWARF_SORT_ROLE, Qt::SortOrder); private: QPoint m_p; QList<int> m_spacer_indexes; bool m_shade_column_headers; bool m_header_text_bottom; QFont m_font; int m_hovered_column; int m_last_sorted_idx; //tracks the last sorted column from the user. internal column sorting (global sort) can't be shown as the column is hidden int m_preferred_height; private slots: //! called by a sorting context menu action void sort_action(); //! called by context menu on sections void toggle_set_action(); }; #endif
958
828
<filename>hasor-rsf/hasor-land/src/main/java/net/hasor/land/election/ElectionServiceManager.java<gh_stars>100-1000 /* * Copyright 2008-2009 the original author or 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. */ package net.hasor.land.election; import io.netty.util.Timeout; import io.netty.util.TimerTask; import net.hasor.core.EventListener; import net.hasor.core.Init; import net.hasor.core.Inject; import net.hasor.core.InjectSettings; import net.hasor.land.bootstrap.LandContext; import net.hasor.land.domain.ServerStatus; import net.hasor.land.node.NodeData; import net.hasor.land.node.Operation; import net.hasor.land.node.RunLock; import net.hasor.land.node.Server; import net.hasor.land.replicator.DataContext; import net.hasor.land.utils.TermUtils; import net.hasor.rsf.RsfContext; import net.hasor.utils.future.FutureCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; /** * 选举服务,负责选出 Leader * * @version : 2016年09月10日 * @author 赵永春 (<EMAIL>) */ public class ElectionServiceManager implements ElectionService, EventListener<ServerStatus> { protected Logger logger = LoggerFactory.getLogger(getClass()); @Inject private Server server; @Inject private DataContext dataContext; @Inject private LandContext landContext; @Inject private RsfContext rsfContext; private AtomicBoolean landStatus; // @InjectSettings("hasor.land.timeout") private int baseTimeout; // 基准心跳时间 @InjectSettings("hasor.land.leaderHeartbeat") private int leaderHeartbeat; // Leader 心跳时间 private AtomicBoolean followerTimer; // follower 定时器 private AtomicBoolean candidateTimer; // candidate定时器 private AtomicBoolean leaderTimer; // leader 定时器 // // @Init public void start() { this.landStatus = new AtomicBoolean(true); this.followerTimer = new AtomicBoolean(false); this.candidateTimer = new AtomicBoolean(false); this.leaderTimer = new AtomicBoolean(false); // this.landContext.addStatusListener(this); // this.startFollowerTimer(); this.startCandidateTimer(); this.startLeaderTimer(); // this.server.lockRun(new RunLock() { public void run(Operation object) { String selfServerID = landContext.getServerID(); String selfTerm = object.getCurrentTerm(); switchToFollow(object, selfServerID, selfTerm); } }); } // // -------------------------------------------------------------------------------------------- // .状态切换事件 // 当发生角色转换,负责更新各个定时器状态 public void onEvent(String event, ServerStatus eventData) { this.followerTimer.set(false); this.candidateTimer.set(false); this.leaderTimer.set(false); // logger.info("Land[Status] - switchTo -> {}.", eventData); if (eventData == ServerStatus.Follower) { this.followerTimer.set(true); return; } // .一旦成为候选人那么马上进行选举 if (eventData == ServerStatus.Candidate) { this.candidateTimer.set(true); return; } // .一旦成为 Leader 马上发送一个 term 以建立权威,然后通过心跳维持权威 if (eventData == ServerStatus.Leader) { this.leaderTimer.set(true); return; } } // -------------------------------------------------------------------------------------------- // .follower // startFollowerTimer 启动定时器 // processFollowerTimer 定时器的循环调用 // processFollower follower 逻辑代码 private void startFollowerTimer() { if (!this.followerTimer.compareAndSet(false, true)) { this.logger.error("Land[Follower] - followerTimer -> already started"); return; } this.logger.info("Land[Follower] - start followerTimer."); final long lastLeaderHeartbeat = this.server.getLastHeartbeat(); this.landContext.atTime(new TimerTask() { public void run(Timeout timeout) throws Exception { processFollowerTimer(lastLeaderHeartbeat); } }, genTimeout()); } private void processFollowerTimer(long lastLeaderHeartbeat) { // .如果系统退出,那么结束定时器循环 if (!this.landStatus.get()) { return; } // .执行 Follower 任务 try { this.processFollower(lastLeaderHeartbeat); } catch (Exception e) { logger.error("Land[Follower] - " + e.getMessage(), e); } // .重启定时器 final long curLeaderHeartbeat = this.server.getLastHeartbeat(); this.landContext.atTime(new TimerTask() { public void run(Timeout timeout) throws Exception { processFollowerTimer(curLeaderHeartbeat); } }, genTimeout()); } private void processFollower(final long lastLeaderHeartbeat) { /* 确保 lockRun 中的方法在并发场景中是线程安全的 */ this.server.lockRun(new RunLock() { public void run(Operation object) { if (!followerTimer.get()) { return; } // .如果已经不在处于追随者,那么放弃后续处理 if (object.getStatus() != ServerStatus.Follower) { logger.info("Land[Follower] -> server mast be Follower, but ->" + object.getStatus()); return; } // // .判断启动定时器之后是否收到最新的 Leader 心跳 ,如果收到了心跳,那么放弃后续处理维持 Follower 状态 // (新的Leader心跳时间比启动定时器之前心跳时间要新,即为收到了心跳) boolean leaderHeartbeat = object.getLastHeartbeat() > lastLeaderHeartbeat; if (leaderHeartbeat) { printLeader(); return; } // // .确保状态从 Follower 切换到 Candidate logger.info("Land[Follower] -> initiate the election."); if (object.getStatus() == ServerStatus.Follower) { landContext.fireStatus(ServerStatus.Candidate); } } }); // } // -------------------------------------------------------------------------------------------- // .candidate // startCandidateTimer 启动定时器 // processCandidateTimer 定时器的循环调用 // processCandidate candidate 逻辑代码 private void startCandidateTimer() { if (!this.candidateTimer.compareAndSet(false, true)) { this.logger.error("Land[Candidate] - candidateTimer -> already started"); return; } this.logger.info("Land[Candidate] - start candidateTimer."); this.landContext.atTime(new TimerTask() { public void run(Timeout timeout) throws Exception { processCandidateTimer(); } }, this.genTimeout()); } private void processCandidateTimer() { // .如果系统退出,那么结束定时器循环 if (!this.landStatus.get()) { return; } // .执行 Candidate 任务 try { this.processCandidate(); } catch (Exception e) { logger.error("Land[Candidate] - " + e.getMessage(), e); } // .重启定时器 this.landContext.atTime(new TimerTask() { public void run(Timeout timeout) throws Exception { processCandidateTimer(); } }, genTimeout()); } private void processCandidate() { /* 确保 lockRun 中的方法在并发场景中是线程安全的 */ this.server.lockRun(new RunLock() { public void run(Operation object) { if (!candidateTimer.get()) { return; } if (object.getStatus() != ServerStatus.Candidate) { return; } // .候选人会继续保持着当前状态直到以下三件事情之一发生: // (a) 他自己赢得了这次的选举, -> 成为 Leader // (b) 其他的服务器成为领导者, -> 成为 Follower // (c) 一段时间之后没有任何获胜的, -> 重新开始选举 // // // .term自增 object.incrementAndGetTerm(); object.clearVoted(); logger.info("Land[Candidate] -> solicit votes , current Trem is {}", object.getCurrentTerm()); // // .发起选举然后收集选票 List<NodeData> nodeList = object.getOnlineNodes(); for (NodeData nodeData : nodeList) { // .如果目标是自己,那么直接投给自己 if (nodeData.isSelf()) { landContext.fireVotedFor(nodeData.getServerID()); object.applyVoted(nodeData.getServerID(), true); continue; } // .征集选票(并发) nodeData.collectVote(object, dataContext, new FutureCallback<CollectVoteResult>() { public void completed(CollectVoteResult result) { doVote(result); } public void failed(Throwable ex) { doFailed(ex); } }); } // // } }); } // -------------------------------------------------------------------------------------------- // .leader // startLeaderTimer 启动定时器 // processLeaderTimer 定时器的循环调用 // processLeader leader 逻辑代码 private void startLeaderTimer() { if (!this.leaderTimer.compareAndSet(false, true)) { this.logger.error("Land[Leader] - leaderTimer -> already started"); return; } this.logger.info("Land[Leader] - start leaderTimer."); this.landContext.atTime(new TimerTask() { public void run(Timeout timeout) throws Exception { processLeaderTimer(); } }, this.leaderHeartbeat); } private void processLeaderTimer() { // .如果系统退出,那么结束定时器循环 if (!this.landStatus.get()) { return; } // .执行 Leader 任务 try { this.processLeader(); } catch (Exception e) { logger.error("Land[Leader] - " + e.getMessage(), e); } // .重启定时器 this.landContext.atTime(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { processLeaderTimer(); } }, this.leaderHeartbeat); } private void processLeader() { /* 确保 lockRun 中的方法在并发场景中是线程安全的 */ this.server.lockRun(new RunLock() { public void run(Operation object) { if (!leaderTimer.get()) { return; } // printLeader(); // // .发送心跳log以维持 Leader 权威 List<NodeData> nodeList = object.getOnlineNodes(); for (NodeData nodeData : nodeList) { // // .如果心跳目标是自己,那么直接更新心跳时间 if (nodeData.isSelf()) { object.newLastLeaderHeartbeat(); continue; } // .发送Leader心跳包(并发) nodeData.leaderHeartbeat(object, dataContext, new FutureCallback<LeaderBeatResult>() { public void completed(LeaderBeatResult result) { doHeartbeat(result); } public void failed(Throwable ex) { doFailed(ex); } }); } } }); } // -------------------------------------------------------------------------------------------- // .拉选票 // collectVote 处理拉票操作 // doVote 投票结果处理 @Override public CollectVoteResult collectVote(CollectVoteData voteData) { final String selfTerm = this.server.getCurrentTerm(); final String remoteTerm = voteData.getTerm(); final String remoteServerID = voteData.getServerID(); // final CollectVoteResult voteResult = new CollectVoteResult(); voteResult.setServerID(this.landContext.getServerID()); voteResult.setRemoteTerm(selfTerm); // // .无条件接受来自,自己的邀票 if (this.landContext.getServerID().equals(remoteServerID)) { logger.info("Land[Vote] -> accept votes from self."); voteResult.setVoteGranted(true); return voteResult; } // // .处理拉票操作(线程安全) this.server.lockRun(new RunLock() { public void run(Operation object) { // // .如果远程的term比自己大,那么成为 Follower if (TermUtils.gtFirst(selfTerm, remoteTerm)) { logger.info("Land[Vote] -> accept votes from {}.", remoteServerID); voteResult.setVoteGranted(true); switchToFollow(object, remoteServerID, remoteTerm); return; } // .拒绝投给他 voteResult.setVoteGranted(false); logger.info("Land[Vote] -> reject to {} votes. cause: currentTerm({}) > remoteTerm({})", // remoteServerID, selfTerm, remoteTerm); // } }); return voteResult; } public void doVote(final CollectVoteResult voteData) { final String remoteTerm = voteData.getRemoteTerm(); final String remoteServerID = voteData.getServerID(); final boolean granted = voteData.isVoteGranted(); // // .没有赢得选票,如果对方比自己大那么直接转换为 Follower this.server.lockRun(new RunLock() { public void run(Operation object) { String localTerm = object.getCurrentTerm(); boolean gtFirst = TermUtils.gtFirst(localTerm, remoteTerm); if (!granted && gtFirst) { logger.info("Land[Vote] -> this server follower to {}. L:R is {}:{}", remoteServerID, localTerm, remoteTerm); switchToFollow(object, remoteServerID, remoteTerm); } // // .记录选票结果 object.applyVoted(remoteServerID, voteData.isVoteGranted()); } // }); // .赢得了选票 -> 计票 -> 尝试成为 Leader if (granted) { this.server.lockRun(new RunLock() { public void run(Operation object) { // .计票,尝试成为 Leader( 返回true表示赢得了这次的选举 ) if (!isTestToLeader(object)) return; // landContext.fireVotedFor(landContext.getServerID()); landContext.fireStatus(ServerStatus.Leader); logger.info("Land[Vote] -> this server is elected leader."); } }); return; } } // -------------------------------------------------------------------------------------------- // .Leader心跳 // leaderHeartbeat Leader进行心跳 // doHeartbeat 心跳结果处理 @Override public LeaderBeatResult leaderHeartbeat(final LeaderBeatData beatResult) { // final String remoteTerm = beatResult.getCurrentTerm(); final String remoteServerID = beatResult.getServerID(); final LeaderBeatResult result = new LeaderBeatResult(); result.setServerID(this.landContext.getServerID()); // // .更新 term 和 Leadeer 一致 if (remoteServerID.equals(this.server.getVotedFor())) { this.server.lockRun(new RunLock() { public void run(Operation object) { String selfTerm = server.getCurrentTerm(); if (TermUtils.gtFirst(selfTerm, remoteTerm)) { object.updateTermTo(remoteTerm); logger.info("Land[Beat] -> follow leader update term to {}.", remoteTerm); } object.newLastLeaderHeartbeat(); } }); result.setAccept(true); return result; } // // .确定是否是已知的Leader List<NodeData> allNodes = this.server.getOnlineNodes(); NodeData atNode = null; for (NodeData nodeData : allNodes) { if (nodeData.getServerID().equalsIgnoreCase(remoteServerID)) { atNode = nodeData; break; } } // // .未知的 Server 想要成为 Leader 直接决绝。 if (atNode == null) { result.setAccept(false); return result; } // // .检查这个 Leader 的 Term 是否够大 this.server.lockRun(new RunLock() { public void run(Operation object) { String selfTerm = server.getCurrentTerm(); if (TermUtils.gtFirst(selfTerm, remoteTerm)) { switchToFollow(object, remoteServerID, remoteTerm); logger.info("Land[Beat] -> follow the new leader {} , new term is {}", remoteServerID, remoteTerm); result.setAccept(true); } else { logger.info("Land[Beat] -> refused to field {} leader heartbeat. L:R is {}:{}",// remoteServerID, selfTerm, remoteTerm); result.setAccept(false); } } }); // return result; } public void doHeartbeat(final LeaderBeatResult leaderBeatResult) { // // .更新自己的支持者列表 this.server.lockRun(new RunLock() { public void run(Operation object) { object.applyVoted(leaderBeatResult.getServerID(), leaderBeatResult.isAccept()); } }); // .如果出现拒绝者,那么测试自己是否还有足够的支持者支持自己成为 Leader,如果支持者足够,那么自增 term。 if (!leaderBeatResult.isAccept()) { this.server.lockRun(new RunLock() { public void run(Operation object) { if (isTestToLeader(object)) { object.incrementAndGetTerm(); logger.info("Land[Beat] -> [{},{}] leader conflict, strengthen shelf. term update to {}",// leaderBeatResult.getServerID(), landContext.getServerID(), object.getCurrentTerm()); } } }); } return; } // -------------------------------------------------------------------------------------------- // /** 10秒打印一次 Leader 的心跳 */ private long lastPrintLeaderLog; private void printLeader() { boolean printLeaderLog = this.lastPrintLeaderLog + 5000L < System.currentTimeMillis(); if (printLeaderLog) { this.lastPrintLeaderLog = System.currentTimeMillis(); this.logger.info("Land[Leader] -> leader is {} , term is {}", this.server.getVotedFor(), this.server.getCurrentTerm()); } } /** 处理异常信息的打印 */ private void doFailed(Throwable ex) { if (ex.getCause() != null) { ex = ex.getCause(); } logger.error(ex.getMessage()); } /** 生成最长:“n ~ n + (150 ~ 300)” 的一个随机数。用作超时时间 */ public int genTimeout() { return this.baseTimeout + new Random(System.currentTimeMillis()).nextInt(150) + 300; } /** 测试当前服务器是否可以成为 Leader,成为 Leader 的条件是得到半数选票。 */ private boolean isTestToLeader(Operation object) { List<NodeData> nodeList = object.getOnlineNodes(); int grantedCount = nodeList.size(); int serverCount = 0; for (NodeData nodeData : nodeList) { serverCount++; if (object.testVote(nodeData.getServerID())) { grantedCount++; } } return grantedCount * 2 > serverCount; } /** 成为 Follower 并追随一个 Leader */ public void switchToFollow(Operation object, String targetServer, String remoteTerm) { object.updateTermTo(remoteTerm); landContext.fireVotedFor(targetServer); landContext.fireStatus(ServerStatus.Follower); object.newLastLeaderHeartbeat(); } }
11,301
663
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import os from typing import Any, Dict import yaml from datadog_checks.base.utils.common import get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__)) HOST = get_docker_hostname() PORT = 8002 MARKLOGIC_VERSION = os.environ.get('MARKLOGIC_VERSION') API_URL = "http://{}:{}".format(HOST, PORT) ADMIN_USERNAME = 'admin' ADMIN_PASSWORD = '<PASSWORD>' MANAGE_ADMIN_USERNAME = 'datadog_admin' MANAGE_USER_USERNAME = 'datadog_user' PASSWORD = '<PASSWORD>' COMMON_TAGS = ['foo:bar'] INSTANCE = { 'url': API_URL, 'username': MANAGE_ADMIN_USERNAME, 'password': PASSWORD, 'enable_health_service_checks': True, 'auth_type': 'digest', 'tags': COMMON_TAGS, } INSTANCE_SIMPLE_USER = { 'url': API_URL, 'username': MANAGE_USER_USERNAME, 'password': PASSWORD, 'auth_type': 'digest', 'tags': COMMON_TAGS, } INSTANCE_FILTERS = { 'url': API_URL, 'username': MANAGE_ADMIN_USERNAME, 'password': PASSWORD, 'auth_type': 'digest', 'enable_health_service_checks': True, 'tags': COMMON_TAGS, 'resource_filters': [ {'resource_type': 'forest', 'pattern': '^S[a-z]*'}, # Match Security and Schemas {'resource_type': 'forest', 'pattern': '^Sch*', 'include': False}, # Unmatch Schemas {'resource_type': 'database', 'pattern': '^Doc'}, # Match Documents {'resource_type': 'server', 'pattern': 'Admin', 'group': 'Default'}, ], } CHECK_CONFIG = { 'init_config': {}, 'instances': [INSTANCE], } SERVICE_CHECKS_HEALTH_TAG = { 'database': [ 'database_name:App-Services', 'database_name:Documents', 'database_name:Extensions', 'database_name:Fab', 'database_name:Last-Login', 'database_name:Meters', 'database_name:Modules', 'database_name:Schemas', 'database_name:Security', 'database_name:Triggers', ], 'forest': [ 'forest_name:App-Services', 'forest_name:Documents', 'forest_name:Extensions', 'forest_name:Fab', 'forest_name:Last-Login', 'forest_name:Meters', 'forest_name:Modules', 'forest_name:Schemas', 'forest_name:Security', 'forest_name:Triggers', ], } def read_fixture_file(fname): # type: (str) -> Dict[str, Any] with open(os.path.join(HERE, 'fixtures', fname)) as f: return yaml.safe_load(f.read())
1,117
2,752
<reponame>Spacha/MineCraft-One-Week-Challenge<filename>Source/World/Block/ChunkBlock.h #ifndef CHUNKBLOCK_H_INCLUDED #define CHUNKBLOCK_H_INCLUDED #include "BlockId.h" struct BlockDataHolder; class BlockType; struct ChunkBlock { ChunkBlock() = default; ChunkBlock(Block_t id); ChunkBlock(BlockId id); const BlockDataHolder &getData() const; const BlockType &getType() const; bool operator==(ChunkBlock other) const { return id == other.id; } bool operator!=(ChunkBlock other) const { return id != other.id; } Block_t id = 0; }; #endif // CHUNKBLOCK_H_INCLUDED
263
868
<reponame>AriCheng/flare<gh_stars>100-1000 // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. #ifndef FLARE_FIBER_DETAIL_ASSEMBLY_H_ #define FLARE_FIBER_DETAIL_ASSEMBLY_H_ #include <cstddef> #include <cstdint> namespace flare::fiber::detail { // Emit (a series of) pause(s) to relax CPU. // // This can be used to delay execution for some time, or backoff from contention // in case you're doing some "lock-free" algorithm. template <std::size_t N = 1> [[gnu::always_inline]] inline void Pause() { if constexpr (N != 0) { Pause<N - 1>(); #if defined(__x86_64__) asm volatile("pause" ::: "memory"); // x86-64 only. #elif defined(__aarch64__) asm volatile("yield" ::: "memory"); #elif defined(__powerpc__) // FIXME: **RATHER** slow. asm volatile("or 31,31,31 # very low priority" ::: "memory"); #else #error Unsupported architecture. #endif } } // GCC's builtin `__builtin_popcount` won't generated `popcnt` unless compiled // with at least `-march=corei7`, so we use assembly here. // // `popcnt` is an SSE4.2 instruction, and should have already been widely // supported. inline int CountNonZeros(std::uint64_t value) { #if defined(__x86_64__) std::uint64_t rc; asm volatile("popcnt %1, %0;" : "=r"(rc) : "r"(value)); return rc; #else return __builtin_popcount(value); #endif } } // namespace flare::fiber::detail #endif // FLARE_FIBER_DETAIL_ASSEMBLY_H_
687
310
{ "name": "<NAME>", "description": "One of the traditional cocktails of Valencia", "github": "reyesbalejandroe", "ingredients": [ { "quantity": "500", "measure": "ml", "ingredient": "fresh-squeezed Valencia orange juice" }, { "quantity": "300", "measure": "ml", "ingredient": "cava (or champagne)" }, { "quantity": "100", "measure": "ml", "ingredient": "gin" }, { "quantity": "100", "measure": "ml", "ingredient": "vodka" }, { "quantity": "1", "measure": "spoon", "ingredient": "sugar" } ], "directions": [ "Start by making fresh-squeezed orange juice (if you can find Valencia oranges, all the better). It may be a bit labor intensive, but trust me, you will taste the difference! Fresh-squeezed orange juice has a much lighter, fresher taste that will make your Agua de Valencia super refreshing. In Spain, many grocery stores have orange juice machines where you can simply press a button to get a liter of Valencia’s famous orange juice. Taste your orange juice and take note of its sweetness. If its on the bitter side, you may need to add some sugar.", "Pour all the liquid ingredients in your pitcher. Mix together and taste. If you used a bitter cava or type of champagne, this will also affect how much sugar needs to be added. Agua de Valencia is not meant to be a super sugary drink, but it isn’t meant to be bitter either!", "Grab a couple of large wine glasses and pour your fresh Spanish cocktail over ice. Chop a few orange slices and add them as a garnish. Clink your glasses, say “¡Salud!” and enjoy!" ], "image": "agua-de-valencia.jpg", "source":"https://gogoespana.com/en/blog/agua-de-valencia/", "keywords": [ "alcoholic", "fruit", "vegan", "orange", "vodka" ] }
850
435
<gh_stars>100-1000 { "copyright_text": null, "description": "Is it true that Python is not returning memory back to OS? What happens with variables which are no longer needed? How important is a garbage collector? How to trace and profile memory usage?\n\nLet's find out answers to these and maybe some more questions.\n\nTalk overview:\n\nIntroduction: Why do I need to care about memory management in Python? Objects in Python \u2013 what are they?\nMemory management: How memory is being allocated at start/while running \u2013 blocks/pools/arenas? How is memory being freed \u2013 reference counting/garbage collector? Extras - small integer\u2019s identity, sys.intern, sys.getsizeof, lists/dicts dynamic allocations. How to find cycles in variables referencing?\nTools for memory management: Overview of available tools for managing memory. How and why Instagram disabled/re-enabled garbage collector?", "duration": 2081, "language": "eng", "recorded": "2018-06-03", "related_urls": [ { "label": "Conference schedule", "url": "https://cz.pycon.org/2018/programme/schedule/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/ALDUKcg6W9o/hqdefault.jpg", "title": "Bits and bytes of Python memory management", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=ALDUKcg6W9o" } ] }
448
709
<reponame>security-geeks/jackhammer package com.olacabs.jackhammer.models; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.sql.Date; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class HardcodeSecret extends AbstractModel { private long commitsDepth; private Date commitsStartDate; private String regex; }
136
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.match; import com.yahoo.document.Document; import com.yahoo.document.DocumentOperation; import com.yahoo.search.Query; import com.yahoo.search.Result; import com.yahoo.search.Searcher; import com.yahoo.search.searchchain.Execution; /** * A searchable database of documents * * @author bratseth */ public class DocumentDb extends Searcher { /** * Put a document or apply an update to this document db */ public void put(DocumentOperation op) { } /** Remove a document from this document db */ public void remove(Document document) { } /** Search this document db */ @Override public Result search(Query query, Execution execution) { Result r = execution.search(query); return r; } }
276
689
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2019. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #include <ucs/sys/compiler.h> extern int test_module_loaded; UCS_STATIC_INIT { ++test_module_loaded; }
90
1,144
/* SPDX-License-Identifier: GPL-2.0+ */ /* * Copyright (C) 2012 * <NAME> <<EMAIL>> */ #ifndef __ASM_ARCH_MX27_GPIO_H #define __ASM_ARCH_MX27_GPIO_H /* GPIO registers */ struct gpio_regs { u32 gpio_dir; /* DDIR */ u32 ocr1; u32 ocr2; u32 iconfa1; u32 iconfa2; u32 iconfb1; u32 iconfb2; u32 gpio_dr; /* DR */ u32 gius; u32 gpio_psr; /* SSR */ u32 icr1; u32 icr2; u32 imr; u32 isr; u32 gpr; u32 swr; u32 puen; u32 res[0x2f]; }; /* This structure is used by the function imx_gpio_mode */ struct gpio_port_regs { struct gpio_regs port[6]; }; /* * GPIO Module and I/O Multiplexer */ #define PORTA 0 #define PORTB 1 #define PORTC 2 #define PORTD 3 #define PORTE 4 #define PORTF 5 #define GPIO_PIN_MASK 0x1f #define GPIO_PORT_SHIFT 5 #define GPIO_PORT_MASK (0x7 << GPIO_PORT_SHIFT) #define GPIO_PORTA (PORTA << GPIO_PORT_SHIFT) #define GPIO_PORTB (PORTB << GPIO_PORT_SHIFT) #define GPIO_PORTC (PORTC << GPIO_PORT_SHIFT) #define GPIO_PORTD (PORTD << GPIO_PORT_SHIFT) #define GPIO_PORTE (PORTE << GPIO_PORT_SHIFT) #define GPIO_PORTF (PORTF << GPIO_PORT_SHIFT) #endif
520
373
package com.dianrong.common.uniauth.common.client.cxf; import com.dianrong.common.uniauth.common.apicontrol.StringHeaderValueOperator; import com.dianrong.common.uniauth.common.client.cxf.ApiControlHeaderHolder.HeaderHolder; import com.dianrong.common.uniauth.common.client.cxf.exp.InvalidHeaderKeyException; import com.dianrong.common.uniauth.common.util.Assert; /** * 操作cxf的header. * * @author wanglin */ public class CxfHeaderOperator implements StringHeaderValueOperator { @Override public String getHeader(String key) { Assert.notNull(key); HeaderHolder headerHolder = getHeaderHolder(key); return headerHolder.get(key); } @Override public void setHeader(String key, String value) { Assert.notNull(key); HeaderHolder headerHolder = getHeaderHolder(key); headerHolder.set(key, value); } private HeaderHolder getHeaderHolder(String key) { HeaderHolder requestHeaderHolder = ApiControlHeaderHolder.getRequestHeaderHolder(); if (requestHeaderHolder.getAllKeys().contains(key)) { return requestHeaderHolder; } HeaderHolder responseHeaderHolder = ApiControlHeaderHolder.getResponseHeaderHolder(); if (responseHeaderHolder.getAllKeys().contains(key)) { return responseHeaderHolder; } throw new InvalidHeaderKeyException(); } }
452
1,021
<filename>Plugin/Test/ExrTest.cpp #include "pch.h" #include "TestCommon.h" template<class T> void ExrTestImpl(fcIExrContext *ctx, const char *filename) { const int Width = 320; const int Height = 240; int channels = GetPixelFormat<T>::value & fcPixelFormat_ChannelMask; const char *channel_names[] = { "R", "G", "B", "A" }; RawVector<T> video_frame(Width * Height); CreateVideoData(&video_frame[0], Width, Height, 0); fcExrBeginImage(ctx, filename, Width, Height); for (int i = 0; i < channels; ++i) { fcExrAddLayerPixels(ctx, &video_frame[0], GetPixelFormat<T>::value, i, channel_names[i]); } fcExrEndImage(ctx); } void ExrTest() { if (!fcExrIsSupported()) { printf("ExrTest: exr is not supported\n"); return; } printf("ExrTest begin\n"); fcIExrContext *ctx = fcExrCreateContext(); ExrTestImpl<RGBAu8 >(ctx, "RGBAu8.exr"); ExrTestImpl<RGBAf16>(ctx, "RGBAf16.exr"); ExrTestImpl<RGBAf32>(ctx, "RGBAf32.exr"); fcReleaseContext(ctx); printf("ExrTest end\n"); }
503
1,666
#!/usr/bin/env python3 # Copyright 2016 Google Inc. 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. from absl.testing import parameterized from fruit_test_common import * COMMON_DEFINITIONS = ''' #include "test_common.h" struct X {}; struct Y {}; struct Annotation1 {}; using IntAnnot1 = fruit::Annotated<Annotation1, int>; using XAnnot1 = fruit::Annotated<Annotation1, X>; struct Annotation2 {}; using IntAnnot2 = fruit::Annotated<Annotation2, int>; using XAnnot2 = fruit::Annotated<Annotation2, X>; ''' class TestComponentAndInjectorParams(parameterized.TestCase): @multiple_parameters([ ('X', 'X'), ('X', 'const X'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, X>'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, const X>'), ], [ 'Component', 'NormalizedComponent', 'Injector', ]) def test_duplicate_type(self, XAnnot, MaybeConstXAnnot, Class): source = ''' InstantiateType(fruit::Class<MaybeConstXAnnot, MaybeConstXAnnot>) ''' expect_compile_error( 'RepeatedTypesError<XAnnot,XAnnot>', 'A type was specified more than once.', COMMON_DEFINITIONS, source, locals()) @multiple_parameters([ ('X', 'const X'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, const X>'), ], [ 'Component', 'NormalizedComponent', 'Injector', ]) def test_duplicate_type_different_constness(self, XAnnot, ConstXAnnot, Class): source = ''' InstantiateType(fruit::Class<XAnnot, ConstXAnnot>) ''' expect_compile_error( 'RepeatedTypesError<XAnnot,XAnnot>', 'A type was specified more than once.', COMMON_DEFINITIONS, source, locals()) def test_duplicate_type_with_different_annotation_ok(self): source = ''' fruit::Component<XAnnot1, XAnnot2> getComponent() { return fruit::createComponent() .registerConstructor<XAnnot1()>() .registerConstructor<XAnnot2()>(); } int main() { fruit::Injector<XAnnot1, XAnnot2> injector1(getComponent); injector1.get<XAnnot1>(); injector1.get<XAnnot2>(); fruit::NormalizedComponent<XAnnot1, XAnnot2> normalizedComponent(getComponent); fruit::Injector<XAnnot1, XAnnot2> injector2(getComponent); injector2.get<XAnnot1>(); injector2.get<XAnnot2>(); } ''' expect_success( COMMON_DEFINITIONS, source) @multiple_parameters([ ('X', 'X'), ('X', 'const X'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, X>'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, const X>'), ], [ 'Component', 'NormalizedComponent', ]) def test_duplicate_type_in_required(self, XAnnot, MaybeConstXAnnot, Class): source = ''' InstantiateType(fruit::Class<fruit::Required<MaybeConstXAnnot, MaybeConstXAnnot>>) ''' expect_compile_error( 'RepeatedTypesError<XAnnot,XAnnot>', 'A type was specified more than once.', COMMON_DEFINITIONS, source, locals()) @multiple_parameters([ 'Component', 'NormalizedComponent', ], [ ('X', 'const X'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, const X>'), ]) def test_component_duplicate_type_in_required_different_constness(self, Class, XAnnot, ConstXAnnot): source = ''' InstantiateType(fruit::Class<fruit::Required<XAnnot, ConstXAnnot>>) ''' expect_compile_error( 'RepeatedTypesError<XAnnot,XAnnot>', 'A type was specified more than once.', COMMON_DEFINITIONS, source, locals()) @multiple_parameters([ ('X', 'X'), ('X', 'const X'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, X>'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, const X>'), ], [ 'Component', 'NormalizedComponent', ]) def test_same_type_in_required_and_provided(self, XAnnot, MaybeConstXAnnot, Class): source = ''' InstantiateType(fruit::Class<fruit::Required<MaybeConstXAnnot>, MaybeConstXAnnot>) ''' expect_compile_error( 'RepeatedTypesError<XAnnot,XAnnot>', 'A type was specified more than once.', COMMON_DEFINITIONS, source, locals()) @multiple_parameters([ ('X', 'X', 'const X'), ('X', 'const X', 'X'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, const X>'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation1, const X>', 'fruit::Annotated<Annotation1, X>'), ], [ 'Component', 'NormalizedComponent', ]) def test_same_type_in_required_and_provided_different_constness(self, XAnnot, XAnnotInRequirements, XAnnotInProvides, Class): source = ''' InstantiateType(fruit::Class<fruit::Required<XAnnotInRequirements>, XAnnotInProvides>) ''' expect_compile_error( 'RepeatedTypesError<XAnnot,XAnnot>', 'A type was specified more than once.', COMMON_DEFINITIONS, source, locals()) def test_same_type_in_required_and_provided_different_annotation_ok(self): source = ''' fruit::Component<fruit::Required<XAnnot1>, XAnnot2> getComponent() { return fruit::createComponent() .registerConstructor<XAnnot2()>(); } fruit::Component<XAnnot1, XAnnot2> getRootComponent() { return fruit::createComponent() .install(getComponent) .registerConstructor<XAnnot1()>(); } fruit::Component<> getEmptyComponent() { return fruit::createComponent(); } int main() { fruit::Injector<XAnnot1, XAnnot2> injector1(getRootComponent); injector1.get<XAnnot1>(); injector1.get<XAnnot2>(); fruit::NormalizedComponent<XAnnot1, XAnnot2> normalizedComponent(getRootComponent); fruit::Injector<XAnnot1, XAnnot2> injector2(normalizedComponent, getEmptyComponent); injector2.get<XAnnot1>(); injector2.get<XAnnot2>(); } ''' expect_success( COMMON_DEFINITIONS, source) @multiple_parameters([ ('X*', r'X\*'), ('const X*', r'const X\*'), ('X&', r'X&'), ('const X&', r'const X&'), ('std::shared_ptr<X>', r'std::shared_ptr<X>'), ('fruit::Annotated<Annotation1, X*>', r'X\*'), ('fruit::Annotated<Annotation1, const X*>', r'const X\*'), ('fruit::Annotated<Annotation1, X&>', r'X&'), ('fruit::Annotated<Annotation1, const X&>', r'const X&'), ('fruit::Annotated<Annotation1, std::shared_ptr<X>>', r'std::shared_ptr<X>'), ], [ 'Component', 'NormalizedComponent', 'Injector', ]) def test_error_non_class_type(self, XVariantAnnot, XVariantRegexp, Class): source = ''' InstantiateType(fruit::Class<XVariantAnnot>) ''' expect_compile_error( 'NonClassTypeError<XVariantRegexp,X>', 'A non-class type T was specified. Use C instead.', COMMON_DEFINITIONS, source, locals()) @multiple_parameters([ ('const X', 'const X'), ('fruit::Annotated<Annotation1, const X>', 'const X'), ], [ 'Component', 'NormalizedComponent', 'Injector', ]) def test_const_provided_type_ok(self, XVariantAnnot, XVariantRegexp, Class): source = ''' InstantiateType(fruit::Class<XVariantAnnot>) ''' expect_success( COMMON_DEFINITIONS, source, locals()) @multiple_parameters([ ('X*', r'X\*'), ('const X*', r'const X\*'), ('X&', r'X&'), ('const X&', r'const X&'), ('std::shared_ptr<X>', r'std::shared_ptr<X>'), ('fruit::Annotated<Annotation1, X*>', r'X\*'), ('fruit::Annotated<Annotation1, const X*>', r'const X\*'), ('fruit::Annotated<Annotation1, X&>', r'X&'), ('fruit::Annotated<Annotation1, const X&>', r'const X&'), ('fruit::Annotated<Annotation1, std::shared_ptr<X>>', r'std::shared_ptr<X>'), ], [ 'Component', 'NormalizedComponent', ]) def test_error_non_class_type_in_requirements(self, XVariantAnnot, XVariantRegexp, Class): source = ''' InstantiateType(fruit::Class<fruit::Required<XVariantAnnot>>) ''' expect_compile_error( 'NonClassTypeError<XVariantRegexp,X>', 'A non-class type T was specified. Use C instead.', COMMON_DEFINITIONS, source, locals()) @parameterized.parameters([ ('const Z', 'Z'), ('fruit::Annotated<Annotation1, const Z>', 'fruit::Annotated<Annotation1, Z>'), ]) def test_const_class_type_ok(self, ConstZAnnot, ZAnnot): source = ''' struct Z {}; const Z z{}; fruit::Component<ConstZAnnot> getComponent() { return fruit::createComponent() .bindInstance<ZAnnot, Z>(z); } fruit::Component<> getEmptyComponent() { return fruit::createComponent(); } int main() { fruit::NormalizedComponent<ConstZAnnot> normalizedComponent(getComponent); fruit::Injector<ConstZAnnot> injector(normalizedComponent, getEmptyComponent); injector.get<ZAnnot>(); } ''' expect_success( COMMON_DEFINITIONS, source, locals()) @parameterized.parameters([ ('const Z', 'Z'), ('fruit::Annotated<Annotation1, const Z>', 'fruit::Annotated<Annotation1, Z>'), ]) def test_const_class_type_in_requirements_ok(self, ConstZAnnot, ZAnnot): source = ''' struct Z {}; fruit::Component<fruit::Required<ConstZAnnot>> getComponent() { return fruit::createComponent(); } const Z z{}; fruit::Component<ConstZAnnot> getEmptyComponent() { return fruit::createComponent() .bindInstance<ZAnnot, Z>(z); } int main() { fruit::NormalizedComponent<fruit::Required<ConstZAnnot>> normalizedComponent(getComponent); fruit::Injector<ConstZAnnot> injector(normalizedComponent, getEmptyComponent); injector.get<ZAnnot>(); } ''' expect_success( COMMON_DEFINITIONS, source, locals()) @parameterized.parameters([ 'Component', 'NormalizedComponent', ]) def test_two_required_lists_error(self, Class): source = ''' InstantiateType(fruit::Class<fruit::Required<X>, fruit::Required<Y>>) ''' expect_compile_error( 'RequiredTypesInComponentArgumentsError<fruit::Required<Y>>', 'A Required<...> type was passed as a non-first template parameter to fruit::Component or fruit::NormalizedComponent', COMMON_DEFINITIONS, source, locals()) @parameterized.parameters([ 'Component', 'NormalizedComponent', ]) def test_required_list_not_first_argument_error(self, Class): source = ''' InstantiateType(fruit::Class<X, fruit::Required<Y>>) ''' expect_compile_error( 'RequiredTypesInComponentArgumentsError<fruit::Required<Y>>', 'A Required<...> type was passed as a non-first template parameter to fruit::Component or fruit::NormalizedComponent', COMMON_DEFINITIONS, source, locals()) def test_multiple_required_types_ok(self): source = ''' fruit::Component<fruit::Required<X, Y>> getEmptyComponent() { return fruit::createComponent(); } fruit::Component<X, Y> getComponent() { return fruit::createComponent() .install(getEmptyComponent) .registerConstructor<X()>() .registerConstructor<Y()>(); } int main() { fruit::NormalizedComponent<fruit::Required<X, Y>> normalizedComponent(getEmptyComponent); fruit::Injector<X> injector(normalizedComponent, getComponent); injector.get<X>(); } ''' expect_success( COMMON_DEFINITIONS, source) @parameterized.parameters([ ('X', 'Y'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation2, Y>'), ]) def test_error_requirements_in_injector(self, XAnnot, YAnnot): source = ''' InstantiateType(fruit::Injector<fruit::Required<YAnnot>, XAnnot>) ''' expect_compile_error( 'InjectorWithRequirementsError<YAnnot>', 'Injectors can.t have requirements.', COMMON_DEFINITIONS, source, locals()) @parameterized.parameters([ ('X', 'Y'), ('fruit::Annotated<Annotation1, X>', 'fruit::Annotated<Annotation2, Y>'), ]) def test_error_requirements_in_injector_second_argument(self, XAnnot, YAnnot): source = ''' InstantiateType(fruit::Injector<XAnnot, fruit::Required<YAnnot>>) ''' expect_compile_error( 'InjectorWithRequirementsError<YAnnot>', 'Injectors can.t have requirements.', COMMON_DEFINITIONS, source, locals()) if __name__ == '__main__': absltest.main()
7,395
782
/* * Copyright (c) 2020, <NAME>. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.transform.pyramid; import boofcv.alg.misc.ImageMiscOps; import boofcv.struct.image.GrayF32; import boofcv.struct.image.ImageType; import boofcv.testing.BoofStandardJUnit; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; /** * @author <NAME> */ class TestPyramidDiscreteNN2 extends BoofStandardJUnit { @Test void basicTest() { GrayF32 input = new GrayF32(40, 80); ImageMiscOps.fillUniform(input, rand, -20, 50); PyramidDiscreteNN2<GrayF32> alg = new PyramidDiscreteNN2<>(ImageType.single(GrayF32.class)); alg.getConfigLayers().numLevelsRequested = 3; checkSolution(input, alg); } private void checkSolution( GrayF32 input, PyramidDiscreteNN2<GrayF32> alg ) { alg.process(input); // Level zero is the input image assertSame(input, alg.getLayer(0)); // There should be 3 levels assertEquals(3, alg.getLevelsCount()); // nearest-neighbor interpolation assertEquals(input.get(0, 0), alg.getLayer(1).get(0, 0), 1e-4); assertEquals(input.get(2, 2), alg.getLayer(1).get(1, 1), 1e-4); assertEquals(input.get(6, 4), alg.getLayer(1).get(3, 2), 1e-4); } }
657
568
<reponame>khesoem/nfe<filename>src/test/java/com/fincatto/documentofiscal/nfe400/classes/nota/NFNotaInfoItemImpostoCOFINSAliquotaTest.java package com.fincatto.documentofiscal.nfe400.classes.nota; import com.fincatto.documentofiscal.nfe400.FabricaDeObjetosFake; import com.fincatto.documentofiscal.nfe400.classes.NFNotaInfoSituacaoTributariaCOFINS; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; public class NFNotaInfoItemImpostoCOFINSAliquotaTest { @Test(expected = NumberFormatException.class) public void naoDevePermitirValorTamanhoInvalido() { new NFNotaInfoItemImpostoCOFINSAliquota().setValor(new BigDecimal("10000000000000")); } @Test(expected = NumberFormatException.class) public void naoDevePermitirValorBaseCaluloTamanhoInvalido() { new NFNotaInfoItemImpostoCOFINSAliquota().setValorBaseCalculo(new BigDecimal("10000000000000")); } @Test(expected = NumberFormatException.class) public void naoDevePermitirPercentualAliquotaTamanhoInvalido() { new NFNotaInfoItemImpostoCOFINSAliquota().setPercentualAliquota(new BigDecimal("1000")); } @Test(expected = IllegalStateException.class) public void naoDeveValorBaseCalculoNulo() { final NFNotaInfoItemImpostoCOFINSAliquota cofinsAliquota = new NFNotaInfoItemImpostoCOFINSAliquota(); cofinsAliquota.setPercentualAliquota(new BigDecimal("99.99")); cofinsAliquota.setSituacaoTributaria(NFNotaInfoSituacaoTributariaCOFINS.CREDITO_PRESUMIDO_OUTRAS_OPERACOES); cofinsAliquota.setValor(new BigDecimal("999999999999.99")); cofinsAliquota.toString(); } @Test(expected = IllegalStateException.class) public void naoDeveValorAliquotaNulo() { final NFNotaInfoItemImpostoCOFINSAliquota cofinsAliquota = new NFNotaInfoItemImpostoCOFINSAliquota(); cofinsAliquota.setPercentualAliquota(new BigDecimal("99.99")); cofinsAliquota.setSituacaoTributaria(NFNotaInfoSituacaoTributariaCOFINS.CREDITO_PRESUMIDO_OUTRAS_OPERACOES); cofinsAliquota.setValorBaseCalculo(new BigDecimal("999999999999.99")); cofinsAliquota.toString(); } @Test(expected = IllegalStateException.class) public void naoDeveSituacaoTributariaAliquotaNulo() { final NFNotaInfoItemImpostoCOFINSAliquota cofinsAliquota = new NFNotaInfoItemImpostoCOFINSAliquota(); cofinsAliquota.setPercentualAliquota(new BigDecimal("99.99")); cofinsAliquota.setValor(new BigDecimal("999999999999.99")); cofinsAliquota.setValorBaseCalculo(new BigDecimal("999999999999.99")); cofinsAliquota.toString(); } @Test(expected = IllegalStateException.class) public void naoDevePermitirPercentualAliquotaNulo() { final NFNotaInfoItemImpostoCOFINSAliquota cofinsAliquota = new NFNotaInfoItemImpostoCOFINSAliquota(); cofinsAliquota.setSituacaoTributaria(NFNotaInfoSituacaoTributariaCOFINS.CREDITO_PRESUMIDO_OUTRAS_OPERACOES); cofinsAliquota.setValor(new BigDecimal("999999999999.99")); cofinsAliquota.setValorBaseCalculo(new BigDecimal("999999999999.99")); cofinsAliquota.toString(); } @Test public void deveGerarXMLDeAcordoComOPadraoEstabelecido() { final String xmlEsperado = "<NFNotaInfoItemImpostoCOFINSAliquota><CST>01</CST><vBC>999999999999.99</vBC><pCOFINS>99.99</pCOFINS><vCOFINS>999999999999.99</vCOFINS></NFNotaInfoItemImpostoCOFINSAliquota>"; Assert.assertEquals(xmlEsperado, FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSAliquota().toString()); } }
1,547
718
<reponame>SoccerField24x7/tomighty<gh_stars>100-1000 /* * Copyright (c) 2010-2012 <NAME>. * * 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 org.tomighty.resources.cache; import java.io.File; import com.google.inject.Injector; import org.tomighty.config.Directories; import javax.inject.Inject; public class Caches { @Inject private Injector injector; private File rootDirectory; @Inject public Caches(Directories directories) { rootDirectory = new File(directories.configuration(), "cache"); } public Cache of(Class<? extends EntryType> type) { EntryType entryType = injector.getInstance(type); String cacheName = entryType.name(); File directory = new File(rootDirectory, cacheName); Cache cache = new Cache(entryType, directory); return cache; } }
430
473
/* * Copyright (C) <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "libcgc.h" #include "cgc_libc.h" #include "cgc_service.h" int cgc_nextRecord(Record* record) { int bytesRead = 0; int ret; bytesRead = cgc_recv(STDIN, (char *)record, sizeof(Record)); if(bytesRead < 0) cgc__terminate(RECEIVE_ERROR); if(record->x == BALANCE_RECORD) return BALANCE_RECORD; if(record->x > 0 && record->y > 0 && record->x < 0xFFFF) return STOCK_RECORD; return NO_MORE_RECORDS; } float cgc_squareRoot(float value) { float low, high, mid, oldmid, midsqr; low = 0; high = mid = value; oldmid = -1; while (cgc_fabs(oldmid - mid) >= 0.001) { oldmid = mid; mid = (high + low) / 2; midsqr = mid * mid; if (mid * mid > value) { high = mid; } else { low = mid; } } return mid; } void cgc_addRecordToDataset(Dataset* dataset, Record record) { float priceRelative, oldMean; dataset->sampleSize++; priceRelative = (float)record.x/record.y; oldMean = dataset->mean; dataset->mean = oldMean + (priceRelative - oldMean) / dataset->sampleSize; dataset->Q = dataset->Q + (priceRelative - oldMean) * (priceRelative - dataset->mean); dataset->variance = dataset->Q / dataset->sampleSize; dataset->stdDev = cgc_squareRoot(dataset->variance); } Stock* cgc_getNextFreeEntry(Portfolio* portfolio) { int entry; for(entry=0; entry<portfolio->numEntries; entry++) { Stock* stock; stock = &portfolio->stocks[entry]; if(stock->symbol == 0) { return stock; } } int ret, oldNumEntries; Stock* oldStocks; oldStocks = portfolio->stocks; oldNumEntries = portfolio->numEntries; #ifdef PATCHED // The first integer overflow, will set numEntries to 0, which will cause allocate to error and a _terminate to occur. portfolio->numEntries = oldNumEntries*16; #else // Causes numEntries to be set to 65, which will cause a Segmentation Fault when entry = 66 on the for loop. portfolio->numEntries = oldNumEntries*64 + 1; #endif ret = cgc_allocate(sizeof(Stock)*portfolio->numEntries, 0, (void **) &portfolio->stocks); if(ret != 0) cgc__terminate(ALLOCATE_ERROR); for(entry=0; entry<oldNumEntries; entry++) { portfolio->stocks[entry].symbol = oldStocks[entry].symbol; portfolio->stocks[entry].purchasedPrice = oldStocks[entry].purchasedPrice; portfolio->stocks[entry].currentPrice = oldStocks[entry].currentPrice; } ret = cgc_deallocate(oldStocks, sizeof(Stock)*oldNumEntries); if(ret !=0) cgc__terminate(DEALLOCATE_ERROR); return &portfolio->stocks[oldNumEntries]; } void cgc_addStockToPortfolio(Stock stock, Portfolio* portfolio) { Stock* newStock; newStock = cgc_getNextFreeEntry(portfolio); newStock->symbol = stock.symbol; newStock->purchasedPrice = stock.purchasedPrice; newStock->currentPrice = stock.currentPrice; } void cgc_buyStock(const char symbol, unsigned int price, Portfolio* portfolio) { if(portfolio->cashBalance >= price) { Stock stock; stock.symbol = symbol; stock.purchasedPrice = price; stock.currentPrice = price; cgc_addStockToPortfolio(stock, portfolio); portfolio->cashBalance -= price; } } Stock* cgc_findMostExpensiveStock(char symbol, Portfolio* portfolio) { Stock* mostExpensiveStock=NULL; int entry; int price=0; // Checks to make sure portfolio has been initiated. for(entry = 0; portfolio->numEntries > 0 && portfolio->stocks[entry].purchasedPrice != 0 && entry<portfolio->numEntries; entry++) { Stock* stock; stock = &portfolio->stocks[entry]; if(stock->symbol == symbol) { if(stock->purchasedPrice > price) { mostExpensiveStock = stock; price = stock->purchasedPrice; } } } return mostExpensiveStock; } void cgc_sellStock(char symbol, unsigned int price, Portfolio* portfolio) { if(portfolio->numEntries > 0) { Stock *stock; stock = cgc_findMostExpensiveStock(symbol, portfolio); if(stock != NULL) { portfolio->cashBalance += price; // remove stock form portfolio stock->symbol = 0; stock->purchasedPrice = 0; stock->currentPrice = 0; } } } void cgc_tradeStocks(Record record, Dataset dataset, Portfolio* portfolio) { float priceRelative; priceRelative = (float)record.x / record.y; if(priceRelative > dataset.mean + dataset.stdDev) { cgc_sellStock(X_STR, record.x, portfolio); cgc_buyStock(Y_STR, record.y, portfolio); } if(priceRelative < dataset.mean - dataset.stdDev) { cgc_sellStock(Y_STR, record.y, portfolio); cgc_buyStock(X_STR, record.x, portfolio); } } void cgc_sendGoalNotification() { int ret; ret = cgc_transmit_all(STDOUT, GOAL_STR, cgc_strlen(GOAL_STR)); if(ret != 0) cgc__terminate(TRANSMIT_ERROR); } void cgc_sellAllStock(Record record, Portfolio* portfolio) { int entry; #ifdef PATCHED // Checks to make sure portfolio has been initiated. for(entry = 0; portfolio->numEntries > 0 && portfolio->stocks[entry].purchasedPrice != 0 && entry<portfolio->numEntries; entry++) { #else // If a Balance record has not been set, then portfolio isn't initailized and the for loop condition will cause a Segementation fault. for(entry = 0; portfolio->stocks[entry].purchasedPrice != 0; entry++) { #endif cgc_sellStock(portfolio->stocks[entry].symbol, portfolio->stocks[entry].currentPrice, portfolio); } } void cgc_updateStockValues(Record record, Portfolio* portfolio) { int entry; #ifdef PATCHED // Checks to make sure portfolio has been initiated. for(entry = 0; portfolio->numEntries > 0 && portfolio->stocks[entry].purchasedPrice != 0 && entry<portfolio->numEntries; entry++) { #else // If a Balance record has not been set, then portfolio isn't initailized and the for loop condition will cause a Segementation fault. for(entry = 0; portfolio->stocks[entry].purchasedPrice != 0; entry++) { #endif Stock* stock; stock = &portfolio->stocks[entry]; portfolio->assetBalance -= stock->currentPrice; if(stock->symbol == X_STR) stock->currentPrice = record.x; if(stock->symbol == Y_STR) stock->currentPrice = record.y; portfolio->assetBalance += stock->currentPrice; } } void cgc_initPortfolio(Portfolio* portfolio, unsigned int startingBalance) { int ret; portfolio->cashBalance = startingBalance; portfolio->assetBalance = portfolio->cashBalance; portfolio->goal = portfolio->assetBalance*2; portfolio->numEntries = INIT_ENTRY_LIST; ret = cgc_allocate(sizeof(Stock)*portfolio->numEntries, 0, (void **) &portfolio->stocks); if(ret != 0) cgc__terminate(ALLOCATE_ERROR); } int main(int cgc_argc, char *cgc_argv[]) { Dataset dataset; Portfolio portfolio; Record record; int recordType; dataset.sampleSize = 0; while((recordType = cgc_nextRecord(&record)) != NO_MORE_RECORDS) { if(recordType == BALANCE_RECORD) { cgc_initPortfolio(&portfolio, record.y); continue; } if(dataset.sampleSize > LEARNING_MODE_SIZE) { cgc_updateStockValues(record, &portfolio); if(portfolio.assetBalance >= portfolio.goal) { cgc_sellAllStock(record, &portfolio); cgc_sendGoalNotification(); } // check to see if out of cash if(portfolio.cashBalance == 0) { // If out of stock, quit if(portfolio.assetBalance == 0) break; // sell all stock to raise cash cgc_sellAllStock(record, &portfolio); } cgc_tradeStocks(record, dataset, &portfolio); } cgc_addRecordToDataset(&dataset, record); } return 0; }
2,992
3,055
<gh_stars>1000+ /* u8x8_d_ssd1326.c Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) Copyright (c) 2016, <EMAIL> 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "u8x8.h" /* ER OLED */ static const uint8_t u8x8_d_ssd1326_er_256x32_init_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_CA(0x0fd, 0x012), /* unlock (not required, this is default by reset) */ U8X8_C(0x0ae), /* display off */ U8X8_CA(0x0a8, 0x01f), /* multiplex ratio: 0x03f * 1/64 duty - changed by CREESOO, acc. to datasheet, 100317*/ U8X8_CA(0x0a1, 0x000), /* display start line */ U8X8_CA(0x0a2, 0x000), /* display offset, shift mapping ram counter */ //U8X8_CA(0x0ad, 0x002), /* master configuration: disable embedded DC-DC, enable internal VCOMH */ U8X8_CA(0x0a0, 0x052), /* remap configuration, horizontal address increment (bit 2 = 0), enable nibble remap (upper nibble is left, bit 1 = 1) */ U8X8_C(0x086), /* full current range (0x084, 0x085, 0x086) */ U8X8_C(0x0b7), /* set default gray scale table */ U8X8_CA(0x081, 0x027), /* contrast, brightness, 0..128 */ U8X8_CA(0x0b1, 0x071), /* phase length */ //U8X8_CA(0x0b2, 0x051), /* frame frequency (row period) */ U8X8_CA(0x0b3, 0x0f0), /* set display clock divide ratio/oscillator frequency (set clock as 135 frames/sec) */ //U8X8_CA(0x0b4, 0x002), /* set pre-charge compensation level (not documented in the SDD1325 datasheet, but used in the NHD init seq.) */ //U8X8_CA(0x0b0, 0x028), /* enable pre-charge compensation (not documented in the SDD1325 datasheet, but used in the NHD init seq.) */ U8X8_CAA(0x0bb, 0x035, 0x0ff), /* set precharge */ U8X8_CA(0x0bc, 0x01f), /* pre-charge voltage level */ U8X8_CA(0x0be, 0x00f), /* VCOMH voltage */ U8X8_CA(0x0bf, 0x002|0x00d), /* VSL voltage level (not documented in the SDD1325 datasheet, but used in the NHD init seq.) */ U8X8_C(0x0a4), /* normal display mode */ //U8X8_CA(0x023, 0x003), /* graphics accelleration: fill pixel */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; static const uint8_t u8x8_d_ssd1326_256x32_nhd_powersave0_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_C(0x0af), /* display on */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; static const uint8_t u8x8_d_ssd1326_256x32_nhd_powersave1_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_C(0x0ae), /* display off */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; static const uint8_t u8x8_d_ssd1326_256x32_nhd_flip0_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_CA(0x0a0, 0x052), /* remap */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; static const uint8_t u8x8_d_ssd1326_256x32_nhd_flip1_seq[] = { U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ U8X8_CA(0x0a0, 0x041), /* remap */ U8X8_END_TRANSFER(), /* disable chip */ U8X8_END() /* end of sequence */ }; /* input: one tile (8 Bytes) output: Tile for ssd1326 (32 Bytes) */ static uint8_t u8x8_ssd1326_8to32_dest_buf[32]; static uint8_t *u8x8_ssd1326_8to32(U8X8_UNUSED u8x8_t *u8x8, uint8_t *ptr) { uint8_t v; uint8_t a,b; uint8_t i, j; uint8_t *dest; for( j = 0; j < 4; j++ ) { dest = u8x8_ssd1326_8to32_dest_buf; dest += j; a =*ptr; ptr++; b = *ptr; ptr++; for( i = 0; i < 8; i++ ) { v = 0; if ( a&1 ) v |= 0xf0; if ( b&1 ) v |= 0x0f; *dest = v; dest+=4; a >>= 1; b >>= 1; } } return u8x8_ssd1326_8to32_dest_buf; } static uint8_t u8x8_d_ssd1326_256x32_generic(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr) { uint8_t x, y, c; uint8_t *ptr; switch(msg) { /* handled by the calling function case U8X8_MSG_DISPLAY_SETUP_MEMORY: u8x8_d_helper_display_setup_memory(u8x8, &u8x8_ssd1326_256x32_nhd_display_info); break; */ case U8X8_MSG_DISPLAY_INIT: u8x8_d_helper_display_init(u8x8); u8x8_cad_SendSequence(u8x8, u8x8_d_ssd1326_er_256x32_init_seq); break; case U8X8_MSG_DISPLAY_SET_POWER_SAVE: if ( arg_int == 0 ) u8x8_cad_SendSequence(u8x8, u8x8_d_ssd1326_256x32_nhd_powersave0_seq); else u8x8_cad_SendSequence(u8x8, u8x8_d_ssd1326_256x32_nhd_powersave1_seq); break; case U8X8_MSG_DISPLAY_SET_FLIP_MODE: if ( arg_int == 0 ) { u8x8_cad_SendSequence(u8x8, u8x8_d_ssd1326_256x32_nhd_flip0_seq); u8x8->x_offset = u8x8->display_info->default_x_offset; } else { u8x8_cad_SendSequence(u8x8, u8x8_d_ssd1326_256x32_nhd_flip1_seq); u8x8->x_offset = u8x8->display_info->flipmode_x_offset; } break; #ifdef U8X8_WITH_SET_CONTRAST case U8X8_MSG_DISPLAY_SET_CONTRAST: u8x8_cad_StartTransfer(u8x8); u8x8_cad_SendCmd(u8x8, 0x081 ); u8x8_cad_SendArg(u8x8, arg_int ); /* ssd1326 has range from 0 to 255 */ u8x8_cad_EndTransfer(u8x8); break; #endif case U8X8_MSG_DISPLAY_DRAW_TILE: u8x8_cad_StartTransfer(u8x8); x = ((u8x8_tile_t *)arg_ptr)->x_pos; x *= 4; y = (((u8x8_tile_t *)arg_ptr)->y_pos); y *= 8; y += u8x8->x_offset; /* x_offset is used as y offset for the ssd1326 */ do { c = ((u8x8_tile_t *)arg_ptr)->cnt; ptr = ((u8x8_tile_t *)arg_ptr)->tile_ptr; do { /* tile is empty, use the graphics acceleration command */ /* are this really available on the ssd1326??? */ u8x8_cad_SendCmd(u8x8, 0x024 ); // draw rectangle u8x8_cad_SendArg(u8x8, x ); u8x8_cad_SendArg(u8x8, y ); u8x8_cad_SendArg(u8x8, x+3 ); u8x8_cad_SendArg(u8x8, y+7 ); u8x8_cad_SendArg(u8x8, 0 ); // clear ptr += 8; x += 4; c--; } while( c > 0 ); //x += 4; arg_int--; } while( arg_int > 0 ); u8x8_cad_EndTransfer(u8x8); break; default: return 0; } return 1; } static const u8x8_display_info_t u8x8_ssd1326_256x32_display_info = { /* chip_enable_level = */ 0, /* chip_disable_level = */ 1, /* post_chip_enable_wait_ns = */ 20, /* pre_chip_disable_wait_ns = */ 15, /* reset_pulse_width_ms = */ 100, /* post_reset_wait_ms = */ 100, /**/ /* sda_setup_time_ns = */ 100, /* ssd1326 */ /* sck_pulse_width_ns = */ 100, /* ssd1326 */ /* sck_clock_hz = */ 4000000UL, /* since Arduino 1.6.0, the SPI bus speed in Hz. Should be 1000000000/sck_pulse_width_ns */ /* spi_mode = */ 0, /* active high, rising edge */ /* i2c_bus_clock_100kHz = */ 4, /* data_setup_time_ns = */ 40, /* write_pulse_width_ns = */ 60, /* ssd1326 */ /* tile_width = */ 32, /* tile_hight = */ 4, /* default_x_offset = */ 0, /* x_offset is used as y offset for the ssd1326 */ /* flipmode_x_offset = */ 0, /* x_offset is used as y offset for the ssd1326 */ /* pixel_width = */ 256, /* pixel_height = */ 32 }; uint8_t u8x8_d_ssd1326_er_256x32(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr) { if ( msg == U8X8_MSG_DISPLAY_SETUP_MEMORY ) { u8x8_d_helper_display_setup_memory(u8x8, &u8x8_ssd1326_256x32_display_info); return 1; } return u8x8_d_ssd1326_256x32_generic(u8x8, msg, arg_int, arg_ptr); }
4,564
313
<filename>titus-api/src/test/java/com/netflix/titus/api/loadbalancer/model/sanitizer/DefaultLoadBalancerJobValidatorTest.java /* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.api.loadbalancer.model.sanitizer; import java.util.Optional; import java.util.concurrent.TimeUnit; import com.netflix.titus.api.jobmanager.model.job.Container; import com.netflix.titus.api.jobmanager.model.job.ContainerResources; import com.netflix.titus.api.jobmanager.model.job.Image; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.JobState; import com.netflix.titus.api.jobmanager.model.job.JobStatus; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.service.JobManagerException; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.service.LoadBalancerException; import com.netflix.titus.api.loadbalancer.store.LoadBalancerStore; import com.netflix.titus.runtime.store.v3.memory.InMemoryLoadBalancerStore; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultLoadBalancerJobValidatorTest { private static Logger logger = LoggerFactory.getLogger(DefaultLoadBalancerJobValidatorTest.class); private static final long TIMEOUT_MS = 30_000; private V3JobOperations jobOperations; private LoadBalancerStore loadBalancerStore; private LoadBalancerValidationConfiguration loadBalancerValidationConfiguration; private DefaultLoadBalancerJobValidator loadBalancerValidator; private static final String JOB_ID = "Titus-123"; @Before public void setUp() throws Exception { jobOperations = mock(V3JobOperations.class); loadBalancerStore = new InMemoryLoadBalancerStore(); loadBalancerValidationConfiguration = mock(LoadBalancerValidationConfiguration.class); loadBalancerValidator = new DefaultLoadBalancerJobValidator(jobOperations, loadBalancerStore, loadBalancerValidationConfiguration); } @Test public void testValidateJobExists() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.empty()); Throwable thrown = catchThrowable(() -> loadBalancerValidator.validateJobId(JOB_ID)); assertThat(thrown).isInstanceOf(JobManagerException.class); assertThat(((JobManagerException) thrown).getErrorCode()).isEqualTo(JobManagerException.ErrorCode.JobNotFound); } @Test public void testValidateJobAccepted() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.of(Job.newBuilder() .withId(JOB_ID) .withStatus(JobStatus.newBuilder() .withState(JobState.Finished) .build()) .build())); Throwable thrown = catchThrowable(() -> loadBalancerValidator.validateJobId(JOB_ID)); assertThat(thrown).isInstanceOf(JobManagerException.class); assertThat(((JobManagerException) thrown).getErrorCode()).isEqualTo(JobManagerException.ErrorCode.UnexpectedJobState); } @Test public void testValidateJobIsService() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.of(Job.<BatchJobExt>newBuilder() .withId(JOB_ID) .withStatus(JobStatus.newBuilder() .withState(JobState.Accepted) .build()) .withJobDescriptor(JobDescriptor.<BatchJobExt>newBuilder() .build()) .build())); Throwable thrown = catchThrowable(() -> loadBalancerValidator.validateJobId(JOB_ID)); assertThat(thrown).isInstanceOf(JobManagerException.class); assertThat(((JobManagerException) thrown).getErrorCode()).isEqualTo(JobManagerException.ErrorCode.NotServiceJob); } @Test public void testValidateMaxLoadBalancers() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.of(Job.<ServiceJobExt>newBuilder() .withId(JOB_ID) .withStatus(JobStatus.newBuilder() .withState(JobState.Accepted) .build()) .withJobDescriptor(JobDescriptor.<ServiceJobExt>newBuilder() .withExtensions(ServiceJobExt.newBuilder().build()) .withContainer(Container.newBuilder() .withImage(Image.newBuilder().build()) .withContainerResources(ContainerResources.newBuilder() .withAllocateIP(true) .build()) .build()) .build()) .build())); when(loadBalancerValidationConfiguration.getMaxLoadBalancersPerJob()).thenReturn(30); for (int i = 0; i < loadBalancerValidationConfiguration.getMaxLoadBalancersPerJob() + 1; i++) { loadBalancerStore.addOrUpdateLoadBalancer(new JobLoadBalancer(JOB_ID, "LoadBalancer-" + i), JobLoadBalancer.State.ASSOCIATED).await(TIMEOUT_MS, TimeUnit.MILLISECONDS); } Throwable thrown = catchThrowable(() -> loadBalancerValidator.validateJobId(JOB_ID)); assertThat(thrown).isInstanceOf(LoadBalancerException.class); assertThat(((LoadBalancerException) thrown).getErrorCode()).isEqualTo(LoadBalancerException.ErrorCode.JobMaxLoadBalancers); } @Test public void testValidJob() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.of(Job.<ServiceJobExt>newBuilder() .withId(JOB_ID) .withStatus(JobStatus.newBuilder() .withState(JobState.Accepted) .build()) .withJobDescriptor(JobDescriptor.<ServiceJobExt>newBuilder() .withExtensions(ServiceJobExt.newBuilder().build()) .withContainer(Container.newBuilder() .withImage(Image.newBuilder().build()) .withContainerResources(ContainerResources.newBuilder() .withAllocateIP(true) .build()) .build()) .build()) .build())); assertThatCode(() -> loadBalancerValidator.validateJobId(JOB_ID)).doesNotThrowAnyException(); } }
3,161
1,253
// // FILE: unit_test_001.cpp // AUTHOR: <NAME> // VERSION: 0.1.0 // DATE: 2020-12-03 // PURPOSE: unit tests for the SHT31 temperature and humidity sensor // https://github.com/RobTillaart/SHT31 // https://www.adafruit.com/product/2857 // https://github.com/Arduino-CI/arduino_ci/blob/master/REFERENCE.md // // supported assertions // ---------------------------- // assertEqual(expected, actual) // assertNotEqual(expected, actual) // assertLess(expected, actual) // assertMore(expected, actual) // assertLessOrEqual(expected, actual) // assertMoreOrEqual(expected, actual) // assertTrue(actual) // assertFalse(actual) // assertNull(actual) /* most unit tests will test for fail as there is no sensor connected and there is no mockup. It appears that Wire.write does not fail without sensor... */ #include <ArduinoUnitTests.h> #include "Arduino.h" #include "SHT31.h" int expect; // TODO needed as there seems a problem with 8 bit comparisons (char?) uint32_t start, stop; unittest_setup() { fprintf(stderr, "SHT31_LIB_VERSION: %s\n", (char *) SHT31_LIB_VERSION); } unittest_teardown() { } unittest(test_constants_1) { fprintf(stderr, "fields readStatus\n"); assertEqual(SHT31_STATUS_ALERT_PENDING , (1 << 15) ); assertEqual(SHT31_STATUS_HEATER_ON , (1 << 13) ); assertEqual(SHT31_STATUS_HUM_TRACK_ALERT , (1 << 11) ); assertEqual(SHT31_STATUS_TEMP_TRACK_ALERT, (1 << 10) ); assertEqual(SHT31_STATUS_SYSTEM_RESET , (1 << 4) ); assertEqual(SHT31_STATUS_COMMAND_STATUS , (1 << 1) ); assertEqual(SHT31_STATUS_WRITE_CRC_STATUS, (1 << 0) ); } unittest(test_constants_2) { fprintf(stderr, "error codes\n"); assertEqual(SHT31_OK , 0x00); assertEqual(SHT31_ERR_WRITECMD , 0x81); assertEqual(SHT31_ERR_READBYTES , 0x82); assertEqual(SHT31_ERR_HEATER_OFF , 0x83); assertEqual(SHT31_ERR_NOT_CONNECT , 0x84); assertEqual(SHT31_ERR_CRC_TEMP , 0x85); assertEqual(SHT31_ERR_CRC_HUM , 0x86); assertEqual(SHT31_ERR_CRC_STATUS , 0x87); assertEqual(SHT31_ERR_HEATER_COOLDOWN, 0x88); assertEqual(SHT31_ERR_HEATER_ON , 0x89); } unittest(test_begin) { SHT31 sht; bool b = sht.begin(0x44); assertEqual(b, true); assertTrue(sht.reset()); expect = SHT31_OK; assertEqual(expect, sht.getError()); Serial.println(sht.getTemperature()); Serial.println(sht.getHumidity()); Serial.println(sht.getRawTemperature()); Serial.println(sht.getRawHumidity()); // default value == 0 assertEqual(-45, sht.getTemperature()); assertEqual(0, sht.getHumidity()); assertEqual(0, sht.getRawTemperature()); assertEqual(0, sht.getRawHumidity()); } unittest(test_read) { SHT31 sht; bool b = sht.begin(0x44); assertEqual(b, true); assertTrue(sht.isConnected()); expect = SHT31_OK; assertEqual(expect, sht.getError()); assertFalse(sht.read()); expect = SHT31_ERR_READBYTES; assertEqual(expect, sht.getError()); start = millis(); assertFalse(sht.read(false)); stop = millis(); Serial.println(stop - start); expect = SHT31_ERR_READBYTES; assertEqual(expect, sht.getError()); start = millis(); assertFalse(sht.read(true)); stop = millis(); Serial.println(stop - start); expect = SHT31_ERR_READBYTES; assertEqual(expect, sht.getError()); } unittest(test_readStatus) { SHT31 sht; bool b = sht.begin(0x44); assertEqual(b, true); assertEqual(0xFFFF, sht.readStatus()); expect = SHT31_ERR_READBYTES; assertEqual(expect, sht.getError()); } unittest(test_heater) { SHT31 sht; bool b = sht.begin(0x44); assertEqual(b, true); assertTrue(sht.heatOn()); expect = SHT31_OK; assertEqual(expect, sht.getError()); assertTrue(sht.heatOff()); expect = SHT31_OK; assertEqual(expect, sht.getError()); assertFalse(sht.isHeaterOn()); expect = SHT31_OK; assertEqual(expect, sht.getError()); } unittest(test_async) { SHT31 sht; bool b = sht.begin(0x44); assertEqual(b, true); assertTrue(sht.requestData()); expect = SHT31_OK; assertEqual(expect, sht.getError()); assertFalse(sht.dataReady()); expect = SHT31_OK; assertEqual(expect, sht.getError()); assertFalse(sht.readData()); expect = SHT31_ERR_READBYTES; assertEqual(expect, sht.getError()); assertFalse(sht.readData(true)); expect = SHT31_ERR_READBYTES; assertEqual(expect, sht.getError()); assertFalse(sht.readData(false)); expect = SHT31_ERR_READBYTES; assertEqual(expect, sht.getError()); } unittest_main() // --------
1,938
1,186
<filename>hyper/package.json { "name": "hyperterm-new-moon-theme", "version": "1.0.0", "description": "A Hyper theme based on New Moon", "main": "index.js", "author": "<NAME> <<EMAIL>> (http://twitter.com/tmeister)", "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/Tmeister/hyperterm-new-moon-theme.git" }, "bugs": { "url": "https://github.com/Tmeister/hyperterm-new-moon-theme/issues" }, "homepage": "https://github.com/Tmeister/hyperterm-new-moon-theme#readme", "files": [ "index.js" ], "keywords": [ "hyper", "hyper-theme", "hyperterm", "theme", "ui", "terminal", "new moon" ] }
296
501
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sshd.common.session; import java.time.Duration; import java.util.EnumSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.sshd.common.CommonModuleProperties; import org.apache.sshd.common.PropertyResolver; import org.apache.sshd.common.util.GenericUtils; /** * @author <a href="mailto:<EMAIL>">Apache MINA SSHD Project</a> */ public interface SessionHeartbeatController extends PropertyResolver { enum HeartbeatType { /** No heartbeat */ NONE, /** Use {@code SSH_MSG_IGNORE} packets */ IGNORE, /** Custom mechanism via {@code ReservedSessionMessagesHandler} */ RESERVED; public static final Set<HeartbeatType> VALUES = EnumSet.allOf(HeartbeatType.class); public static HeartbeatType fromName(String name) { return GenericUtils.isEmpty(name) ? null : VALUES.stream() .filter(v -> name.equalsIgnoreCase(v.name())) .findAny() .orElse(null); } } default HeartbeatType getSessionHeartbeatType() { return CommonModuleProperties.SESSION_HEARTBEAT_TYPE.getRequired(this); } default Duration getSessionHeartbeatInterval() { return CommonModuleProperties.SESSION_HEARTBEAT_INTERVAL.getRequired(this); } /** * Disables the session heartbeat feature - <B>Note:</B> if heartbeat already in progress then it may be ignored. */ default void disableSessionHeartbeat() { setSessionHeartbeat(HeartbeatType.NONE, Duration.ZERO); } default void setSessionHeartbeat(HeartbeatType type, TimeUnit unit, long count) { Objects.requireNonNull(unit, "No heartbeat time unit provided"); setSessionHeartbeat(type, Duration.ofMillis(TimeUnit.MILLISECONDS.convert(count, unit))); } /** * Set the session heartbeat * * @param type The type of {@link HeartbeatType heartbeat} to use * @param interval The (never {@code null}) heartbeat interval - its milliseconds value is used */ default void setSessionHeartbeat(HeartbeatType type, Duration interval) { Objects.requireNonNull(type, "No heartbeat type specified"); Objects.requireNonNull(interval, "No heartbeat time interval provided"); CommonModuleProperties.SESSION_HEARTBEAT_TYPE.set(this, type); CommonModuleProperties.SESSION_HEARTBEAT_INTERVAL.set(this, interval); } }
1,178
370
<reponame>luoyongheng/dtslam #define DLONG #include <../Source/umf_mem_alloc_tail_block.c>
39
1,097
import csv from .renderers import StringIO def parse_csv(string): """ Rough port of wq/pandas.js to Python. Useful for validating CSV output generated by Django REST Pandas. """ if not string.startswith(','): data = [] for row in csv.DictReader(StringIO(string)): for key, val in row.items(): try: row[key] = float(val) except ValueError: pass data.append(row) return [{ 'data': data }] reader = csv.reader(StringIO(string)) val_cols = None val_start = None id_cols = None for row in reader: if row[0] == '' and not val_cols: val_start = row.count('') val_cols = row[val_start:] col_meta = [{} for v in val_cols] elif row[-1] != '' and val_cols and not id_cols: key = row[0] for i, meta in enumerate(row[val_start:]): col_meta[i].update(**{key: meta}) elif row[-1] == '' and not id_cols: id_cols = row[:row.index('')] meta_index = {} meta_i = 0 datasets = [] for i, ds1 in enumerate(col_meta): if i in meta_index: continue meta_index[i] = meta_i meta_i += 1 datasets.append(ds1) if i < len(col_meta): for j, ds2 in enumerate(col_meta[i + 1:]): if ds1 == ds2: meta_index[i + j + 1] = i for d in datasets: d['data'] = [] elif val_cols and id_cols: ids = { key: val for key, val in zip(id_cols, row[:len(id_cols)]) } records = {} for i, val in enumerate(row[len(id_cols):]): mi = meta_index[i] if mi not in records: data = ids.copy() else: data = records[mi] try: val = float(val) except ValueError: pass if val != '': data[val_cols[i]] = val records[mi] = data for mi, data in records.items(): datasets[mi]['data'].append(data) return datasets
1,435
190,993
/* Copyright 2017 The TensorFlow 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. ==============================================================================*/ #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/lib/constants.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/core/util/mirror_pad_mode.h" #include "tensorflow/stream_executor/lib/statusor.h" namespace tensorflow { namespace { class MirrorPadOp : public XlaOpKernel { public: explicit MirrorPadOp(OpKernelConstruction* context) : XlaOpKernel(context) {} StatusOr<xla::XlaOp> DoMirrorPad(const xla::XlaOp t, const xla::Shape& original_shape, const xla::LiteralSlice& pad_literal, const MirrorPadMode mode, xla::XlaBuilder* b) { // The difference in the semantics of REFLECT and SYMMETRIC is that REFLECT // will not mirror the border values while symmetric does. // e.g. input is [1, 2, 3] and paddings is [0, 2], then the output is: // - [1, 2, 3, 2, 1] in reflect mode // - [1, 2, 3, 3, 2] in symmetric mode. int64_t excluded_edges = mode == MirrorPadMode::REFLECT ? 1 : 0; xla::XlaOp accum = t; for (int64_t dimno = original_shape.rank() - 1; dimno >= 0; --dimno) { auto t_rev = xla::Rev(accum, {dimno}); int64_t lhs_padding = pad_literal.Get<int64_t>({dimno, 0}); int64_t rhs_padding = pad_literal.Get<int64_t>({dimno, 1}); int64_t dim_size = original_shape.dimensions(dimno); // Padding amounts on each side must be no more than the size of the // original shape. TF_RET_CHECK(lhs_padding >= 0 && lhs_padding <= dim_size - excluded_edges); TF_RET_CHECK(rhs_padding >= 0 && rhs_padding <= dim_size - excluded_edges); auto lhs_pad = xla::SliceInDim(t_rev, dim_size - excluded_edges - lhs_padding, dim_size - excluded_edges, 1, dimno); auto rhs_pad = xla::SliceInDim(t_rev, excluded_edges, excluded_edges + rhs_padding, 1, dimno); accum = xla::ConcatInDim(b, {lhs_pad, accum, rhs_pad}, dimno); } return accum; } void Compile(XlaOpKernelContext* ctx) override { const TensorShape input_shape = ctx->InputShape("input"); const TensorShape pad_shape = ctx->InputShape("paddings"); MirrorPadMode mode; OP_REQUIRES_OK(ctx, GetNodeAttr(def(), "mode", &mode)); OP_REQUIRES( ctx, mode == MirrorPadMode::REFLECT || mode == MirrorPadMode::SYMMETRIC, xla::Unimplemented("Unsupported MirrorPad mode. Only SYMMETRIC and " "REFLECT modes are currently supported")); const int dims = input_shape.dims(); OP_REQUIRES( ctx, TensorShapeUtils::IsMatrix(pad_shape) && pad_shape.dim_size(1) == 2, errors::InvalidArgument("paddings must be a matrix with 2 columns: ", pad_shape.DebugString())); OP_REQUIRES( ctx, dims == pad_shape.dim_size(0), errors::InvalidArgument( "The first dimension of paddings must be the rank of inputs", pad_shape.DebugString(), " ", input_shape.DebugString())); // Evaluate the 'padding' constant input, reshaping to a matrix. xla::Literal pad_literal; OP_REQUIRES_OK(ctx, ctx->ConstantInputAsInt64Literal("paddings", &pad_literal)); xla::XlaBuilder* b = ctx->builder(); auto in0 = ctx->Input("input"); StatusOr<xla::Shape> in0_shape = b->GetShape(in0); OP_REQUIRES(ctx, in0_shape.ok(), in0_shape.status()); StatusOr<xla::XlaOp> accum_status = DoMirrorPad(in0, in0_shape.ValueOrDie(), pad_literal, mode, b); OP_REQUIRES_OK(ctx, accum_status.status()); ctx->SetOutput(0, accum_status.ValueOrDie()); } private: TF_DISALLOW_COPY_AND_ASSIGN(MirrorPadOp); }; REGISTER_XLA_OP(Name("MirrorPad").CompileTimeConstantInput("paddings"), MirrorPadOp); class MirrorPadGradOp : public XlaOpKernel { public: explicit MirrorPadGradOp(OpKernelConstruction* context) : XlaOpKernel(context) {} StatusOr<xla::XlaOp> DoMirrorPadGrad(const xla::XlaOp t, const xla::Shape& original_shape, const xla::LiteralSlice& pad_literal, const MirrorPadMode mode, xla::XlaBuilder* b) { // The difference in the semantics of REFLECT and SYMMETRIC is that REFLECT // will not mirror the border values while symmetric does. // e.g. input is [1, 2, 3] and paddings is [0, 2], then the output is: // - [1, 2, 3, 2, 1] in reflect mode // - [1, 2, 3, 3, 2] in symmetric mode. int64_t excluded_edges = mode == MirrorPadMode::REFLECT ? 1 : 0; xla::XlaOp grad = t; for (int64_t dimno = original_shape.rank() - 1; dimno >= 0; --dimno) { int64_t lhs_padding = pad_literal.Get<int64_t>({dimno, 0}); int64_t rhs_padding = pad_literal.Get<int64_t>({dimno, 1}); int64_t dim_size = original_shape.dimensions(dimno); int64_t result_dim_size = dim_size - lhs_padding - rhs_padding; // Padding amounts on each side must be no more than the size of the // original shape. TF_RET_CHECK(lhs_padding >= 0 && lhs_padding <= dim_size - excluded_edges); TF_RET_CHECK(rhs_padding >= 0 && rhs_padding <= dim_size - excluded_edges); xla::XlaOp lhs_pad = xla::SliceInDim(grad, 0, lhs_padding, 1, dimno); xla::XlaOp reverse_lhs_pad = xla::Rev(lhs_pad, {dimno}); xla::XlaOp padded_lhs_pad = xla::PadInDim( reverse_lhs_pad, xla::ScalarLike(reverse_lhs_pad, 0), dimno, /*pad_lo=*/excluded_edges, /*pad_hi=*/result_dim_size - lhs_padding - excluded_edges); xla::XlaOp rhs_pad = xla::SliceInDim(grad, dim_size - rhs_padding, dim_size, 1, dimno); xla::XlaOp reverse_rhs_pad = xla::Rev(rhs_pad, {dimno}); xla::XlaOp padded_rhs_pad = xla::PadInDim( reverse_rhs_pad, xla::ScalarLike(reverse_rhs_pad, 0), dimno, /*pad_lo=*/result_dim_size - rhs_padding - excluded_edges, /*pad_hi=*/excluded_edges); xla::XlaOp grad_core = xla::SliceInDim(grad, lhs_padding, dim_size - rhs_padding, 1, dimno); grad = padded_lhs_pad + grad_core + padded_rhs_pad; } return grad; } void Compile(XlaOpKernelContext* ctx) override { const TensorShape input_shape = ctx->InputShape("input"); const TensorShape pad_shape = ctx->InputShape("paddings"); MirrorPadMode mode; OP_REQUIRES_OK(ctx, GetNodeAttr(def(), "mode", &mode)); OP_REQUIRES( ctx, mode == MirrorPadMode::REFLECT || mode == MirrorPadMode::SYMMETRIC, xla::Unimplemented("Unsupported MirrorPadGrad mode. Only SYMMETRIC and " "REFLECT modes are currently supported")); const int dims = input_shape.dims(); OP_REQUIRES( ctx, TensorShapeUtils::IsMatrix(pad_shape) && pad_shape.dim_size(1) == 2, errors::InvalidArgument("paddings must be a matrix with 2 columns: ", pad_shape.DebugString())); OP_REQUIRES( ctx, dims == pad_shape.dim_size(0), errors::InvalidArgument( "The first dimension of paddings must be the rank of inputs", pad_shape.DebugString(), " ", input_shape.DebugString())); // Evaluate the 'padding' constant input, reshaping to a matrix. xla::Literal pad_literal; OP_REQUIRES_OK(ctx, ctx->ConstantInputAsInt64Literal("paddings", &pad_literal)); xla::XlaBuilder* b = ctx->builder(); auto in0 = ctx->Input("input"); StatusOr<xla::Shape> in0_shape = b->GetShape(in0); OP_REQUIRES(ctx, in0_shape.ok(), in0_shape.status()); StatusOr<xla::XlaOp> accum_status = DoMirrorPadGrad(in0, in0_shape.ValueOrDie(), pad_literal, mode, b); OP_REQUIRES_OK(ctx, accum_status.status()); ctx->SetOutput(0, accum_status.ValueOrDie()); } private: TF_DISALLOW_COPY_AND_ASSIGN(MirrorPadGradOp); }; REGISTER_XLA_OP(Name("MirrorPadGrad").CompileTimeConstantInput("paddings"), MirrorPadGradOp); } // namespace } // namespace tensorflow
4,040
1,069
<gh_stars>1000+ package com.githang.statusbar; import android.annotation.TargetApi; import android.os.Build; import android.view.Window; import android.view.WindowManager; /** * 兼容LOLLIPOP版本 * * @author msdx (<EMAIL>) * @version 0.5 * @since 0.3 */ class StatusBarLollipopImpl implements IStatusBar { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void setStatusBarColor(Window window, int color) { //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏 window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色 window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); //设置状态栏颜色 window.setStatusBarColor(color); } }
396
428
<reponame>RichardCory/svgpp #include <svgpp/detail/names_dictionary.hpp> #include <gtest/gtest.h> #define SVGPP_ON_NS(ns, name, str) TEST(Dictionary, ElementChar) { typedef svgpp::detail::element_name_to_id_dictionary dict; EXPECT_EQ(dict::find("font-face-uri"), svgpp::detail::element_type_id_font_face_uri); EXPECT_EQ(dict::find("font-face-ur"), svgpp::detail::unknown_element_type_id); EXPECT_EQ(dict::find("font-face-uri "), svgpp::detail::unknown_element_type_id); EXPECT_EQ(dict::find("font-face-urj"), svgpp::detail::unknown_element_type_id); EXPECT_EQ(dict::find("a"), svgpp::detail::element_type_id_a); EXPECT_EQ(dict::find("0"), svgpp::detail::unknown_element_type_id); EXPECT_EQ(dict::find("aaaa"), svgpp::detail::unknown_element_type_id); EXPECT_EQ(dict::find("vkern"), svgpp::detail::element_type_id_vkern); EXPECT_EQ(dict::find("vkern "), svgpp::detail::unknown_element_type_id); EXPECT_EQ(dict::find("vkero"), svgpp::detail::unknown_element_type_id); #define SVGPP_ON(name, str) EXPECT_EQ(svgpp::detail::element_type_id_ ## name, dict::find(#str)); #include <svgpp/detail/dict/enumerate_all_elements.inc> #undef SVGPP_ON } TEST(Dictionary, ElementWChar) { typedef svgpp::detail::element_name_to_id_dictionary dict; EXPECT_EQ(dict::find(L"font-face-uri"), svgpp::detail::element_type_id_font_face_uri); EXPECT_EQ(dict::find(std::wstring(L"font-face-uri")), svgpp::detail::element_type_id_font_face_uri); #define SVGPP_ON(name, str) EXPECT_EQ(svgpp::detail::element_type_id_ ## name, dict::find(L ## #str)); #include <svgpp/detail/dict/enumerate_all_elements.inc> #undef SVGPP_ON } TEST(Dictionary, AttributeChar) { typedef svgpp::detail::svg_attribute_name_to_id_dictionary dict; EXPECT_EQ(dict::find("baseline-shift"), svgpp::detail::attribute_id_baseline_shift); EXPECT_EQ(dict::find("baseline-shifT"), svgpp::detail::unknown_attribute_id); EXPECT_EQ(dict::find("specularConstant"), svgpp::detail::attribute_id_specularConstant); EXPECT_EQ(dict::find("specularconstant"), svgpp::detail::unknown_attribute_id); #define SVGPP_ON(name, str) EXPECT_EQ(svgpp::detail::attribute_id_ ## name, dict::find(#str)); #define SVGPP_ON_STYLE(name, str) SVGPP_ON(name, str) #include <svgpp/detail/dict/enumerate_all_attributes.inc> #undef SVGPP_ON #undef SVGPP_ON_STYLE } TEST(Dictionary, CSSProperty) { typedef svgpp::detail::css_property_name_to_id_dictionary dict; EXPECT_EQ(dict::find_ignore_case("baseline-shift"), svgpp::detail::attribute_id_baseline_shift); EXPECT_EQ(dict::find_ignore_case("baseline-shifT"), svgpp::detail::attribute_id_baseline_shift); EXPECT_EQ(dict::find_ignore_case(std::wstring(L"leTtEr-spacIng")), svgpp::detail::attribute_id_letter_spacing); #define SVGPP_ON(name, str) EXPECT_EQ(svgpp::detail::unknown_attribute_id, dict::find(#str)); #define SVGPP_ON_STYLE(name, str) EXPECT_EQ(svgpp::detail::attribute_id_ ## name, dict::find(#str)); #include <svgpp/detail/dict/enumerate_all_attributes.inc> #undef SVGPP_ON #undef SVGPP_ON_STYLE #define SVGPP_ON(name, str) #define SVGPP_ON_STYLE(name, str) EXPECT_EQ(boost::to_lower_copy(std::string(#str)), #str); #include <svgpp/detail/dict/enumerate_all_attributes.inc> #undef SVGPP_ON #undef SVGPP_ON_STYLE }
1,326
5,514
<gh_stars>1000+ package com.u9porn.ui.basemain; import com.u9porn.data.db.entity.Category; import java.util.List; /** * @author flymegoc * @date 2018/1/25 */ public interface IBaseMain { void loadAllCategoryData(int categoryType); void loadCategoryData(int categoryType); Category findCategoryById(Long id); void updateCategoryData(List<Category> categoryList); }
136
3,195
<gh_stars>1000+ import mxnet as mx import mxnext as X # Use symbol for internal variables computation for better parallelization # Use custom python op to control loss/gradient flow """ ---Sigmoid Focal Loss--- def forward(self, is_train, req, in_data, out_data, aux): logits = in_data[0] labels = in_data[1] nonignore_mask = in_data[2] p = 1 / (1 + mx.nd.exp(-logits)) mask_logits_GE_zero = mx.nd.broadcast_greater_equal(lhs=logits, rhs=mx.nd.zeros((1,1))) minus_abs_logits = logits - 2*logits*mask_logits_GE_zero #mx.nd.abs(logits) term1 = self.alpha * \ (1-p)**self.gamma * \ mx.nd.log(mx.nd.clip(p, a_min=1e-5, a_max=1)) * \ labels term2 = (1 - self.alpha) * \ p**self.gamma * \ ( -1. * logits * mask_logits_GE_zero - mx.nd.log(1. + mx.nd.exp(minus_abs_logits)) ) * \ (1 - labels) loss = -1 * (term1 + term2) * nonignore_mask / (mx.nd.sum(nonignore_mask) + in_data[0].shape[0]) self.assign(out_data[0], req[0], loss) def backward(self, req, out_grad, in_data, out_data, in_grad, aux): logits = in_data[0] labels = in_data[1] nonignore_mask = in_data[2] p = 1 / (1 + mx.nd.exp(-logits)) mask_logits_GE_zero = mx.nd.broadcast_greater_equal(lhs=logits, rhs=mx.nd.zeros((1,1))) minus_abs_logits = logits - 2*logits*mask_logits_GE_zero #mx.nd.abs(logits) term1 = self.alpha * \ (1-p)**self.gamma * \ ( 1 - p - p * self.gamma * mx.nd.log(mx.nd.clip(p, a_min=1e-5, a_max=1)) ) * \ labels term2 = (1 - self.alpha) * \ p**self.gamma * \ (( -1. * logits * mask_logits_GE_zero - mx.nd.log(1. + mx.nd.exp(minus_abs_logits)) ) * (1 - p) * self.gamma - p) * \ (1 - labels) grad = -1 * (term1 + term2) * nonignore_mask / (mx.nd.sum(nonignore_mask) + in_data[0].shape[0]) self.assign(in_grad[0], req[0], grad)""" # the formula is better demonstrated above class ComputeSigmoidFocalLoss(mx.operator.CustomOp): def __init__(self): super(ComputeSigmoidFocalLoss, self).__init__() def forward(self, is_train, req, in_data, out_data, aux): loss = in_data[1] self.assign(out_data[0], req[0], loss) def backward(self, req, out_grad, in_data, out_data, in_grad, aux): grad = in_data[2] self.assign(in_grad[0], req[0], grad) @mx.operator.register("compute_focal_loss") class ComputeSigmoidFocalLossProp(mx.operator.CustomOpProp): def __init__(self): super(ComputeSigmoidFocalLossProp, self).__init__(need_top_grad=True) def list_arguments(self): return ['logits', 'loss', 'grad'] def list_outputs(self): return ['focal_loss'] def infer_shape(self, in_shape): return in_shape, [[1]], [] def infer_type(self, in_type): return in_type, [in_type[0]], [] def create_operator(self, ctx, shapes, dtypes): return ComputeSigmoidFocalLoss() def make_sigmoid_focal_loss(gamma, alpha, logits, labels, nonignore_mask): p = 1 / (1 + mx.sym.exp(-logits)) # sigmoid mask_logits_GE_zero = mx.sym.broadcast_greater_equal(lhs=logits, rhs=mx.sym.zeros((1,1))) # logits>=0 minus_logits_mask = -1. * logits * mask_logits_GE_zero # -1 * logits * [logits>=0] negative_abs_logits = logits - 2*logits*mask_logits_GE_zero # logtis - 2 * logits * [logits>=0] log_one_exp_minus_abs = mx.sym.log(1. + mx.sym.exp(negative_abs_logits)) minus_log = minus_logits_mask - log_one_exp_minus_abs alpha_one_p_gamma_labels = alpha * (1-p)**gamma * labels log_p_clip = mx.sym.log(mx.sym.clip(p, a_min=1e-5, a_max=1)) one_alpha_p_gamma_one_labels = (1 - alpha) * p**gamma * (1 - labels) norm = mx.sym.sum(labels*nonignore_mask) + 1 forward_term1 = alpha_one_p_gamma_labels * log_p_clip forward_term2 = one_alpha_p_gamma_one_labels * minus_log loss = mx.sym.sum(-1 * (forward_term1 + forward_term2) * nonignore_mask) / norm backward_term1 = alpha_one_p_gamma_labels * ( 1 - p - p * gamma * log_p_clip ) backward_term2 = one_alpha_p_gamma_one_labels * (minus_log * (1 - p) * gamma - p) grad = mx.sym.broadcast_div( lhs=-1 * (backward_term1 + backward_term2) * nonignore_mask, rhs=norm.reshape((1,1)) ) loss = X.block_grad(loss) # symbols are only used for computation grad = X.block_grad(grad) # use custom op to control gradient flow instead loss = mx.sym.Custom(logits=logits, loss=loss, grad=grad, op_type='compute_focal_loss', name='focal_loss') return loss # ------------------------------------------------------- class ComputeBCELoss(mx.operator.CustomOp): def __init__(self): super(ComputeBCELoss, self).__init__() def forward(self, is_train, req, in_data, out_data, aux): loss = in_data[1] self.assign(out_data[0], req[0], loss) def backward(self, req, out_grad, in_data, out_data, in_grad, aux): grad = in_data[2] self.assign(in_grad[0], req[0], grad) @mx.operator.register("compute_bce_loss") class ComputeBCELossProp(mx.operator.CustomOpProp): def __init__(self): super(ComputeBCELossProp, self).__init__(need_top_grad=True) def list_arguments(self): return ['logits', 'loss', 'grad'] def list_outputs(self): return ['bce_loss'] def infer_shape(self, in_shape): return in_shape, [[1]], [] def infer_type(self, in_type): return in_type, [in_type[0]], [] def create_operator(self, ctx, shapes, dtypes): return ComputeBCELoss() def make_binary_cross_entropy_loss(logits, labels, nonignore_mask): p = 1 / (1 + mx.sym.exp(-logits)) loss = -labels * mx.sym.log(mx.sym.clip(p, a_min=1e-5, a_max=1)) - (1 - labels) * mx.sym.log(mx.sym.clip(1 - p, a_min=1e-5, a_max=1)) loss = mx.sym.sum(loss * nonignore_mask) / (mx.sym.sum(nonignore_mask) + 1e-30) grad = mx.sym.broadcast_div( lhs=(p - labels) * nonignore_mask, rhs=mx.sym.sum(nonignore_mask) + 1e-30 ) loss = X.block_grad(loss) grad = X.block_grad(grad) return mx.sym.Custom(logits=logits, loss=loss, grad=grad, op_type='compute_bce_loss', name='sigmoid_bce_loss') # ------------------------------------------------------- def IoULoss(x_box, y_box, ignore_offset, centerness_label, name='iouloss'): centerness_label = mx.sym.reshape(centerness_label, shape=(0,1,-1)) y_box = X.block_grad(y_box) target_left = mx.sym.slice_axis(y_box, axis=1, begin=0, end=1) target_top = mx.sym.slice_axis(y_box, axis=1, begin=1, end=2) target_right = mx.sym.slice_axis(y_box, axis=1, begin=2, end=3) target_bottom = mx.sym.slice_axis(y_box, axis=1, begin=3, end=4) # filter out out-of-bbox area, loss is only computed inside bboxes nonignore_mask = mx.sym.broadcast_logical_and(lhs = mx.sym.broadcast_not_equal(lhs=target_left, rhs=ignore_offset), rhs = mx.sym.broadcast_greater( lhs=centerness_label, rhs=mx.sym.full((1,1,1), 0) ) ) nonignore_mask = X.block_grad(nonignore_mask) x_box = mx.sym.clip(x_box, a_min=0, a_max=1e4) x_box = mx.sym.broadcast_mul(lhs=x_box, rhs=nonignore_mask) centerness_label = centerness_label * nonignore_mask pred_left = mx.sym.slice_axis(x_box, axis=1, begin=0, end=1) pred_top = mx.sym.slice_axis(x_box, axis=1, begin=1, end=2) pred_right = mx.sym.slice_axis(x_box, axis=1, begin=2, end=3) pred_bottom = mx.sym.slice_axis(x_box, axis=1, begin=3, end=4) target_area = (target_left + target_right) * (target_top + target_bottom) pred_area = (pred_left + pred_right) * (pred_top + pred_bottom) w_intersect = mx.sym.min(mx.sym.stack(pred_left, target_left, axis=0), axis=0) + mx.sym.min(mx.sym.stack(pred_right, target_right, axis=0), axis=0) h_intersect = mx.sym.min(mx.sym.stack(pred_bottom, target_bottom, axis=0), axis=0) + mx.sym.min(mx.sym.stack(pred_top, target_top, axis=0), axis=0) area_intersect = w_intersect * h_intersect area_union = (target_area + pred_area - area_intersect) loss = -mx.sym.log((area_intersect + 1.0) / (area_union + 1.0)) loss = mx.sym.broadcast_mul(lhs=loss, rhs=centerness_label) loss = mx.sym.sum(loss) / (mx.sym.sum(centerness_label) + 1e-30) return X.loss(loss, grad_scale=1, name=name)
3,985
391
<reponame>zmhbh/spring-android /* * Copyright 2002-2014 the original author or 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. */ package org.springframework.http.converter; import java.io.IOException; import java.io.StringReader; import java.nio.charset.Charset; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import org.springframework.core.io.AssetResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import android.os.Build; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; /** * @author <NAME> * @author <NAME> */ public class FormHttpMessageConverterTests extends AndroidTestCase { private static final boolean javaxXmlTransformPresent = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO); private FormHttpMessageConverter converter; @Override public void setUp() throws Exception { super.setUp(); if (javaxXmlTransformPresent) { converter = new AllEncompassingFormHttpMessageConverter(); } else { // javax.xml.transform not available on this version of Android converter = new FormHttpMessageConverter(); } } @Override public void tearDown() { converter = null; } @SmallTest public void testCanRead() { assertTrue(converter.canRead(MultiValueMap.class, new MediaType("application", "x-www-form-urlencoded"))); assertFalse(converter.canRead(MultiValueMap.class, new MediaType("multipart", "form-data"))); } @SmallTest public void testCanWrite() { assertTrue(converter.canWrite(MultiValueMap.class, new MediaType("application", "x-www-form-urlencoded"))); assertTrue(converter.canWrite(MultiValueMap.class, new MediaType("multipart", "form-data"))); assertTrue(converter.canWrite(MultiValueMap.class, MediaType.valueOf("multipart/form-data; charset=utf-8"))); assertTrue(converter.canWrite(MultiValueMap.class, MediaType.ALL)); } @SmallTest public void testReadForm() throws Exception { String body = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3"; Charset iso88591 = Charset.forName("ISO-8859-1"); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(iso88591.displayName())); inputMessage.getHeaders().setContentType(new MediaType("application", "x-www-form-urlencoded", iso88591)); MultiValueMap<String, String> result = converter.read(null, inputMessage); assertEquals("Invalid result", 3, result.size()); assertEquals("Invalid result", "value 1", result.getFirst("name 1")); List<String> values = result.get("name 2"); assertEquals("Invalid result", 2, values.size()); assertEquals("Invalid result", "value 2+1", values.get(0)); assertEquals("Invalid result", "value 2+2", values.get(1)); assertNull("Invalid result", result.getFirst("name 3")); } @SmallTest public void testWriteForm() throws IOException { MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>(); body.set("name 1", "value 1"); body.add("name 2", "value 2+1"); body.add("name 2", "value 2+2"); body.add("name 3", null); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(body, MediaType.APPLICATION_FORM_URLENCODED, outputMessage); assertEquals("Invalid result", "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3", outputMessage.getBodyAsString(Charset.forName("UTF-8"))); assertEquals("Invalid content-type", new MediaType("application", "x-www-form-urlencoded"), outputMessage.getHeaders().getContentType()); assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length, outputMessage.getHeaders().getContentLength()); } @SmallTest public void testWriteMultipart() throws Exception { MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); parts.add("name 1", "value 1"); parts.add("name 2", "value 2+1"); parts.add("name 2", "value 2+2"); parts.add("name 3", null); Resource logo = new AssetResource(getContext().getAssets(), "logo.jpg"); parts.add("logo", logo); Source xml = new StreamSource(new StringReader("<root><child/></root>")); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.setContentType(MediaType.TEXT_XML); HttpEntity<Source> entity = new HttpEntity<Source>(xml, entityHeaders); parts.add("xml", entity); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(parts, new MediaType("multipart", "form-data", Charset.forName("UTF-8")), outputMessage); final MediaType contentType = outputMessage.getHeaders().getContentType(); assertNotNull("No boundary found", contentType.getParameter("boundary")); // // see if Commons FileUpload can read what we wrote // FileItemFactory fileItemFactory = new DiskFileItemFactory(); // FileUpload fileUpload = new FileUpload(fileItemFactory); // List<FileItem> items = fileUpload.parseRequest(new MockHttpOutputMessageRequestContext(outputMessage)); // assertEquals(5, items.size()); // FileItem item = items.get(0); // assertTrue(item.isFormField()); // assertEquals("name 1", item.getFieldName()); // assertEquals("value 1", item.getString()); // // item = items.get(1); // assertTrue(item.isFormField()); // assertEquals("name 2", item.getFieldName()); // assertEquals("value 2+1", item.getString()); // // item = items.get(2); // assertTrue(item.isFormField()); // assertEquals("name 2", item.getFieldName()); // assertEquals("value 2+2", item.getString()); // // item = items.get(3); // assertFalse(item.isFormField()); // assertEquals("logo", item.getFieldName()); // assertEquals("logo.jpg", item.getName()); // assertEquals("image/jpeg", item.getContentType()); // assertEquals(logo.getFile().length(), item.getSize()); // // item = items.get(4); // assertEquals("xml", item.getFieldName()); // assertEquals("text/xml", item.getContentType()); // verify(outputMessage.getBody(), never()).close(); } // private static class MockHttpOutputMessageRequestContext implements RequestContext { // // private final MockHttpOutputMessage outputMessage; // // private MockHttpOutputMessageRequestContext(MockHttpOutputMessage outputMessage) { // this.outputMessage = outputMessage; // } // // @Override // public String getCharacterEncoding() { // MediaType contentType = outputMessage.getHeaders().getContentType(); // return contentType != null && contentType.getCharSet() != null ? contentType.getCharSet().name() : null; // } // // @Override // public String getContentType() { // MediaType contentType = outputMessage.getHeaders().getContentType(); // return contentType != null ? contentType.toString() : null; // } // // @Override // public int getContentLength() { // return outputMessage.getBodyAsBytes().length; // } // // @Override // public InputStream getInputStream() throws IOException { // return new ByteArrayInputStream(outputMessage.getBodyAsBytes()); // } // } }
2,592
716
<gh_stars>100-1000 /* * 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 * */ /* clang-format off */ /** \file * Implements DFLIB findfileqq subprogram. */ #include <string.h> #include <stdlib.h> /* must include ent3f.h AFTER io3f.h */ #include "io3f.h" #include "ent3f.h" #if defined(WIN64) || defined(WIN32) extern char *__fstr2cstr(); int ENT3F(FINDFILEQQ, findfileqq)(DCHAR(fname), DCHAR(fvarname), DCHAR(fpath) DCLEN(fname) DCLEN(fvarname) DCLEN(fpath)) { char *path, *name, *varname; int rslt = 0; path = __fstr2cstr(CADR(fpath), CLEN(fpath)); name = __fstr2cstr(CADR(fname), CLEN(fname)); varname = __fstr2cstr(CADR(fvarname), CLEN(fvarname)); if (!path || !name || !varname) { __io_errno(); goto rtn; } /* errno_t _searchenv_s( const char *filename, const char *varname, char *pathname, size_t numberOfElements ); */ if (_searchenv_s(name, varname, path, CLEN(fpath)) == 0) { rslt = strlen(path); __fcp_cstr(CADR(fpath), CLEN(fpath), path); } rtn: __cstr_free(path); __cstr_free(name); __cstr_free(varname); return rslt; } #else int ENT3F(FINDFILEQQ, findfileqq)(DCHAR(fname), DCHAR(fvarname), DCHAR(fpath) DCLEN(fname) DCLEN(fvarname) DCLEN(fpath)) { fprintf(__io_stderr(), "findfileqq() not implemented on this target\n"); return 0; } #endif
802
521
<filename>third_party/virtualbox/src/VBox/Frontends/VirtualBox/src/selector/graphics/details/UIGDetailsElement.cpp /* $Id: UIGDetailsElement.cpp $ */ /** @file * VBox Qt GUI - UIGDetailsElement class implementation. */ /* * Copyright (C) 2012-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifdef VBOX_WITH_PRECOMPILED_HEADERS # include <precomp.h> #else /* !VBOX_WITH_PRECOMPILED_HEADERS */ /* Qt includes: */ # include <QGraphicsView> # include <QStateMachine> # include <QPropertyAnimation> # include <QSignalTransition> # include <QStyleOptionGraphicsItem> # include <QGraphicsSceneMouseEvent> /* GUI includes: */ # include "UIGDetailsElement.h" # include "UIGDetailsSet.h" # include "UIGDetailsModel.h" # include "UIGraphicsRotatorButton.h" # include "UIGraphicsTextPane.h" # include "UIActionPool.h" # include "UIIconPool.h" # include "UIConverter.h" # include "VBoxGlobal.h" #endif /* !VBOX_WITH_PRECOMPILED_HEADERS */ UIGDetailsElement::UIGDetailsElement(UIGDetailsSet *pParent, DetailsElementType type, bool fOpened) : UIGDetailsItem(pParent) , m_pSet(pParent) , m_type(type) , m_iCornerRadius(QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize) / 2) , m_iMinimumHeaderWidth(0) , m_iMinimumHeaderHeight(0) , m_pButton(0) , m_fClosed(!fOpened) , m_iAdditionalHeight(0) , m_fAnimationRunning(false) , m_pTextPane(0) , m_fHovered(false) , m_fNameHovered(false) , m_pHighlightMachine(0) , m_pForwardAnimation(0) , m_pBackwardAnimation(0) , m_iAnimationDuration(400) , m_iDefaultDarkness(100) , m_iHighlightDarkness(90) , m_iAnimationDarkness(m_iDefaultDarkness) { /* Prepare element: */ prepareElement(); /* Prepare button: */ prepareButton(); /* Prepare text-pane: */ prepareTextPane(); /* Setup size-policy: */ setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); /* Add item to the parent: */ AssertMsg(parentItem(), ("No parent set for details element!")); parentItem()->addItem(this); } UIGDetailsElement::~UIGDetailsElement() { /* Remove item from the parent: */ AssertMsg(parentItem(), ("No parent set for details element!")); parentItem()->removeItem(this); } void UIGDetailsElement::close(bool fAnimated /* = true */) { m_pButton->setToggled(false, fAnimated); } void UIGDetailsElement::open(bool fAnimated /* = true */) { m_pButton->setToggled(true, fAnimated); } void UIGDetailsElement::updateAppearance() { /* Reset name hover state: */ m_fNameHovered = false; updateNameHoverLink(); /* Update anchor role restrictions: */ ConfigurationAccessLevel cal = m_pSet->configurationAccessLevel(); m_pTextPane->setAnchorRoleRestricted("#mount", cal == ConfigurationAccessLevel_Null); m_pTextPane->setAnchorRoleRestricted("#attach", cal != ConfigurationAccessLevel_Full); } void UIGDetailsElement::markAnimationFinished() { /* Mark animation as non-running: */ m_fAnimationRunning = false; /* Recursively update size-hint: */ updateGeometry(); /* Repaint: */ update(); } UITextTable &UIGDetailsElement::text() const { /* Retrieve text from text-pane: */ return m_pTextPane->text(); } void UIGDetailsElement::setText(const UITextTable &text) { /* Pass text to text-pane: */ m_pTextPane->setText(text); } void UIGDetailsElement::sltToggleButtonClicked() { emit sigToggleElement(m_type, closed()); } void UIGDetailsElement::sltElementToggleStart() { /* Mark animation running: */ m_fAnimationRunning = true; /* Setup animation: */ updateAnimationParameters(); /* Invert toggle-state: */ m_fClosed = !m_fClosed; } void UIGDetailsElement::sltElementToggleFinish(bool fToggled) { /* Update toggle-state: */ m_fClosed = !fToggled; /* Notify about finishing: */ emit sigToggleElementFinished(); } void UIGDetailsElement::sltHandleAnchorClicked(const QString &strAnchor) { /* Current anchor role: */ const QString strRole = strAnchor.section(',', 0, 0); const QString strData = strAnchor.section(',', 1); /* Handle known anchor roles: */ if ( strRole == "#mount" // Optical and floppy attachments.. || strRole == "#attach" // Hard-drive attachments.. ) { /* Prepare storage-menu: */ UIMenu menu; menu.setShowToolTip(true); /* Storage-controller name: */ QString strControllerName = strData.section(',', 0, 0); /* Storage-slot: */ StorageSlot storageSlot = gpConverter->fromString<StorageSlot>(strData.section(',', 1)); /* Fill storage-menu: */ vboxGlobal().prepareStorageMenu(menu, this, SLOT(sltMountStorageMedium()), machine(), strControllerName, storageSlot); /* Exec menu: */ menu.exec(QCursor::pos()); } } void UIGDetailsElement::sltMountStorageMedium() { /* Sender action: */ QAction *pAction = qobject_cast<QAction*>(sender()); AssertMsgReturnVoid(pAction, ("This slot should only be called by menu action!\n")); /* Current mount-target: */ const UIMediumTarget target = pAction->data().value<UIMediumTarget>(); /* Update current machine mount-target: */ vboxGlobal().updateMachineStorage(machine(), target); } void UIGDetailsElement::resizeEvent(QGraphicsSceneResizeEvent*) { /* Update layout: */ updateLayout(); } QString UIGDetailsElement::description() const { return tr("%1 details", "like 'General details' or 'Storage details'").arg(m_strName); } QVariant UIGDetailsElement::data(int iKey) const { /* Provide other members with required data: */ switch (iKey) { /* Hints: */ case ElementData_Margin: return QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize) / 4; case ElementData_Spacing: return QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize) / 2; /* Default: */ default: break; } return QVariant(); } void UIGDetailsElement::updateMinimumHeaderWidth() { /* Prepare variables: */ int iSpacing = data(ElementData_Spacing).toInt(); /* Update minimum-header-width: */ m_iMinimumHeaderWidth = m_pixmapSize.width() + iSpacing + m_nameSize.width() + iSpacing + m_buttonSize.width(); } void UIGDetailsElement::updateMinimumHeaderHeight() { /* Update minimum-header-height: */ m_iMinimumHeaderHeight = qMax(m_pixmapSize.height(), m_nameSize.height()); m_iMinimumHeaderHeight = qMax(m_iMinimumHeaderHeight, m_buttonSize.height()); } void UIGDetailsElement::setIcon(const QIcon &icon) { /* Cache icon: */ if (icon.isNull()) { /* No icon provided: */ m_pixmapSize = QSize(); m_pixmap = QPixmap(); } else { /* Determine default the icon size: */ const QStyle *pStyle = QApplication::style(); const int iIconMetric = pStyle->pixelMetric(QStyle::PM_SmallIconSize); m_pixmapSize = QSize(iIconMetric, iIconMetric); /* Acquire the icon of the corresponding size: */ m_pixmap = icon.pixmap(m_pixmapSize); } /* Update linked values: */ updateMinimumHeaderWidth(); updateMinimumHeaderHeight(); } void UIGDetailsElement::setName(const QString &strName) { /* Cache name: */ m_strName = strName; QFontMetrics fm(m_nameFont, model()->paintDevice()); m_nameSize = QSize(fm.width(m_strName), fm.height()); /* Update linked values: */ updateMinimumHeaderWidth(); updateMinimumHeaderHeight(); } const CMachine& UIGDetailsElement::machine() { return m_pSet->machine(); } int UIGDetailsElement::minimumWidthHint() const { /* Prepare variables: */ int iMargin = data(ElementData_Margin).toInt(); int iMinimumWidthHint = 0; /* Maximum width: */ iMinimumWidthHint = qMax(m_iMinimumHeaderWidth, (int)m_pTextPane->minimumSizeHint().width()); /* And 4 margins: 2 left and 2 right: */ iMinimumWidthHint += 4 * iMargin; /* Return result: */ return iMinimumWidthHint; } int UIGDetailsElement::minimumHeightHint(bool fClosed) const { /* Prepare variables: */ int iMargin = data(ElementData_Margin).toInt(); int iMinimumHeightHint = 0; /* Two margins: */ iMinimumHeightHint += 2 * iMargin; /* Header height: */ iMinimumHeightHint += m_iMinimumHeaderHeight; /* Element is opened? */ if (!fClosed) { /* Add text height: */ if (!m_pTextPane->isEmpty()) iMinimumHeightHint += 2 * iMargin + (int)m_pTextPane->minimumSizeHint().height(); } /* Additional height during animation: */ if (m_fAnimationRunning) iMinimumHeightHint += m_iAdditionalHeight; /* Return value: */ return iMinimumHeightHint; } int UIGDetailsElement::minimumHeightHint() const { return minimumHeightHint(m_fClosed); } void UIGDetailsElement::updateLayout() { /* Prepare variables: */ QSize size = geometry().size().toSize(); int iMargin = data(ElementData_Margin).toInt(); /* Layout button: */ int iButtonWidth = m_buttonSize.width(); int iButtonHeight = m_buttonSize.height(); int iButtonX = size.width() - 2 * iMargin - iButtonWidth; int iButtonY = iButtonHeight == m_iMinimumHeaderHeight ? iMargin : iMargin + (m_iMinimumHeaderHeight - iButtonHeight) / 2; m_pButton->setPos(iButtonX, iButtonY); /* If closed: */ if (closed()) { /* Hide text-pane if still visible: */ if (m_pTextPane->isVisible()) m_pTextPane->hide(); } /* If opened: */ else { /* Layout text-pane: */ int iTextPaneX = 2 * iMargin; int iTextPaneY = iMargin + m_iMinimumHeaderHeight + 2 * iMargin; m_pTextPane->setPos(iTextPaneX, iTextPaneY); m_pTextPane->resize(size.width() - 4 * iMargin, size.height() - 4 * iMargin - m_iMinimumHeaderHeight); /* Show text-pane if still invisible and animation finished: */ if (!m_pTextPane->isVisible() && !isAnimationRunning()) m_pTextPane->show(); } } void UIGDetailsElement::setAdditionalHeight(int iAdditionalHeight) { /* Cache new value: */ m_iAdditionalHeight = iAdditionalHeight; /* Update layout: */ updateLayout(); /* Repaint: */ update(); } void UIGDetailsElement::addItem(UIGDetailsItem*) { AssertMsgFailed(("Details element do NOT support children!")); } void UIGDetailsElement::removeItem(UIGDetailsItem*) { AssertMsgFailed(("Details element do NOT support children!")); } QList<UIGDetailsItem*> UIGDetailsElement::items(UIGDetailsItemType) const { AssertMsgFailed(("Details element do NOT support children!")); return QList<UIGDetailsItem*>(); } bool UIGDetailsElement::hasItems(UIGDetailsItemType) const { AssertMsgFailed(("Details element do NOT support children!")); return false; } void UIGDetailsElement::clearItems(UIGDetailsItemType) { AssertMsgFailed(("Details element do NOT support children!")); } void UIGDetailsElement::prepareElement() { /* Initialization: */ m_nameFont = font(); m_nameFont.setWeight(QFont::Bold); m_textFont = font(); /* Create highlight machine: */ m_pHighlightMachine = new QStateMachine(this); /* Create 'default' state: */ QState *pStateDefault = new QState(m_pHighlightMachine); pStateDefault->assignProperty(this, "animationDarkness", m_iDefaultDarkness); /* Create 'highlighted' state: */ QState *pStateHighlighted = new QState(m_pHighlightMachine); pStateHighlighted->assignProperty(this, "animationDarkness", m_iHighlightDarkness); /* Forward animation: */ m_pForwardAnimation = new QPropertyAnimation(this, "animationDarkness", this); m_pForwardAnimation->setDuration(m_iAnimationDuration); m_pForwardAnimation->setStartValue(m_iDefaultDarkness); m_pForwardAnimation->setEndValue(m_iHighlightDarkness); /* Backward animation: */ m_pBackwardAnimation = new QPropertyAnimation(this, "animationDarkness", this); m_pBackwardAnimation->setDuration(m_iAnimationDuration); m_pBackwardAnimation->setStartValue(m_iHighlightDarkness); m_pBackwardAnimation->setEndValue(m_iDefaultDarkness); /* Add state transitions: */ QSignalTransition *pDefaultToHighlighted = pStateDefault->addTransition(this, SIGNAL(sigHoverEnter()), pStateHighlighted); pDefaultToHighlighted->addAnimation(m_pForwardAnimation); QSignalTransition *pHighlightedToDefault = pStateHighlighted->addTransition(this, SIGNAL(sigHoverLeave()), pStateDefault); pHighlightedToDefault->addAnimation(m_pBackwardAnimation); /* Initial state is 'default': */ m_pHighlightMachine->setInitialState(pStateDefault); /* Start state-machine: */ m_pHighlightMachine->start(); connect(this, SIGNAL(sigToggleElement(DetailsElementType, bool)), model(), SLOT(sltToggleElements(DetailsElementType, bool))); connect(this, SIGNAL(sigLinkClicked(const QString&, const QString&, const QString&)), model(), SIGNAL(sigLinkClicked(const QString&, const QString&, const QString&))); } void UIGDetailsElement::prepareButton() { /* Setup toggle-button: */ m_pButton = new UIGraphicsRotatorButton(this, "additionalHeight", !m_fClosed, true /* reflected */); m_pButton->setAutoHandleButtonClick(false); connect(m_pButton, SIGNAL(sigButtonClicked()), this, SLOT(sltToggleButtonClicked())); connect(m_pButton, SIGNAL(sigRotationStart()), this, SLOT(sltElementToggleStart())); connect(m_pButton, SIGNAL(sigRotationFinish(bool)), this, SLOT(sltElementToggleFinish(bool))); m_buttonSize = m_pButton->minimumSizeHint().toSize(); } void UIGDetailsElement::prepareTextPane() { /* Create text-pane: */ m_pTextPane = new UIGraphicsTextPane(this, model()->paintDevice()); connect(m_pTextPane, SIGNAL(sigGeometryChanged()), this, SLOT(sltUpdateGeometry())); connect(m_pTextPane, SIGNAL(sigAnchorClicked(const QString&)), this, SLOT(sltHandleAnchorClicked(const QString&))); } void UIGDetailsElement::paint(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption, QWidget*) { /* Update button visibility: */ updateButtonVisibility(); /* Configure painter shape: */ configurePainterShape(pPainter, pOption, m_iCornerRadius); /* Paint decorations: */ paintDecorations(pPainter, pOption); /* Paint element info: */ paintElementInfo(pPainter, pOption); } void UIGDetailsElement::paintDecorations(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption) { /* Paint background: */ paintBackground(pPainter, pOption); } void UIGDetailsElement::paintElementInfo(QPainter *pPainter, const QStyleOptionGraphicsItem*) { /* Initialize some necessary variables: */ int iMargin = data(ElementData_Margin).toInt(); int iSpacing = data(ElementData_Spacing).toInt(); /* Calculate attributes: */ int iPixmapHeight = m_pixmapSize.height(); int iNameHeight = m_nameSize.height(); int iMaximumHeight = qMax(iPixmapHeight, iNameHeight); /* Prepare color: */ QPalette pal = palette(); QColor buttonTextColor = pal.color(QPalette::Active, QPalette::ButtonText); QColor linkTextColor = pal.color(QPalette::Active, QPalette::Link); /* Paint pixmap: */ int iElementPixmapX = 2 * iMargin; int iElementPixmapY = iPixmapHeight == iMaximumHeight ? iMargin : iMargin + (iMaximumHeight - iPixmapHeight) / 2; paintPixmap(/* Painter: */ pPainter, /* Rectangle to paint in: */ QRect(QPoint(iElementPixmapX, iElementPixmapY), m_pixmapSize), /* Pixmap to paint: */ m_pixmap); /* Paint name: */ int iMachineNameX = iElementPixmapX + m_pixmapSize.width() + iSpacing; int iMachineNameY = iNameHeight == iMaximumHeight ? iMargin : iMargin + (iMaximumHeight - iNameHeight) / 2; paintText(/* Painter: */ pPainter, /* Rectangle to paint in: */ QPoint(iMachineNameX, iMachineNameY), /* Font to paint text: */ m_nameFont, /* Paint device: */ model()->paintDevice(), /* Text to paint: */ m_strName, /* Name hovered? */ m_fNameHovered ? linkTextColor : buttonTextColor); } void UIGDetailsElement::paintBackground(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption) { /* Save painter: */ pPainter->save(); /* Prepare variables: */ int iMargin = data(ElementData_Margin).toInt(); int iHeaderHeight = 2 * iMargin + m_iMinimumHeaderHeight; QRect optionRect = pOption->rect; QRect fullRect = !m_fAnimationRunning ? optionRect : QRect(optionRect.topLeft(), QSize(optionRect.width(), iHeaderHeight + m_iAdditionalHeight)); int iFullHeight = fullRect.height(); /* Prepare color: */ QPalette pal = palette(); QColor headerColor = pal.color(QPalette::Active, QPalette::Button); QColor strokeColor = pal.color(QPalette::Active, QPalette::Mid); QColor bodyColor = pal.color(QPalette::Active, QPalette::Base); /* Add clipping: */ QPainterPath path; path.moveTo(m_iCornerRadius, 0); path.arcTo(QRectF(path.currentPosition(), QSizeF(2 * m_iCornerRadius, 2 * m_iCornerRadius)).translated(-m_iCornerRadius, 0), 90, 90); path.lineTo(path.currentPosition().x(), iFullHeight - m_iCornerRadius); path.arcTo(QRectF(path.currentPosition(), QSizeF(2 * m_iCornerRadius, 2 * m_iCornerRadius)).translated(0, -m_iCornerRadius), 180, 90); path.lineTo(fullRect.width() - m_iCornerRadius, path.currentPosition().y()); path.arcTo(QRectF(path.currentPosition(), QSizeF(2 * m_iCornerRadius, 2 * m_iCornerRadius)).translated(-m_iCornerRadius, -2 * m_iCornerRadius), 270, 90); path.lineTo(path.currentPosition().x(), m_iCornerRadius); path.arcTo(QRectF(path.currentPosition(), QSizeF(2 * m_iCornerRadius, 2 * m_iCornerRadius)).translated(-2 * m_iCornerRadius, -m_iCornerRadius), 0, 90); path.closeSubpath(); pPainter->setClipPath(path); /* Calculate top rectangle: */ QRect tRect = fullRect; tRect.setBottom(tRect.top() + iHeaderHeight); /* Calculate bottom rectangle: */ QRect bRect = fullRect; bRect.setTop(tRect.bottom()); /* Prepare top gradient: */ QLinearGradient tGradient(tRect.bottomLeft(), tRect.topLeft()); tGradient.setColorAt(0, headerColor.darker(110)); tGradient.setColorAt(1, headerColor.darker(animationDarkness())); /* Paint all the stuff: */ pPainter->fillRect(tRect, tGradient); pPainter->fillRect(bRect, bodyColor); /* Stroke path: */ pPainter->setClipping(false); pPainter->strokePath(path, strokeColor); /* Restore painter: */ pPainter->restore(); } void UIGDetailsElement::hoverMoveEvent(QGraphicsSceneHoverEvent *pEvent) { /* Update hover state: */ if (!m_fHovered) { m_fHovered = true; emit sigHoverEnter(); } /* Update name-hover state: */ handleHoverEvent(pEvent); } void UIGDetailsElement::hoverLeaveEvent(QGraphicsSceneHoverEvent *pEvent) { /* Update hover state: */ if (m_fHovered) { m_fHovered = false; emit sigHoverLeave(); } /* Update name-hover state: */ handleHoverEvent(pEvent); } void UIGDetailsElement::mousePressEvent(QGraphicsSceneMouseEvent *pEvent) { /* Only for hovered header: */ if (!m_fNameHovered) return; /* Process link click: */ pEvent->accept(); QString strCategory; if (m_type >= DetailsElementType_General && m_type < DetailsElementType_Description) strCategory = QString("#%1").arg(gpConverter->toInternalString(m_type)); else if (m_type == DetailsElementType_Description) strCategory = QString("#%1%%mTeDescription").arg(gpConverter->toInternalString(m_type)); emit sigLinkClicked(strCategory, QString(), machine().GetId()); } void UIGDetailsElement::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *pEvent) { /* Only for left-button: */ if (pEvent->button() != Qt::LeftButton) return; /* Process left-button double-click: */ emit sigToggleElement(m_type, closed()); } void UIGDetailsElement::updateButtonVisibility() { if (m_fHovered && !m_pButton->isVisible()) m_pButton->show(); else if (!m_fHovered && m_pButton->isVisible()) m_pButton->hide(); } void UIGDetailsElement::handleHoverEvent(QGraphicsSceneHoverEvent *pEvent) { /* Not for 'preview' element type: */ if (m_type == DetailsElementType_Preview) return; /* Prepare variables: */ int iMargin = data(ElementData_Margin).toInt(); int iSpacing = data(ElementData_Spacing).toInt(); int iNameHeight = m_nameSize.height(); int iElementNameX = 2 * iMargin + m_pixmapSize.width() + iSpacing; int iElementNameY = iNameHeight == m_iMinimumHeaderHeight ? iMargin : iMargin + (m_iMinimumHeaderHeight - iNameHeight) / 2; /* Simulate hyperlink hovering: */ QPoint point = pEvent->pos().toPoint(); bool fNameHovered = QRect(QPoint(iElementNameX, iElementNameY), m_nameSize).contains(point); if ( m_pSet->configurationAccessLevel() != ConfigurationAccessLevel_Null && m_fNameHovered != fNameHovered) { m_fNameHovered = fNameHovered; updateNameHoverLink(); } } void UIGDetailsElement::updateNameHoverLink() { if (m_fNameHovered) VBoxGlobal::setCursor(this, Qt::PointingHandCursor); else VBoxGlobal::unsetCursor(this); update(); } void UIGDetailsElement::updateAnimationParameters() { /* Recalculate animation parameters: */ int iOpenedHeight = minimumHeightHint(false); int iClosedHeight = minimumHeightHint(true); int iAdditionalHeight = iOpenedHeight - iClosedHeight; if (m_fClosed) m_iAdditionalHeight = 0; else m_iAdditionalHeight = iAdditionalHeight; m_pButton->setAnimationRange(0, iAdditionalHeight); }
8,782
347
<gh_stars>100-1000 package org.ovirt.engine.core.common.businessentities; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public enum GuestAgentStatus { DoesntExist(0), Exists(1), UpdateNeeded(2); private static final Map<Integer, GuestAgentStatus> mappings = Stream.of(values()).collect(Collectors.toMap(GuestAgentStatus::getValue, Function.identity())); private int value; GuestAgentStatus(int value) { this.value = value; } public int getValue() { return value; } public static GuestAgentStatus forValue(int value) { return mappings.get(value); } }
267
675
/* * Copyright 2016 The Bazel 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 com.google.idea.blaze.base.sync.actions; import com.google.idea.blaze.base.sync.BlazeSyncManager; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; /** Allows a partial sync of the working set. */ public class SyncWorkingSetAction extends BlazeProjectSyncAction { @Override protected void runSync(Project project, AnActionEvent e) { BlazeSyncManager.getInstance(project).workingSetSync(/* reason= */ "SyncWorkingSetAction"); } }
309
460
#ifndef NX_COLLISION_NXTRIANGLEMESHSHAPEDESC #define NX_COLLISION_NXTRIANGLEMESHSHAPEDESC /*----------------------------------------------------------------------------*\ | | Public Interface to NovodeX Technology | | www.novodex.com | \*----------------------------------------------------------------------------*/ #include "NxShapeDesc.h" #include "NxTriangleMeshShape.h" /** Descriptor class for NxTriangleMeshShape. */ class NxTriangleMeshShapeDesc : public NxShapeDesc { public: NxTriangleMesh* meshData; //!< References the triangle mesh that we want to instance. NxU32 flags; //!< Combination of NxTriangleMeshShape::NxMeshShapeFlag(s) /** constructor sets to default. */ NX_INLINE NxTriangleMeshShapeDesc(); /** (re)sets the structure to the default. */ NX_INLINE virtual void setToDefault(); /** returns true if the current settings are valid */ NX_INLINE virtual bool isValid() const; }; NX_INLINE NxTriangleMeshShapeDesc::NxTriangleMeshShapeDesc() : NxShapeDesc(NX_SHAPE_MESH) //constructor sets to default { setToDefault(); } NX_INLINE void NxTriangleMeshShapeDesc::setToDefault() { NxShapeDesc::setToDefault(); meshData = NULL; flags = NX_MESH_SMOOTH_SPHERE_COLLISIONS; } NX_INLINE bool NxTriangleMeshShapeDesc::isValid() const { if(!meshData) return false; return NxShapeDesc::isValid(); } #endif
569
964
<gh_stars>100-1000 { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "myStackWithParams": { "Type": "AWS::CloudFormation::Stack", "Properties": { "NotificationARNs": [ "string" ], "TemplateURL": "https://s3.amazonaws.com/cloudformation-templates-us-east-2/EC2ChooseAMI.template", "Parameters": { "InstanceType": "t1.micro", "KeyName": "mykey" } } } } }
231
460
<reponame>dyzmapl/BumpTop #include "../../../tools/designer/src/lib/shared/shared_enums_p.h"
42
705
<reponame>JohnieBraaf/django-river<gh_stars>100-1000 from __future__ import unicode_literals from django.db import models from django.db.models import PROTECT from django.utils.translation import ugettext_lazy as _ from river.models import State, Workflow from river.models.base_model import BaseModel class TransitionMeta(BaseModel): class Meta: app_label = 'river' verbose_name = _("Transition Meta") verbose_name_plural = _("Transition Meta") unique_together = [('workflow', 'source_state', 'destination_state')] workflow = models.ForeignKey(Workflow, verbose_name=_("Workflow"), related_name='transition_metas', on_delete=PROTECT) source_state = models.ForeignKey(State, verbose_name=_("Source State"), related_name='transition_meta_as_source', on_delete=PROTECT) destination_state = models.ForeignKey(State, verbose_name=_("Destination State"), related_name='transition_meta_as_destination', on_delete=PROTECT) def __str__(self): return 'Field Name:%s, %s -> %s' % ( self.workflow, self.source_state, self.destination_state )
428
545
<filename>mcc_generated_files/boot/com_adaptor_uart.c /** @Generated 16-bit Bootloader Source File @Company: Microchip Technology Inc. @File Name: com_adaptor_uart.c @Summary: This is the com_adaptor_uart.c file generated using 16-bit Bootloader @Description: This header file provides implementations for driver APIs for all modules selected in the GUI. Generation Information : Product Revision : 16-bit Bootloader - 1.17.2 Device : PIC24EP256GP204 The generated drivers are tested against the following: Compiler : XC16 v1.36B MPLAB : MPLAB X v5.15 */ /* Copyright (c) [2012-2019] Microchip Technology Inc. All rights reserved. You are permitted to use the accompanying software and its derivatives with Microchip products. See the Microchip license agreement accompanying this software, if any, for additional info regarding your rights and obligations. MICROCHIP SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY FOR ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES, OR OTHER SIMILAR COSTS. To the fullest extend allowed by law, Microchip and its licensors liability will not exceed the amount of fees, if any, that you paid directly to Microchip to use this software. THIRD PARTY SOFTWARE: Notwithstanding anything to the contrary, any third party software accompanying this software is subject to the terms and conditions of the third party's license agreement. To the extent required by third party licenses covering such third party software, the terms of such license will apply in lieu of the terms provided in this notice or applicable license. To the extent the terms of such third party licenses prohibit any of the restrictions described here, such restrictions will not apply to such third party software. */ #include <string.h> #include "com_adaptor.h" #include "boot_config.h" #include "boot_private.h" #include "../uart1.h" struct COM_DATA_STRUCT { uint8_t pendingCommand[BOOT_CONFIG_MAX_PACKET_SIZE]; uint16_t pendingCommandLength; bool isPendingCommandLoaded; uint8_t responseBuffer[BOOT_CONFIG_MAX_PACKET_SIZE]; uint16_t responseBufferLength; bool isResponseLoaded; }; struct COM_DATA_STRUCT uartComData; uint8_t BOOT_COM_Peek(uint16_t location) { return uartComData.pendingCommand[location]; } uint16_t BOOT_COM_Read(uint8_t* data, uint16_t length) { uint16_t i = 0; if (BOOT_COM_GetBytesReady() >= length) { for (i = 0; i < length; i++) { data[i] = uartComData.pendingCommand[i]; } i = length; uartComData.pendingCommandLength = 0; uartComData.isPendingCommandLoaded = false; } return i; }; void BOOT_COM_Write(uint8_t* data, uint16_t length) { while(length) { if (UART1_IsTxReady()) { UART1_Write(*data++); length--; } } while (UART1_IsTxDone()==false); uartComData.responseBufferLength = 0; uartComData.isResponseLoaded = 0; }; uint16_t BOOT_COM_GetBytesReady() { static bool initilized=false; if (!initilized) { // ====================================================================================================== // During com_adaptor_initialization the user may want to check the UART for any errors here before // proceeding. Make sure the RX line is either driven high by the transmitter or pulled high via a pullup. // Failure to do so could cause the user to encounter frame errors or other line errors which can be // difficult to debug. // ====================================================================================================== memset(&uartComData,0, sizeof(struct COM_DATA_STRUCT )/sizeof(uint8_t)); initilized = true; } while ( UART1_IsRxReady() && (uartComData.pendingCommandLength < BOOT_CONFIG_MAX_PACKET_SIZE) ) { uartComData.pendingCommand[uartComData.pendingCommandLength++]= UART1_Read(); } return uartComData.pendingCommandLength; }
1,838
1,198
/* * Copyright 2019 <NAME> * Copyright 2019 <NAME> * * 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 toothpick.configuration; import toothpick.Scope; /** Check strategy to detect when mutiple roots are created in TP scope forest. */ interface MultipleRootScopeCheckConfiguration { /** * Check that a scope doesn't introduce a second root in TP scope forest. * * @param scope a newly created scope. */ void checkMultipleRootScopes(Scope scope); /** Reset the state of the detector. */ void onScopeForestReset(); }
282
2,003
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utils/schema_utils.h" #include <sstream> #include <glog/logging.h> namespace tera { bool IsSchemaCfDiff(const TableSchema& a, const TableSchema& b) { std::stringstream s0; std::stringstream s1; for (int i = 0; i < a.column_families_size(); ++i) { s0 << a.column_families(i).ShortDebugString(); } LOG(INFO) << "[utils] " << s0.str(); for (int i = 0; i < b.column_families_size(); ++i) { s1 << b.column_families(i).ShortDebugString(); } LOG(INFO) << "[utils] " << s1.str(); return (s0.str().compare(s1.str()) != 0); } bool IsSchemaLgDiff(const TableSchema& a, const TableSchema& b) { std::stringstream s0; std::stringstream s1; for (int i = 0; i < a.locality_groups_size(); ++i) { s0 << a.locality_groups(i).ShortDebugString(); } LOG(INFO) << "[utils] " << s0.str(); for (int i = 0; i < b.locality_groups_size(); ++i) { s1 << b.locality_groups(i).ShortDebugString(); } LOG(INFO) << "[utils] " << s1.str(); return (s0.str().compare(s1.str()) != 0); } } // namespace tera
483
2,151
#define _STLP_PLATFORM "Free BSD" #define _STLP_USE_UNIX_IO
29
416
#include <AudioToolbox/AUComponent.h>
13
14,668
<reponame>zealoussnow/chromium<gh_stars>1000+ // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_TEST_FORM_STRUCTURE_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_TEST_FORM_STRUCTURE_H_ #include <vector> #include "components/autofill/core/browser/form_structure.h" namespace autofill { class TestFormStructure : public FormStructure { public: explicit TestFormStructure(const FormData& form); TestFormStructure(const TestFormStructure&) = delete; TestFormStructure& operator=(const TestFormStructure&) = delete; ~TestFormStructure() override; void SetFieldTypes(const std::vector<ServerFieldType>& heuristic_types, const std::vector<ServerFieldType>& server_types); }; } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_TEST_FORM_STRUCTURE_H_
333
1,671
// Copyright 2019 SoloKeys Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #ifndef _RNG_H_ #define _RNG_H_ #include <stdint.h> void rng_get_bytes(uint8_t * dst, size_t sz); float shannon_entropy(float * p, size_t sz); float rng_test(size_t n); #endif
185
841
<filename>testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/sse/SseAPI.java package org.jboss.resteasy.test.providers.sse; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.sse.SseEventSink; public interface SseAPI { @Path("/events") @GET @Produces({ "text/event-stream" }) void events(@Context SseEventSink sseEvents) throws Exception; @Path("send") @POST void send(String msg); }
228
372
<filename>clients/google-api-services-dlp/v2/1.30.1/com/google/api/services/dlp/v2/model/GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues.java /* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dlp.v2.model; /** * A tuple of values for the quasi-identifier columns. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Data Loss Prevention (DLP) API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues extends com.google.api.client.json.GenericJson { /** * The estimated probability that a given individual sharing these quasi-identifier values is in * the dataset. This value, typically called δ, is the ratio between the number of records in the * dataset with these quasi-identifier values, and the total number of individuals (inside *and* * outside the dataset) with these quasi-identifier values. For example, if there are 15 * individuals in the dataset who share the same quasi-identifier values, and an estimated 100 * people in the entire population with these values, then δ is 0.15. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Double estimatedProbability; /** * The quasi-identifier values. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GooglePrivacyDlpV2Value> quasiIdsValues; /** * The estimated probability that a given individual sharing these quasi-identifier values is in * the dataset. This value, typically called δ, is the ratio between the number of records in the * dataset with these quasi-identifier values, and the total number of individuals (inside *and* * outside the dataset) with these quasi-identifier values. For example, if there are 15 * individuals in the dataset who share the same quasi-identifier values, and an estimated 100 * people in the entire population with these values, then δ is 0.15. * @return value or {@code null} for none */ public java.lang.Double getEstimatedProbability() { return estimatedProbability; } /** * The estimated probability that a given individual sharing these quasi-identifier values is in * the dataset. This value, typically called δ, is the ratio between the number of records in the * dataset with these quasi-identifier values, and the total number of individuals (inside *and* * outside the dataset) with these quasi-identifier values. For example, if there are 15 * individuals in the dataset who share the same quasi-identifier values, and an estimated 100 * people in the entire population with these values, then δ is 0.15. * @param estimatedProbability estimatedProbability or {@code null} for none */ public GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues setEstimatedProbability(java.lang.Double estimatedProbability) { this.estimatedProbability = estimatedProbability; return this; } /** * The quasi-identifier values. * @return value or {@code null} for none */ public java.util.List<GooglePrivacyDlpV2Value> getQuasiIdsValues() { return quasiIdsValues; } /** * The quasi-identifier values. * @param quasiIdsValues quasiIdsValues or {@code null} for none */ public GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues setQuasiIdsValues(java.util.List<GooglePrivacyDlpV2Value> quasiIdsValues) { this.quasiIdsValues = quasiIdsValues; return this; } @Override public GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues set(String fieldName, Object value) { return (GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues) super.set(fieldName, value); } @Override public GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues clone() { return (GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues) super.clone(); } }
1,418
540
<reponame>intel/parallelstl // -*- C++ -*- //===-- execution_sycl_defs.h ---------------------------------------------===// // // Copyright (C) Intel Corporation // // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // // This file incorporates work covered by the following copyright and permission // notice: // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // //===----------------------------------------------------------------------===// #ifndef _ONEDPL_execution_sycl_defs_H #define _ONEDPL_execution_sycl_defs_H #include "../../onedpl_config.h" #include "../../execution_defs.h" #include "sycl_defs.h" namespace oneapi { namespace dpl { namespace execution { inline namespace __dpl { struct DefaultKernelName; //We can create device_policy object: // 1. from sycl::queue // 2. from sycl::device_selector (implicitly through sycl::queue) // 3. from sycl::device // 4. from other device_policy encapsulating the same queue type template <typename KernelName = DefaultKernelName> class device_policy { public: using kernel_name = KernelName; device_policy() = default; template <typename OtherName> device_policy(const device_policy<OtherName>& other) : q(other.queue()) { } explicit device_policy(sycl::queue q_) : q(q_) {} explicit device_policy(sycl::device d_) : q(d_) {} operator sycl::queue() const { return q; } sycl::queue queue() const { return q; } // For internal use only static constexpr ::std::true_type __allow_unsequenced() { return ::std::true_type{}; } // __allow_vector is needed for __is_vectorization_preferred static constexpr ::std::true_type __allow_vector() { return ::std::true_type{}; } static constexpr ::std::true_type __allow_parallel() { return ::std::true_type{}; } private: sycl::queue q; }; #if _ONEDPL_FPGA_DEVICE struct DefaultKernelNameFPGA; template <unsigned int factor = 1, typename KernelName = DefaultKernelNameFPGA> class fpga_policy : public device_policy<KernelName> { using base = device_policy<KernelName>; public: static constexpr unsigned int unroll_factor = factor; fpga_policy() : base(sycl::queue( # if _ONEDPL_FPGA_EMU __dpl_sycl::__fpga_emulator_selector {} # else __dpl_sycl::__fpga_selector {} # endif // _ONEDPL_FPGA_EMU )) { } template <unsigned int other_factor, typename OtherName> fpga_policy(const fpga_policy<other_factor, OtherName>& other) : base(other.queue()){}; explicit fpga_policy(sycl::queue q) : base(q) {} explicit fpga_policy(sycl::device d) : base(d) {} }; #endif // _ONEDPL_FPGA_DEVICE // 2.8, Execution policy objects #if _ONEDPL_PREDEFINED_POLICIES // In order to be useful oneapi::dpl::execution::dpcpp_default.queue() from one translation unit should be equal to // oneapi::dpl::execution::dpcpp_default.queue() from another TU. // Starting with c++17 we can simply define sycl as inline variable. // But for c++11 we need to simulate this feature using local static variable and inline function to achieve // a single definition across all TUs. As it's required for underlying sycl's queue to behave in the same way // as it's copy, we simply copy-construct a static variable from a reference to that object. # if __cplusplus >= 201703L inline device_policy<> dpcpp_default{}; # if _ONEDPL_FPGA_DEVICE inline fpga_policy<> dpcpp_fpga{}; # endif // _ONEDPL_FPGA_DEVICE # else template <typename DeviceSelector> inline device_policy<>& __get_default_policy_object(DeviceSelector selector) { static device_policy<> __single_base_obj(selector); return __single_base_obj; } static device_policy<> dpcpp_default{__get_default_policy_object(sycl::default_selector{})}; # if _ONEDPL_FPGA_DEVICE inline fpga_policy<>& __get_fpga_policy_object() { static fpga_policy<> __single_base_obj{}; return __single_base_obj; } static fpga_policy<> dpcpp_fpga{__get_fpga_policy_object()}; # endif // _ONEDPL_FPGA_DEVICE # endif // __cplusplus >= 201703L #endif // _ONEDPL_PREDEFINED_POLICIES // make_policy functions template <typename KernelName = DefaultKernelName> device_policy<KernelName> make_device_policy(sycl::queue q) { return device_policy<KernelName>(q); } template <typename KernelName = DefaultKernelName> device_policy<KernelName> make_device_policy(sycl::device d) { return device_policy<KernelName>(d); } template <typename NewKernelName, typename OldKernelName = DefaultKernelName> device_policy<NewKernelName> make_device_policy(const device_policy<OldKernelName>& policy #if _ONEDPL_PREDEFINED_POLICIES = dpcpp_default #endif // _ONEDPL_PREDEFINED_POLICIES ) { return device_policy<NewKernelName>(policy); } template <typename NewKernelName, typename OldKernelName = DefaultKernelName> device_policy<NewKernelName> make_hetero_policy(const device_policy<OldKernelName>& policy) { return device_policy<NewKernelName>(policy); } #if _ONEDPL_FPGA_DEVICE template <unsigned int unroll_factor = 1, typename KernelName = DefaultKernelNameFPGA> fpga_policy<unroll_factor, KernelName> make_fpga_policy(sycl::queue q) { return fpga_policy<unroll_factor, KernelName>(q); } template <unsigned int unroll_factor = 1, typename KernelName = DefaultKernelNameFPGA> fpga_policy<unroll_factor, KernelName> make_fpga_policy(sycl::device d) { return fpga_policy<unroll_factor, KernelName>(d); } template <unsigned int new_unroll_factor, typename NewKernelName, unsigned int old_unroll_factor = 1, typename OldKernelName = DefaultKernelNameFPGA> fpga_policy<new_unroll_factor, NewKernelName> make_fpga_policy(const fpga_policy<old_unroll_factor, OldKernelName>& policy # if _ONEDPL_PREDEFINED_POLICIES = dpcpp_fpga # endif // _ONEDPL_PREDEFINED_POLICIES ) { return fpga_policy<new_unroll_factor, NewKernelName>(policy); } template <unsigned int new_unroll_factor, typename NewKernelName, unsigned int old_unroll_factor = 1, typename OldKernelName = DefaultKernelNameFPGA> fpga_policy<new_unroll_factor, NewKernelName> make_hetero_policy(const fpga_policy<old_unroll_factor, OldKernelName>& policy) { return fpga_policy<new_unroll_factor, NewKernelName>(policy); } #endif // _ONEDPL_FPGA_DEVICE } // namespace __dpl inline namespace v1 { // 2.3, Execution policy type trait template <typename... PolicyParams> struct is_execution_policy<__dpl::device_policy<PolicyParams...>> : ::std::true_type { }; #if _ONEDPL_FPGA_DEVICE template <unsigned int unroll_factor, typename... PolicyParams> struct is_execution_policy<__dpl::fpga_policy<unroll_factor, PolicyParams...>> : ::std::true_type { }; #endif } // namespace v1 } // namespace execution namespace __internal { // Extension: hetero execution policy type trait template <typename _T> struct __is_hetero_execution_policy : ::std::false_type { }; template <typename... PolicyParams> struct __is_hetero_execution_policy<execution::device_policy<PolicyParams...>> : ::std::true_type { }; template <typename _T> struct __is_device_execution_policy : ::std::false_type { }; template <typename... PolicyParams> struct __is_device_execution_policy<execution::device_policy<PolicyParams...>> : ::std::true_type { }; template <typename _T> struct __is_fpga_execution_policy : ::std::false_type { }; #if _ONEDPL_FPGA_DEVICE template <unsigned int unroll_factor, typename... PolicyParams> struct __is_hetero_execution_policy<execution::fpga_policy<unroll_factor, PolicyParams...>> : ::std::true_type { }; template <unsigned int unroll_factor, typename... PolicyParams> struct __is_fpga_execution_policy<execution::fpga_policy<unroll_factor, PolicyParams...>> : ::std::true_type { }; template <typename _T, unsigned int unroll_factor, typename... PolicyParams> struct __ref_or_copy_impl<execution::fpga_policy<unroll_factor, PolicyParams...>, _T> { using type = _T; }; #endif template <typename _T, typename... PolicyParams> struct __ref_or_copy_impl<execution::device_policy<PolicyParams...>, _T> { using type = _T; }; // Extension: check if parameter pack is convertible to events template <bool...> struct __is_true_helper { }; template <bool... _Ts> using __is_all_true = ::std::is_same<__is_true_helper<_Ts..., true>, __is_true_helper<true, _Ts...>>; template <class... _Ts> using __is_convertible_to_event = __is_all_true<::std::is_convertible<typename ::std::decay<_Ts>::type, sycl::event>::value...>; template <typename _T, typename... _Events> using __enable_if_convertible_to_events = typename ::std::enable_if<oneapi::dpl::__internal::__is_convertible_to_event<_Events...>::value, _T>::type; // Extension: execution policies type traits template <typename _ExecPolicy, typename _T, typename... _Events> using __enable_if_device_execution_policy = typename ::std::enable_if< oneapi::dpl::__internal::__is_device_execution_policy<typename ::std::decay<_ExecPolicy>::type>::value && oneapi::dpl::__internal::__is_convertible_to_event<_Events...>::value, _T>::type; template <typename _ExecPolicy, typename _T> using __enable_if_hetero_execution_policy = typename ::std::enable_if< oneapi::dpl::__internal::__is_hetero_execution_policy<typename ::std::decay<_ExecPolicy>::type>::value, _T>::type; template <typename _ExecPolicy, typename _T> using __enable_if_fpga_execution_policy = typename ::std::enable_if< oneapi::dpl::__internal::__is_fpga_execution_policy<typename ::std::decay<_ExecPolicy>::type>::value, _T>::type; //----------------------------------------------------------------------------- // Device run-time information helpers //----------------------------------------------------------------------------- #if _ONEDPL_DEBUG_SYCL template <typename _ExecutionPolicy> ::std::string __device_info(_ExecutionPolicy&& __policy) { return __policy.queue().get_device().template get_info<sycl::info::device::name>(); } #endif template <typename _ExecutionPolicy> ::std::size_t __max_work_group_size(_ExecutionPolicy&& __policy) { return __policy.queue().get_device().template get_info<sycl::info::device::max_work_group_size>(); } template <typename _ExecutionPolicy, typename _Size> _Size __max_local_allocation_size(_ExecutionPolicy&& __policy, _Size __type_size, _Size __local_allocation_size) { return ::std::min(__policy.queue().get_device().template get_info<sycl::info::device::local_mem_size>() / __type_size, __local_allocation_size); } #if _USE_SUB_GROUPS template <typename _ExecutionPolicy> ::std::size_t __max_sub_group_size(_ExecutionPolicy&& __policy) { auto __supported_sg_sizes = __policy.queue().get_device().template get_info<sycl::info::device::sub_group_sizes>(); //The result of get_info<sycl::info::device::sub_group_sizes>() can be empty - the function returns 0; return __supported_sg_sizes.empty() ? 0 : __supported_sg_sizes.back(); } #endif template <typename _ExecutionPolicy> auto __max_compute_units(_ExecutionPolicy&& __policy) -> decltype(__policy.queue().get_device().template get_info<sycl::info::device::max_compute_units>()) { return __policy.queue().get_device().template get_info<sycl::info::device::max_compute_units>(); } //----------------------------------------------------------------------------- // Kernel run-time information helpers //----------------------------------------------------------------------------- // 20201214 value corresponds to Intel(R) oneAPI C++ Compiler Classic 2021.1.2 Patch release #define _USE_KERNEL_DEVICE_SPECIFIC_API (__SYCL_COMPILER_VERSION > 20201214) template <typename _ExecutionPolicy> ::std::size_t __kernel_work_group_size(_ExecutionPolicy&& __policy, const sycl::kernel& __kernel) { const sycl::device& __device = __policy.queue().get_device(); const ::std::size_t __max_wg_size = #if _USE_KERNEL_DEVICE_SPECIFIC_API __kernel.template get_info<sycl::info::kernel_device_specific::work_group_size>(__device); #else __kernel.template get_work_group_info<sycl::info::kernel_work_group::work_group_size>(__device); #endif // The variable below is needed to achieve better performance on CPU devices. // Experimentally it was found that the most common divisor is 4 with all patterns. // TODO: choose the divisor according to specific pattern. ::std::size_t __cpu_divisor = 1; if (__device.is_cpu() && __max_wg_size >= 4) __cpu_divisor = 4; return __max_wg_size / __cpu_divisor; } template <typename _ExecutionPolicy> ::std::uint32_t __kernel_sub_group_size(_ExecutionPolicy&& __policy, const sycl::kernel& __kernel) { const sycl::device& __device = __policy.queue().get_device(); const ::std::size_t __wg_size = __kernel_work_group_size(::std::forward<_ExecutionPolicy>(__policy), __kernel); const ::std::uint32_t __sg_size = #if _USE_KERNEL_DEVICE_SPECIFIC_API __kernel.template get_info<sycl::info::kernel_device_specific::max_sub_group_size>( #else __kernel.template get_sub_group_info<sycl::info::kernel_sub_group::max_sub_group_size>( #endif __device, sycl::range<3>{__wg_size, 1, 1}); return __sg_size; } } // namespace __internal } // namespace dpl } // namespace oneapi #endif /* _ONEDPL_execution_sycl_defs_H */
4,939
782
<gh_stars>100-1000 /* * Copyright (c) 2021, <NAME>. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.geo.h; import boofcv.alg.geo.MultiViewOps; import boofcv.struct.geo.AssociatedPair; import boofcv.struct.geo.AssociatedPair3D; import boofcv.testing.BoofStandardJUnit; import georegression.geometry.GeometryMath_F64; import georegression.struct.point.Point3D_F64; import georegression.struct.point.Point4D_F64; import georegression.struct.point.Vector3D_F64; import georegression.struct.se.Se3_F64; import georegression.struct.se.SpecialEuclideanOps_F64; import georegression.transform.se.SePointOps_F64; import org.ejml.data.DMatrixRMaj; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Creates two views of a planar scene for checking homography related algorithms * * @author <NAME> */ public class CommonHomographyChecks extends BoofStandardJUnit { // create a reasonable calibration matrix protected DMatrixRMaj K = new DMatrixRMaj(3, 3, true, 60, 0.01, 200, 0, 80, 150, 0, 0, 1); protected Se3_F64 motion = SpecialEuclideanOps_F64.eulerXyz(0.1, -0.1, 0.01, 0.05, -0.03, 0.02, null); protected List<Point3D_F64> pts; protected List<AssociatedPair> pairs2D; protected List<AssociatedPair3D> pairs3D; protected double d = 3; // distance plane is from camera protected DMatrixRMaj solution = new DMatrixRMaj(3, 3); public void createScene( int numPoints, boolean isPixels ) { // randomly generate points in space pts = createRandomPlane(rand, d, numPoints); // transform points into second camera's reference frame pairs2D = new ArrayList<>(); for (Point3D_F64 p1 : pts) { Point3D_F64 p2 = SePointOps_F64.transform(motion, p1, null); AssociatedPair pair = new AssociatedPair(); pair.p1.setTo(p1.x/p1.z, p1.y/p1.z); pair.p2.setTo(p2.x/p2.z, p2.y/p2.z); pairs2D.add(pair); if (isPixels) { GeometryMath_F64.mult(K, pair.p1, pair.p1); GeometryMath_F64.mult(K, pair.p2, pair.p2); } } pairs3D = new ArrayList<>(); for (int i = 0; i < pairs2D.size(); i++) { AssociatedPair p2 = pairs2D.get(i); AssociatedPair3D p3 = new AssociatedPair3D(); // same point but in homogenous coordinates and Z isn't always 1 double z = 1.0 + rand.nextGaussian()*0.1; p3.p1.setTo(p2.p1.x*z, p2.p1.y*z, z); p3.p2.setTo(p2.p2.x*z, p2.p2.y*z, z); pairs3D.add(p3); } } protected DMatrixRMaj computeH( boolean isPixel ) { if (isPixel) return MultiViewOps.createHomography(motion.R, motion.T, 1, new Vector3D_F64(0, 0, -1), K); else return MultiViewOps.createHomography(motion.R, motion.T, 1, new Vector3D_F64(0, 0, -1)); } /** * Creates a set of random points along the (X,Y) plane */ public static List<Point3D_F64> createRandomPlane( Random rand, double d, int N ) { List<Point3D_F64> ret = new ArrayList<>(); for (int i = 0; i < N; i++) { double x = (rand.nextDouble() - 0.5)*2; double y = (rand.nextDouble() - 0.5)*2; ret.add(new Point3D_F64(x, y, d)); } return ret; } /** * Create a random set of points which line on the x-y plane at distance 'd' */ public static List<Point4D_F64> createRandomPlaneH( Random rand, double d, int N ) { List<Point4D_F64> ret = new ArrayList<>(); for (int i = 0; i < N; i++) { double x = (rand.nextDouble() - 0.5)*2; double y = (rand.nextDouble() - 0.5)*2; // make it more interesting by not having the same W for all the point double scale = rand.nextDouble() + 0.1; if (rand.nextBoolean()) scale *= -1; ret.add(new Point4D_F64(scale*x, scale*y, scale*d, scale)); } return ret; } }
1,646
400
<gh_stars>100-1000 #ifndef BLAKE_H #define BLAKE_H // nothing to see here... move along #endif // #ifndef BLAKE_H
51
411
<reponame>elihschiff/Submitty def up(config, database, semester, course): database.execute("""DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'notifications_component') THEN CREATE TYPE notifications_component AS ENUM ('forum'); END IF; END$$;""") database.execute("""CREATE TABLE IF NOT EXISTS notifications ( id serial NOT NULL PRIMARY KEY, component notifications_component NOT NULL, metadata TEXT NOT NULL, content TEXT NOT NULL, from_user_id VARCHAR(255), to_user_id VARCHAR(255) NOT NULL, created_at timestamp with time zone NOT NULL, seen_at timestamp with time zone)""") database.execute("ALTER TABLE ONLY notifications DROP CONSTRAINT IF EXISTS notifications_to_user_id_fkey") database.execute("ALTER TABLE ONLY notifications ADD CONSTRAINT notifications_to_user_id_fkey FOREIGN KEY (to_user_id) REFERENCES users(user_id) ON UPDATE CASCADE") database.execute("ALTER TABLE ONLY notifications DROP CONSTRAINT IF EXISTS notifications_from_user_id_fkey") database.execute("ALTER TABLE ONLY notifications ADD CONSTRAINT notifications_from_user_id_fkey FOREIGN KEY (from_user_id) REFERENCES users(user_id) ON UPDATE CASCADE")
470
6,215
{ "client_id": "<invalid_client_id>", "client_secret": "<invalid_client_secret>", "refresh_token": "<invalid_refresh_token>", "realm_id": "<invalid_realm_id>", "user_agent": "invalid <EMAIL>", "start_date": "2021-01-01T00:00:00Z", "sandbox": true }
116
358
<reponame>alanjjenkins/awacs<gh_stars>100-1000 # Copyright (c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "Amazon Cognito Identity" prefix = "cognito-identity" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateIdentityPool = Action("CreateIdentityPool") DeleteIdentities = Action("DeleteIdentities") DeleteIdentityPool = Action("DeleteIdentityPool") DescribeIdentity = Action("DescribeIdentity") DescribeIdentityPool = Action("DescribeIdentityPool") GetCredentialsForIdentity = Action("GetCredentialsForIdentity") GetId = Action("GetId") GetIdentityPoolRoles = Action("GetIdentityPoolRoles") GetOpenIdToken = Action("GetOpenIdToken") GetOpenIdTokenForDeveloperIdentity = Action("GetOpenIdTokenForDeveloperIdentity") GetPrincipalTagAttributeMap = Action("GetPrincipalTagAttributeMap") ListIdentities = Action("ListIdentities") ListIdentityPools = Action("ListIdentityPools") ListTagsForResource = Action("ListTagsForResource") LookupDeveloperIdentity = Action("LookupDeveloperIdentity") MergeDeveloperIdentities = Action("MergeDeveloperIdentities") SetIdentityPoolRoles = Action("SetIdentityPoolRoles") SetPrincipalTagAttributeMap = Action("SetPrincipalTagAttributeMap") TagResource = Action("TagResource") UnlinkDeveloperIdentity = Action("UnlinkDeveloperIdentity") UnlinkIdentity = Action("UnlinkIdentity") UntagResource = Action("UntagResource") UpdateIdentityPool = Action("UpdateIdentityPool")
562
327
<filename>cola-cloud-framework/cola-cloud-framework-util/src/main/java/com/honvay/cola/cloud/framework/util/ObjectUtils.java<gh_stars>100-1000 package com.honvay.cola.cloud.framework.util; import org.apache.commons.lang3.StringUtils; import java.util.Objects; /** * @author LIQIU * @date 2018-4-19 **/ public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils{ public static boolean isNull(Object value){ if(value instanceof String){ return StringUtils.isEmpty((String)value); } return Objects.isNull(value); } }
225
1,886
<reponame>mananpal1997/cinder /* C accelerator implementation for PyIce */ #include "Python.h" #include "bytes_methods.h" #include <stdint.h> /* Structures for the in-memory/on-disk format */ typedef struct { int64_t marker; /* ICEPACK<version byte> */ uint32_t timestamp; /* timestamp of latest file */ unsigned int modules; /* offset to module table */ unsigned int codes; /* offset to code object table */ unsigned int strings; /* offset to string table */ unsigned int bytes; /* offset to byte table */ unsigned int ints; /* offset to int table */ unsigned int bigints; /* offset to big int table */ unsigned int floats; /* offset to float table */ unsigned int complexes; /* offset to complex table */ unsigned int tuples; /* offset to tuple table */ unsigned int frozensets; /* offset to frozen set table */ } IcePackHeader; typedef struct { unsigned int count; unsigned int offsets[1]; } OffsetSection; typedef struct { unsigned int count; unsigned int padding; double values[1]; } FloatSection; typedef struct { unsigned int count; unsigned int padding; Py_complex values[1]; } ComplexSection; typedef struct { unsigned int count; int values[1]; } IntSection; typedef struct { unsigned int name; unsigned int code; unsigned int is_package; unsigned int filename; unsigned int children; } ModuleInfo; typedef struct { unsigned int count; ModuleInfo modules[1]; } ModuleSection; typedef struct { unsigned int bytes; unsigned int argcount; unsigned int kwonlyargcount; unsigned int nlocals; unsigned int stacksize; unsigned int flags; unsigned int firstlineno; unsigned int name; unsigned int filename; unsigned int lnotab; unsigned int cellvars; unsigned int freevars; unsigned int names; unsigned int varnames; unsigned int consts; } CodeObject; typedef struct { unsigned int len; const char data[1]; } IcePackStr; typedef struct { unsigned int len; const unsigned char data[1]; } IcePackBytes; typedef struct { unsigned int count; unsigned int values[1]; } IcePackArray; /* Python objects */ typedef struct { PyObject_HEAD PyObject *obj; PyObject* base_dir; PyObject* filename_map; // Pointers into our memory mapped buffer that represent different sections ModuleSection* section_modules; OffsetSection* section_code, *section_frozenset, * section_str, *section_bytes, *section_bigint, *section_tuple; FloatSection* section_float; ComplexSection* section_complex; IntSection *section_int; // Caches of Python objects produced from the sections PyObject** str_cache; PyObject** bytes_cache; PyObject** float_cache; PyObject** complex_cache; PyObject** int_cache; PyObject** bigint_cache; PyObject** tuple_cache; PyObject** frozenset_cache; Py_buffer codebuffer; } CIceBreaker; typedef struct { PyObject_HEAD const char* data; size_t size; Py_ssize_t hash; CIceBreaker *breaker; size_t exports; PyObject* code_obj; // borrowed reference, the code object keeps us alive } CIceBreakerCode; typedef struct { PyObject_HEAD PyObject* value; Py_hash_t hash; } CObjectValue; static PyTypeObject CIceBreakerType; static PyTypeObject CIceBreakerCodeType; static PyTypeObject CObjectValueType; static PyObject *IcePackError; #define CIceBreakerObject_Check(v) (Py_TYPE(v) == &CIceBreakerType) #define CIceBreakerCodeObject_Check(v) (Py_TYPE(v) == &CIceBreakerCodeType) #define CLEANUP_IF_NULL(x) if (x == NULL) goto cleanup /* CIceBreaker methods */ static void clear_cache(PyObject** cache, unsigned int count) { if (cache != NULL) { for (unsigned int i = 0; i<count; i++) { Py_XDECREF(cache[i]); } } } static inline int validate_index(CIceBreaker *self, const void* pointer, const char* source) { if (pointer < self->codebuffer.buf || pointer >= (void*)(((char*)self->codebuffer.buf) + self->codebuffer.len)) { char buf[81]; if (pointer < self->codebuffer.buf) { snprintf(buf, sizeof(buf), "Invalid icepack: reading %s negative offset %ld", source, (char*)self->codebuffer.buf - (char*)pointer); } else { snprintf(buf, sizeof(buf), "Invalid icepack: reading %s offset %ld is out of bounds %ld", source, (char*)self->codebuffer.buf - (char*)pointer, self->codebuffer.len); } PyErr_SetString(PyExc_MemoryError, "Invalid Icepack"); return 0; } return 1; } static void CIceBreaker_dealloc(CIceBreaker *self) { if (self->section_str != NULL) { clear_cache(self->str_cache, self->section_str->count); } if (self->section_bytes != NULL) { clear_cache(self->bytes_cache, self->section_bytes->count); } if (self->section_float != NULL) { clear_cache(self->float_cache, self->section_float->count); } if (self->section_complex != NULL) { clear_cache(self->complex_cache, self->section_complex->count); } if (self->section_int != NULL) { clear_cache(self->int_cache, self->section_int->count); } if (self->section_bigint != NULL) { clear_cache(self->bigint_cache, self->section_bigint->count); } if (self->section_tuple != NULL) { clear_cache(self->tuple_cache, self->section_tuple->count); } if (self->section_frozenset != NULL) { clear_cache(self->frozenset_cache, self->section_frozenset->count); } Py_XDECREF(self->base_dir); Py_XDECREF(self->filename_map); PyBuffer_Release(&self->codebuffer); if (self->obj != NULL) { Py_DECREF(self->obj); } Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * read_const(CIceBreaker *self, unsigned int const_val, int* can_cache); static PyObject * CIceBreaker__exit__(CIceBreaker *self, PyObject *args) { // Release our buffer when we're used as a context manager PyBuffer_Release(&self->codebuffer); self->codebuffer = (Py_buffer) { 0 }; // Call __exit__ on our super class if it's defined, so it can release // the mmap as well. PyObject* super_args = NULL, *super = NULL, *func = NULL; PyObject* res = NULL; super_args = PyTuple_New(2); if (super_args == NULL) { goto cleanup; } PyTuple_SET_ITEM(super_args, 0, (PyObject*)&CIceBreakerType); Py_INCREF(&CIceBreakerType); PyTuple_SET_ITEM(super_args, 1, (PyObject*)self); Py_INCREF(self); super = PyType_GenericNew(&PySuper_Type, super_args, NULL); if (super == NULL || super->ob_type->tp_init(super, super_args, NULL)) { goto cleanup; } func = PyObject_GetAttrString(super, "__exit__"); if (func != NULL) { res = PyObject_Call(func, args, NULL); if (res == NULL) { goto cleanup; } } else { PyErr_Clear(); res = Py_None; Py_INCREF(res); } cleanup: Py_XDECREF(super); Py_XDECREF(super_args); Py_XDECREF(func); return res; } #define CHECK_CACHED(type) \ if (index >= self->section_##type->count) { \ PyErr_SetString(PyExc_ValueError, "Invalid " #type " index"); \ return NULL; \ } else if (self->type##_cache[index] != NULL) { \ PyObject* res = self->type##_cache[index]; \ Py_INCREF(res); \ return res; \ } #define VALIDATE_TABLE_INDEX(type) \ if (index >= self->section_##type->count) { \ PyErr_SetString(PyExc_ValueError, "Invalid " #type " index"); \ return NULL; \ } #define DEFINE_CACHED_READER(type) \ static PyObject * \ read_##type(CIceBreaker* self, unsigned int index) { \ VALIDATE_TABLE_INDEX(type) \ \ PyObject* res = self->type##_cache[index]; \ if (res == NULL) { \ res = read_##type##_uncached(self, index); \ self->type##_cache[index] = res; \ } \ Py_XINCREF(res); \ return res; \ } static PyObject * read_float_uncached(CIceBreaker* self, unsigned int index) { return PyFloat_FromDouble(self->section_float->values[index]); } DEFINE_CACHED_READER(float) static PyObject * read_complex_uncached(CIceBreaker* self, unsigned int index) { return PyComplex_FromCComplex(self->section_complex->values[index]); } DEFINE_CACHED_READER(complex) static PyObject * read_int_uncached(CIceBreaker* self, unsigned int index) { return PyLong_FromLong(self->section_int->values[index]); } DEFINE_CACHED_READER(int) static PyObject * read_str_uncached(CIceBreaker* self, unsigned int index) { unsigned int location = self->section_str->offsets[index]; IcePackStr *str = (IcePackStr*)((char*)self->codebuffer.buf + location); if (str->len != 0 && !validate_index(self, &str->data[str->len - 1], "str")) { return NULL; } PyObject* res = PyUnicode_DecodeUTF8(str->data, str->len, "surrogatepass"); if (res != NULL) { // When we construct a code object all of the strings got interned, so // we intern from the cache PyUnicode_InternInPlace(&res); } return res; } DEFINE_CACHED_READER(str) static PyObject * read_bytes_uncached(CIceBreaker* self, unsigned int index) { unsigned int location = self->section_bytes->offsets[index]; IcePackStr *str = (IcePackStr*)((char*)self->codebuffer.buf + location); if (str->len != 0 && !validate_index(self, &str->data[str->len - 1], "bytes")) { return NULL; } return PyBytes_FromStringAndSize(str->data, str->len); } DEFINE_CACHED_READER(bytes) static PyObject* read_bigint_uncached(CIceBreaker* self, unsigned int index) { unsigned int location = self->section_bigint->offsets[index]; IcePackBytes *bytes = (IcePackBytes*)((char*)self->codebuffer.buf + location); if (bytes->len != 0 && !validate_index(self, &bytes->data[bytes->len - 1], "bigint")) { return NULL; } return _PyLong_FromByteArray(bytes->data, bytes->len, 1, 1); } DEFINE_CACHED_READER(bigint) static PyObject* read_tuple(CIceBreaker* self, unsigned int index, int* can_cache_outer) { VALIDATE_TABLE_INDEX(tuple) if (self->tuple_cache[index] != NULL) { PyObject* res = self->tuple_cache[index]; Py_INCREF(res); return res; } unsigned int location = self->section_tuple->offsets[index]; IcePackArray *items = (IcePackArray*)((char*)self->codebuffer.buf + location); if (items->count != 0 && !validate_index(self, &items->values[items->count - 1], "tuple")) { return NULL; } PyObject* tuple = PyTuple_New(items->count); if (tuple == NULL) { return NULL; } int can_cache = 1; for (unsigned int i = 0; i<items->count; i++) { PyObject* str = read_const(self, items->values[i], &can_cache); if (str == NULL) { Py_DECREF(tuple); return NULL; } PyTuple_SET_ITEM(tuple, i, str); } if (can_cache) { self->tuple_cache[index] = tuple; Py_INCREF(tuple); // saved in the cache } else if (can_cache_outer) { can_cache_outer = 0; } return tuple; } static PyObject* read_frozenset_uncached(CIceBreaker* self, unsigned int index) { unsigned int location = self->section_frozenset->offsets[index]; IcePackArray *items = (IcePackArray*)((char*)self->codebuffer.buf + location); if (items->count != 0 && !validate_index(self, &items->values[items->count - 1], "frozenset")) { return NULL; } PyObject* set = PyFrozenSet_New(NULL); if (set == NULL) { return NULL; } int can_cache = 1; for (unsigned int i = 0; i<items->count; i++) { PyObject* val = read_const(self, items->values[i], &can_cache); if (val == NULL || PySet_Add(set, val) == -1) { Py_DECREF(set); return NULL; } } return set; } DEFINE_CACHED_READER(frozenset) static PyObject* read_code(CIceBreaker* self, unsigned int index) { if (index >= self->section_code->count) { PyErr_SetString(PyExc_ValueError, "Invalid code index"); return NULL; } unsigned int location = self->section_code->offsets[index]; CodeObject *header = (CodeObject*)((char*)self->codebuffer.buf + location); if (!validate_index(self, ((char*)header) + sizeof(CodeObject) - 1, "code")) { return NULL; } PyObject* res = NULL, *name = NULL, *filename = NULL, *lnotab = NULL, *cellvars = NULL, *freevars = NULL, *names = NULL, *varnames = NULL, *consts = NULL, *fixed_fn = NULL; CIceBreakerCode* code = PyObject_New(CIceBreakerCode, &CIceBreakerCodeType); CLEANUP_IF_NULL(code); unsigned int bytes_loc = self->section_bytes->offsets[header->bytes]; IcePackStr *bytes = (IcePackStr*)((char*)self->codebuffer.buf + bytes_loc); if (bytes->len != 0 && !validate_index(self, &bytes->data[bytes->len - 1], "code bytes")) { goto cleanup; } code->data = &bytes->data[0]; code->size = bytes->len; code->hash = -1; code->breaker = self; Py_INCREF(self); name = read_str(self, header->name); CLEANUP_IF_NULL(name); filename = read_str(self, header->filename); CLEANUP_IF_NULL(filename); lnotab = read_bytes(self, header->lnotab); CLEANUP_IF_NULL(lnotab); cellvars = read_tuple(self, header->cellvars, NULL); CLEANUP_IF_NULL(cellvars); freevars = read_tuple(self, header->freevars, NULL); CLEANUP_IF_NULL(freevars); names = read_tuple(self, header->names, NULL); CLEANUP_IF_NULL(names); varnames = read_tuple(self, header->varnames, NULL); CLEANUP_IF_NULL(varnames); consts = read_tuple(self, header->consts, NULL); CLEANUP_IF_NULL(consts); fixed_fn = PyDict_GetItem(self->filename_map, filename); if (fixed_fn == NULL) { fixed_fn = PyUnicode_Concat(self->base_dir, filename); CLEANUP_IF_NULL(fixed_fn); int set = PyDict_SetItem(self->filename_map, filename, fixed_fn); // fixed_fn will be borrowed from dictionary to hand off to PyCode_new // or freed if we failed to insert it into the dictionary Py_DECREF(fixed_fn); if (set == -1) { goto cleanup; } } res = (PyObject*)PyCode_New(header->argcount, header->kwonlyargcount, header->nlocals, header->stacksize, header->flags, (PyObject*)code, consts, names, varnames, freevars, cellvars, fixed_fn, name, header->firstlineno, lnotab); code->code_obj = res; cleanup: Py_XDECREF(code); Py_XDECREF(name); Py_XDECREF(filename); Py_XDECREF(lnotab); Py_XDECREF(cellvars); Py_XDECREF(freevars); Py_XDECREF(names); Py_XDECREF(varnames); Py_XDECREF(consts); return res; } static PyObject * CIceBreaker_find_module(CIceBreaker *self, PyObject *o) { if (!PyUnicode_Check(o)) { PyErr_SetString(PyExc_TypeError, "expected module name as str"); return NULL; } const ModuleSection* cur = self->section_modules; const char* name = PyUnicode_AsUTF8(o); int last_segment; const char* buf = self->codebuffer.buf; do { unsigned int len; const char* end; if ((end = strchr(name, '.')) == NULL) { len = strlen(name); last_segment = 1; } else { len = end - name; last_segment = 0; } // Binary search the module tree int low = 0, high = cur->count - 1; while (low <= high) { int i = (low + high) / 2; if (!validate_index(self, &cur->modules[i], "module table")) { return NULL; } unsigned int str_index = cur->modules[i].name; unsigned int location = self->section_str->offsets[str_index]; char* str_mem = (char*)self->codebuffer.buf + location; IcePackStr *str = (IcePackStr*)str_mem; if (str->len != 0 && !validate_index(self, &str->data[str->len - 1], "module name")) { return NULL; } int cmp = strncmp(name, &str->data[0], len < str->len ? len : str->len); if (cmp == 0 && str->len == len) { if (last_segment) { PyObject *code = read_code(self, cur->modules[i].code); if (code == NULL) { return NULL; } PyObject *filename = read_str(self, cur->modules[i].filename); if (filename == NULL) { Py_DECREF(code); return NULL; } PyObject *res = PyTuple_New(3); if (res == NULL) { Py_DECREF(filename); Py_DECREF(code); return NULL; } PyObject* is_pkg = cur->modules[i].is_package ? Py_True : Py_False; Py_INCREF(is_pkg); PyTuple_SET_ITEM(res, 0, code); PyTuple_SET_ITEM(res, 1, is_pkg); PyTuple_SET_ITEM(res, 2, filename); return res; } else if (cur->modules[i].children == 0) { goto not_found; } cur = (ModuleSection*)(buf + cur->modules[i].children); name = name + len + 1; break; } else if (cmp > 0 || (cmp == 0 && str->len < len)) { low = i + 1; } else { /* cmp < 0 */ high = i - 1; } } if (low > high) { goto not_found; } } while(!last_segment); not_found: Py_INCREF(Py_None); return Py_None; } static PyObject * CIceBreaker_read_code(CIceBreaker *self, PyObject *o) { unsigned long index = PyLong_AsUnsignedLong(o); if (index == (unsigned long)-1 && PyErr_Occurred()) { return NULL; } return read_code(self, index); } static PyObject * CIceBreaker_read_str(CIceBreaker *self, PyObject *o) { unsigned long index = PyLong_AsUnsignedLong(o); if (index == (unsigned long)-1 && PyErr_Occurred()) { return NULL; } return read_str(self, index); } static PyObject * CIceBreaker_read_bytes(CIceBreaker *self, PyObject *o) { unsigned long index = PyLong_AsUnsignedLong(o); if (index == (unsigned long)-1 && PyErr_Occurred()) { return NULL; } return read_bytes(self, index); } static PyObject * read_const(CIceBreaker *self, unsigned int const_val, int* can_cache) { unsigned int data = const_val >> 8; switch (const_val & 0xff) { case 0x00: if (data == 0) { Py_INCREF(Py_None); return Py_None; } break; case 0x01: switch (data) { case 0: Py_INCREF(Py_False); return Py_False; case 1: Py_INCREF(Py_True); return Py_True; case 2: Py_INCREF(Py_Ellipsis); return Py_Ellipsis; } break; case 0x03: return read_int(self, data); case 0x04: return read_bigint(self, data); case 0x05: return read_bytes(self, data); case 0x06: return read_str(self, data); case 0x07: return read_float(self, data); case 0x08: return read_complex(self, data); case 0x09: return read_tuple(self, data, can_cache); case 0x0A: if (can_cache != NULL) { // caching anything containing a code object sets up a circular // reference leading to a memory leak. *can_cache = 0; } return read_code(self, data); case 0x0B: return read_frozenset(self, data); } PyErr_SetString(PyExc_ValueError, "Unknown constant"); return NULL; } static PyObject * CIceBreaker_read_const(CIceBreaker *self, PyObject *o) { unsigned long const_val = PyLong_AsUnsignedLong(o); if (const_val == (unsigned long)-1 && PyErr_Occurred()) { return NULL; } return read_const(self, const_val, NULL); } static PyMethodDef CIceBreaker_methods[] = { {"__exit__", (PyCFunction)CIceBreaker__exit__, METH_VARARGS}, {"find_module", (PyCFunction)CIceBreaker_find_module, METH_O}, {"read_bytes", (PyCFunction)CIceBreaker_read_bytes, METH_O}, {"read_code", (PyCFunction)CIceBreaker_read_code, METH_O}, {"read_const", (PyCFunction)CIceBreaker_read_const, METH_O}, {"read_str", (PyCFunction)CIceBreaker_read_str, METH_O}, {NULL, NULL} /* sentinel */ }; static PyObject * CIceBreaker_New(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { if (!PyTuple_Check(args)) { PyErr_SetString(PyExc_TypeError, "Expected tuple for args"); return NULL; } else if (PyTuple_Size(args) != 2) { PyErr_SetString(PyExc_TypeError, "CIceBreaker: expected buffer, base filename"); return NULL; } PyObject* res = subtype->tp_alloc(subtype, 0); if (res == NULL) { return NULL; } CIceBreaker* breaker = (CIceBreaker*)res; Py_buffer codebuffer = {}; PyObject* base_dir = PyTuple_GET_ITEM(args, 1); Py_INCREF(base_dir); if (!PyUnicode_CheckExact(base_dir)) { PyErr_SetString(PyExc_TypeError, "CIceBreaker: expected base_dir to be a str"); goto cleanup; } else if (PyObject_GetBuffer(PyTuple_GET_ITEM(args, 0), &codebuffer, PyBUF_SIMPLE) != 0) { PyErr_SetString(PyExc_TypeError, "CIceBreaker: expected bufferable argument"); goto cleanup; } breaker->codebuffer = codebuffer; breaker->obj = PyTuple_GET_ITEM(args, 0); Py_INCREF(breaker->obj); breaker->base_dir = base_dir; Py_INCREF(breaker->base_dir); breaker->filename_map = PyDict_New(); CLEANUP_IF_NULL(breaker->filename_map); IcePackHeader* header = (IcePackHeader*)codebuffer.buf; if (header->marker != 0x004b434150454349) { // ICEPACK\0 PyErr_SetString(IcePackError, "CIceBreaker: expected IcePack file, bad header"); goto cleanup; } else if ((size_t)codebuffer.len < sizeof(IcePackHeader)) { PyErr_SetString(IcePackError, "CIceBreaker: expected IcePack file, too short"); goto cleanup; } char *mem = (char*)codebuffer.buf; #define CLEANUP_IF_INVALID(x) if(!validate_index(breaker, x, "section")) goto cleanup; breaker->section_modules = (ModuleSection*)(mem + header->modules); CLEANUP_IF_INVALID(breaker->section_modules); breaker->section_code = (OffsetSection*)(mem + header->codes); CLEANUP_IF_INVALID(breaker->section_code); breaker->section_str = (OffsetSection*)(mem + header->strings); CLEANUP_IF_INVALID(breaker->section_str); breaker->section_bytes = (OffsetSection*)(mem + header->bytes); CLEANUP_IF_INVALID(breaker->section_bytes); breaker->section_int = (IntSection*)(mem + header->ints); CLEANUP_IF_INVALID(breaker->section_int); breaker->section_bigint = (OffsetSection*)(mem + header->bigints); CLEANUP_IF_INVALID(breaker->section_bigint); breaker->section_float = (FloatSection*)(mem + header->floats); CLEANUP_IF_INVALID(breaker->section_float); breaker->section_complex = (ComplexSection*)(mem + header->complexes); CLEANUP_IF_INVALID(breaker->section_complex); breaker->section_tuple = (OffsetSection*)(mem + header->tuples); CLEANUP_IF_INVALID(breaker->section_tuple); breaker->section_frozenset = (OffsetSection*)(mem + header->frozensets); CLEANUP_IF_INVALID(breaker->section_frozenset); breaker->str_cache = (PyObject**)PyMem_RawCalloc( breaker->section_str->count, sizeof(PyObject*)); CLEANUP_IF_NULL(breaker->str_cache); breaker->bytes_cache = (PyObject**)PyMem_RawCalloc( breaker->section_bytes->count, sizeof(PyObject*)); CLEANUP_IF_NULL(breaker->bytes_cache); breaker->int_cache = (PyObject**)PyMem_RawCalloc( breaker->section_int->count, sizeof(PyObject*)); CLEANUP_IF_NULL(breaker->int_cache); breaker->bigint_cache = (PyObject**)PyMem_RawCalloc( breaker->section_bigint->count, sizeof(PyObject*)); CLEANUP_IF_NULL(breaker->bigint_cache); breaker->float_cache = (PyObject**)PyMem_RawCalloc( breaker->section_float->count, sizeof(PyObject*)); CLEANUP_IF_NULL(breaker->float_cache); breaker->complex_cache = (PyObject**)PyMem_RawCalloc( breaker->section_complex->count, sizeof(PyObject*)); CLEANUP_IF_NULL(breaker->complex_cache); breaker->tuple_cache = (PyObject**)PyMem_RawCalloc( breaker->section_tuple->count, sizeof(PyObject*)); CLEANUP_IF_NULL(breaker->tuple_cache); breaker->frozenset_cache = (PyObject**)PyMem_RawCalloc( breaker->section_frozenset->count, sizeof(PyObject*)); CLEANUP_IF_NULL(breaker->frozenset_cache); return res; cleanup: Py_DECREF(res); return NULL; } static PyObject * CIceBreakerType_timestamp(CIceBreaker *self) { IcePackHeader* header = (IcePackHeader*)self->codebuffer.buf; unsigned int timestamp = header->timestamp; return PyLong_FromLong(timestamp); } static PyGetSetDef CIceBreaker_getset[] = { { "timestamp", (getter)CIceBreakerType_timestamp, (setter)NULL, "the timestamp of the latest file in the icepack", NULL }, }; static PyTypeObject CIceBreakerType = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(NULL, 0) "_pyice.CIceBreaker", /*tp_name*/ sizeof(CIceBreaker), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)CIceBreaker_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ CIceBreaker_methods, /*tp_methods*/ 0, /*tp_members*/ CIceBreaker_getset, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ CIceBreaker_New, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; /* --------------------------------------------------------------------- */ static void CIceBreakerCode_dealloc(CIceBreakerCode *self) { Py_DECREF(self->breaker); Py_TYPE(self)->tp_free((PyObject*)self); } static PyMethodDef CIceBreakerCode_methods[] = { {NULL, NULL} /* sentinel */ }; // This is similar to a memoryview, but is designed to be more compatible w/ /* Buffer methods */ static Py_ssize_t code_strides[1] = {1}; static int codetype_getbuf(CIceBreakerCode *self, Py_buffer *view, int flags) { if (flags & PyBUF_WRITABLE) { PyErr_SetString(PyExc_BufferError, "CIceBreakerCode: read-only buffer"); return -1; } view->obj = (PyObject*)self; Py_INCREF(self); view->buf = (void*)self->data; view->len = self->size; view->readonly = 1; view->itemsize = 1; view->ndim = 1; view->format = "B"; view->suboffsets = NULL; view->shape = (Py_ssize_t*)&self->size; view->strides = &code_strides[0]; view->internal = NULL; self->exports++; return 0; } static void codetype_releasebuf(CIceBreakerCode *self, Py_buffer *view) { self->exports--; return; } static PyBufferProcs codetype_as_buffer = { (getbufferproc)codetype_getbuf, /* bf_getbuffer */ (releasebufferproc)codetype_releasebuf, /* bf_releasebuffer */ }; static Py_ssize_t codetype_length(CIceBreakerCode *self) { return self->size; } static PyObject * codetype_item(CIceBreakerCode *self, Py_ssize_t i) { if (i < 0 || (size_t)i >= self->size) { PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } return PyLong_FromLong((unsigned char)self->data[i]); } static int codetype_contains(CIceBreakerCode *self, PyObject *arg) { return _Py_bytes_contains(self->data, self->size, arg); } PyObject *codetype_richcompare(CIceBreakerCode *a, PyObject *b, int op) { const char *bytes; size_t len; PyObject* result = NULL; Py_buffer codebuffer = {}; if ((PyObject*)a == b) { switch (op) { case Py_EQ: case Py_LE: case Py_GE: /* a string is equal to itself */ result = Py_True; break; case Py_NE: case Py_LT: case Py_GT: result = Py_False; break; default: PyErr_BadArgument(); return NULL; } } if (PyBytes_Check(b)) { bytes = PyBytes_AS_STRING(b); len = PyBytes_GET_SIZE(b); } else if(CIceBreakerCodeObject_Check(b)) { bytes = ((CIceBreakerCode*)b)->data; len = ((CIceBreakerCode*)b)->size; } else if(PyObject_GetBuffer(b, &codebuffer, PyBUF_SIMPLE) != 0) { PyErr_Clear(); Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } else { bytes = codebuffer.buf; len = codebuffer.len; } if (op == Py_EQ || op == Py_NE) { if (len != a->size) { result = Py_False; } else if(len == 0) { result = Py_True; } else { int eq = memcmp(a->data, bytes, len); eq ^= (op == Py_EQ); result = eq ? Py_True : Py_False; } } else { Py_ssize_t min_len = Py_MIN(len, a->size); int c; if (min_len > 0) { c = memcmp(a->data, bytes, min_len); } else { c = 0; } if (c == 0) { c = (a->size < len) ? -1 : (a->size > len) ? 1 : 0; } switch (op) { case Py_LT: c = c < 0; break; case Py_LE: c = c <= 0; break; case Py_GT: c = c > 0; break; case Py_GE: c = c >= 0; break; default: PyErr_BadArgument(); goto error; } result = c ? Py_True : Py_False; } Py_INCREF(result); error: PyBuffer_Release(&codebuffer); return result; } static PyObject* codetype_subscript(CIceBreakerCode* self, PyObject* item) { if (PyIndex_Check(item)) { Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return NULL; return codetype_item(self, i); } else if (PySlice_Check(item)) { Py_ssize_t start, stop, step, slicelength, cur, i; char* result_buf; PyObject* result; if (PySlice_Unpack(item, &start, &stop, &step) < 0) { return NULL; } slicelength = PySlice_AdjustIndices(self->size, &start, &stop, step); if (slicelength <= 0) { return PyBytes_FromStringAndSize("", 0); } else if (step == 1) { return PyBytes_FromStringAndSize( self->data + start, slicelength); } else { result = PyBytes_FromStringAndSize(NULL, slicelength); if (result == NULL) { return NULL; } result_buf = PyBytes_AS_STRING(result); for (cur = start, i = 0; i < slicelength; cur += step, i++) { result_buf[i] = self->data[cur]; } return result; } } else { PyErr_Format(PyExc_TypeError, "byte indices must be integers or slices, not %.200s", Py_TYPE(item)->tp_name); return NULL; } } static Py_hash_t codetype_hash(CIceBreakerCode *a) { if (a->hash == -1) { /* Can't fail */ a->hash = _Py_HashBytes(a->data, a->size); } return a->hash; } static PySequenceMethods codetype_as_sequence = { (lenfunc)codetype_length, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ (ssizeargfunc)codetype_item, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ (objobjproc)codetype_contains /*sq_contains*/ }; static PyMappingMethods codetype_as_mapping = { (lenfunc)codetype_length, (binaryfunc)codetype_subscript, 0, }; static PyTypeObject CIceBreakerCodeType = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(NULL, 0) "_pyice.CIceBreakerCode", /*tp_name*/ sizeof(CIceBreakerCode), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)CIceBreakerCode_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ &codetype_as_sequence, /*tp_as_sequence*/ &codetype_as_mapping, /*tp_as_mapping*/ (hashfunc)codetype_hash, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &codetype_as_buffer, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ (richcmpfunc)&codetype_richcompare, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ CIceBreakerCode_methods, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; static void CObjectValue_dealloc(CObjectValue *self) { Py_DECREF(self->value); Py_TYPE(self)->tp_free((PyObject*)self); } static PyMethodDef CObjectValue_methods[] = { {NULL, NULL} /* sentinel */ }; Py_hash_t CObjectValue_hash(CObjectValue *o) { return o->hash; } int float_equals(double a, double b) { if (Py_IS_NAN(a) && Py_IS_NAN(b)) { return 1; } else if (a == 0.0 && b == 0.0) { if (copysign(1, a) != copysign(1, b)) { return 0; } } return a == b; } PyObject *CObjectValue_richcompare(CObjectValue *a, PyObject *b, int op) { if (op != Py_EQ) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } else if (b->ob_type != &CObjectValueType) { Py_INCREF(Py_False); return Py_False; } CObjectValue* obval = (CObjectValue*)b; if (a->hash != obval->hash || a->value->ob_type != obval->value->ob_type) { Py_INCREF(Py_False); return Py_False; } else if (PyFloat_Check(a->value)) { double af = PyFloat_AsDouble(a->value); double bf = PyFloat_AsDouble(obval->value); if (float_equals(af, bf)) { Py_INCREF(Py_True); return Py_True; } else { Py_INCREF(Py_False); return Py_False; } } else if (PyComplex_Check(a->value)) { Py_complex ac = PyComplex_AsCComplex(a->value); Py_complex bc = PyComplex_AsCComplex(obval->value); if (float_equals(ac.real, bc.real) && float_equals(ac.imag, bc.imag)) { Py_INCREF(Py_True); return Py_True; } else { Py_INCREF(Py_False); return Py_False; } } return PyObject_RichCompare(a->value, obval->value, op); } static PyObject* CObjectValue_wrap(PyObject* from) { PyObject* value = from; CObjectValue* self = PyObject_New(CObjectValue, &CObjectValueType); if (self == NULL) { return NULL; } if (PyTuple_Check(value)) { PyObject* tuple = PyTuple_New(PyTuple_Size(value)); if (tuple == NULL) { Py_DECREF(self); return NULL; } for (int i = 0; i<PyTuple_Size(value); i++) { PyObject* wrapped = CObjectValue_wrap(PyTuple_GET_ITEM(value, i)); if (wrapped == NULL) { Py_DECREF(self); Py_DECREF(tuple); return NULL; } PyTuple_SET_ITEM(tuple, i, wrapped); } self->value = tuple; } else if (PyFrozenSet_CheckExact(value)) { PyObject* set = PyFrozenSet_New(NULL); if (set == NULL) { Py_DECREF(self); return NULL; } Py_ssize_t pos = 0; PyObject *key; Py_hash_t hash; while (_PySet_NextEntry(value, &pos, &key, &hash)) { PyObject* wrapped = CObjectValue_wrap(key); if (wrapped == NULL || PySet_Add(set, wrapped) == -1) { Py_DECREF(self); Py_DECREF(set); return NULL; } } self->value = set; } else { self->value = value; Py_INCREF(self->value); } self->hash = PyObject_Hash(self->value); return (PyObject*)self; } static PyObject * CObjectValue_New(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { if (!PyTuple_CheckExact(args)) { return NULL; } else if(PyTuple_Size(args) != 1) { PyErr_SetString(PyExc_ValueError, "Expected a single argument"); return NULL; } return CObjectValue_wrap(PyTuple_GET_ITEM(args, 0)); } static PyObject * CObjectValue_value(CObjectValue *self) { Py_INCREF(self->value); return self->value; } static PyGetSetDef CObjectValue_getset[] = { {"value", (getter)CObjectValue_value, (setter)NULL, "the wrapped value", NULL}, }; static PyTypeObject CObjectValueType = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(NULL, 0) "_pyice.CObjectValue", /*tp_name*/ sizeof(CObjectValue), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)CObjectValue_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ (hashfunc)CObjectValue_hash, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ (richcmpfunc)CObjectValue_richcompare, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ CObjectValue_methods, /*tp_methods*/ 0, /*tp_members*/ CObjectValue_getset, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ CObjectValue_New, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; /* List of functions defined in the module */ static PyMethodDef pyice_methods[] = { {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "Provides C accelerators for the PyIce package."); static int pyice_exec(PyObject *m) { /* object; doing it here is required for portability, too. */ if (PyType_Ready(&CIceBreakerType) < 0) goto fail; if (PyType_Ready(&CIceBreakerCodeType) < 0) goto fail; if (PyType_Ready(&CObjectValueType) < 0) goto fail; IcePackError = PyErr_NewException("pyice.IcepackError", NULL, NULL); if (IcePackError == NULL) { goto fail; } /* Add exception object to your module */ PyModule_AddObject(m, "IcePackError", IcePackError); PyModule_AddObject(m, "CIceBreaker", (PyObject *)&CIceBreakerType); PyModule_AddObject(m, "CIceBreakerCode", (PyObject *)&CIceBreakerCodeType); PyModule_AddObject(m, "CObjectValue", (PyObject *)&CObjectValueType); return 0; fail: Py_XDECREF(m); return -1; } static struct PyModuleDef_Slot pyice_slots[] = { {Py_mod_exec, pyice_exec}, {0, NULL}, }; static struct PyModuleDef pyicemodule = { PyModuleDef_HEAD_INIT, "_pyice", module_doc, 0, pyice_methods, pyice_slots, NULL, NULL, NULL }; /* Export function for the module */ PyMODINIT_FUNC PyInit__pyice(void) { return PyModuleDef_Init(&pyicemodule); }
22,152
1,133
#include "ImageAccessor.h" #include <exception> #include <cmath> #include <complex> #include <sstream> #include <iostream> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> using namespace std; void ImageAccessor::createFile(int fileLength) { LineAccessor::createFile(&fileLength); } void ImageAccessor::finalizeImageAccessor() { LineAccessor::finalizeLineAccessor(); } void ImageAccessor::getElements(char * dataLine, int * row, int * col, int numEl) { LineAccessor::getElements(dataLine, row, col, &numEl); } void ImageAccessor::getLineSequential(char * dataLine, int & eof) { LineAccessor::getLineSequential(dataLine, &eof); } void ImageAccessor::getSequentialElements(char * dataLine, int row, int col, int & numEl) { LineAccessor::getSequentialElements(dataLine, &row, &col, &numEl); } void ImageAccessor::getLine(char * dataLine, int & row) { LineAccessor::getLine(dataLine, &row); } void ImageAccessor::initImageAccessor(string filename, string filemode, char endianFile, string type, int col, int row) { LineAccessor::initLineAccessor(filename,filemode,endianFile,type,row,col); } void ImageAccessor::initSequentialAccessor(int begLine) { LineAccessor::initSequentialAccessor(&begLine); } void ImageAccessor::setElements(char * dataLine, int * row, int * col, int numEl) { LineAccessor::setElements(dataLine, row, col, &numEl); } void ImageAccessor::setLine(char * dataLine, int row) { LineAccessor::setLine(dataLine, &row); } void ImageAccessor::setLineSequential(char * dataLine) { LineAccessor::setLineSequential(dataLine); } void ImageAccessor::setSequentialElements(char * dataLine, int row, int col, int numEl) { LineAccessor::setSequentialElements(dataLine,&row,&col,&numEl); }
646
801
<reponame>vishalbelsare/neupy import os from collections import namedtuple from bs4 import BeautifulSoup from six.moves.urllib.parse import urljoin, urlparse from webgraph import Link def iter_html_files(directory): for path, directories, filenames in os.walk(directory): for filename in filenames: if filename.endswith('.html'): yield os.path.join(path, filename) def extract_title(html): headers = html.select("h1,h2,h3,h4,h5") first_header = headers[0] return first_header.text def extrat_object_snippet(html): # We take only first paragraph from the description and ignore other # even if they continue class'/function's description. paragraphs = html.select('dd:nth-of-type(1) > p:nth-of-type(1)') if not paragraphs: return '' snippet = paragraphs[0] return snippet.text class ParseHTML(object): def __init__(self, html, url): self.raw_html = html self.html = BeautifulSoup(html, "html.parser") self.url = url @classmethod def fromfile(cls, filepath, url): with open(filepath) as html_file: html = html_file.read() return cls(html, url) def text(self): articles = self.html.select('div.main-container .body article') if not articles: return '' content = articles[0] for tag in content.findAll(['script', 'style', 'noscript']): tag.extract() return content.text def extract_links(self, html): for anchor in html.findAll('a'): uri = urlparse(anchor['href']) if uri.netloc in ('neupy.com', ''): url = urljoin(self.url, uri.path) if uri.fragment: url = url + "#" + uri.fragment yield Link(uri=url, text=anchor.text) def links(self): return self.extract_links(self.html) def subdocuments(self): Subdocument = namedtuple("Subdocument", "uri links html text title snippet") subdocuments = [] apidocs = self.html.select('dl.function,dl.class,dl.exception') if apidocs: for subdoc in apidocs: first_child = subdoc.findChild() object_name = first_child.select('.descname') title = object_name[0].text subdocuments.append( Subdocument( uri=self.url + "#" + first_child['id'], links=list(self.extract_links(subdoc)), html=str(subdoc), text=subdoc.text, title=title, snippet=extrat_object_snippet(subdoc))) else: main_container = self.html.select('.main-container') suptitle = extract_title(main_container[0]) for subdoc in self.html.select('div.section'): for section in subdoc.select('div.section,div#contents'): section.extract() title = extract_title(subdoc) if suptitle and suptitle != title: title = suptitle + " / " + title subdocuments.append( Subdocument( uri=self.url + "#" + subdoc['id'], links=list(self.extract_links(subdoc)), html=str(subdoc), text=subdoc.text, title=title, snippet='')) if not subdocuments or (len(subdocuments) == 1 and not apidocs): subdocumets = [ Subdocument( uri=self.url, links=self.links(), html=self.raw_html, text=self.text(), title=extract_title(subdoc), snippet='')] return subdocuments def __reduce__(self): arguments = (self.raw_html, self.url) return (self.__class__, arguments)
2,091
498
// // lager - library for functional interactive c++ programs // Copyright (C) 2017 <NAME> // // This file is part of lager. // // lager is free software: you can redistribute it and/or modify // it under the terms of the MIT License, as detailed in the LICENSE // file located at the root of this source code distribution, // or here: <https://github.com/arximboldi/lager/blob/master/LICENSE> // #pragma once #include <lager/commit.hpp> #include <lager/reader.hpp> namespace lager { namespace detail { template <typename T> class constant_node : public root_node<T, reader_node> { using base_t = root_node<T, reader_node>; public: using base_t::base_t; virtual void recompute() final {} }; template <typename T> auto make_constant_node(T&& v) { return std::make_shared<constant_node<std::decay_t<T>>>(std::forward<T>(v)); } } // namespace detail //! @defgroup cursors //! @{ template <typename T> class constant : public reader_base<detail::constant_node<T>> { using base_t = reader_base<detail::constant_node<T>>; public: using value_type = T; constant(T v) : base_t{detail::make_constant_node(std::move(v))} {} private: friend class detail::access; auto roots() const { return detail::access::node(*this); } }; template <typename T> auto make_constant(T&& v) -> constant<std::decay_t<T>> { return std::forward<T>(v); } //! @} } // namespace lager
527
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-mc84-xr9p-938r", "modified": "2021-09-15T18:50:22Z", "published": "2019-09-23T18:31:05Z", "aliases": [ ], "summary": "High severity vulnerability that affects generator-jhipster", "details": "## Generated code uses repository configuration that downloads over HTTP instead of HTTPS\n\n### Impact\nGradle users were using the http://repo.spring.io/plugins-release repositories in plain HTTP, and not HTTPS, so a man-in-the-middle attack was possible at build time.\n\n### Patches\n\nMaven users should at least upgrade to 6.3.0 while Gradle users should update to 6.3.1.\nIf you are not able to upgrade make sure not to use a Maven repository via `http` in your build file.\n\n### Workarounds\n\nReplace all custom repository definitions in `build.gradle` or `pom.xml` with their `https` version.\n\ne.g.\n\n```xml\n <repository>\n <id>oss.sonatype.org-snapshot</id>\n <url>https://oss.sonatype.org/content/repositories/snapshots</url> // <-- must be httpS\n <releases>\n <enabled>false</enabled>\n </releases>\n <snapshots>\n <enabled>true</enabled>\n </snapshots>\n</repository>\n```\n\n```gradle\nmaven { url \"https://repo.spring.io/plugins-release\" } // <-- must be httpS\n```\n\n### References\n* https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator?vector=AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H\n* https://max.computer/blog/how-to-take-over-the-computer-of-any-java-or-clojure-or-scala-developer/\n\n### For more information\nIf you have any questions or comments about this advisory:\n* Open an issue in [https://github.com/jhipster/generator-jhipster/issues](https://github.com/jhipster/generator-jhipster/issues)\n\n", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ { "package": { "ecosystem": "npm", "name": "generator-jhipster" }, "ranges": [ { "type": "ECOSYSTEM", "events": [ { "introduced": "0" }, { "fixed": "6.3.1" } ] } ] } ], "references": [ { "type": "WEB", "url": "https://github.com/jhipster/generator-jhipster/security/advisories/GHSA-mc84-xr9p-938r" }, { "type": "ADVISORY", "url": "https://github.com/advisories/GHSA-mc84-xr9p-938r" }, { "type": "WEB", "url": "https://snyk.io/vuln/SNYK-JS-GENERATORJHIPSTER-536074" }, { "type": "PACKAGE", "url": "https://github.com/jhipster/generator-jhipster/" } ], "database_specific": { "cwe_ids": [ "CWE-494", "CWE-829" ], "severity": "HIGH", "github_reviewed": true } }
1,393
930
package com.dianping.pigeon.remoting.netty.channel; import com.dianping.pigeon.log.Logger; import com.dianping.pigeon.log.LoggerLoader; import com.dianping.pigeon.remoting.common.channel.ChannelFactory; import com.dianping.pigeon.remoting.common.exception.NetworkException; import com.dianping.pigeon.remoting.common.pool.ChannelPoolException; import com.dianping.pigeon.remoting.netty.invoker.NettyClient; /** * @author qi.yin * 2016/09/23 上午10:47. */ public class NettyChannelFactory implements ChannelFactory<NettyChannel> { private static final Logger logger = LoggerLoader.getLogger(NettyChannelFactory.class); private NettyClient client; public NettyChannelFactory(NettyClient client) { this.client = client; } @Override public NettyChannel createChannel() { NettyChannel channel = new DefaultNettyChannel( client.getBootstrap(), client.getHost(), client.getPort(), client.getTimeout()); try { channel.connect(); } catch (NetworkException e) { logger.info("[createChannel] failed.", e); } return channel; } }
489
3,768
from __future__ import print_function import urllib.parse from ast import parse from IPython import get_ipython from IPython.core.magic import Magics, line_cell_magic, magics_class from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring from IPython.display import IFrame, display from .. import Profiler from ._utils import PrePostAstTransformer _active_profiler = None def _get_active_profiler(): """ Allows the code inserted into the cell to access the pyinstrument Profiler instance, to start/stop it. """ return _active_profiler @magics_class class PyinstrumentMagic(Magics): def __init__(self, shell): super().__init__(shell) # This will leak _get_active_profiler into the users space until we can magle it self.pre = parse( "\nfrom pyinstrument.magic.magic import _get_active_profiler; _get_active_profiler().start()\n" ) self.post = parse("\n_get_active_profiler().stop()") self._transformer = PrePostAstTransformer(self.pre, self.post) @magic_arguments() @argument( "--interval", type=float, default=0.001, help="The minimum time, in seconds, between each stack sample. See: https://pyinstrument.readthedocs.io/en/latest/reference.html#pyinstrument.Profiler.interval", ) @argument( "--async_mode", default="enabled", help="Configures how this Profiler tracks time in a program that uses async/await. See: https://pyinstrument.readthedocs.io/en/latest/reference.html#pyinstrument.Profiler.async_mode", ) @argument( "--height", "-h", default=400, help="Output height", ) @argument( "--timeline", type=bool, default=False, help="Show output timeline view", ) @argument( "code", type=str, nargs="*", help="When used as a line magic, the code to profile", ) @line_cell_magic def pyinstrument(self, line, cell=None): """ Run a cell with the pyinstrument statistical profiler. Converts the line/cell's AST to something like: try: profiler.start() run_code finally: profiler.stop() profiler.output_html() """ global _active_profiler args = parse_argstring(self.pyinstrument, line) ip = get_ipython() if not ip: raise RuntimeError("couldn't get ipython shell instance") code = cell or line if not code: return # Turn off the last run (e.g. a user interrupted) if _active_profiler and _active_profiler.is_running: _active_profiler.stop() if self._transformer in ip.ast_transformers: ip.ast_transformers.remove(self._transformer) _active_profiler = Profiler(interval=args.interval, async_mode=args.async_mode) ip.ast_transformers.append(self._transformer) ip.run_cell(code) ip.ast_transformers.remove(self._transformer) html = _active_profiler.output_html(timeline=args.timeline) as_iframe = IFrame( src="data:text/html, " + urllib.parse.quote(html), width="100%", height=args.height, extras=['style="resize: vertical"'], ) as_text = _active_profiler.output_text(timeline=args.timeline) # repr_html may be a bit fragile, but it's been stable for a while display({"text/html": as_iframe._repr_html_(), "text/plain": as_text}, raw=True) assert not _active_profiler.is_running _active_profiler = None
1,587
354
<filename>setup.py import os from setuptools import setup, find_packages def _package_files(directory: str, suffix: str) -> list: """ Get all of the file paths in the directory specified by suffix. :param directory: :return: """ paths = [] for (path, directories, filenames) in os.walk(directory): for filename in filenames: if filename.endswith(suffix): paths.append(os.path.join('..', path, filename)) return paths with open ("README.md", "r") as fh: long_description = fh.read() path = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(path, 'requirements.txt'), 'r') as f: requirements = f.readlines() setup( name='Frida-iOS-Hook', version='3.4', description='Trace Class/Function & Modify Return Value', author='noobpk', author_email='<EMAIL>', long_description =long_description, long_description_content_type="text/markdown", url='https://github.com/noobpk/frida-ios-hook/', packages=find_packages(), # include other files package_data={ '': _package_files(os.path.join(path, 'frida-ios-hook'), '.js') + _package_files(os.path.join(path, 'frida-ios-hook/frida-scripts'), '.js') + _package_files(os.path.join(path, 'frida-ios-hook/methods'), '.js') }, install_requires=requirements, classifiers=[ "Programming Language :: Python :: 3 :: Only", 'Natural Language :: English', "License :: OSI Approved :: MIT License", "Operating System :: OS Independent" ], python_requires='>=3.0', entry_points={ 'console_scripts': [ 'ioshook=core.hook.run:run', ], }, )
724
3,710
<filename>toonz/sources/include/toonz/tcenterlinevectorizer.h #pragma once #ifndef T_CENTERLINE_VECTORIZER #define T_CENTERLINE_VECTORIZER #include "toonz/vectorizerparameters.h" #include "tvectorimage.h" #include <deque> #include <list> #include <QObject> #undef DVAPI #undef DVVAR #ifdef TOONZLIB_EXPORTS #define DVAPI DV_EXPORT_API #define DVVAR DV_EXPORT_VAR #else #define DVAPI DV_IMPORT_API #define DVVAR DV_IMPORT_VAR #endif //============================== // Core vectorizer class //============================== //! Contains specific vectorization methods and deals with partial progress //! notifications (using Qt signals). /*!VectorizerCore class is the lowest layer of a vectorization process, it provides vectorization of a single input raster image by calling the \b vectorize method. It can also deal notifications about its progress status, and is receptive to user cancels. \sa VectorizerPopup, Vectorizer, VectorizerConfiguration classes.*/ class DVAPI VectorizerCore final : public QObject { Q_OBJECT int m_currPartial; int m_totalPartials; bool m_isCanceled; public: VectorizerCore() : m_currPartial(0), m_isCanceled(false) {} ~VectorizerCore() {} /*!Calls the appropriate technique to convert \b image to vectors depending on \b c. Also provides post-processing operations such as regions computing and painting (using colors found in \b palette). Returns the \b TVectorImageP converted image.*/ TVectorImageP vectorize(const TImageP &image, const VectorizerConfiguration &c, TPalette *palette); //! Returns true if vectorization was aborted at user's request bool isCanceled() { return m_isCanceled; } //!\b (\b Internal \b use \b only) Sets the maximum number of partial //! notifications. void setOverallPartials(int total) { m_totalPartials = total; } //!\b (\b Internal \b use \b only) Emits partial progress signal and updates //! partial progresses internal count. void emitPartialDone(void); private: /*!Converts \b image to vectors in centerline mode, depending on \b configuration. Returns image converted. Note: if true==configuration.m_naaSource then it change the image, transforming it to a ToonzImage */ TVectorImageP centerlineVectorize( TImageP &image, const CenterlineConfiguration &configuration, TPalette *palette); /*!Converts \b image to vectors in outline mode, depending on \b configuration. Returns image converted.*/ TVectorImageP outlineVectorize(const TImageP &image, const OutlineConfiguration &configuration, TPalette *palette); /*!Converts \b image to vectors in outline mode, depending on \b configuration. Returns image converted.*/ TVectorImageP newOutlineVectorize( const TImageP &image, const NewOutlineConfiguration &configuration, TPalette *palette); //! Calculates and applies fill colors once regions of \b vi have been //! computed. void applyFillColors(TVectorImageP vi, const TImageP &img, TPalette *palette, const VectorizerConfiguration &c); void applyFillColors(TRegion *r, const TRasterP &ras, TPalette *palette, const CenterlineConfiguration &c, int regionCount); // void applyFillColors(TRegion *r, const TRasterP &ras, TPalette *palette, // const OutlineConfiguration &c, int regionCount); //! Traduces the input VectorizerConfiguration into an edible form. VectorizerConfiguration traduceConfiguration( const VectorizerConfiguration &configuration); bool isInkRegionEdge(TStroke *stroke); bool isInkRegionEdgeReversed(TStroke *stroke); void clearInkRegionFlags(TVectorImageP vi); signals: //! Partial progress \b par1 of overall \b par2 is notified. void partialDone(int, int); protected slots: //! Receives a user cancel signal and attempts an early exit from //! vectorization process. void onCancel() { m_isCanceled = true; } }; #endif // T_CENTERLINE_VECTORIZER
1,340
1,338
<filename>src/tests/servers/app/text_rendering/main.cpp<gh_stars>1000+ #include <Application.h> #include <String.h> #include <View.h> #include <Window.h> class View : public BView { public: View(BRect bounds) : BView(bounds, "test", B_FOLLOW_ALL, B_WILL_DRAW) { } virtual void Draw(BRect updateRect) { BFont font; GetFont(&font); const BRect bounds = Bounds(); const BString text = "The quick brown fox jumps over the lazy dog!"; float size = 2.0f; float y = 30.0f; while (size < 48 && y - size < bounds.bottom) { font.SetSize(size); SetFont(&font); BString textAndSize = text; textAndSize << " (" << size << ")"; DrawString(textAndSize, BPoint(30.0f, y)); y = (int)(y + size * 1.2f); size *= 1.08; } } }; class Window : public BWindow { public: Window() : BWindow(BRect(30, 30, 600, 500), "Text rendering test", B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_QUIT_ON_WINDOW_CLOSE) { AddChild(new View(Bounds())); } }; class Application : public BApplication { public: Application() :BApplication("application/x-vnd.haiku.text-rendering-test") { } virtual void ReadyToRun() { (new Window())->Show(); } }; int main() { Application app; app.Run(); return 0; }
524
312
{ "syncs": [ { "syncName": "syncDownContacts", "syncType": "syncDown", "soupName": "contacts", "target": {"type":"soql", "query":"SELECT FirstName, LastName, Title, MobilePhone, Email, Department, HomePhone FROM Contact LIMIT 10000"}, "options": {"mergeMode":"OVERWRITE"} }, { "syncName": "syncUpContacts", "syncType": "syncUp", "soupName": "contacts", "target": {"createFieldlist":["FirstName", "LastName", "Title", "MobilePhone", "Email", "Department", "HomePhone"]}, "options": {"fieldlist":["Id", "FirstName", "LastName", "Title", "MobilePhone", "Email", "Department", "HomePhone"], "mergeMode":"LEAVE_IF_CHANGED"} } ] }
278
588
package com.flycms; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.embedded.jetty.JettyReactiveWebServerFactory; import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; @SpringBootApplication @ServletComponentScan @EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class,DataSourceAutoConfiguration.class}) //此注解表示动态扫描DAO接口所在包 @MapperScan("com.flycms.module.**.dao") @EnableCaching public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } /** * @param args */ public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
473
371
try: import torch except (ModuleNotFoundError, ImportError) as e: raise ModuleNotFoundError("torch is not currently installed. Run 'pip install convokit[craft]' if you would like to use the CRAFT model.") import pandas as pd from convokit.forecaster.CRAFT.CRAFTUtil import loadPrecomputedVoc, batchIterator, CONSTANTS from .CRAFT.CRAFTNN import initialize_model, makeContextEncoderInput, Predictor from .forecasterModel import ForecasterModel import numpy as np import torch.nn.functional as F from torch import optim from sklearn.model_selection import train_test_split from typing import Dict import os default_options = { 'hidden_size': 500, 'encoder_n_layers': 2, 'context_encoder_n_layers': 2, 'decoder_n_layers': 2, 'dropout': 0.1, 'batch_size': 64, 'clip': 50.0, 'learning_rate': 1e-5, 'print_every': 10, 'train_epochs': 30, 'validation_size': 0.2, 'max_length': 80, 'trained_model_output_filepath': "finetuned_model.tar" } # To understand the separation of concerns for the CRAFT files: # CRAFT/craftNN.py contains the class implementations needed to initialize the CRAFT Neural Network model # CRAFT/craftUtil.py contains utility methods for manipulating the data for it to be passed to the CRAFT model class CRAFTModel(ForecasterModel): """ CRAFTModel is one of the Forecaster models that can be used with the Forecaster Transformer. By default, CRAFTModel will be initialized with default options - hidden_size: 500 - encoder_n_layers: 2 - context_encoder_n_layers: 2 - decoder_n_layers: 2 - dropout: 0.1 - batch_size (batch size for computation, i.e. how many (context, reply, id) tuples to use per batch of evaluation): 64 - clip: 50.0 - learning_rate: 1e-5 - print_every: 10 - train_epochs (number of epochs for training): 30 - validation_size (percentage of training input data to use as validation): 0.2 - max_length (maximum utterance length in the dataset): 80 :param device_type: 'cpu' or 'cuda', default: 'cpu' :param model_path: filepath to CRAFT model if loading a custom CRAFT model :param options: configuration options for the neural network: uses default options otherwise. :param forecast_attribute_name: name of DataFrame column containing predictions, default: "prediction" :param forecast_prob_attribute_name: name of DataFrame column containing prediction scores, default: "score" """ def __init__(self, device_type: str = 'cpu', model_path: str = None, options: Dict = None, forecast_attribute_name: str = "prediction", forecast_feat_name=None, forecast_prob_attribute_name: str = "pred_score", forecast_prob_feat_name=None): super().__init__(forecast_attribute_name=forecast_attribute_name, forecast_feat_name=forecast_feat_name, forecast_prob_attribute_name=forecast_prob_attribute_name, forecast_prob_feat_name=forecast_prob_feat_name) assert device_type in ['cuda', 'cpu'] # device: controls GPU usage: 'cuda' to enable GPU, 'cpu' to run on CPU only. self.device = torch.device(device_type) self.device_type = device_type # voc: the vocabulary object (convokit.forecaster.craftUtil.Voc) used by predictor. # Used to convert text data into numerical input for CRAFT. self.voc = loadPrecomputedVoc("wikiconv", CONSTANTS['WORD2INDEX_URL'], CONSTANTS['INDEX2WORD_URL']) if options is None: self.options = default_options else: for k, v in default_options.items(): if k not in options: options[k] = v self.options = options print("Initializing CRAFT model with options:") print(self.options) if model_path is not None: if not os.path.isfile(model_path) or not model_path.endswith(".tar"): print("Could not find CRAFT model tar file at: {}".format(model_path)) model_path = None self.predictor: Predictor = initialize_model(model_path, self.voc, self.device, self.device_type, self.options['hidden_size'], self.options['encoder_n_layers'], self.options['dropout'], self.options['context_encoder_n_layers']) def _evaluate_batch(self, predictor, input_batch, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, true_batch_size): """ Helper for _evaluate_dataset. Runs CRAFT evaluation on a single batch; _evaluate_dataset calls this helper iteratively to get results for the entire dataset. :param predictor: the trained CRAFT model to use, provided as a PyTorch Model instance. :param input_batch: the batch to run CRAFT on (produced by convokit.forecaster.craftUtil.batchIterator, formatted as a batch of utterances) :param dialog_lengths: how many comments are in each conversation in this batch, as a PyTorch Tensor :param dialog_lengths_list: same as dialog_lengths, but as a Python List :param utt_lengths: for each conversation, records the number of tokens in each utterance of the conversation :param batch_indices: used by CRAFT to reconstruct the original dialog batch from the given utterance batch. Records which dialog each utterance originally came from. :param dialog_indices: used by CRAFT to reconstruct the original dialog batch from the given utterance batch. Records where in the dialog the utterance originally came from. :param true_batch_size: number of dialogs in the original dialog batch this utterance batch was generated from. :return: per-utterance scores and binarized predictions. """ # Set device options input_batch = input_batch.to(self.device) dialog_lengths = dialog_lengths.to(self.device) utt_lengths = utt_lengths.to(self.device) # Predict future attack using predictor scores = predictor(input_batch, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, true_batch_size, self.options['max_length']) predictions = (scores > 0.5).float() return predictions, scores def _evaluate_dataset(self, predictor, dataset): """ Run a trained CRAFT model over an entire dataset in a batched fashion. :param predictor: the trained CRAFT model to use, provided as a PyTorch Model instance. :param dataset: the dataset to evaluate on, formatted as a list of (context, reply, id_of_reply) tuples. :return: a DataFrame, indexed by utterance ID, of CRAFT scores for each utterance, and the corresponding binary prediction. """ # create a batch iterator for the given data batch_iterator = batchIterator(self.voc, dataset, self.options['batch_size'], shuffle=False) # find out how many iterations we will need to cover the whole dataset n_iters = len(dataset) // self.options['batch_size'] + int(len(dataset) % self.options['batch_size'] > 0) output_df = { "id": [], self.forecast_attribute_name: [], self.forecast_prob_attribute_name: [] } for iteration in range(1, n_iters+1): batch, batch_dialogs, true_batch_size = next(batch_iterator) # Extract fields from batch input_variable, dialog_lengths, utt_lengths, batch_indices, dialog_indices, \ labels, batch_ids, target_variable, mask, max_target_len = batch dialog_lengths_list = [len(x) for x in batch_dialogs] # run the model predictions, scores = self._evaluate_batch(predictor, input_variable, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, true_batch_size) # format the output as a dataframe (which we can later re-join with the corpus) for i in range(true_batch_size): utt_id = batch_ids[i] pred = predictions[i].item() score = scores[i].item() output_df["id"].append(utt_id) output_df[self.forecast_attribute_name].append(pred) output_df[self.forecast_prob_attribute_name].append(score) print("Iteration: {}; Percent complete: {:.1f}%".format(iteration, iteration / n_iters * 100)) return pd.DataFrame(output_df).set_index("id") def _train_NN(self, input_variable, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, labels, # input/output arguments encoder, context_encoder, attack_clf, # network arguments encoder_optimizer, context_encoder_optimizer, attack_clf_optimizer, # optimization arguments batch_size, clip): # misc arguments # Zero gradients encoder_optimizer.zero_grad() context_encoder_optimizer.zero_grad() attack_clf_optimizer.zero_grad() # Set device options input_variable = input_variable.to(self.device) dialog_lengths = dialog_lengths.to(self.device) utt_lengths = utt_lengths.to(self.device) labels = labels.to(self.device) # Forward pass through utterance encoder _, utt_encoder_hidden = encoder(input_variable, utt_lengths) # Convert utterance encoder final states to batched dialogs for use by context encoder context_encoder_input = makeContextEncoderInput(utt_encoder_hidden, dialog_lengths_list, batch_size, batch_indices, dialog_indices) # Forward pass through context encoder context_encoder_outputs, _ = context_encoder(context_encoder_input, dialog_lengths) # Forward pass through classifier to get prediction logits logits = attack_clf(context_encoder_outputs, dialog_lengths) # Calculate loss loss = F.binary_cross_entropy_with_logits(logits, labels) # Perform backpropatation loss.backward() # Clip gradients: gradients are modified in place _ = torch.nn.utils.clip_grad_norm_(encoder.parameters(), clip) _ = torch.nn.utils.clip_grad_norm_(context_encoder.parameters(), clip) _ = torch.nn.utils.clip_grad_norm_(attack_clf.parameters(), clip) # Adjust model weights encoder_optimizer.step() context_encoder_optimizer.step() attack_clf_optimizer.step() return loss.item() def _validate(self, predictor, dataset): # create a batch iterator for the given data batch_iterator = batchIterator(self.voc, dataset, self.options['batch_size'], shuffle=False) # find out how many iterations we will need to cover the whole dataset n_iters = len(dataset) // self.options['batch_size'] + int(len(dataset) % self.options['batch_size'] > 0) # containers for full prediction results so we can compute accuracy at the end all_preds = [] all_labels = [] for iteration in range(1, n_iters+1): batch, batch_dialogs, true_batch_size = next(batch_iterator) # Extract fields from batch input_variable, dialog_lengths, utt_lengths, batch_indices, dialog_indices, \ batch_labels, batch_ids, target_variable, mask, max_target_len = batch dialog_lengths_list = [len(x) for x in batch_dialogs] # run the model predictions, scores = self._evaluate_batch(predictor, input_variable, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, true_batch_size) # aggregate results for computing accuracy at the end all_preds += [p.item() for p in predictions] all_labels += [l.item() for l in batch_labels] print("Iteration: {}; Percent complete: {:.1f}%".format(iteration, iteration / n_iters * 100)) # compute and return the accuracy return (np.asarray(all_preds) == np.asarray(all_labels)).mean() def _train_iters(self, train_pairs, val_pairs, encoder, context_encoder, attack_clf, encoder_optimizer, context_encoder_optimizer, attack_clf_optimizer, embedding, n_iteration, validate_every): # create a batch iterator for training data batch_iterator = batchIterator(self.voc, train_pairs, self.options['batch_size']) # Initializations print('Initializing ...') start_iteration = 1 print_loss = 0 # Training loop print("Training...") # keep track of best validation accuracy - only save when we have a model that beats the current best best_acc = 0 for iteration in range(start_iteration, n_iteration + 1): training_batch, training_dialogs, true_batch_size = next(batch_iterator) # Extract fields from batch input_variable, dialog_lengths, utt_lengths, batch_indices, dialog_indices, \ labels, batch_ids, target_variable, mask, max_target_len = training_batch dialog_lengths_list = [len(x) for x in training_dialogs] # Run a training iteration with batch loss = self._train_NN(input_variable, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, labels, # input/output arguments encoder, context_encoder, attack_clf, # network arguments encoder_optimizer, context_encoder_optimizer, attack_clf_optimizer, # optimization arguments true_batch_size, self.options['clip']) # misc arguments print_loss += loss # Print progress if iteration % self.options['print_every'] == 0: print_loss_avg = print_loss / self.options['print_every'] print("Iteration: {}; Percent complete: {:.1f}%; Average loss: {:.4f}".format(iteration, iteration / n_iteration * 100, print_loss_avg)) print_loss = 0 # Evaluate on validation set if iteration % validate_every == 0: print("Validating!") # put the network components into evaluation mode encoder.eval() context_encoder.eval() attack_clf.eval() predictor = Predictor(encoder, context_encoder, attack_clf) accuracy = self._validate(predictor, val_pairs) print("Validation set accuracy: {:.2f}%".format(accuracy * 100)) # keep track of our best model so far if accuracy > best_acc: print("Validation accuracy better than current best; saving model...") best_acc = accuracy torch.save({ 'iteration': iteration, 'en': encoder.state_dict(), 'ctx': context_encoder.state_dict(), 'atk_clf': attack_clf.state_dict(), 'en_opt': encoder_optimizer.state_dict(), 'ctx_opt': context_encoder_optimizer.state_dict(), 'atk_clf_opt': attack_clf_optimizer.state_dict(), 'loss': loss, 'voc_dict': self.voc.__dict__, 'embedding': embedding.state_dict() }, self.options['trained_model_output_filepath']) # put the network components back into training mode encoder.train() context_encoder.train() attack_clf.train() def train(self, id_to_context_reply_label): ids = list(id_to_context_reply_label) train_pair_ids, val_pair_ids = train_test_split(ids, test_size=self.options['validation_size']) train_pairs = [id_to_context_reply_label[pair_id] for pair_id in train_pair_ids] val_pairs = [id_to_context_reply_label[pair_id] for pair_id in val_pair_ids] # Compute the number of training iterations we will need in order to achieve the number of epochs specified in the settings at the start of the notebook n_iter_per_epoch = len(train_pairs) // self.options['batch_size'] + int(len(train_pairs) % self.options['batch_size'] == 1) n_iteration = n_iter_per_epoch * self.options['train_epochs'] # Put dropout layers in train mode self.predictor.encoder.train() self.predictor.context_encoder.train() self.predictor.classifier.train() # Initialize optimizers print('Building optimizers...') encoder_optimizer = optim.Adam(self.predictor.encoder.parameters(), lr=self.options['learning_rate']) context_encoder_optimizer = optim.Adam(self.predictor.context_encoder.parameters(), lr=self.options['learning_rate']) attack_clf_optimizer = optim.Adam(self.predictor.classifier.parameters(), lr=self.options['learning_rate']) # Run training iterations, validating after every epoch print("Starting Training!") print("Will train for {} iterations".format(n_iteration)) self._train_iters(train_pairs, val_pairs, self.predictor.encoder, self.predictor.context_encoder, self.predictor.classifier, encoder_optimizer, context_encoder_optimizer, attack_clf_optimizer, self.predictor.encoder.embedding, n_iteration, n_iter_per_epoch) def forecast(self, id_to_context_reply_label): """ Compute forecasts and forecast scores for the given dictionary of utterance id to (context, reply) pairs. Return the values in a DataFrame. :param id_to_context_reply_label: dict mapping utterance id to (context, reply, label) :return: a pandas DataFrame """ dataset = [(context, reply, label, id_) for id_, (context, reply, label) in id_to_context_reply_label.items()] return self._evaluate_dataset(self.predictor, dataset)
8,116
3,967
# Copyright 2021 <NAME>. 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. # ============================================================================== from model import YOLOv4Model, calc_loss import numpy as np import tensorflow as tf from img import read_img, draw_img from dali.pipeline import YOLOv4Pipeline from np.pipeline import YOLOv4PipelineNumpy import utils import math import os import random SET_MEMORY_GROWTH = True class SaveWeightsCallback(tf.keras.callbacks.Callback): def __init__(self, ckpt_dir): self.ckpt_dir = ckpt_dir def on_epoch_begin(self, epoch, logs=None): self.model.save_weights(self.ckpt_dir + '/epoch_' + str(epoch) + '.h5') class YOLOLearningRateSchedule(tf.keras.optimizers.schedules.LearningRateSchedule): def __init__(self, init_lr): self.init_lr = init_lr def __call__(self, step): warmup = tf.math.minimum(1.0, tf.cast(step, tf.float32) / 1000) return warmup * self.init_lr def train(file_root, annotations, batch_size, epochs, steps_per_epoch, **kwargs): seed = kwargs.get("seed") if not seed: seed = int.from_bytes(os.urandom(4), "little") else: os.environ['PYTHONHASHSEED']=str(seed) tf.random.set_seed(seed) np.random.seed(seed) random.seed(seed) os.environ['TF_DETERMINISTIC_OPS'] = '1' os.environ['TF_CUDNN_DETERMINISTIC'] = '1' if SET_MEMORY_GROWTH: pds = tf.config.list_physical_devices('GPU') for pd in pds: tf.config.experimental.set_memory_growth(pd, True) pipeline = kwargs.get("pipeline") use_mosaic = kwargs.get("use_mosaic") log_dir = kwargs.get("log_dir") ckpt_dir = kwargs.get("ckpt_dir") start_weights = kwargs.get("start_weights") def get_dataset_fn(file_root, annotations, batch_size, pipeline, is_training): def dataset_fn(input_context): image_size = (608, 608) device_id = input_context.input_pipeline_id num_threads = input_context.num_input_pipelines if pipeline == 'dali-gpu' or pipeline == 'dali-cpu': with tf.device("/gpu:{}".format(input_context.input_pipeline_id)): yolo = YOLOv4Pipeline( file_root, annotations, batch_size, image_size, num_threads, device_id, seed, use_gpu=pipeline == 'dali-gpu', is_training=is_training, use_mosaic=use_mosaic ) return yolo.dataset() if pipeline == 'numpy': yolo = YOLOv4PipelineNumpy( file_root, annotations, batch_size, image_size, num_threads, device_id, seed, is_training=is_training, use_mosaic=use_mosaic ) return yolo.dataset() return dataset_fn total_steps = epochs * steps_per_epoch initial_lr = kwargs.get("lr") lr_fn = YOLOLearningRateSchedule(initial_lr) initial_epoch = 0 multigpu = kwargs.get("multigpu") strategy = tf.distribute.MirroredStrategy() if multigpu else tf.distribute.get_strategy() with strategy.scope(): model = YOLOv4Model() model.compile( optimizer=tf.keras.optimizers.SGD(learning_rate=lr_fn) ) if start_weights: model.load_weights(start_weights) fn = start_weights.split('/')[-1] if fn.endswith('.h5') and fn.startswith('epoch_'): initial_epoch = int(fn[6 : -3]) input_options = tf.distribute.InputOptions( experimental_place_dataset_on_device = True, experimental_fetch_to_device = False, experimental_replication_mode = tf.distribute.InputReplicationMode.PER_REPLICA) dataset = strategy.distribute_datasets_from_function( get_dataset_fn(file_root, annotations, batch_size, pipeline, True), input_options) eval_file_root = kwargs.get('eval_file_root') eval_annotations = kwargs.get('eval_annotations') eval_dataset = None if not eval_file_root is None and not eval_annotations is None: eval_dataset = strategy.distribute_datasets_from_function( get_dataset_fn(eval_file_root, eval_annotations, 1, 'dali-cpu', False), tf.distribute.InputOptions() ) callbacks = [] if log_dir: callbacks.append(tf.keras.callbacks.TensorBoard( log_dir=log_dir, update_freq='epoch' )) if ckpt_dir: callbacks.append(SaveWeightsCallback(ckpt_dir)) model.fit( dataset, epochs=epochs, steps_per_epoch=steps_per_epoch, initial_epoch=initial_epoch, callbacks=callbacks, validation_data=eval_dataset, validation_steps=kwargs.get('eval_steps'), validation_freq=kwargs.get('eval_frequency'), ) return model
2,506
419
#include "Core.h" #ifdef CC_BUILD_GL #include "_GraphicsBase.h" #include "Chat.h" #include "Errors.h" #include "Logger.h" #include "Window.h" /* The OpenGL backend is a bit of a mess, since it's really 3 backends in one: * - OpenGL 1.1 (completely lacking GPU, fallbacks to say Windows built-in software rasteriser) * - OpenGL 1.5 or OpenGL 1.2 + GL_ARB_vertex_buffer_object (default desktop backend) * - OpenGL 2.0 (alternative modern-ish backend) */ #if defined CC_BUILD_WIN /* Avoid pointless includes */ #define WIN32_LEAN_AND_MEAN #define NOSERVICE #define NOMCX #define NOIME #include <windows.h> #include <GL/gl.h> #elif defined CC_BUILD_IOS #include <OpenGLES/ES2/gl.h> #elif defined CC_BUILD_MACOS #include <OpenGL/gl.h> #elif defined CC_BUILD_GLES && defined CC_BUILD_GLMODERN #include <GLES2/gl2.h> #elif defined CC_BUILD_GLES #include <GLES/gl.h> #else #define GL_GLEXT_PROTOTYPES #include <GL/gl.h> #endif /* Not present in gl.h on Windows (only up to OpenGL 1.1) */ #define _GL_ARRAY_BUFFER 0x8892 #define _GL_ELEMENT_ARRAY_BUFFER 0x8893 #define _GL_STATIC_DRAW 0x88E4 #define _GL_DYNAMIC_DRAW 0x88E8 #define _GL_TEXTURE_MAX_LEVEL 0x813D #define _GL_FRAGMENT_SHADER 0x8B30 #define _GL_VERTEX_SHADER 0x8B31 #define _GL_COMPILE_STATUS 0x8B81 #define _GL_LINK_STATUS 0x8B82 #define _GL_INFO_LOG_LENGTH 0x8B84 #if defined CC_BUILD_GL11 static GLuint activeList; #define gl_DYNAMICLISTID 1234567891 static void* dynamicListData; static cc_uint16 gl_indices[GFX_MAX_INDICES]; #elif defined CC_BUILD_GLMODERN #define _glBindBuffer(t,b) glBindBuffer(t,b) #define _glDeleteBuffers(n,b) glDeleteBuffers(n,b) #define _glGenBuffers(n,b) glGenBuffers(n,b) #define _glBufferData(t,s,d,u) glBufferData(t,s,d,u) #define _glBufferSubData(t,o,s,d) glBufferSubData(t,o,s,d) #else /* OpenGL functions use stdcall instead of cdecl on Windows */ #ifndef APIENTRY #define APIENTRY #endif static void (APIENTRY *_glBindBuffer)(GLenum target, GLuint buffer); static void (APIENTRY *_glDeleteBuffers)(GLsizei n, const GLuint *buffers); static void (APIENTRY *_glGenBuffers)(GLsizei n, GLuint *buffers); static void (APIENTRY *_glBufferData)(GLenum target, cc_uintptr size, const GLvoid* data, GLenum usage); static void (APIENTRY *_glBufferSubData)(GLenum target, cc_uintptr offset, cc_uintptr size, const GLvoid* data); #endif #if defined CC_BUILD_WEB || defined CC_BUILD_ANDROID #define PIXEL_FORMAT GL_RGBA #else #define PIXEL_FORMAT 0x80E1 /* GL_BGRA_EXT */ #endif #if defined CC_BIG_ENDIAN /* Pixels are stored in memory as A,R,G,B but GL_UNSIGNED_BYTE will interpret as B,G,R,A */ /* So use GL_UNSIGNED_INT_8_8_8_8_REV instead to remedy this */ #define TRANSFER_FORMAT GL_UNSIGNED_INT_8_8_8_8_REV #else /* Pixels are stored in memory as B,G,R,A and GL_UNSIGNED_BYTE will interpret as B,G,R,A */ /* So fine to just use GL_UNSIGNED_BYTE here */ #define TRANSFER_FORMAT GL_UNSIGNED_BYTE #endif typedef void (*GL_SetupVBFunc)(void); typedef void (*GL_SetupVBRangeFunc)(int startVertex); static GL_SetupVBFunc gfx_setupVBFunc; static GL_SetupVBRangeFunc gfx_setupVBRangeFunc; /* Current format and size of vertices */ static int gfx_stride, gfx_format = -1; static void GL_UpdateVsync(void) { GLContext_SetFpsLimit(gfx_vsync, gfx_minFrameMs); } static void GL_CheckSupport(void); void Gfx_Create(void) { GLContext_Create(); glGetIntegerv(GL_MAX_TEXTURE_SIZE, &Gfx.MaxTexWidth); Gfx.MaxTexHeight = Gfx.MaxTexWidth; Gfx.Created = true; GL_CheckSupport(); Gfx_RestoreState(); GL_UpdateVsync(); } cc_bool Gfx_TryRestoreContext(void) { return GLContext_TryRestore(); } void Gfx_Free(void) { Gfx_FreeState(); GLContext_Free(); } #define gl_Toggle(cap) if (enabled) { glEnable(cap); } else { glDisable(cap); } static void* tmpData; static int tmpSize; static void* FastAllocTempMem(int size) { if (size > tmpSize) { Mem_Free(tmpData); tmpData = Mem_Alloc(size, 1, "Gfx_AllocTempMemory"); } tmpSize = size; return tmpData; } /*########################################################################################################################* *---------------------------------------------------------Textures--------------------------------------------------------* *#########################################################################################################################*/ static void Gfx_DoMipmaps(int x, int y, struct Bitmap* bmp, int rowWidth, cc_bool partial) { BitmapCol* prev = bmp->scan0; BitmapCol* cur; int lvls = CalcMipmapsLevels(bmp->width, bmp->height); int lvl, width = bmp->width, height = bmp->height; for (lvl = 1; lvl <= lvls; lvl++) { x /= 2; y /= 2; if (width > 1) width /= 2; if (height > 1) height /= 2; cur = (BitmapCol*)Mem_Alloc(width * height, 4, "mipmaps"); GenMipmaps(width, height, cur, prev, rowWidth); if (partial) { glTexSubImage2D(GL_TEXTURE_2D, lvl, x, y, width, height, PIXEL_FORMAT, TRANSFER_FORMAT, cur); } else { glTexImage2D(GL_TEXTURE_2D, lvl, GL_RGBA, width, height, 0, PIXEL_FORMAT, TRANSFER_FORMAT, cur); } if (prev != bmp->scan0) Mem_Free(prev); prev = cur; rowWidth = width; } if (prev != bmp->scan0) Mem_Free(prev); } GfxResourceID Gfx_CreateTexture(struct Bitmap* bmp, cc_uint8 flags, cc_bool mipmaps) { GLuint texId; glGenTextures(1, &texId); glBindTexture(GL_TEXTURE_2D, texId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if (!Math_IsPowOf2(bmp->width) || !Math_IsPowOf2(bmp->height)) { Logger_Abort("Textures must have power of two dimensions"); } if (Gfx.LostContext) return 0; if (mipmaps) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); if (customMipmapsLevels) { int lvls = CalcMipmapsLevels(bmp->width, bmp->height); glTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_MAX_LEVEL, lvls); } } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bmp->width, bmp->height, 0, PIXEL_FORMAT, TRANSFER_FORMAT, bmp->scan0); if (mipmaps) Gfx_DoMipmaps(0, 0, bmp, bmp->width, false); return texId; } #define UPDATE_FAST_SIZE (64 * 64) static CC_NOINLINE void UpdateTextureSlow(int x, int y, struct Bitmap* part, int rowWidth) { BitmapCol buffer[UPDATE_FAST_SIZE]; void* ptr = (void*)buffer; int count = part->width * part->height; /* cannot allocate memory on the stack for very big updates */ if (count > UPDATE_FAST_SIZE) { ptr = Mem_Alloc(count, 4, "Gfx_UpdateTexture temp"); } CopyTextureData(ptr, part->width << 2, part, rowWidth << 2); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, part->width, part->height, PIXEL_FORMAT, TRANSFER_FORMAT, ptr); if (count > UPDATE_FAST_SIZE) Mem_Free(ptr); } void Gfx_UpdateTexture(GfxResourceID texId, int x, int y, struct Bitmap* part, int rowWidth, cc_bool mipmaps) { glBindTexture(GL_TEXTURE_2D, (GLuint)texId); /* TODO: Use GL_UNPACK_ROW_LENGTH for Desktop OpenGL */ if (part->width == rowWidth) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, part->width, part->height, PIXEL_FORMAT, TRANSFER_FORMAT, part->scan0); } else { UpdateTextureSlow(x, y, part, rowWidth); } if (mipmaps) Gfx_DoMipmaps(x, y, part, rowWidth, true); } void Gfx_UpdateTexturePart(GfxResourceID texId, int x, int y, struct Bitmap* part, cc_bool mipmaps) { Gfx_UpdateTexture(texId, x, y, part, part->width, mipmaps); } void Gfx_BindTexture(GfxResourceID texId) { glBindTexture(GL_TEXTURE_2D, (GLuint)texId); } void Gfx_DeleteTexture(GfxResourceID* texId) { GLuint id = (GLuint)(*texId); if (!id) return; glDeleteTextures(1, &id); *texId = 0; } void Gfx_EnableMipmaps(void) { } void Gfx_DisableMipmaps(void) { } /*########################################################################################################################* *-----------------------------------------------------State management----------------------------------------------------* *#########################################################################################################################*/ static PackedCol gfx_clearColor, gfx_fogColor; static float gfx_fogEnd = -1.0f, gfx_fogDensity = -1.0f; static int gfx_fogMode = -1; void Gfx_SetFaceCulling(cc_bool enabled) { gl_Toggle(GL_CULL_FACE); } void Gfx_SetAlphaBlending(cc_bool enabled) { gl_Toggle(GL_BLEND); } void Gfx_SetAlphaArgBlend(cc_bool enabled) { } static void GL_ClearCol(PackedCol col) { glClearColor(PackedCol_R(col) / 255.0f, PackedCol_G(col) / 255.0f, PackedCol_B(col) / 255.0f, PackedCol_A(col) / 255.0f); } void Gfx_ClearCol(PackedCol col) { if (col == gfx_clearColor) return; GL_ClearCol(col); gfx_clearColor = col; } void Gfx_SetColWriteMask(cc_bool r, cc_bool g, cc_bool b, cc_bool a) { glColorMask(r, g, b, a); } void Gfx_SetDepthWrite(cc_bool enabled) { glDepthMask(enabled); } void Gfx_SetDepthTest(cc_bool enabled) { gl_Toggle(GL_DEPTH_TEST); } void Gfx_CalcOrthoMatrix(float width, float height, struct Matrix* matrix) { Matrix_Orthographic(matrix, 0.0f, width, 0.0f, height, ORTHO_NEAR, ORTHO_FAR); } void Gfx_CalcPerspectiveMatrix(float fov, float aspect, float zFar, struct Matrix* matrix) { float zNear = 0.1f; Matrix_PerspectiveFieldOfView(matrix, fov, aspect, zNear, zFar); } /*########################################################################################################################* *-------------------------------------------------------Index buffers-----------------------------------------------------* *#########################################################################################################################*/ #ifndef CC_BUILD_GL11 static GLuint GL_GenAndBind(GLenum target) { GLuint id; _glGenBuffers(1, &id); _glBindBuffer(target, id); return id; } GfxResourceID Gfx_CreateIb(void* indices, int indicesCount) { GLuint id = GL_GenAndBind(_GL_ELEMENT_ARRAY_BUFFER); cc_uint32 size = indicesCount * 2; _glBufferData(_GL_ELEMENT_ARRAY_BUFFER, size, indices, _GL_STATIC_DRAW); return id; } void Gfx_BindIb(GfxResourceID ib) { _glBindBuffer(_GL_ELEMENT_ARRAY_BUFFER, (GLuint)ib); } void Gfx_DeleteIb(GfxResourceID* ib) { GLuint id = (GLuint)(*ib); if (!id) return; _glDeleteBuffers(1, &id); *ib = 0; } #else GfxResourceID Gfx_CreateIb(void* indices, int indicesCount) { return 0; } void Gfx_BindIb(GfxResourceID ib) { } void Gfx_DeleteIb(GfxResourceID* ib) { } #endif /*########################################################################################################################* *------------------------------------------------------Vertex buffers-----------------------------------------------------* *#########################################################################################################################*/ #ifndef CC_BUILD_GL11 GfxResourceID Gfx_CreateVb(VertexFormat fmt, int count) { return GL_GenAndBind(_GL_ARRAY_BUFFER); } void Gfx_BindVb(GfxResourceID vb) { _glBindBuffer(_GL_ARRAY_BUFFER, (GLuint)vb); } void Gfx_DeleteVb(GfxResourceID* vb) { GLuint id = (GLuint)(*vb); if (!id) return; _glDeleteBuffers(1, &id); *vb = 0; } void* Gfx_LockVb(GfxResourceID vb, VertexFormat fmt, int count) { return FastAllocTempMem(count * strideSizes[fmt]); } void Gfx_UnlockVb(GfxResourceID vb) { _glBufferData(_GL_ARRAY_BUFFER, tmpSize, tmpData, _GL_STATIC_DRAW); } #else static void UpdateDisplayList(GLuint list, void* vertices, VertexFormat fmt, int count) { /* We need to restore client state afer building the list */ int realFormat = gfx_format; void* dyn_data = dynamicListData; Gfx_SetVertexFormat(fmt); dynamicListData = vertices; glNewList(list, GL_COMPILE); gfx_setupVBFunc(); glDrawElements(GL_TRIANGLES, ICOUNT(count), GL_UNSIGNED_SHORT, gl_indices); glEndList(); Gfx_SetVertexFormat(realFormat); dynamicListData = dyn_data; } GfxResourceID Gfx_CreateVb(VertexFormat fmt, int count) { return glGenLists(1); } void Gfx_BindVb(GfxResourceID vb) { activeList = (GLuint)vb; } void Gfx_DeleteVb(GfxResourceID* vb) { GLuint id = (GLuint)(*vb); if (id) glDeleteLists(id, 1); *vb = 0; } /* NOTE! Building chunk in Builder.c relies on vb being ignored */ /* If that changes, you must fix Builder.c to properly call Gfx_LockVb */ static VertexFormat tmpFormat; static int tmpCount; void* Gfx_LockVb(GfxResourceID vb, VertexFormat fmt, int count) { tmpFormat = fmt; tmpCount = count; return FastAllocTempMem(count * strideSizes[fmt]); } void Gfx_UnlockVb(GfxResourceID vb) { UpdateDisplayList((GLuint)vb, tmpData, tmpFormat, tmpCount); } GfxResourceID Gfx_CreateVb2(void* vertices, VertexFormat fmt, int count) { GLuint list = glGenLists(1); UpdateDisplayList(list, vertices, fmt, count); return list; } #endif /*########################################################################################################################* *--------------------------------------------------Dynamic vertex buffers-------------------------------------------------* *#########################################################################################################################*/ #ifndef CC_BUILD_GL11 GfxResourceID Gfx_CreateDynamicVb(VertexFormat fmt, int maxVertices) { GLuint id; cc_uint32 size; if (Gfx.LostContext) return 0; id = GL_GenAndBind(_GL_ARRAY_BUFFER); size = maxVertices * strideSizes[fmt]; _glBufferData(_GL_ARRAY_BUFFER, size, NULL, _GL_DYNAMIC_DRAW); return id; } void* Gfx_LockDynamicVb(GfxResourceID vb, VertexFormat fmt, int count) { return FastAllocTempMem(count * strideSizes[fmt]); } void Gfx_UnlockDynamicVb(GfxResourceID vb) { _glBindBuffer(_GL_ARRAY_BUFFER, (GLuint)vb); _glBufferSubData(_GL_ARRAY_BUFFER, 0, tmpSize, tmpData); } void Gfx_SetDynamicVbData(GfxResourceID vb, void* vertices, int vCount) { cc_uint32 size = vCount * gfx_stride; _glBindBuffer(_GL_ARRAY_BUFFER, (GLuint)vb); _glBufferSubData(_GL_ARRAY_BUFFER, 0, size, vertices); } #else GfxResourceID Gfx_CreateDynamicVb(VertexFormat fmt, int maxVertices) { return (GfxResourceID)Mem_Alloc(maxVertices, strideSizes[fmt], "creating dynamic vb"); } void Gfx_BindDynamicVb(GfxResourceID vb) { activeList = gl_DYNAMICLISTID; dynamicListData = (void*)vb; } void Gfx_DeleteDynamicVb(GfxResourceID* vb) { void* addr = (void*)(*vb); if (addr) Mem_Free(addr); *vb = 0; } void* Gfx_LockDynamicVb(GfxResourceID vb, VertexFormat fmt, int count) { return (void*)vb; } void Gfx_UnlockDynamicVb(GfxResourceID vb) { Gfx_BindDynamicVb(vb); } void Gfx_SetDynamicVbData(GfxResourceID vb, void* vertices, int vCount) { Gfx_BindDynamicVb(vb); Mem_Copy((void*)vb, vertices, vCount * gfx_stride); } #endif /*########################################################################################################################* *-----------------------------------------------------------Misc----------------------------------------------------------* *#########################################################################################################################*/ static BitmapCol* GL_GetRow(struct Bitmap* bmp, int y) { /* OpenGL stores bitmap in bottom-up order, so flip order when saving */ return Bitmap_GetRow(bmp, (bmp->height - 1) - y); } cc_result Gfx_TakeScreenshot(struct Stream* output) { struct Bitmap bmp; cc_result res; GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); /* { x, y, width, height } */ bmp.width = vp[2]; bmp.height = vp[3]; bmp.scan0 = (BitmapCol*)Mem_TryAlloc(bmp.width * bmp.height, 4); if (!bmp.scan0) return ERR_OUT_OF_MEMORY; glReadPixels(0, 0, bmp.width, bmp.height, PIXEL_FORMAT, TRANSFER_FORMAT, bmp.scan0); res = Png_Encode(&bmp, output, GL_GetRow, false); Mem_Free(bmp.scan0); return res; } static void AppendVRAMStats(cc_string* info) { static const cc_string memExt = String_FromConst("GL_NVX_gpu_memory_info"); GLint totalKb, curKb; float total, cur; /* NOTE: glGetString returns UTF8, but I just treat it as code page 437 */ cc_string exts = String_FromReadonly((const char*)glGetString(GL_EXTENSIONS)); if (!String_CaselessContains(&exts, &memExt)) return; glGetIntegerv(0x9048, &totalKb); glGetIntegerv(0x9049, &curKb); if (totalKb <= 0 || curKb <= 0) return; total = totalKb / 1024.0f; cur = curKb / 1024.0f; String_Format2(info, "Video memory: %f2 MB total, %f2 free\n", &total, &cur); } void Gfx_GetApiInfo(cc_string* info) { GLint depthBits; int pointerSize = sizeof(void*) * 8; glGetIntegerv(GL_DEPTH_BITS, &depthBits); String_Format1(info, "-- Using OpenGL (%i bit) --\n", &pointerSize); String_Format1(info, "Vendor: %c\n", glGetString(GL_VENDOR)); String_Format1(info, "Renderer: %c\n", glGetString(GL_RENDERER)); String_Format1(info, "GL version: %c\n", glGetString(GL_VERSION)); AppendVRAMStats(info); String_Format2(info, "Max texture size: (%i, %i)\n", &Gfx.MaxTexWidth, &Gfx.MaxTexHeight); String_Format1(info, "Depth buffer bits: %i\n", &depthBits); GLContext_GetApiInfo(info); } void Gfx_SetFpsLimit(cc_bool vsync, float minFrameMs) { gfx_minFrameMs = minFrameMs; gfx_vsync = vsync; if (Gfx.Created) GL_UpdateVsync(); } void Gfx_BeginFrame(void) { frameStart = Stopwatch_Measure(); } void Gfx_Clear(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Gfx_EndFrame(void) { if (!GLContext_SwapBuffers()) Gfx_LoseContext("GLContext lost"); if (gfx_minFrameMs) LimitFPS(); } void Gfx_OnWindowResize(void) { GLContext_Update(); /* In case GLContext_Update changes window bounds */ /* TODO: Eliminate this nasty hack.. */ Game_UpdateDimensions(); glViewport(0, 0, Game.Width, Game.Height); } /*########################################################################################################################* *------------------------------------------------------OpenGL modern------------------------------------------------------* *#########################################################################################################################*/ #ifdef CC_BUILD_GLMODERN #define FTR_TEXTURE_UV (1 << 0) #define FTR_ALPHA_TEST (1 << 1) #define FTR_TEX_OFFSET (1 << 2) #define FTR_LINEAR_FOG (1 << 3) #define FTR_DENSIT_FOG (1 << 4) #define FTR_HASANY_FOG (FTR_LINEAR_FOG | FTR_DENSIT_FOG) #define FTR_FS_MEDIUMP (1 << 7) #define UNI_MVP_MATRIX (1 << 0) #define UNI_TEX_OFFSET (1 << 1) #define UNI_FOG_COL (1 << 2) #define UNI_FOG_END (1 << 3) #define UNI_FOG_DENS (1 << 4) #define UNI_MASK_ALL 0x1F /* cached uniforms (cached for multiple programs */ static struct Matrix _view, _proj, _mvp; static cc_bool gfx_alphaTest, gfx_texTransform; static float _texX, _texY; /* shader programs (emulate fixed function) */ static struct GLShader { int features; /* what features are enabled for this shader */ int uniforms; /* which associated uniforms need to be resent to GPU */ GLuint program; /* OpenGL program ID (0 if not yet compiled) */ int locations[5]; /* location of uniforms (not constant) */ } shaders[6 * 3] = { /* no fog */ { 0 }, { 0 | FTR_ALPHA_TEST }, { FTR_TEXTURE_UV }, { FTR_TEXTURE_UV | FTR_ALPHA_TEST }, { FTR_TEXTURE_UV | FTR_TEX_OFFSET }, { FTR_TEXTURE_UV | FTR_TEX_OFFSET | FTR_ALPHA_TEST }, /* linear fog */ { FTR_LINEAR_FOG | 0 }, { FTR_LINEAR_FOG | 0 | FTR_ALPHA_TEST }, { FTR_LINEAR_FOG | FTR_TEXTURE_UV }, { FTR_LINEAR_FOG | FTR_TEXTURE_UV | FTR_ALPHA_TEST }, { FTR_LINEAR_FOG | FTR_TEXTURE_UV | FTR_TEX_OFFSET }, { FTR_LINEAR_FOG | FTR_TEXTURE_UV | FTR_TEX_OFFSET | FTR_ALPHA_TEST }, /* density fog */ { FTR_DENSIT_FOG | 0 }, { FTR_DENSIT_FOG | 0 | FTR_ALPHA_TEST }, { FTR_DENSIT_FOG | FTR_TEXTURE_UV }, { FTR_DENSIT_FOG | FTR_TEXTURE_UV | FTR_ALPHA_TEST }, { FTR_DENSIT_FOG | FTR_TEXTURE_UV | FTR_TEX_OFFSET }, { FTR_DENSIT_FOG | FTR_TEXTURE_UV | FTR_TEX_OFFSET | FTR_ALPHA_TEST }, }; static struct GLShader* gfx_activeShader; /* Generates source code for a GLSL vertex shader, based on shader's flags */ static void GenVertexShader(const struct GLShader* shader, cc_string* dst) { int uv = shader->features & FTR_TEXTURE_UV; int tm = shader->features & FTR_TEX_OFFSET; String_AppendConst(dst, "attribute vec3 in_pos;\n"); String_AppendConst(dst, "attribute vec4 in_col;\n"); if (uv) String_AppendConst(dst, "attribute vec2 in_uv;\n"); String_AppendConst(dst, "varying vec4 out_col;\n"); if (uv) String_AppendConst(dst, "varying vec2 out_uv;\n"); String_AppendConst(dst, "uniform mat4 mvp;\n"); if (tm) String_AppendConst(dst, "uniform vec2 texOffset;\n"); String_AppendConst(dst, "void main() {\n"); String_AppendConst(dst, " gl_Position = mvp * vec4(in_pos, 1.0);\n"); String_AppendConst(dst, " out_col = in_col;\n"); if (uv) String_AppendConst(dst, " out_uv = in_uv;\n"); if (tm) String_AppendConst(dst, " out_uv = out_uv + texOffset;\n"); String_AppendConst(dst, "}"); } /* Generates source code for a GLSL fragment shader, based on shader's flags */ static void GenFragmentShader(const struct GLShader* shader, cc_string* dst) { int uv = shader->features & FTR_TEXTURE_UV; int al = shader->features & FTR_ALPHA_TEST; int fl = shader->features & FTR_LINEAR_FOG; int fd = shader->features & FTR_DENSIT_FOG; int fm = shader->features & FTR_HASANY_FOG; #ifdef CC_BUILD_GLES int mp = shader->features & FTR_FS_MEDIUMP; if (mp) String_AppendConst(dst, "precision mediump float;\n"); else String_AppendConst(dst, "precision highp float;\n"); #endif String_AppendConst(dst, "varying vec4 out_col;\n"); if (uv) String_AppendConst(dst, "varying vec2 out_uv;\n"); if (uv) String_AppendConst(dst, "uniform sampler2D texImage;\n"); if (fm) String_AppendConst(dst, "uniform vec3 fogCol;\n"); if (fl) String_AppendConst(dst, "uniform float fogEnd;\n"); if (fd) String_AppendConst(dst, "uniform float fogDensity;\n"); String_AppendConst(dst, "void main() {\n"); if (uv) String_AppendConst(dst, " vec4 col = texture2D(texImage, out_uv) * out_col;\n"); else String_AppendConst(dst, " vec4 col = out_col;\n"); if (al) String_AppendConst(dst, " if (col.a < 0.5) discard;\n"); if (fm) String_AppendConst(dst, " float depth = gl_FragCoord.z / gl_FragCoord.w;\n"); if (fl) String_AppendConst(dst, " float f = clamp((fogEnd - depth) / fogEnd, 0.0, 1.0);\n"); if (fd) String_AppendConst(dst, " float f = clamp(exp(fogDensity * depth), 0.0, 1.0);\n"); if (fm) String_AppendConst(dst, " col.rgb = mix(fogCol, col.rgb, f);\n"); String_AppendConst(dst, " gl_FragColor = col;\n"); String_AppendConst(dst, "}"); } /* Tries to compile GLSL shader code */ static GLint CompileShader(GLint shader, const cc_string* src) { const char* str = src->buffer; int len = src->length; GLint temp; glShaderSource(shader, 1, &str, &len); glCompileShader(shader); glGetShaderiv(shader, _GL_COMPILE_STATUS, &temp); return temp; } /* Logs information then aborts program */ static void ShaderFailed(GLint shader) { char logInfo[2048]; GLint temp; if (!shader) Logger_Abort("Failed to create shader"); temp = 0; glGetShaderiv(shader, _GL_INFO_LOG_LENGTH, &temp); if (temp > 1) { glGetShaderInfoLog(shader, 2047, NULL, logInfo); logInfo[2047] = '\0'; Window_ShowDialog("Failed to compile shader", logInfo); } Logger_Abort("Failed to compile shader"); } /* Tries to compile vertex and fragment shaders, then link into an OpenGL program */ static void CompileProgram(struct GLShader* shader) { char tmpBuffer[2048]; cc_string tmp; GLuint vs, fs, program; GLint temp; vs = glCreateShader(_GL_VERTEX_SHADER); if (!vs) { Platform_LogConst("Failed to create vertex shader"); return; } String_InitArray(tmp, tmpBuffer); GenVertexShader(shader, &tmp); if (!CompileShader(vs, &tmp)) ShaderFailed(vs); fs = glCreateShader(_GL_FRAGMENT_SHADER); if (!fs) { Platform_LogConst("Failed to create fragment shader"); glDeleteShader(vs); return; } tmp.length = 0; GenFragmentShader(shader, &tmp); if (!CompileShader(fs, &tmp)) { /* Sometimes fails 'highp precision is not supported in fragment shader' */ /* So try compiling shader again without highp precision */ shader->features |= FTR_FS_MEDIUMP; tmp.length = 0; GenFragmentShader(shader, &tmp); if (!CompileShader(fs, &tmp)) ShaderFailed(fs); } program = glCreateProgram(); if (!program) Logger_Abort("Failed to create program"); shader->program = program; glAttachShader(program, vs); glAttachShader(program, fs); /* Force in_pos/in_col/in_uv attributes to be bound to 0,1,2 locations */ /* Although most browsers assign the attributes in this order anyways, */ /* the specification does not require this. (e.g. Safari doesn't) */ glBindAttribLocation(program, 0, "in_pos"); glBindAttribLocation(program, 1, "in_col"); glBindAttribLocation(program, 2, "in_uv"); glLinkProgram(program); glGetProgramiv(program, _GL_LINK_STATUS, &temp); if (temp) { glDetachShader(program, vs); glDetachShader(program, fs); glDeleteShader(vs); glDeleteShader(fs); shader->locations[0] = glGetUniformLocation(program, "mvp"); shader->locations[1] = glGetUniformLocation(program, "texOffset"); shader->locations[2] = glGetUniformLocation(program, "fogCol"); shader->locations[3] = glGetUniformLocation(program, "fogEnd"); shader->locations[4] = glGetUniformLocation(program, "fogDensity"); return; } temp = 0; glGetProgramiv(program, _GL_INFO_LOG_LENGTH, &temp); if (temp > 0) { glGetProgramInfoLog(program, 2047, NULL, tmpBuffer); tmpBuffer[2047] = '\0'; Window_ShowDialog("Failed to compile program", tmpBuffer); } Logger_Abort("Failed to compile program"); } /* Marks a uniform as changed on all programs */ static void DirtyUniform(int uniform) { int i; for (i = 0; i < Array_Elems(shaders); i++) { shaders[i].uniforms |= uniform; } } /* Sends changed uniforms to the GPU for current program */ static void ReloadUniforms(void) { struct GLShader* s = gfx_activeShader; if (!s) return; /* NULL if context is lost */ if (s->uniforms & UNI_MVP_MATRIX) { glUniformMatrix4fv(s->locations[0], 1, false, (float*)&_mvp); s->uniforms &= ~UNI_MVP_MATRIX; } if ((s->uniforms & UNI_TEX_OFFSET) && (s->features & FTR_TEX_OFFSET)) { glUniform2f(s->locations[1], _texX, _texY); s->uniforms &= ~UNI_TEX_OFFSET; } if ((s->uniforms & UNI_FOG_COL) && (s->features & FTR_HASANY_FOG)) { glUniform3f(s->locations[2], PackedCol_R(gfx_fogColor) / 255.0f, PackedCol_G(gfx_fogColor) / 255.0f, PackedCol_B(gfx_fogColor) / 255.0f); s->uniforms &= ~UNI_FOG_COL; } if ((s->uniforms & UNI_FOG_END) && (s->features & FTR_LINEAR_FOG)) { glUniform1f(s->locations[3], gfx_fogEnd); s->uniforms &= ~UNI_FOG_END; } if ((s->uniforms & UNI_FOG_DENS) && (s->features & FTR_DENSIT_FOG)) { /* See https://docs.microsoft.com/en-us/previous-versions/ms537113(v%3Dvs.85) */ /* The equation for EXP mode is exp(-density * z), so just negate density here */ glUniform1f(s->locations[4], -gfx_fogDensity); s->uniforms &= ~UNI_FOG_DENS; } } /* Switches program to one that duplicates current fixed function state */ /* Compiles program and reloads uniforms if needed */ static void SwitchProgram(void) { struct GLShader* shader; int index = 0; if (gfx_fogEnabled) { index += 6; /* linear fog */ if (gfx_fogMode >= 1) index += 6; /* exp fog */ } if (gfx_format == VERTEX_FORMAT_TEXTURED) index += 2; if (gfx_texTransform) index += 2; if (gfx_alphaTest) index += 1; shader = &shaders[index]; if (shader == gfx_activeShader) { ReloadUniforms(); return; } if (!shader->program) CompileProgram(shader); gfx_activeShader = shader; glUseProgram(shader->program); ReloadUniforms(); } void Gfx_SetFog(cc_bool enabled) { gfx_fogEnabled = enabled; SwitchProgram(); } void Gfx_SetFogCol(PackedCol col) { if (col == gfx_fogColor) return; gfx_fogColor = col; DirtyUniform(UNI_FOG_COL); ReloadUniforms(); } void Gfx_SetFogDensity(float value) { if (gfx_fogDensity == value) return; gfx_fogDensity = value; DirtyUniform(UNI_FOG_DENS); ReloadUniforms(); } void Gfx_SetFogEnd(float value) { if (gfx_fogEnd == value) return; gfx_fogEnd = value; DirtyUniform(UNI_FOG_END); ReloadUniforms(); } void Gfx_SetFogMode(FogFunc func) { if (gfx_fogMode == func) return; gfx_fogMode = func; SwitchProgram(); } void Gfx_SetTexturing(cc_bool enabled) { } void Gfx_SetAlphaTest(cc_bool enabled) { gfx_alphaTest = enabled; SwitchProgram(); } void Gfx_LoadMatrix(MatrixType type, const struct Matrix* matrix) { if (type == MATRIX_VIEW) _view = *matrix; if (type == MATRIX_PROJECTION) _proj = *matrix; Matrix_Mul(&_mvp, &_view, &_proj); DirtyUniform(UNI_MVP_MATRIX); ReloadUniforms(); } void Gfx_LoadIdentityMatrix(MatrixType type) { Gfx_LoadMatrix(type, &Matrix_Identity); } void Gfx_EnableTextureOffset(float x, float y) { _texX = x; _texY = y; gfx_texTransform = true; DirtyUniform(UNI_TEX_OFFSET); SwitchProgram(); } void Gfx_DisableTextureOffset(void) { gfx_texTransform = false; SwitchProgram(); } static void GL_CheckSupport(void) { #ifndef CC_BUILD_GLES customMipmapsLevels = true; #endif } static void Gfx_FreeState(void) { int i; FreeDefaultResources(); gfx_activeShader = NULL; for (i = 0; i < Array_Elems(shaders); i++) { glDeleteProgram(shaders[i].program); shaders[i].program = 0; } } static void Gfx_RestoreState(void) { InitDefaultResources(); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); gfx_format = -1; DirtyUniform(UNI_MASK_ALL); GL_ClearCol(gfx_clearColor); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthFunc(GL_LEQUAL); } cc_bool Gfx_WarnIfNecessary(void) { return false; } static void GL_SetupVbColoured(void) { glVertexAttribPointer(0, 3, GL_FLOAT, false, SIZEOF_VERTEX_COLOURED, (void*)0); glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, SIZEOF_VERTEX_COLOURED, (void*)12); } static void GL_SetupVbTextured(void) { glVertexAttribPointer(0, 3, GL_FLOAT, false, SIZEOF_VERTEX_TEXTURED, (void*)0); glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, SIZEOF_VERTEX_TEXTURED, (void*)12); glVertexAttribPointer(2, 2, GL_FLOAT, false, SIZEOF_VERTEX_TEXTURED, (void*)16); } static void GL_SetupVbColoured_Range(int startVertex) { cc_uint32 offset = startVertex * SIZEOF_VERTEX_COLOURED; glVertexAttribPointer(0, 3, GL_FLOAT, false, SIZEOF_VERTEX_COLOURED, (void*)(offset)); glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, SIZEOF_VERTEX_COLOURED, (void*)(offset + 12)); } static void GL_SetupVbTextured_Range(int startVertex) { cc_uint32 offset = startVertex * SIZEOF_VERTEX_TEXTURED; glVertexAttribPointer(0, 3, GL_FLOAT, false, SIZEOF_VERTEX_TEXTURED, (void*)(offset)); glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, SIZEOF_VERTEX_TEXTURED, (void*)(offset + 12)); glVertexAttribPointer(2, 2, GL_FLOAT, false, SIZEOF_VERTEX_TEXTURED, (void*)(offset + 16)); } void Gfx_SetVertexFormat(VertexFormat fmt) { if (fmt == gfx_format) return; gfx_format = fmt; gfx_stride = strideSizes[fmt]; if (fmt == VERTEX_FORMAT_TEXTURED) { glEnableVertexAttribArray(2); gfx_setupVBFunc = GL_SetupVbTextured; gfx_setupVBRangeFunc = GL_SetupVbTextured_Range; } else { glDisableVertexAttribArray(2); gfx_setupVBFunc = GL_SetupVbColoured; gfx_setupVBRangeFunc = GL_SetupVbColoured_Range; } SwitchProgram(); } void Gfx_DrawVb_Lines(int verticesCount) { gfx_setupVBFunc(); glDrawArrays(GL_LINES, 0, verticesCount); } void Gfx_DrawVb_IndexedTris_Range(int verticesCount, int startVertex) { gfx_setupVBRangeFunc(startVertex); glDrawElements(GL_TRIANGLES, ICOUNT(verticesCount), GL_UNSIGNED_SHORT, NULL); } void Gfx_DrawVb_IndexedTris(int verticesCount) { gfx_setupVBFunc(); glDrawElements(GL_TRIANGLES, ICOUNT(verticesCount), GL_UNSIGNED_SHORT, NULL); } void Gfx_BindVb_Textured(GfxResourceID vb) { Gfx_BindVb(vb); GL_SetupVbTextured(); } void Gfx_DrawIndexedTris_T2fC4b(int verticesCount, int startVertex) { if (startVertex + verticesCount > GFX_MAX_VERTICES) { GL_SetupVbTextured_Range(startVertex); glDrawElements(GL_TRIANGLES, ICOUNT(verticesCount), GL_UNSIGNED_SHORT, NULL); GL_SetupVbTextured(); } else { /* ICOUNT(startVertex) * 2 = startVertex * 3 */ glDrawElements(GL_TRIANGLES, ICOUNT(verticesCount), GL_UNSIGNED_SHORT, (void*)(startVertex * 3)); } } #endif /*########################################################################################################################* *------------------------------------------------------OpenGL legacy------------------------------------------------------* *#########################################################################################################################*/ #ifndef CC_BUILD_GLMODERN void Gfx_SetFog(cc_bool enabled) { gfx_fogEnabled = enabled; gl_Toggle(GL_FOG); } void Gfx_SetFogCol(PackedCol col) { float rgba[4]; if (col == gfx_fogColor) return; rgba[0] = PackedCol_R(col) / 255.0f; rgba[1] = PackedCol_G(col) / 255.0f; rgba[2] = PackedCol_B(col) / 255.0f; rgba[3] = PackedCol_A(col) / 255.0f; glFogfv(GL_FOG_COLOR, rgba); gfx_fogColor = col; } void Gfx_SetFogDensity(float value) { if (value == gfx_fogDensity) return; glFogf(GL_FOG_DENSITY, value); gfx_fogDensity = value; } void Gfx_SetFogEnd(float value) { if (value == gfx_fogEnd) return; glFogf(GL_FOG_END, value); gfx_fogEnd = value; } void Gfx_SetFogMode(FogFunc func) { static GLint modes[3] = { GL_LINEAR, GL_EXP, GL_EXP2 }; if (func == gfx_fogMode) return; #ifdef CC_BUILD_GLES /* OpenGL ES doesn't support glFogi, so use glFogf instead */ /* https://www.khronos.org/registry/OpenGL-Refpages/es1.1/xhtml/ */ glFogf(GL_FOG_MODE, modes[func]); #else glFogi(GL_FOG_MODE, modes[func]); #endif gfx_fogMode = func; } void Gfx_SetTexturing(cc_bool enabled) { gl_Toggle(GL_TEXTURE_2D); } void Gfx_SetAlphaTest(cc_bool enabled) { gl_Toggle(GL_ALPHA_TEST); } static GLenum matrix_modes[3] = { GL_PROJECTION, GL_MODELVIEW, GL_TEXTURE }; static int lastMatrix; void Gfx_LoadMatrix(MatrixType type, const struct Matrix* matrix) { if (type != lastMatrix) { lastMatrix = type; glMatrixMode(matrix_modes[type]); } glLoadMatrixf((const float*)matrix); } void Gfx_LoadIdentityMatrix(MatrixType type) { if (type != lastMatrix) { lastMatrix = type; glMatrixMode(matrix_modes[type]); } glLoadIdentity(); } static struct Matrix texMatrix = Matrix_IdentityValue; void Gfx_EnableTextureOffset(float x, float y) { texMatrix.row4.X = x; texMatrix.row4.Y = y; Gfx_LoadMatrix(2, &texMatrix); } void Gfx_DisableTextureOffset(void) { Gfx_LoadIdentityMatrix(2); } static void Gfx_FreeState(void) { FreeDefaultResources(); } static void Gfx_RestoreState(void) { InitDefaultResources(); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); gfx_format = -1; glHint(GL_FOG_HINT, GL_NICEST); glAlphaFunc(GL_GREATER, 0.5f); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthFunc(GL_LEQUAL); } cc_bool Gfx_WarnIfNecessary(void) { cc_string renderer = String_FromReadonly((const char*)glGetString(GL_RENDERER)); #ifdef CC_BUILD_GL11 Chat_AddRaw("&cYou are using the very outdated OpenGL backend."); Chat_AddRaw("&cAs such you may experience poor performance."); Chat_AddRaw("&cIt is likely you need to install video card drivers."); #endif if (!String_ContainsConst(&renderer, "Intel")) return false; Chat_AddRaw("&cIntel graphics cards are known to have issues with the OpenGL build."); Chat_AddRaw("&cVSync may not work, and you may see disappearing clouds and map edges."); #ifdef CC_BUILD_WIN Chat_AddRaw("&cTry downloading the Direct3D 9 build instead."); #endif return true; } /*########################################################################################################################* *-------------------------------------------------------Compatibility-----------------------------------------------------* *#########################################################################################################################*/ #ifdef CC_BUILD_GL11 static void GL_CheckSupport(void) { MakeIndices(gl_indices, GFX_MAX_INDICES); } #else /* fake vertex buffer objects with client side pointers */ typedef struct fake_buffer { cc_uint8* data; } fake_buffer; static fake_buffer* cur_ib; static fake_buffer* cur_vb; #define fake_GetBuffer(target) (target == _GL_ELEMENT_ARRAY_BUFFER ? &cur_ib : &cur_vb); static void APIENTRY fake_glBindBuffer(GLenum target, GLuint src) { fake_buffer** buffer = fake_GetBuffer(target); *buffer = (fake_buffer*)src; } static void APIENTRY fake_glDeleteBuffers(GLsizei n, const GLuint *buffers) { Mem_Free((void*)buffers[0]); } static void APIENTRY fake_glGenBuffers(GLsizei n, GLuint *buffers) { fake_buffer* buffer = (fake_buffer*)Mem_TryAlloc(1, sizeof(fake_buffer)); buffer->data = NULL; buffers[0] = (GLuint)buffer; } static void APIENTRY fake_glBufferData(GLenum target, cc_uintptr size, const GLvoid* data, GLenum usage) { fake_buffer* buffer = *fake_GetBuffer(target); Mem_Free(buffer->data); buffer->data = Mem_TryAlloc(size, 1); if (data) Mem_Copy(buffer->data, data, size); } static void APIENTRY fake_glBufferSubData(GLenum target, cc_uintptr offset, cc_uintptr size, const GLvoid* data) { fake_buffer* buffer = *fake_GetBuffer(target); Mem_Copy(buffer->data, data, size); } static void GL_CheckSupport(void) { static const struct DynamicLibSym coreVboFuncs[5] = { DynamicLib_Sym2("glBindBuffer", glBindBuffer), DynamicLib_Sym2("glDeleteBuffers", glDeleteBuffers), DynamicLib_Sym2("glGenBuffers", glGenBuffers), DynamicLib_Sym2("glBufferData", glBufferData), DynamicLib_Sym2("glBufferSubData", glBufferSubData) }; static const struct DynamicLibSym arbVboFuncs[5] = { DynamicLib_Sym2("glBindBufferARB", glBindBuffer), DynamicLib_Sym2("glDeleteBuffersARB", glDeleteBuffers), DynamicLib_Sym2("glGenBuffersARB", glGenBuffers), DynamicLib_Sym2("glBufferDataARB", glBufferData), DynamicLib_Sym2("glBufferSubDataARB", glBufferSubData) }; static const cc_string vboExt = String_FromConst("GL_ARB_vertex_buffer_object"); cc_string extensions = String_FromReadonly((const char*)glGetString(GL_EXTENSIONS)); const GLubyte* ver = glGetString(GL_VERSION); /* Version string is always: x.y. (and whatever afterwards) */ int major = ver[0] - '0', minor = ver[2] - '0'; /* Supported in core since 1.5 */ if (major > 1 || (major == 1 && minor >= 5)) { GLContext_GetAll(coreVboFuncs, Array_Elems(coreVboFuncs)); } else if (String_CaselessContains(&extensions, &vboExt)) { GLContext_GetAll(arbVboFuncs, Array_Elems(arbVboFuncs)); } else { Logger_Abort("Only OpenGL 1.1 supported.\n\n" \ "Compile the game with CC_BUILD_GL11, or ask on the ClassiCube forums for it"); _glBindBuffer = fake_glBindBuffer; _glDeleteBuffers = fake_glDeleteBuffers; _glGenBuffers = fake_glGenBuffers; _glBufferData = fake_glBufferData; _glBufferSubData = fake_glBufferSubData; } customMipmapsLevels = true; } #endif /*########################################################################################################################* *----------------------------------------------------------Drawing--------------------------------------------------------* *#########################################################################################################################*/ #ifdef CC_BUILD_GL11 /* point to client side dynamic array */ #define VB_PTR ((cc_uint8*)dynamicListData) #define IB_PTR gl_indices #else /* no client side array, use vertex buffer object */ #define VB_PTR 0 #define IB_PTR NULL #endif static void GL_SetupVbColoured(void) { glVertexPointer(3, GL_FLOAT, SIZEOF_VERTEX_COLOURED, (void*)(VB_PTR + 0)); glColorPointer(4, GL_UNSIGNED_BYTE, SIZEOF_VERTEX_COLOURED, (void*)(VB_PTR + 12)); } static void GL_SetupVbTextured(void) { glVertexPointer(3, GL_FLOAT, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + 0)); glColorPointer(4, GL_UNSIGNED_BYTE, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + 12)); glTexCoordPointer(2, GL_FLOAT, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + 16)); } static void GL_SetupVbColoured_Range(int startVertex) { cc_uint32 offset = startVertex * SIZEOF_VERTEX_COLOURED; glVertexPointer(3, GL_FLOAT, SIZEOF_VERTEX_COLOURED, (void*)(VB_PTR + offset)); glColorPointer(4, GL_UNSIGNED_BYTE, SIZEOF_VERTEX_COLOURED, (void*)(VB_PTR + offset + 12)); } static void GL_SetupVbTextured_Range(int startVertex) { cc_uint32 offset = startVertex * SIZEOF_VERTEX_TEXTURED; glVertexPointer(3, GL_FLOAT, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + offset)); glColorPointer(4, GL_UNSIGNED_BYTE, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + offset + 12)); glTexCoordPointer(2, GL_FLOAT, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + offset + 16)); } void Gfx_SetVertexFormat(VertexFormat fmt) { if (fmt == gfx_format) return; gfx_format = fmt; gfx_stride = strideSizes[fmt]; if (fmt == VERTEX_FORMAT_TEXTURED) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); gfx_setupVBFunc = GL_SetupVbTextured; gfx_setupVBRangeFunc = GL_SetupVbTextured_Range; } else { glDisableClientState(GL_TEXTURE_COORD_ARRAY); gfx_setupVBFunc = GL_SetupVbColoured; gfx_setupVBRangeFunc = GL_SetupVbColoured_Range; } } void Gfx_DrawVb_Lines(int verticesCount) { gfx_setupVBFunc(); glDrawArrays(GL_LINES, 0, verticesCount); } void Gfx_DrawVb_IndexedTris_Range(int verticesCount, int startVertex) { #ifdef CC_BUILD_GL11 if (activeList != gl_DYNAMICLISTID) { glCallList(activeList); return; } #endif gfx_setupVBRangeFunc(startVertex); glDrawElements(GL_TRIANGLES, ICOUNT(verticesCount), GL_UNSIGNED_SHORT, IB_PTR); } void Gfx_DrawVb_IndexedTris(int verticesCount) { #ifdef CC_BUILD_GL11 if (activeList != gl_DYNAMICLISTID) { glCallList(activeList); return; } #endif gfx_setupVBFunc(); glDrawElements(GL_TRIANGLES, ICOUNT(verticesCount), GL_UNSIGNED_SHORT, IB_PTR); } #ifdef CC_BUILD_GL11 void Gfx_DrawIndexedTris_T2fC4b(int verticesCount, int startVertex) { glCallList(activeList); } #else void Gfx_DrawIndexedTris_T2fC4b(int verticesCount, int startVertex) { cc_uint32 offset = startVertex * SIZEOF_VERTEX_TEXTURED; glVertexPointer(3, GL_FLOAT, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + offset)); glColorPointer(4, GL_UNSIGNED_BYTE, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + offset + 12)); glTexCoordPointer(2, GL_FLOAT, SIZEOF_VERTEX_TEXTURED, (void*)(VB_PTR + offset + 16)); glDrawElements(GL_TRIANGLES, ICOUNT(verticesCount), GL_UNSIGNED_SHORT, IB_PTR); } #endif /* !CC_BUILD_GL11 */ #endif /* !CC_BUILD_GLMODERN */ #endif
17,900
716
<gh_stars>100-1000 /* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <errno.h> #include <stdint.h> #include <stdio.h> #include <sys/ptrace.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "PidUtils.h" namespace unwindstack { static bool Exited(pid_t pid) { int status; pid_t wait_pid = waitpid(pid, &status, WNOHANG); if (wait_pid != pid) { return false; } if (WIFEXITED(status)) { fprintf(stderr, "%d died: Process exited with code %d\n", pid, WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { fprintf(stderr, "%d died: Process exited due to signal %d\n", pid, WTERMSIG(status)); } else { fprintf(stderr, "%d died: Process finished for unknown reason\n", pid); } return true; } bool Quiesce(pid_t pid) { siginfo_t si; // Wait for up to 10 seconds. for (time_t start_time = time(nullptr); time(nullptr) - start_time < 10;) { if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) { return true; } if (errno != ESRCH) { if (errno == EINVAL) { // The process is in group-stop state, so try and kick the // process out of that state. if (ptrace(PTRACE_LISTEN, pid, 0, 0) == -1) { // Cannot recover from this, so just pretend it worked and see // if we can unwind. return true; } } else { perror("ptrace getsiginfo failed"); return false; } } usleep(5000); } fprintf(stderr, "Did not quiesce in 10 seconds\n"); return false; } bool Attach(pid_t pid) { // Wait up to 45 seconds to attach. for (time_t start_time = time(nullptr); time(nullptr) - start_time < 45;) { if (ptrace(PTRACE_ATTACH, pid, 0, 0) == 0) { break; } if (errno != ESRCH) { perror("Failed to attach"); return false; } usleep(5000); } if (Quiesce(pid)) { return true; } if (ptrace(PTRACE_DETACH, pid, 0, 0) == -1) { perror("Failed to detach"); } return false; } bool Detach(pid_t pid) { if (ptrace(PTRACE_DETACH, pid, 0, 0) == -1) { perror("ptrace detach failed"); return false; } return true; } bool RunWhenQuiesced(pid_t pid, bool leave_attached, std::function<PidRunEnum()> fn) { // Wait up to 120 seconds to run the fn. PidRunEnum status = PID_RUN_KEEP_GOING; for (time_t start_time = time(nullptr); time(nullptr) - start_time < 120 && status == PID_RUN_KEEP_GOING;) { if (Attach(pid)) { status = fn(); if (status == PID_RUN_PASS && leave_attached) { return true; } if (!Detach(pid)) { return false; } } else if (Exited(pid)) { return false; } usleep(5000); } if (status == PID_RUN_KEEP_GOING) { fprintf(stderr, "Timed out waiting for pid %d to be ready\n", pid); } return status == PID_RUN_PASS; } } // namespace unwindstack
1,421
2,201
""" Copyright (c) 2018-2022 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from collections import OrderedDict import warnings from ..utils import read_json, read_txt, check_file_existence from ..representation import ClassificationAnnotation from ..data_readers import ClipIdentifier from ..config import PathField, NumberField, StringField, BoolField, ConfigError from .format_converter import BaseFormatConverter, ConverterReturn, verify_label_map class ActionRecognitionConverter(BaseFormatConverter): __provider__ = 'clip_action_recognition' annotation_types = (ClassificationAnnotation, ) @classmethod def parameters(cls): params = super().parameters() params.update({ 'annotation_file': PathField(description="Path to annotation file."), 'data_dir': PathField(is_directory=True, description="Path to data directory."), 'clips_per_video': NumberField( value_type=int, optional=True, min_value=0, default=3, description="Number of clips per video." ), 'clip_duration': NumberField( value_type=int, optional=True, min_value=0, default=16, description="Clip duration." ), 'temporal_stride': NumberField( value_type=int, optional=True, min_value=0, default=2, description="Temporal Stride." ), 'subset': StringField( choices=['train', 'test', 'validation'], default='validation', optional=True, description="Subset: train, test or validation." ), 'dataset_meta_file': PathField( description='path to json file with dataset meta (e.g. label_map)', optional=True ), 'numpy_input': BoolField(description='use numpy arrays as input', optional=True, default=False), 'two_stream_input': BoolField(description='use two streams: images and numpy arrays as input', optional=True, default=False), 'image_subpath': StringField(description="sub-directory for images", optional=True), 'numpy_subpath': StringField(description="sub-directory for numpy arrays", optional=True), 'num_samples': NumberField( description='number of samples used for annotation', optional=True, value_type=int, min_value=1 ) }) return params def configure(self): self.annotation_file = self.get_value_from_config('annotation_file') self.data_dir = self.get_value_from_config('data_dir') self.clips_per_video = self.get_value_from_config('clips_per_video') self.clip_duration = self.get_value_from_config('clip_duration') self.temporal_stride = self.get_value_from_config('temporal_stride') self.subset = self.get_value_from_config('subset') self.dataset_meta = self.get_value_from_config('dataset_meta_file') self.numpy_input = self.get_value_from_config('numpy_input') self.two_stream_input = self.get_value_from_config('two_stream_input') self.numpy_subdir = self.get_value_from_config('numpy_subpath') self.image_subdir = self.get_value_from_config('image_subpath') self.num_samples = self.get_value_from_config('num_samples') if self.numpy_subdir and (self.numpy_input or self.two_stream_input) and not (self.data_dir / self.numpy_subdir).exists(): raise ConfigError('Please check numpy_subpath or data_dir. ' 'Path {} does not exist'.format(self.data_dir / self.numpy_subdir)) if self.image_subdir and (not self.numpy_input or self.two_stream_input) and not (self.data_dir / self.image_subdir).exists(): raise ConfigError('Please check image_subpath or data_dir. ' 'Path {} does not exist'.format(self.data_dir / self.image_subdir)) if self.two_stream_input: if not self.numpy_subdir: raise ConfigError('numpy_subpath should be provided in case of using two streams') if not self.image_subdir: raise ConfigError('image_subpath should be provided in case of using two streams') else: if self.numpy_input and self.numpy_subdir: warnings.warn("numpy_subpath is provided. " "Make sure that data_source is {}".format(self.data_dir / self.numpy_subdir)) if not self.numpy_input and self.image_subdir: warnings.warn("image_subpath is provided. " "Make sure that data_source is {}".format(self.data_dir / self.image_subdir)) def get_meta(self): if self.dataset_meta: dataset_meta = read_json(self.dataset_meta) if 'label_map' in dataset_meta: label_map = dataset_meta['label_map'] label_map = verify_label_map(label_map) return {'label_map': label_map} if 'labels' in dataset_meta: label_map = dict(enumerate(dataset_meta['labels'])) return {'label_map': label_map} full_annotation = read_json(self.annotation_file, object_pairs_hook=OrderedDict) label_map = dict(enumerate(full_annotation['labels'])) return {'label_map': label_map} def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs): full_annotation = read_json(self.annotation_file, object_pairs_hook=OrderedDict) meta = self.get_meta() label_map = meta['label_map'] data_ext, data_dir = self.get_ext_and_dir() video_names, annotations = self.get_video_names_and_annotations(full_annotation['database'], self.subset) class_to_idx = {v: k for k, v in label_map.items()} videos = self.get_videos(video_names, annotations, class_to_idx, data_dir, data_ext) videos = sorted(videos, key=lambda v: v['video_id'].split('/')[-1]) clips = [] for video in videos: clips.extend(self.get_clips(video, self.clips_per_video, self.clip_duration, self.temporal_stride, data_ext)) annotations = [] num_iterations = len(clips) content_errors = None if not check_content else [] for clip_idx, clip in enumerate(clips): if progress_callback is not None and clip_idx % progress_interval: progress_callback(clip_idx * 100 / num_iterations) identifier = [] for ext in data_ext: identifier.append(ClipIdentifier(clip['video_name'], clip_idx, clip['frames_{}'.format(ext)])) if check_content: for ext, dir_ in zip(data_ext, data_dir): content_errors.extend([ '{}: does not exist'.format(dir_ / frame) for frame in clip['frames_{}'.format(ext)] if not check_file_existence(dir_ / frame) ]) if len(identifier) == 1: identifier = identifier[0] annotations.append(ClassificationAnnotation(identifier, clip['label'])) return ConverterReturn(annotations, meta, content_errors) def get_ext_and_dir(self): if self.two_stream_input: return ['jpg', 'npy'], [self.data_dir / self.image_subdir, self.data_dir / self.numpy_subdir] if self.numpy_input: return ['npy'], [self.data_dir / self.numpy_subdir if self.numpy_subdir else self.data_dir] return ['jpg'], [self.data_dir / self.image_subdir if self.image_subdir else self.data_dir] def get_videos(self, video_names, annotations, class_to_idx, data_dir, data_ext): videos = [] for video_name, annotation in zip(video_names, annotations): video_info = { 'video_name': video_name, 'video_id': video_name, 'label': class_to_idx[annotation['label']] } for dir_, ext in zip(data_dir, data_ext): video_path = dir_ / video_name if not video_path.exists(): video_info.clear() continue n_frames_file = video_path / 'n_frames' n_frames = ( int(read_txt(n_frames_file)[0].rstrip('\n\r')) if n_frames_file.exists() else len(list(video_path.glob('*.{}'.format(ext)))) ) if n_frames <= 0: video_info.clear() continue begin_t = 1 end_t = n_frames sample = { 'video_{}'.format(ext): video_path, 'segment_{}'.format(ext): [begin_t, end_t], 'n_frames_{}'.format(ext): n_frames, } video_info.update(sample) if video_info: videos.append(video_info) if self.num_samples and len(videos) == self.num_samples: break return videos @staticmethod def get_clips(video, clips_per_video, clip_duration, temporal_stride=1, file_ext='jpg'): clip_duration *= temporal_stride frames_ext = {} for ext in file_ext: frames = [] shift = int(ext == 'npy') num_frames = video['n_frames_{}'.format(ext)] - shift if clips_per_video == 0: step = clip_duration else: step = max(1, (num_frames - clip_duration) // (clips_per_video - 1)) for clip_start in range(1, 1 + clips_per_video * step, step): clip_end = min(clip_start + clip_duration, num_frames + 1) clip_idxs = list(range(clip_start, clip_end)) if not clip_idxs: return [] # loop clip if it is shorter than clip_duration while len(clip_idxs) < clip_duration: clip_idxs = (clip_idxs * 2)[:clip_duration] frames_idx = clip_idxs[::temporal_stride] frames.append(['image_{:05d}.{}'.format(frame_idx, ext) for frame_idx in frames_idx]) frames_ext.update({ ext: frames }) clips = [] for key, value in frames_ext.items(): if not clips: for _ in range(len(value)): clips.append(dict(video)) for val, clip in zip(value, clips): clip['frames_{}'.format(key)] = val return clips @staticmethod def get_video_names_and_annotations(data, subset): video_names = [] annotations = [] for key, value in data.items(): this_subset = value['subset'] if this_subset == subset: if subset == 'testing': video_names.append('test/{}'.format(key)) else: label = value['annotations']['label'] video_names.append('{}/{}'.format(label, key)) annotations.append(value['annotations']) return video_names, annotations
5,488
1,947
<filename>Samples/cuSolverSp_LinearSolver/cuSolverSp_LinearSolver.cpp /* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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. */ /* * Test three linear solvers, including Cholesky, LU and QR. * The user has to prepare a sparse matrix of "matrix market format" (with extension .mtx). * For example, the user can download matrices in Florida Sparse Matrix Collection. * (http://www.cise.ufl.edu/research/sparse/matrices/) * * The user needs to choose a solver by the switch -R<solver> and * to provide the path of the matrix by the switch -F<file>, then * the program solves * A*x = b * and reports relative error * |b-A*x|/(|A|*|x|+|b|) * * How does it work? * The example solves A*x = b by the following steps * step 1: B = A(Q,Q) * Q is the ordering to minimize zero fill-in. * The user can choose symrcm or symamd. * step 2: solve B*z = Q*b * step 3: x = inv(Q)*z * * Above three steps can be combined by the formula * (Q*A*Q')*(Q*x) = (Q*b) * * The elapsed time is also reported so the user can compare efficiency of different solvers. * * How to use /cuSolverSp_LinearSolver // Default: Cholesky, symrcm & file=lap2D_5pt_n100.mtx * ./cuSolverSp_LinearSolver -R=chol -file=<file> // cholesky factorization * ./cuSolverSp_LinearSolver -R=lu -P=symrcm -file=<file> // symrcm + LU with partial pivoting * ./cuSolverSp_LinearSolver -R=qr -P=symamd -file=<file> // symamd + QR factorization * * * Remark: the absolute error on solution x is meaningless without knowing condition number of A. * The relative error on residual should be close to machine zero, i.e. 1.e-15. */ #include <assert.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cuda_runtime.h> #include "cusolverSp.h" #include "cusparse.h" #include "helper_cuda.h" #include "helper_cusolver.h" template <typename T_ELEM> int loadMMSparseMatrix(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, T_ELEM **aVal, int **aRowInd, int **aColInd, int extendSymMatrix); void UsageSP(void) { printf("<options>\n"); printf("-h : display this help\n"); printf("-R=<name> : choose a linear solver\n"); printf(" chol (cholesky factorization), this is default\n"); printf(" qr (QR factorization)\n"); printf(" lu (LU factorization)\n"); printf("-P=<name> : choose a reordering\n"); printf(" symrcm (Reverse Cuthill-McKee)\n"); printf(" symamd (Approximate Minimum Degree)\n"); printf(" metis (nested dissection)\n"); printf("-file=<filename> : filename containing a matrix in MM format\n"); printf("-device=<device_id> : <device_id> if want to run on specific GPU\n"); exit(0); } void parseCommandLineArguments(int argc, char *argv[], struct testOpts &opts) { memset(&opts, 0, sizeof(opts)); if (checkCmdLineFlag(argc, (const char **)argv, "-h")) { UsageSP(); } if (checkCmdLineFlag(argc, (const char **)argv, "R")) { char *solverType = NULL; getCmdLineArgumentString(argc, (const char **)argv, "R", &solverType); if (solverType) { if ((STRCASECMP(solverType, "chol") != 0) && (STRCASECMP(solverType, "lu") != 0) && (STRCASECMP(solverType, "qr") != 0)) { printf("\nIncorrect argument passed to -R option\n"); UsageSP(); } else { opts.testFunc = solverType; } } } if (checkCmdLineFlag(argc, (const char **)argv, "P")) { char *reorderType = NULL; getCmdLineArgumentString(argc, (const char **)argv, "P", &reorderType); if (reorderType) { if ((STRCASECMP(reorderType, "symrcm") != 0) && (STRCASECMP(reorderType, "symamd") != 0) && (STRCASECMP(reorderType, "metis") != 0)) { printf("\nIncorrect argument passed to -P option\n"); UsageSP(); } else { opts.reorder = reorderType; } } } if (checkCmdLineFlag(argc, (const char **)argv, "file")) { char *fileName = 0; getCmdLineArgumentString(argc, (const char **)argv, "file", &fileName); if (fileName) { opts.sparse_mat_filename = fileName; } else { printf("\nIncorrect filename passed to -file \n "); UsageSP(); } } } int main(int argc, char *argv[]) { struct testOpts opts; cusolverSpHandle_t handle = NULL; cusparseHandle_t cusparseHandle = NULL; /* used in residual evaluation */ cudaStream_t stream = NULL; cusparseMatDescr_t descrA = NULL; int rowsA = 0; /* number of rows of A */ int colsA = 0; /* number of columns of A */ int nnzA = 0; /* number of nonzeros of A */ int baseA = 0; /* base index in CSR format */ /* CSR(A) from I/O */ int *h_csrRowPtrA = NULL; int *h_csrColIndA = NULL; double *h_csrValA = NULL; double *h_z = NULL; /* z = B \ (Q*b) */ double *h_x = NULL; /* x = A \ b */ double *h_b = NULL; /* b = ones(n,1) */ double *h_Qb = NULL; /* Q*b */ double *h_r = NULL; /* r = b - A*x */ int *h_Q = NULL; /* <int> n */ /* reorder to reduce zero fill-in */ /* Q = symrcm(A) or Q = symamd(A) */ /* B = Q*A*Q' or B = A(Q,Q) by MATLAB notation */ int *h_csrRowPtrB = NULL; /* <int> n+1 */ int *h_csrColIndB = NULL; /* <int> nnzA */ double *h_csrValB = NULL; /* <double> nnzA */ int *h_mapBfromA = NULL; /* <int> nnzA */ size_t size_perm = 0; void *buffer_cpu = NULL; /* working space for permutation: B = Q*A*Q^T */ /* device copy of A: used in residual evaluation */ int *d_csrRowPtrA = NULL; int *d_csrColIndA = NULL; double *d_csrValA = NULL; /* device copy of B: used in B*z = Q*b */ int *d_csrRowPtrB = NULL; int *d_csrColIndB = NULL; double *d_csrValB = NULL; int *d_Q = NULL; /* device copy of h_Q */ double *d_z = NULL; /* z = B \ Q*b */ double *d_x = NULL; /* x = A \ b */ double *d_b = NULL; /* a copy of h_b */ double *d_Qb = NULL; /* a copy of h_Qb */ double *d_r = NULL; /* r = b - A*x */ double tol = 1.e-12; const int reorder = 0; /* no reordering */ int singularity = 0; /* -1 if A is invertible under tol. */ /* the constants are used in residual evaluation, r = b - A*x */ const double minus_one = -1.0; const double one = 1.0; double b_inf = 0.0; double x_inf = 0.0; double r_inf = 0.0; double A_inf = 0.0; int errors = 0; int issym = 0; double start, stop; double time_solve_cpu; double time_solve_gpu; parseCommandLineArguments(argc, argv, opts); if (NULL == opts.testFunc) { opts.testFunc = "chol"; /* By default running Cholesky as NO solver selected with -R option. */ } findCudaDevice(argc, (const char **)argv); if (opts.sparse_mat_filename == NULL) { opts.sparse_mat_filename = sdkFindFilePath("lap2D_5pt_n100.mtx", argv[0]); if (opts.sparse_mat_filename != NULL) printf("Using default input file [%s]\n", opts.sparse_mat_filename); else printf("Could not find lap2D_5pt_n100.mtx\n"); } else { printf("Using input file [%s]\n", opts.sparse_mat_filename); } printf("step 1: read matrix market format\n"); if (opts.sparse_mat_filename == NULL) { fprintf(stderr, "Error: input matrix is not provided\n"); return EXIT_FAILURE; } if (loadMMSparseMatrix<double>(opts.sparse_mat_filename, 'd', true, &rowsA, &colsA, &nnzA, &h_csrValA, &h_csrRowPtrA, &h_csrColIndA, true)) { exit(EXIT_FAILURE); } baseA = h_csrRowPtrA[0]; // baseA = {0,1} printf("sparse matrix A is %d x %d with %d nonzeros, base=%d\n", rowsA, colsA, nnzA, baseA); if (rowsA != colsA) { fprintf(stderr, "Error: only support square matrix\n"); return 1; } checkCudaErrors(cusolverSpCreate(&handle)); checkCudaErrors(cusparseCreate(&cusparseHandle)); checkCudaErrors(cudaStreamCreate(&stream)); /* bind stream to cusparse and cusolver*/ checkCudaErrors(cusolverSpSetStream(handle, stream)); checkCudaErrors(cusparseSetStream(cusparseHandle, stream)); /* configure matrix descriptor*/ checkCudaErrors(cusparseCreateMatDescr(&descrA)); checkCudaErrors(cusparseSetMatType(descrA, CUSPARSE_MATRIX_TYPE_GENERAL)); if (baseA) { checkCudaErrors(cusparseSetMatIndexBase(descrA, CUSPARSE_INDEX_BASE_ONE)); } else { checkCudaErrors(cusparseSetMatIndexBase(descrA, CUSPARSE_INDEX_BASE_ZERO)); } h_z = (double *)malloc(sizeof(double) * colsA); h_x = (double *)malloc(sizeof(double) * colsA); h_b = (double *)malloc(sizeof(double) * rowsA); h_Qb = (double *)malloc(sizeof(double) * rowsA); h_r = (double *)malloc(sizeof(double) * rowsA); h_Q = (int *)malloc(sizeof(int) * colsA); h_csrRowPtrB = (int *)malloc(sizeof(int) * (rowsA + 1)); h_csrColIndB = (int *)malloc(sizeof(int) * nnzA); h_csrValB = (double *)malloc(sizeof(double) * nnzA); h_mapBfromA = (int *)malloc(sizeof(int) * nnzA); assert(NULL != h_z); assert(NULL != h_x); assert(NULL != h_b); assert(NULL != h_Qb); assert(NULL != h_r); assert(NULL != h_Q); assert(NULL != h_csrRowPtrB); assert(NULL != h_csrColIndB); assert(NULL != h_csrValB); assert(NULL != h_mapBfromA); checkCudaErrors( cudaMalloc((void **)&d_csrRowPtrA, sizeof(int) * (rowsA + 1))); checkCudaErrors(cudaMalloc((void **)&d_csrColIndA, sizeof(int) * nnzA)); checkCudaErrors(cudaMalloc((void **)&d_csrValA, sizeof(double) * nnzA)); checkCudaErrors( cudaMalloc((void **)&d_csrRowPtrB, sizeof(int) * (rowsA + 1))); checkCudaErrors(cudaMalloc((void **)&d_csrColIndB, sizeof(int) * nnzA)); checkCudaErrors(cudaMalloc((void **)&d_csrValB, sizeof(double) * nnzA)); checkCudaErrors(cudaMalloc((void **)&d_Q, sizeof(int) * colsA)); checkCudaErrors(cudaMalloc((void **)&d_z, sizeof(double) * colsA)); checkCudaErrors(cudaMalloc((void **)&d_x, sizeof(double) * colsA)); checkCudaErrors(cudaMalloc((void **)&d_b, sizeof(double) * rowsA)); checkCudaErrors(cudaMalloc((void **)&d_Qb, sizeof(double) * rowsA)); checkCudaErrors(cudaMalloc((void **)&d_r, sizeof(double) * rowsA)); /* verify if A has symmetric pattern or not */ checkCudaErrors(cusolverSpXcsrissymHost(handle, rowsA, nnzA, descrA, h_csrRowPtrA, h_csrRowPtrA + 1, h_csrColIndA, &issym)); if (0 == strcmp(opts.testFunc, "chol")) { if (!issym) { printf("Error: A has no symmetric pattern, please use LU or QR \n"); exit(EXIT_FAILURE); } } printf("step 2: reorder the matrix A to minimize zero fill-in\n"); printf( " if the user choose a reordering by -P=symrcm, -P=symamd or " "-P=metis\n"); if (NULL != opts.reorder) { if (0 == strcmp(opts.reorder, "symrcm")) { printf("step 2.1: Q = symrcm(A) \n"); checkCudaErrors(cusolverSpXcsrsymrcmHost( handle, rowsA, nnzA, descrA, h_csrRowPtrA, h_csrColIndA, h_Q)); } else if (0 == strcmp(opts.reorder, "symamd")) { printf("step 2.1: Q = symamd(A) \n"); checkCudaErrors(cusolverSpXcsrsymamdHost( handle, rowsA, nnzA, descrA, h_csrRowPtrA, h_csrColIndA, h_Q)); } else if (0 == strcmp(opts.reorder, "metis")) { printf("step 2.1: Q = metis(A) \n"); checkCudaErrors(cusolverSpXcsrmetisndHost(handle, rowsA, nnzA, descrA, h_csrRowPtrA, h_csrColIndA, NULL, /* default setting. */ h_Q)); } else { fprintf(stderr, "Error: %s is unknown reordering\n", opts.reorder); return 1; } } else { printf("step 2.1: no reordering is chosen, Q = 0:n-1 \n"); for (int j = 0; j < rowsA; j++) { h_Q[j] = j; } } printf("step 2.2: B = A(Q,Q) \n"); memcpy(h_csrRowPtrB, h_csrRowPtrA, sizeof(int) * (rowsA + 1)); memcpy(h_csrColIndB, h_csrColIndA, sizeof(int) * nnzA); checkCudaErrors(cusolverSpXcsrperm_bufferSizeHost( handle, rowsA, colsA, nnzA, descrA, h_csrRowPtrB, h_csrColIndB, h_Q, h_Q, &size_perm)); if (buffer_cpu) { free(buffer_cpu); } buffer_cpu = (void *)malloc(sizeof(char) * size_perm); assert(NULL != buffer_cpu); /* h_mapBfromA = Identity */ for (int j = 0; j < nnzA; j++) { h_mapBfromA[j] = j; } checkCudaErrors(cusolverSpXcsrpermHost(handle, rowsA, colsA, nnzA, descrA, h_csrRowPtrB, h_csrColIndB, h_Q, h_Q, h_mapBfromA, buffer_cpu)); /* B = A( mapBfromA ) */ for (int j = 0; j < nnzA; j++) { h_csrValB[j] = h_csrValA[h_mapBfromA[j]]; } printf("step 3: b(j) = 1 + j/n \n"); for (int row = 0; row < rowsA; row++) { h_b[row] = 1.0 + ((double)row) / ((double)rowsA); } /* h_Qb = b(Q) */ for (int row = 0; row < rowsA; row++) { h_Qb[row] = h_b[h_Q[row]]; } printf("step 4: prepare data on device\n"); checkCudaErrors(cudaMemcpyAsync(d_csrRowPtrA, h_csrRowPtrA, sizeof(int) * (rowsA + 1), cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_csrColIndA, h_csrColIndA, sizeof(int) * nnzA, cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_csrValA, h_csrValA, sizeof(double) * nnzA, cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_csrRowPtrB, h_csrRowPtrB, sizeof(int) * (rowsA + 1), cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_csrColIndB, h_csrColIndB, sizeof(int) * nnzA, cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_csrValB, h_csrValB, sizeof(double) * nnzA, cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_b, h_b, sizeof(double) * rowsA, cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_Qb, h_Qb, sizeof(double) * rowsA, cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_Q, h_Q, sizeof(int) * rowsA, cudaMemcpyHostToDevice, stream)); printf("step 5: solve A*x = b on CPU \n"); start = second(); /* solve B*z = Q*b */ if (0 == strcmp(opts.testFunc, "chol")) { checkCudaErrors(cusolverSpDcsrlsvcholHost( handle, rowsA, nnzA, descrA, h_csrValB, h_csrRowPtrB, h_csrColIndB, h_Qb, tol, reorder, h_z, &singularity)); } else if (0 == strcmp(opts.testFunc, "lu")) { checkCudaErrors(cusolverSpDcsrlsvluHost( handle, rowsA, nnzA, descrA, h_csrValB, h_csrRowPtrB, h_csrColIndB, h_Qb, tol, reorder, h_z, &singularity)); } else if (0 == strcmp(opts.testFunc, "qr")) { checkCudaErrors(cusolverSpDcsrlsvqrHost( handle, rowsA, nnzA, descrA, h_csrValB, h_csrRowPtrB, h_csrColIndB, h_Qb, tol, reorder, h_z, &singularity)); } else { fprintf(stderr, "Error: %s is unknown function\n", opts.testFunc); return 1; } /* Q*x = z */ for (int row = 0; row < rowsA; row++) { h_x[h_Q[row]] = h_z[row]; } if (0 <= singularity) { printf("WARNING: the matrix is singular at row %d under tol (%E)\n", singularity, tol); } stop = second(); time_solve_cpu = stop - start; printf("step 6: evaluate residual r = b - A*x (result on CPU)\n"); checkCudaErrors(cudaMemcpyAsync(d_r, d_b, sizeof(double) * rowsA, cudaMemcpyDeviceToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_x, h_x, sizeof(double) * colsA, cudaMemcpyHostToDevice, stream)); /* Wrap raw data into cuSPARSE generic API objects */ cusparseSpMatDescr_t matA = NULL; if (baseA) { checkCudaErrors(cusparseCreateCsr(&matA, rowsA, colsA, nnzA, d_csrRowPtrA, d_csrColIndA, d_csrValA, CUSPARSE_INDEX_32I, CUSPARSE_INDEX_32I, CUSPARSE_INDEX_BASE_ONE, CUDA_R_64F)); } else { checkCudaErrors(cusparseCreateCsr(&matA, rowsA, colsA, nnzA, d_csrRowPtrA, d_csrColIndA, d_csrValA, CUSPARSE_INDEX_32I, CUSPARSE_INDEX_32I, CUSPARSE_INDEX_BASE_ZERO, CUDA_R_64F)); } cusparseDnVecDescr_t vecx = NULL; checkCudaErrors(cusparseCreateDnVec(&vecx, colsA, d_x, CUDA_R_64F)); cusparseDnVecDescr_t vecAx = NULL; checkCudaErrors(cusparseCreateDnVec(&vecAx, rowsA, d_r, CUDA_R_64F)); /* Allocate workspace for cuSPARSE */ size_t bufferSize = 0; checkCudaErrors(cusparseSpMV_bufferSize( cusparseHandle, CUSPARSE_OPERATION_NON_TRANSPOSE, &minus_one, matA, vecx, &one, vecAx, CUDA_R_64F, CUSPARSE_SPMV_ALG_DEFAULT, &bufferSize)); void *buffer = NULL; checkCudaErrors(cudaMalloc(&buffer, bufferSize)); checkCudaErrors(cusparseSpMV(cusparseHandle, CUSPARSE_OPERATION_NON_TRANSPOSE, &minus_one, matA, vecx, &one, vecAx, CUDA_R_64F, CUSPARSE_SPMV_ALG_DEFAULT, buffer)); checkCudaErrors(cudaMemcpyAsync(h_r, d_r, sizeof(double) * rowsA, cudaMemcpyDeviceToHost, stream)); /* wait until h_r is ready */ checkCudaErrors(cudaDeviceSynchronize()); b_inf = vec_norminf(rowsA, h_b); x_inf = vec_norminf(colsA, h_x); r_inf = vec_norminf(rowsA, h_r); A_inf = csr_mat_norminf(rowsA, colsA, nnzA, descrA, h_csrValA, h_csrRowPtrA, h_csrColIndA); printf("(CPU) |b - A*x| = %E \n", r_inf); printf("(CPU) |A| = %E \n", A_inf); printf("(CPU) |x| = %E \n", x_inf); printf("(CPU) |b| = %E \n", b_inf); printf("(CPU) |b - A*x|/(|A|*|x| + |b|) = %E \n", r_inf / (A_inf * x_inf + b_inf)); printf("step 7: solve A*x = b on GPU\n"); start = second(); /* solve B*z = Q*b */ if (0 == strcmp(opts.testFunc, "chol")) { checkCudaErrors(cusolverSpDcsrlsvchol( handle, rowsA, nnzA, descrA, d_csrValB, d_csrRowPtrB, d_csrColIndB, d_Qb, tol, reorder, d_z, &singularity)); } else if (0 == strcmp(opts.testFunc, "lu")) { printf("WARNING: no LU available on GPU \n"); } else if (0 == strcmp(opts.testFunc, "qr")) { checkCudaErrors(cusolverSpDcsrlsvqr(handle, rowsA, nnzA, descrA, d_csrValB, d_csrRowPtrB, d_csrColIndB, d_Qb, tol, reorder, d_z, &singularity)); } else { fprintf(stderr, "Error: %s is unknow function\n", opts.testFunc); return 1; } checkCudaErrors(cudaDeviceSynchronize()); if (0 <= singularity) { printf("WARNING: the matrix is singular at row %d under tol (%E)\n", singularity, tol); } /* Q*x = z */ checkCudaErrors(cusparseDsctr(cusparseHandle, rowsA, d_z, d_Q, d_x, CUSPARSE_INDEX_BASE_ZERO)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve_gpu = stop - start; printf("step 8: evaluate residual r = b - A*x (result on GPU)\n"); checkCudaErrors(cudaMemcpyAsync(d_r, d_b, sizeof(double) * rowsA, cudaMemcpyDeviceToDevice, stream)); checkCudaErrors(cusparseSpMV(cusparseHandle, CUSPARSE_OPERATION_NON_TRANSPOSE, &minus_one, matA, vecx, &one, vecAx, CUDA_R_64F, CUSPARSE_SPMV_ALG_DEFAULT, buffer)); checkCudaErrors(cudaMemcpyAsync(h_x, d_x, sizeof(double) * colsA, cudaMemcpyDeviceToHost, stream)); checkCudaErrors(cudaMemcpyAsync(h_r, d_r, sizeof(double) * rowsA, cudaMemcpyDeviceToHost, stream)); /* wait until h_x and h_r are ready */ checkCudaErrors(cudaDeviceSynchronize()); b_inf = vec_norminf(rowsA, h_b); x_inf = vec_norminf(colsA, h_x); r_inf = vec_norminf(rowsA, h_r); if (0 != strcmp(opts.testFunc, "lu")) { // only cholesky and qr have GPU version printf("(GPU) |b - A*x| = %E \n", r_inf); printf("(GPU) |A| = %E \n", A_inf); printf("(GPU) |x| = %E \n", x_inf); printf("(GPU) |b| = %E \n", b_inf); printf("(GPU) |b - A*x|/(|A|*|x| + |b|) = %E \n", r_inf / (A_inf * x_inf + b_inf)); } fprintf(stdout, "timing %s: CPU = %10.6f sec , GPU = %10.6f sec\n", opts.testFunc, time_solve_cpu, time_solve_gpu); if (0 != strcmp(opts.testFunc, "lu")) { printf("show last 10 elements of solution vector (GPU) \n"); printf("consistent result for different reordering and solver \n"); for (int j = rowsA - 10; j < rowsA; j++) { printf("x[%d] = %E\n", j, h_x[j]); } } if (handle) { checkCudaErrors(cusolverSpDestroy(handle)); } if (cusparseHandle) { checkCudaErrors(cusparseDestroy(cusparseHandle)); } if (stream) { checkCudaErrors(cudaStreamDestroy(stream)); } if (descrA) { checkCudaErrors(cusparseDestroyMatDescr(descrA)); } if (matA) { checkCudaErrors(cusparseDestroySpMat(matA)); } if (vecx) { checkCudaErrors(cusparseDestroyDnVec(vecx)); } if (vecAx) { checkCudaErrors(cusparseDestroyDnVec(vecAx)); } if (h_csrValA) { free(h_csrValA); } if (h_csrRowPtrA) { free(h_csrRowPtrA); } if (h_csrColIndA) { free(h_csrColIndA); } if (h_z) { free(h_z); } if (h_x) { free(h_x); } if (h_b) { free(h_b); } if (h_Qb) { free(h_Qb); } if (h_r) { free(h_r); } if (h_Q) { free(h_Q); } if (h_csrRowPtrB) { free(h_csrRowPtrB); } if (h_csrColIndB) { free(h_csrColIndB); } if (h_csrValB) { free(h_csrValB); } if (h_mapBfromA) { free(h_mapBfromA); } if (buffer_cpu) { free(buffer_cpu); } if (d_csrValA) { checkCudaErrors(cudaFree(d_csrValA)); } if (d_csrRowPtrA) { checkCudaErrors(cudaFree(d_csrRowPtrA)); } if (d_csrColIndA) { checkCudaErrors(cudaFree(d_csrColIndA)); } if (d_csrValB) { checkCudaErrors(cudaFree(d_csrValB)); } if (d_csrRowPtrB) { checkCudaErrors(cudaFree(d_csrRowPtrB)); } if (d_csrColIndB) { checkCudaErrors(cudaFree(d_csrColIndB)); } if (d_Q) { checkCudaErrors(cudaFree(d_Q)); } if (d_z) { checkCudaErrors(cudaFree(d_z)); } if (d_x) { checkCudaErrors(cudaFree(d_x)); } if (d_b) { checkCudaErrors(cudaFree(d_b)); } if (d_Qb) { checkCudaErrors(cudaFree(d_Qb)); } if (d_r) { checkCudaErrors(cudaFree(d_r)); } return 0; }
11,658
13,585
<reponame>694551594/mybatis-plus package com.baomidou.mybatisplus.test.h2.fillperformance.service; import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.test.h2.fillperformance.model.PerformanceModel; public interface IPerformanceModelService extends IService<PerformanceModel> { }
111
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Etuz","circ":"1ère circonscription","dpt":"Haute-Saône","inscrits":459,"abs":249,"votants":210,"blancs":3,"nuls":9,"exp":198,"res":[{"nuance":"REM","nom":"<NAME>","voix":145},{"nuance":"FN","nom":"Mme <NAME>","voix":53}]}
112
1,338
/* * Copyright 2004-2012, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include "RootFileSystem.h" #include <boot/platform.h> #include <boot/vfs.h> #include <boot/menu.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> const char *kNormalColor = "\33[0m"; const char *kDisabledColor = "\33[31m"; // red const char *kTitleColor = "\33[34m"; // blue extern RootFileSystem *gRoot; bool gShowMenu = false; static void print_item_at(int32 line, MenuItem *item, bool clearHelp = true) { if (!item->IsEnabled()) printf("%s ", kDisabledColor); else printf("%2ld. ", line); if (item->Type() == MENU_ITEM_MARKABLE) { printf(" ["); printf("%c", item->IsMarked() ? 'x' : ' '); printf("] "); } else printf(" "); printf(item->Label()); if (item->Submenu() && item->Submenu()->Type() == CHOICE_MENU) { // show the current choice (if any) Menu *subMenu = item->Submenu(); MenuItem *subItem = NULL; for (int32 i = subMenu->CountItems(); i-- > 0; ) { subItem = subMenu->ItemAt(i); if (subItem != NULL && subItem->IsMarked()) break; } printf(" (Current: "); printf(subItem != NULL ? subItem->Label() : "None"); putchar(')'); } if (!item->IsEnabled()) printf(kNormalColor); putchar('\n'); } static void draw_menu(Menu *menu) { printf("\n %s--- ", kTitleColor); if (menu->Title()) printf("%s", menu->Title()); else printf("Welcome To The Haiku Bootloader"); printf(" ---%s\n\n", kNormalColor); MenuItemIterator iterator = menu->ItemIterator(); MenuItem *item; int32 i = 0; while ((item = iterator.Next()) != NULL) { if (item->Type() == MENU_ITEM_SEPARATOR) { putchar('\n'); i++; continue; } print_item_at(i++, item, false); } int32 selected = -1; menu->FindSelected(&selected); printf("\n[%ld]? ", selected); } bool dump_devices_hook(Menu *menu, MenuItem *item) { puts("List of known root directories:"); void *cookie; if (gRoot->Open(&cookie, O_RDONLY) == B_OK) { Directory *directory; while (gRoot->GetNextNode(cookie, (Node **)&directory) == B_OK) { char name[256]; if (directory->GetName(name, sizeof(name)) == B_OK) printf("%s:: %s (%p)%s\n", kTitleColor, name, directory, kNormalColor); void *subCookie; if (directory->Open(&subCookie, O_RDONLY) == B_OK) { while (directory->GetNextEntry(subCookie, name, sizeof(name)) == B_OK) { printf("\t%s\n", name); } directory->Close(subCookie); } } gRoot->Close(cookie); } return false; } // #pragma mark - void platform_add_menus(Menu *menu) { MenuItem *item; switch (menu->Type()) { case MAIN_MENU: menu->AddItem(item = new MenuItem("Dump all recognized volumes")); item->SetTarget(dump_devices_hook); break; default: break; } } void platform_update_menu_item(Menu *menu, MenuItem *item) { } void platform_run_menu(Menu *menu) { // Get selected entry, or select the last one, if there is none int32 selected; MenuItem *item = menu->FindSelected(&selected); if (item == NULL) { selected = menu->CountItems() - 1; item = menu->ItemAt(selected); if (item != NULL) item->Select(true); } while (true) { draw_menu(menu); char buffer[32]; if (fgets(buffer, sizeof(buffer), stdin) == NULL) return; if (buffer[0] != '\n') selected = atoi(buffer); item = menu->ItemAt(selected); if (item == NULL) { printf("Invalid choice."); continue; } item->Select(true); // leave the menu if (item->Submenu() != NULL) { menu->Hide(); platform_run_menu(item->Submenu()); if (item->Target() != NULL) (*item->Target())(menu, item); // restore current menu menu->FindSelected(&selected); menu->Show(); } else if (item->Type() == MENU_ITEM_MARKABLE) { // toggle state item->SetMarked(!item->IsMarked()); if (item->Target() != NULL) (*item->Target())(menu, item); } else if (item->Target() == NULL || (*item->Target())(menu, item)) break; } } size_t platform_get_user_input_text(Menu* menu, MenuItem* item, char* buffer, size_t bufferSize) { return 0; }
1,652
628
import pytest from osf_tests.factories import InstitutionFactory from api.base.settings.defaults import API_BASE from django.core.validators import URLValidator @pytest.mark.django_db class TestInstitutionDetail: expected_relationships = { 'nodes', 'registrations', 'users', 'department_metrics', 'user_metrics', 'summary_metrics' } is_valid_url = URLValidator() @pytest.fixture() def institution(self): return InstitutionFactory() @pytest.fixture() def url(self, institution): return f'/{API_BASE}institutions/{institution._id}/' def test_detail_response(self, app, institution, url): # 404 on wrong _id res = app.get(f'/{institution}institutions/1PO/', expect_errors=True) assert res.status_code == 404 res = app.get(url) assert res.status_code == 200 assert res.json['data']['attributes']['name'] == institution.name assert 'logo_path' in res.json['data']['attributes'] assert 'assets' in res.json['data']['attributes'] assert 'logo' in res.json['data']['attributes']['assets'] assert 'logo_rounded' in res.json['data']['attributes']['assets'] relationships = res.json['data']['relationships'] assert self.expected_relationships == set(relationships.keys()) for relationships in list(relationships.values()): # ↓ returns None if url is valid else throws error. assert self.is_valid_url(relationships['links']['related']['href']) is None # test_return_without_logo_path res = app.get(f'{url}?version=2.14') assert res.status_code == 200 assert 'logo_path' not in res.json['data']['attributes']
724
6,436
#pragma once #include "ofVec3f.h" /// \file /// ofPoint is a typedef (alias) of ofVec3f /// \brief Look at ofVec3f for documentation typedef ofVec3f ofPoint;
69
3,427
/** * Copyright (C) 2015-2016, BMW Car IT GmbH and BMW AG * Author: <NAME> (<EMAIL>) * * 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.graphhopper.matching; /** * Based on <NAME>, and <NAME>. "Hidden Markov map matching through * noise and sparseness." Proceedings of the 17th ACM SIGSPATIAL International * Conference on Advances in Geographic Information Systems. ACM, 2009. */ public class HmmProbabilities { private final double sigma; private final double beta; /** * @param sigma standard deviation of the normal distribution [m] used for * modeling the GPS error * @param beta beta parameter of the exponential distribution used for modeling * transition probabilities */ public HmmProbabilities(double sigma, double beta) { this.sigma = sigma; this.beta = beta; } /** * Returns the logarithmic emission probability density. * * @param distance Absolute distance [m] between GPS measurement and map * matching candidate. */ public double emissionLogProbability(double distance) { return Distributions.logNormalDistribution(sigma, distance); } /** * Returns the logarithmic transition probability density for the given * transition parameters. * * @param routeLength Length of the shortest route [m] between two * consecutive map matching candidates. * @param linearDistance Linear distance [m] between two consecutive GPS * measurements. */ public double transitionLogProbability(double routeLength, double linearDistance) { // Transition metric taken from Newson & Krumm. double transitionMetric = Math.abs(linearDistance - routeLength); return Distributions.logExponentialDistribution(beta, transitionMetric); } }
785
1,251
<reponame>palerdot/BlingFire<gh_stars>1000+ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #include "blingfire-client_src_pch.h" #include "FAConfig.h" #include "FAState2Ow_pack_triv.h" #include "FAEncodeUtils.h" #include "FAFsmConst.h" namespace BlingFire { FAState2Ow_pack_triv::FAState2Ow_pack_triv () : m_pAutImage (NULL), m_DstSize (FAFsmConst::TRIV_PACK_DEF_DST_SIZE) {} void FAState2Ow_pack_triv::SetImage (const unsigned char * pAutImage) { m_pAutImage = pAutImage; if (NULL != m_pAutImage) { // get dst size m_DstSize = *(const int *)(m_pAutImage); if (1 > m_DstSize || 4 < m_DstSize) { m_DstSize = FAFsmConst::TRIV_PACK_DEF_DST_SIZE; } } } const int FAState2Ow_pack_triv::GetOw (const int State) const { DebugLogAssert (m_pAutImage); const unsigned char * pCurrPtr = m_pAutImage + State; const unsigned char info = *pCurrPtr; // get output weight size code, 0 if there are no Ow const int OwSizeCode = (info & 0x60) >> 5; // check whether there is no output weight at this state if (0 == OwSizeCode) { return -1; } // skip info pCurrPtr += sizeof (char); // calc input weight size const int IwSize = ((info & 0x18) >> 3) + 1; DebugLogAssert (sizeof (char) <= (unsigned int) IwSize && \ sizeof (int) >= (unsigned int) IwSize); const char TrType = info & 0x07; // skip transitions switch (TrType) { // prallel arrays case FAFsmConst::TRS_PARA: { unsigned int DstCount; // decode (DstCount - 1) value FADecode_UC_US_UI(pCurrPtr, 0, DstCount, IwSize); // skip encoded (DstCount - 1) value pCurrPtr += IwSize; // skip two parallel arrays of Iws and Dsts pCurrPtr += ((DstCount + 1) * (m_DstSize + IwSize)); break; } // Iw-index array case FAFsmConst::TRS_IWIA: { unsigned int IwBase; unsigned int IwMax; FADecode_UC_US_UI(pCurrPtr, 0, IwBase, IwSize); pCurrPtr += IwSize; FADecode_UC_US_UI(pCurrPtr, 0, IwMax, IwSize); pCurrPtr += IwSize; DebugLogAssert (IwMax >= IwBase); const unsigned int DstCount = IwMax - IwBase + 1; // skip Destination Offsets pCurrPtr += (m_DstSize * DstCount); break; } // ranges case FAFsmConst::TRS_RANGE: { unsigned int RangeCount; // decode (RangeCount - 1) value FADecode_UC_US_UI(pCurrPtr, 0, RangeCount, IwSize); // skip encoded (RangeCount - 1) value pCurrPtr += IwSize; // skip FromIws, ToIws and Dsts pCurrPtr += ((RangeCount + 1) * (m_DstSize + (IwSize * 2))); break; } // implicit transition case FAFsmConst::TRS_IMPL: { // skip input weight pCurrPtr += IwSize; break; } }; // of switch (TrType) ... int Ow; // get the output weight if (1 == OwSizeCode) { Ow = *(const char *)pCurrPtr; } else if (2 == OwSizeCode) { Ow = *(const short *)pCurrPtr; } else { DebugLogAssert (3 == OwSizeCode); Ow = *(const int *)pCurrPtr; } return Ow; } }
1,671
477
<reponame>flying-sheep/goatools #!/usr/bin/env python """This test addresses "Error printing GOTerm #61".""" import os import sys import goatools from goatools.base import download_go_basic_obo def test_go_print(prt=sys.stdout): """Test that all GO Terms can be printed, even if level/depth are not assigned.""" prt_pypath(prt) file_obo = os.path.join(os.getcwd(), "go-basic.obo") obo_file = download_go_basic_obo(file_obo, prt=prt, loading_bar=None) reader = goatools.obo_parser.OBOReader(obo_file) go_terms = list(reader) prt.write("Python Version: {VER}\n\n".format(VER=sys.version)) prt.write("\nOBOReader: {OBJ}\n\n".format(OBJ=reader)) prt.write("format-version: {VER}\n".format(VER=reader.format_version)) prt.write("data-version: {VER}\n\n".format(VER=reader.data_version)) prt.write("Found {N} GO Records:\n".format(N=len(go_terms))) for idx, go_rec in enumerate(go_terms): prt.write("{I:>7,} {RECORD}\n".format(I=idx, RECORD=go_rec)) def prt_pypath(prt): """Print PYTHONPATH contents.""" pypathes = os.environ.get('PYTHONPATH', None) if pypathes: prt.write("\nPYTHONPATH:\n") for idx, pypath in enumerate(pypathes.split(os.pathsep)): prt.write(" {IDX} {PATH}\n".format(IDX=idx, PATH=pypath)) prt.write("\n") if __name__ == '__main__': test_go_print()
613
764
{"symbol": "MAFI","address": "0x4889F721f80C5E9fadE6Ea9B85835D405D79a4f4","overview":{"en": ""},"email": "","website": "https://www.mafi.network/","state": "NORMAL","links": {"blog": "https://t.me/joinchat/AAAAAFRG0UyQJAZrIi2GUw","twitter": "https://twitter.com/Mafia_Network_","telegram": "","github": ""}}
131
348
{"nom":"Courry","circ":"4ème circonscription","dpt":"Gard","inscrits":285,"abs":128,"votants":157,"blancs":26,"nuls":5,"exp":126,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":88},{"nuance":"FN","nom":"Mme <NAME>","voix":38}]}
91
690
<gh_stars>100-1000 """ Evaluation tools, mainly non-straightforward methods. """ from __future__ import print_function from __future__ import division from collections import namedtuple import numpy as np from scipy.stats import pearsonr from scipy.stats import spearmanr from sklearn.metrics import mean_squared_error as mse from . import loader def binclass_accuracy(y, ypred): """ Compute accuracy for binary classification tasks, taking into account grossly unbalanced datasets. Returns (rawacc, y0acc, y1acc, balacc) where balacc is average of y0acc and y1acc, regardless of their true balance in the dataset. (The idea is that even if the unfortunate reality is that we have much less y1 samples, their detection is equally important.) """ rawacc = np.sum((ypred > 0.5) == (y > 0.5)) / ypred.shape[0] y0acc = np.sum(np.logical_and(ypred < 0.5, y < 0.5)) / np.sum(y < 0.5) y1acc = np.sum(np.logical_and(ypred > 0.5, y > 0.5)) / np.sum(y > 0.5) balacc = (y0acc + y1acc) / 2 # XXX could probably simplify and merge with above n_tp = np.sum(np.logical_and(ypred > 0.5, y > 0.5)) n_fp = np.sum(np.logical_and(ypred > 0.5, y < 0.5)) n_fn = np.sum(np.logical_and(ypred < 0.5, y > 0.5)) prec = n_tp / (n_tp + n_fp) # how many reported positives are ok recall = n_tp / (n_tp + n_fn) # how many real positives we catch f_score = 2 * (prec * recall) / (prec + recall) return (rawacc, y0acc, y1acc, balacc, f_score) def multiclass_accuracy(y, ypred): """ Compute accuracy for multiclass classification tasks Returns (rawacc, class_acc) where rawacc is the accuracy on the whole set and class_acc contains accuracies on all classes respectively """ result = np.zeros(ypred.shape) clss=y.shape[1] class_correct=np.zeros(clss) ok=0 for row in range(ypred.shape[0]): result[row,np.argmax(ypred[row])]=1 for cls in range(clss): if y[row,cls]==result[row,cls]: class_correct[cls]+=1 if y[row,cls] == 1: ok += 1 class_acc=np.zeros(clss) for cls in range(clss): class_acc[cls]=(1.0*class_correct[cls])/y.shape[0] rawacc = (ok*1.0)/y.shape[0] return rawacc, class_acc def aggregate_s0(s0, y, ypred, k=None): """ Generate tuples (s0, [(y, ypred), ...]) where the list is sorted by the ypred score. This is useful for a variety of list-based measures in the "anssel"-type tasks. """ ybys0 = dict() for i in range(len(s0)): try: s0is = s0[i].tostring() except AttributeError: s0is = str(s0[i]) if s0is in ybys0: ybys0[s0is].append((y[i], ypred[i])) else: ybys0[s0is] = [(y[i], ypred[i])] for s, yl in ybys0.items(): if k is not None: yl = yl[:k] ys = sorted(yl, key=lambda yy: yy[1], reverse=True) yield (s, ys) def recall_at(s0, y, ypred, N, k=None): """ Compute Recall@N, that is, the expected probability of whether y==1 is within the top N samples sorted by ypred, considering first k samples in dataset (per each s0). """ acc = [] for s, ys in aggregate_s0(s0, y, ypred, k): acc.append(np.sum([yy[0] for yy in ys[:N]]) > 0) return np.mean(acc) def mrr(s0, y, ypred): """ Compute MRR (mean reciprocial rank) of y-predictions, by grouping y-predictions for the same s0 together. This metric is relevant e.g. for the "answer sentence selection" task where we want to identify and take top N most relevant sentences. """ rr = [] for s, ys in aggregate_s0(s0, y, ypred): if np.sum([yy[0] for yy in ys]) == 0: continue # do not include s0 with no right answers in MRR # to get rank, if we are in a larger cluster of same-scored sentences, # we must get |cluster|/2-ranked, not 1-ranked! # python3 -c 'import pysts.eval; import numpy as np; print(pysts.eval.mrr([np.array([0]),np.array([0]),np.array([0]),np.array([1]),np.array([1])], [1,0,0,1,1], [0.4,0.3,0.4,0.5,0.3]))' ysd = dict() for yy in ys: if yy[1] in ysd: ysd[yy[1]].append(yy[0]) else: ysd[yy[1]] = [yy[0]] rank = 0 for yp in sorted(ysd.keys(), reverse=True): if np.sum(ysd[yp]) > 0: rankofs = 1 - np.sum(ysd[yp]) / len(ysd[yp]) rank += len(ysd[yp]) * rankofs break rank += len(ysd[yp]) rr.append(1 / float(1+rank)) return np.mean(rr) def trec_map(s0, s1, y, ypred): """ Use the official trec_eval tool to compute the mean average precision (MAP), a ranking measure that differs from MRR by taking into account also ranking of other than the top-ranked correct samples. """ import subprocess import tempfile def save_trec_qrels(f, s0, s1, y): n = -1 m = 0 last_is0 = '' for is0, is1, iy in zip(s0, s1, y): if hash(tuple(is0)) != last_is0: last_is0 = hash(tuple(is0)) m = 0 n += 1 print('%d 0 %d %d' % (n, m, iy), file=f) m += 1 def save_trec_top(f, s0, s1, y, code): n = -1 m = 0 last_is0 = '' for is0, is1, iy in zip(s0, s1, y): if hash(tuple(is0)) != last_is0: last_is0 = hash(tuple(is0)) m = 0 n += 1 print('%d 0 %d 1 %f %s' % (n, m, iy, code), file=f) m += 1 def trec_eval_get(trec_qrels_file, trec_top_file, qty): p = subprocess.Popen('../trec_eval.8.1/trec_eval %s %s | grep %s | sed "s/.*\t//"' % (trec_qrels_file, trec_top_file, qty), stdout=subprocess.PIPE, shell=True) return float(p.communicate()[0]) with tempfile.NamedTemporaryFile(mode="wt") as qrf: save_trec_qrels(qrf, s0, s1, y) qrf.flush() with tempfile.NamedTemporaryFile(mode="wt") as topf: save_trec_top(topf, s0, s1, ypred, '.') topf.flush() mapt = trec_eval_get(qrf.name, topf.name, 'map') return mapt STSRes = namedtuple('STSRes', ['Pearson', 'Spearman', 'MSE']) def eval_sts(ycat, y, name, quiet=False): """ Evaluate given STS regression-classification predictions and print results. """ if ycat.ndim == 1: ypred = ycat else: ypred = loader.sts_categorical2labels(ycat) if y.ndim == 1: ygold = y else: ygold = loader.sts_categorical2labels(y) pr = pearsonr(ypred, ygold)[0] sr = spearmanr(ypred, ygold)[0] e = mse(ypred, ygold) if not quiet: print('%s Pearson: %f' % (name, pr,)) print('%s Spearman: %f' % (name, sr,)) print('%s MSE: %f' % (name, e,)) return STSRes(pr, sr, e) AnsSelRes = namedtuple('AnsSelRes', ['MRR', 'MAP']) def eval_anssel(ypred, s0, s1, y, name, MAP=False): rawacc, y0acc, y1acc, balacc, f_score = binclass_accuracy(y, ypred) mrr_ = mrr(s0, y, ypred) print('%s Accuracy: raw %f (y=0 %f, y=1 %f), bal %f' % (name, rawacc, y0acc, y1acc, balacc)) print('%s MRR: %f %s' % (name, mrr_, '(on training set, y=0 may be subsampled!)' if name == 'Train' else '')) if MAP: map_ = trec_map(s0, s1, y, ypred) print('%s MAP: %f' % (name, map_)) else: map_ = None return AnsSelRes(mrr_, map_) ParaRes = namedtuple('ParaRes', ['Accuracy', 'F1']) def eval_para(ypred, y, name): rawacc, y0acc, y1acc, balacc, f_score = binclass_accuracy(y, ypred) print('%s Accuracy: raw %f (y=0 %f, y=1 %f), bal %f; F-Score: %f' % (name, rawacc, y0acc, y1acc, balacc, f_score)) return ParaRes(rawacc, f_score) HypEvRes = namedtuple('HypEvRes', ['QAccuracy', 'QF1']) AbcdRes = namedtuple('ABCDRes', ['AbcdAccuracy', 'AbcdMRR']) def eval_hypev(qids, ypred, y, name): if qids is None: rawacc, y0acc, y1acc, balacc, f_score = binclass_accuracy(y, ypred) print('%s QAccuracy: real %f (y=0 %f, y=1 %f, bal %f); F-Score: %f' % (name, rawacc, y0acc, y1acc, balacc, f_score)) return HypEvRes(rawacc, f_score) else: rawacc = recall_at(qids, y, ypred, N=1) mrr_ = mrr(qids, y, ypred) print('%s AbcdAccuracy: %f; MRR: %f' % (name, rawacc, mrr_)) return AbcdRes(rawacc, mrr_) UbuntuRes = namedtuple('UbuntuRes', ['MRR', 'R2_1', 'R10_1', 'R10_2', 'R10_5']) def eval_ubuntu(ypred, s0, y, name): mrr_ = mrr(s0, y, ypred) r1_2 = recall_at(s0, y, ypred, N=1, k=2) r1_10 = recall_at(s0, y, ypred, N=1) r2_10 = recall_at(s0, y, ypred, N=2) r5_10 = recall_at(s0, y, ypred, N=5) print('%s MRR: %f' % (name, mrr_)) print('%s 2-R@1: %f' % (name, r1_2)) print('%s 10-R@1: %f 10-R@2: %f 10-R@5: %f' % (name, r1_10, r2_10, r5_10)) return UbuntuRes(mrr_, r1_2, r1_10, r2_10, r5_10) RTERes = namedtuple('RTERes', ['Accuracy']) def eval_rte(ypred, y, name): cls_names = ['contradiction', 'neutral', 'entailment'] rawacc, cls_acc = multiclass_accuracy(y, ypred) print('%s Accuracy: %.3f, %s accuracy %.3f, %s accuracy %.3f, %s accuracy %.3f' % (name, rawacc, cls_names[0], cls_acc[0], cls_names[1], cls_acc[1], cls_names[2], cls_acc[2])) return RTERes(rawacc)
4,867
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <svtools/fixedhyper.hxx> //......................................................................... namespace svt { //......................................................................... // class FixedHyperlink -------------------------------------------------- FixedHyperlink::FixedHyperlink( Window* pParent, const ResId& rResId ) : ::toolkit::FixedHyperlinkBase( pParent, rResId ), m_nTextLen(0) { Initialize(); } FixedHyperlink::FixedHyperlink( Window* pParent, WinBits nWinStyle ) : ::toolkit::FixedHyperlinkBase( pParent, nWinStyle ), m_nTextLen(0) { Initialize(); } FixedHyperlink::~FixedHyperlink() { } void FixedHyperlink::Initialize() { // saves the old pointer m_aOldPointer = GetPointer(); // changes the font Font aFont = GetControlFont( ); // to underline aFont.SetUnderline( UNDERLINE_SINGLE ); SetControlFont( aFont ); // changes the color to light blue SetTextColor( Color( COL_LIGHTBLUE ) ); // calculates text len m_nTextLen = GetCtrlTextWidth( GetText() ); } void FixedHyperlink::MouseMove( const MouseEvent& rMEvt ) { // changes the pointer if the control is enabled and the mouse is over the text. if ( !rMEvt.IsLeaveWindow() && IsEnabled() && GetPointerPosPixel().X() < m_nTextLen ) SetPointer( POINTER_REFHAND ); else SetPointer( m_aOldPointer ); } void FixedHyperlink::MouseButtonUp( const MouseEvent& ) { // calls the link if the control is enabled and the mouse is over the text. if ( IsEnabled() && GetPointerPosPixel().X() < m_nTextLen ) ImplCallEventListenersAndHandler( VCLEVENT_BUTTON_CLICK, m_aClickHdl, this ); } void FixedHyperlink::RequestHelp( const HelpEvent& rHEvt ) { if ( IsEnabled() && GetPointerPosPixel().X() < m_nTextLen ) FixedText::RequestHelp( rHEvt ); } void FixedHyperlink::GetFocus() { SetTextColor( Color( COL_LIGHTRED ) ); Paint( Rectangle( Point(), GetSizePixel() ) ); ShowFocus( Rectangle( Point( 1, 1 ), Size( m_nTextLen + 4, GetSizePixel().Height() - 2 ) ) ); } void FixedHyperlink::LoseFocus() { SetTextColor( Color( COL_LIGHTBLUE ) ); Paint( Rectangle( Point(), GetSizePixel() ) ); HideFocus(); } void FixedHyperlink::KeyInput( const KeyEvent& rKEvt ) { switch ( rKEvt.GetKeyCode().GetCode() ) { case KEY_SPACE: case KEY_RETURN: m_aClickHdl.Call( this ); break; default: FixedText::KeyInput( rKEvt ); } } void FixedHyperlink::SetURL( const String& rNewURL ) { m_sURL = rNewURL; SetQuickHelpText( m_sURL ); } String FixedHyperlink::GetURL() const { return m_sURL; } void FixedHyperlink::SetDescription( const String& rNewDescription ) { SetText( rNewDescription ); m_nTextLen = GetCtrlTextWidth( GetText() ); } // class FixedHyperlinkImage --------------------------------------------- FixedHyperlinkImage::FixedHyperlinkImage( Window* pParent, const ResId& rResId ) : FixedImage( pParent, rResId ) { Initialize(); } FixedHyperlinkImage::FixedHyperlinkImage( Window* pParent, WinBits nWinStyle ) : FixedImage( pParent, nWinStyle ) { Initialize(); } FixedHyperlinkImage::~FixedHyperlinkImage() { } void FixedHyperlinkImage::Initialize() { // saves the old pointer m_aOldPointer = GetPointer(); } void FixedHyperlinkImage::MouseMove( const MouseEvent& rMEvt ) { // changes the pointer if the control is enabled and the mouse is over the text. if ( !rMEvt.IsLeaveWindow() && IsEnabled() ) SetPointer( POINTER_REFHAND ); else SetPointer( m_aOldPointer ); } void FixedHyperlinkImage::MouseButtonUp( const MouseEvent& ) { // calls the link if the control is enabled and the mouse is over the text. if ( IsEnabled() ) ImplCallEventListenersAndHandler( VCLEVENT_BUTTON_CLICK, m_aClickHdl, this ); Size aSize = GetSizePixel(); Size aImgSz = GetImage().GetSizePixel(); if ( aSize.Width() < aImgSz.Width() ) { DBG_ERRORFILE("xxx"); } } void FixedHyperlinkImage::RequestHelp( const HelpEvent& rHEvt ) { if ( IsEnabled() ) FixedImage::RequestHelp( rHEvt ); } void FixedHyperlinkImage::GetFocus() { Paint( Rectangle( Point(), GetSizePixel() ) ); ShowFocus( Rectangle( Point( 1, 1 ), Size( GetSizePixel().Width() - 2, GetSizePixel().Height() - 2 ) ) ); } void FixedHyperlinkImage::LoseFocus() { Paint( Rectangle( Point(), GetSizePixel() ) ); HideFocus(); } void FixedHyperlinkImage::KeyInput( const KeyEvent& rKEvt ) { switch ( rKEvt.GetKeyCode().GetCode() ) { case KEY_SPACE: case KEY_RETURN: m_aClickHdl.Call( this ); break; default: FixedImage::KeyInput( rKEvt ); } } void FixedHyperlinkImage::SetURL( const String& rNewURL ) { m_sURL = rNewURL; SetQuickHelpText( m_sURL ); } String FixedHyperlinkImage::GetURL() const { return m_sURL; } //......................................................................... } // namespace svt //.........................................................................
2,134
1,232
/*- * << * DBus * == * Copyright (C) 2016 - 2019 Bridata * == * 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.creditease.dbus.notopen.mongo; import com.alibaba.fastjson.JSONObject; import com.creditease.dbus.common.FullPullConstants; import com.creditease.dbus.helper.DBHelper; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class MongoHelper { private static Logger logger = LoggerFactory.getLogger(MongoHelper.class); /** * 判断是否为单独的服务.即没有使用副本集或者分片 * * @param mongoManager the connection * @return true if connected to a standalone server */ public static boolean isStandalone(MongoManager mongoManager) { return !isReplicaSet(mongoManager) && !isSharded(mongoManager); } /** * 判断是否使用了副本集 * * @param mongoManager * @return */ public static boolean isReplicaSet(MongoManager mongoManager) { return runIsMaster(mongoManager).get("setName") != null; } /** * 执行isMaster命令,获取master相关信息 * * @param mongoManager * @return */ public static Document runIsMaster(MongoManager mongoManager) { return mongoManager.getDatabase("admin").runCommand(new Document("ismaster", 1)); } /** * 判断是否使用了分片 * 要检测你客户端连接的mongodb实例是否是mongos,可以使用 isMaster 命令。 * 当客户端连上 mongos,isMaster 返回一个带有msg 字段的文档,且字段值为isdbgrid。 * * @param mongoManager * @return */ public static boolean isSharded(MongoManager mongoManager) { Document document = runIsMaster(mongoManager); Object msg = document.get("msg"); return msg != null && msg.equals("isdbgrid"); } public static boolean getMongoOpenFirst(JSONObject reqJson) { JSONObject payloadJson = reqJson.getJSONObject(FullPullConstants.REQ_PAYLOAD); Integer dsId = Integer.parseInt(payloadJson.getString("DBUS_DATASOURCE_ID")); String schemaName = payloadJson.getString("SCHEMA_NAME"); String tableName = payloadJson.getString("TABLE_NAME"); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; int is_open = 0; try { conn = DBHelper.getDBusMgrConnection(); String sql = "select t.is_open from t_data_tables t where t.ds_id = ? and t.schema_name = ? and t.table_name = ? "; ps = conn.prepareStatement(sql); ps.setInt(1, dsId); ps.setString(2, schemaName); ps.setString(3, tableName); rs = ps.executeQuery(); if (rs.next()) { is_open = rs.getInt("is_open"); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { DBHelper.close(conn, ps, rs); } logger.info("[pull bolt] mongo一级节点展开开关状态:{}", is_open); return is_open == 0 ? false : true; } /** * 获取副本集中主机的hostname和port * * @param mongoManager Mongo对象 * @param stateStrToMatch 副本集中MongoDB节点的状态字符创(primary或者secondary) * @return 主机的hostname和port */ /*public static List<String> getReplicaSetUrls(MongoManager mongoManager, String stateStrToMatch) { Document document = runReplicaSetStatusCommand(mongoManager); List urls = new ArrayList<String>(); //遍历副本集中的成员 for (Map<String, Object> member : (List<Map<String, Object>>) document.get("members")) { String name = (String) member.get("name"); if (!name.contains(":")) { name = name + ":27017"; } name = "mongodb://" + name; if (stateStrToMatch.equalsIgnoreCase((String) member.get("stateStr"))) { urls.add(name); } } if (!urls.isEmpty()) { return urls; } else { throw new IllegalStateException("No member found in state " + stateStrToMatch); } }*/ /*public static Document runReplicaSetStatusCommand(MongoManager mongoManager) { Document document = mongoManager.getDatabase("admin").runCommand(new Document("replSetGetStatus", 1)); String json = document.toJson(); if (json != null && json.indexOf("--replSet") != -1) { System.err.println("---- SecondaryReadTest: This is not a replica set - not testing secondary reads"); return null; } return document; }*/ }
2,326
2,266
<reponame>defc0n1/shoppe_promo #include <stdio.h> void a() { printf ("In function a\n"); }
48
354
import unittest import matplotlib matplotlib.use("Agg") class Test(unittest.TestCase): def test_random(self): import numpy as np import matplotlib.pyplot as plt from smt.sampling_methods import Random xlimits = np.array([[0.0, 4.0], [0.0, 3.0]]) sampling = Random(xlimits=xlimits) num = 50 x = sampling(num) print(x.shape) plt.plot(x[:, 0], x[:, 1], "o") plt.xlabel("x") plt.ylabel("y") plt.show() def test_lhs(self): import numpy as np import matplotlib.pyplot as plt from smt.sampling_methods import LHS xlimits = np.array([[0.0, 4.0], [0.0, 3.0]]) sampling = LHS(xlimits=xlimits) num = 50 x = sampling(num) print(x.shape) plt.plot(x[:, 0], x[:, 1], "o") plt.xlabel("x") plt.ylabel("y") plt.show() def test_full_factorial(self): import numpy as np import matplotlib.pyplot as plt from smt.sampling_methods import FullFactorial xlimits = np.array([[0.0, 4.0], [0.0, 3.0]]) sampling = FullFactorial(xlimits=xlimits) num = 50 x = sampling(num) print(x.shape) plt.plot(x[:, 0], x[:, 1], "o") plt.xlabel("x") plt.ylabel("y") plt.show() if __name__ == "__main__": unittest.main()
734