max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
715
<filename>examples/dsl/v2/homo_nn/mnist_demo/bind_local_path.json { "engine": "PATH", "namespace": "experiment", "name": "mnist_images2", "address": { "path": "$PROJECT_BASE/examples/data/mnist_train" } }
112
372
<filename>clients/google-api-services-gmail/v1/1.31.0/com/google/api/services/gmail/model/Message.java<gh_stars>100-1000 /* * 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.gmail.model; /** * An email message. * * <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 Gmail 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 Message extends com.google.api.client.json.GenericJson { /** * The ID of the last history record that modified this message. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger historyId; /** * The immutable ID of the message. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For * normal SMTP-received email, this represents the time the message was originally accepted by * Google, which is more reliable than the `Date` header. However, for API-migrated mail, it can * be configured by client to be based on the `Date` header. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long internalDate; /** * List of IDs of labels applied to this message. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> labelIds; /** * The parsed email structure in the message parts. * The value may be {@code null}. */ @com.google.api.client.util.Key private MessagePart payload; /** * The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in * `messages.get` and `drafts.get` responses when the `format=RAW` parameter is supplied. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String raw; /** * Estimated size in bytes of the message. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer sizeEstimate; /** * A short part of the message text. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String snippet; /** * The ID of the thread the message belongs to. To add a message or draft to a thread, the * following criteria must be met: 1. The requested `threadId` must be specified on the `Message` * or `Draft.Message` you supply with your request. 2. The `References` and `In-Reply-To` headers * must be set in compliance with the [RFC 2822](https://tools.ietf.org/html/rfc2822) standard. 3. * The `Subject` headers must match. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String threadId; /** * The ID of the last history record that modified this message. * @return value or {@code null} for none */ public java.math.BigInteger getHistoryId() { return historyId; } /** * The ID of the last history record that modified this message. * @param historyId historyId or {@code null} for none */ public Message setHistoryId(java.math.BigInteger historyId) { this.historyId = historyId; return this; } /** * The immutable ID of the message. * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * The immutable ID of the message. * @param id id or {@code null} for none */ public Message setId(java.lang.String id) { this.id = id; return this; } /** * The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For * normal SMTP-received email, this represents the time the message was originally accepted by * Google, which is more reliable than the `Date` header. However, for API-migrated mail, it can * be configured by client to be based on the `Date` header. * @return value or {@code null} for none */ public java.lang.Long getInternalDate() { return internalDate; } /** * The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For * normal SMTP-received email, this represents the time the message was originally accepted by * Google, which is more reliable than the `Date` header. However, for API-migrated mail, it can * be configured by client to be based on the `Date` header. * @param internalDate internalDate or {@code null} for none */ public Message setInternalDate(java.lang.Long internalDate) { this.internalDate = internalDate; return this; } /** * List of IDs of labels applied to this message. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getLabelIds() { return labelIds; } /** * List of IDs of labels applied to this message. * @param labelIds labelIds or {@code null} for none */ public Message setLabelIds(java.util.List<java.lang.String> labelIds) { this.labelIds = labelIds; return this; } /** * The parsed email structure in the message parts. * @return value or {@code null} for none */ public MessagePart getPayload() { return payload; } /** * The parsed email structure in the message parts. * @param payload payload or {@code null} for none */ public Message setPayload(MessagePart payload) { this.payload = payload; return this; } /** * The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in * `messages.get` and `drafts.get` responses when the `format=RAW` parameter is supplied. * @see #decodeRaw() * @return value or {@code null} for none */ public java.lang.String getRaw() { return raw; } /** * The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in * `messages.get` and `drafts.get` responses when the `format=RAW` parameter is supplied. * @see #getRaw() * @return Base64 decoded value or {@code null} for none * * @since 1.14 */ public byte[] decodeRaw() { return com.google.api.client.util.Base64.decodeBase64(raw); } /** * The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in * `messages.get` and `drafts.get` responses when the `format=RAW` parameter is supplied. * @see #encodeRaw() * @param raw raw or {@code null} for none */ public Message setRaw(java.lang.String raw) { this.raw = raw; return this; } /** * The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in * `messages.get` and `drafts.get` responses when the `format=RAW` parameter is supplied. * @see #setRaw() * * <p> * The value is encoded Base64 or {@code null} for none. * </p> * * @since 1.14 */ public Message encodeRaw(byte[] raw) { this.raw = com.google.api.client.util.Base64.encodeBase64URLSafeString(raw); return this; } /** * Estimated size in bytes of the message. * @return value or {@code null} for none */ public java.lang.Integer getSizeEstimate() { return sizeEstimate; } /** * Estimated size in bytes of the message. * @param sizeEstimate sizeEstimate or {@code null} for none */ public Message setSizeEstimate(java.lang.Integer sizeEstimate) { this.sizeEstimate = sizeEstimate; return this; } /** * A short part of the message text. * @return value or {@code null} for none */ public java.lang.String getSnippet() { return snippet; } /** * A short part of the message text. * @param snippet snippet or {@code null} for none */ public Message setSnippet(java.lang.String snippet) { this.snippet = snippet; return this; } /** * The ID of the thread the message belongs to. To add a message or draft to a thread, the * following criteria must be met: 1. The requested `threadId` must be specified on the `Message` * or `Draft.Message` you supply with your request. 2. The `References` and `In-Reply-To` headers * must be set in compliance with the [RFC 2822](https://tools.ietf.org/html/rfc2822) standard. 3. * The `Subject` headers must match. * @return value or {@code null} for none */ public java.lang.String getThreadId() { return threadId; } /** * The ID of the thread the message belongs to. To add a message or draft to a thread, the * following criteria must be met: 1. The requested `threadId` must be specified on the `Message` * or `Draft.Message` you supply with your request. 2. The `References` and `In-Reply-To` headers * must be set in compliance with the [RFC 2822](https://tools.ietf.org/html/rfc2822) standard. 3. * The `Subject` headers must match. * @param threadId threadId or {@code null} for none */ public Message setThreadId(java.lang.String threadId) { this.threadId = threadId; return this; } @Override public Message set(String fieldName, Object value) { return (Message) super.set(fieldName, value); } @Override public Message clone() { return (Message) super.clone(); } }
3,285
544
<reponame>RamakrishnaChilaka/submarine<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. */ package org.apache.submarine.server.api.experimenttemplate; import org.apache.submarine.server.api.spec.ExperimentTemplateSpec; public class ExperimentTemplate { private ExperimentTemplateId experimentTemplateId; private ExperimentTemplateSpec experimentTemplateSpec; public ExperimentTemplateId getExperimentTemplateId() { return this.experimentTemplateId; } public void setExperimentTemplateId(ExperimentTemplateId experimentTemplateId) { this.experimentTemplateId = experimentTemplateId; } public ExperimentTemplateSpec getExperimentTemplateSpec() { return this.experimentTemplateSpec; } public void setExperimentTemplateSpec(ExperimentTemplateSpec experimentTemplateSpec) { this.experimentTemplateSpec = experimentTemplateSpec; } }
471
2,782
package course.examples.audiovideo.videoplay; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.Bundle; import android.widget.MediaController; import android.widget.VideoView; public class AudioVideoVideoPlayActivity extends Activity { VideoView mVideoView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get a reference to the VideoView mVideoView = (VideoView) findViewById(R.id.videoViewer); // Add a Media controller to allow forward/reverse/pause/resume final MediaController mMediaController = new MediaController( AudioVideoVideoPlayActivity.this, true); mMediaController.setEnabled(false); mVideoView.setMediaController(mMediaController); mVideoView .setVideoURI(Uri .parse("android.resource://course.examples.AudioVideo.VideoPlay/raw/moon")); // Add an OnPreparedListener to enable the MediaController once the video is ready mVideoView.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mMediaController.setEnabled(true); } }); } // Clean up and release resources @Override protected void onPause() { if (mVideoView != null && mVideoView.isPlaying()) { mVideoView.stopPlayback(); mVideoView = null; } super.onPause(); } }
488
1,210
import binascii import io from ..intbytes import int2byte from pycoin.coins.SolutionChecker import ScriptError class ScriptTools(object): def __init__(self, opcode_list, IntStreamer, scriptStreamer): self.intStreamer = IntStreamer self.scriptStreamer = scriptStreamer self.opcode_to_int = dict(o for o in opcode_list) self.int_to_opcode = dict(reversed(o) for o in opcode_list) def int_for_opcode(self, opcode): return self.opcode_to_int.get(opcode) def compile_expression(self, t): if (t[0], t[-1]) == ('[', ']'): return binascii.unhexlify(t[1:-1]) if t.startswith("'") and t.endswith("'"): return t[1:-1].encode("utf8") try: t0 = int(t) if abs(t0) <= 0xffffffffffffffff and t[0] != '0': return self.intStreamer.int_to_script_bytes(t0) except (SyntaxError, ValueError): pass try: return binascii.unhexlify(t) except Exception: pass raise SyntaxError("unknown expression %s" % t) def compile(self, s): """ Compile the given script. Returns a bytes object with the compiled script. """ f = io.BytesIO() for t in s.split(): t_up = t.upper() if t_up in self.opcode_to_int: f.write(int2byte(self.opcode_to_int[t])) elif ("OP_%s" % t_up) in self.opcode_to_int: f.write(int2byte(self.opcode_to_int["OP_%s" % t])) elif t_up.startswith("0X"): d = binascii.unhexlify(t[2:]) f.write(d) else: v = self.compile_expression(t) self.write_push_data([v], f) return f.getvalue() def disassemble_for_opcode_data(self, opcode, data): # TODO: check data for int or string representation opcode_str = self.int_to_opcode.get(opcode, "???") if data is not None and len(data) > 0 and opcode_str.startswith("OP_PUSH"): return "[%s]" % binascii.hexlify(data).decode("utf8") return opcode_str def get_opcodes(self, script, verify_minimal_data=False, pc=0): """ Iterator. Return opcode, data, pc, new_pc at each step """ while pc < len(script): opcode, data, new_pc, is_ok = self.scriptStreamer.get_opcode( script, pc, verify_minimal_data=verify_minimal_data) yield opcode, data, pc, new_pc pc = new_pc def opcode_list(self, script): """Disassemble the given script. Returns a list of opcodes.""" opcodes = [] new_pc = 0 try: for opcode, data, pc, new_pc in self.get_opcodes(script): opcodes.append(self.disassemble_for_opcode_data(opcode, data)) except ScriptError: opcodes.append(binascii.hexlify(script[new_pc:]).decode("utf8")) return opcodes def disassemble(self, script): """Disassemble the given script. Returns a string.""" return ' '.join(self.opcode_list(script)) def write_push_data(self, data_list, f): # return bytes that causes the given data to be pushed onto the stack for t in data_list: f.write(self.scriptStreamer.compile_push_data(t)) def compile_push_data_list(self, data_list): return b''.join(self.scriptStreamer.compile_push_data(d) for d in data_list if d is not None)
1,683
852
<gh_stars>100-1000 /** \class PreMixingModule * * PreMixingModule is the EDProducer subclass that overlays premixed * MC events on top of MC. It is similar to DataMixingModule, but * tailored for premixing use case. * ************************************************************/ #include "Mixing/Base/interface/BMixingModule.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventPrincipal.h" #include "FWCore/Framework/interface/ModuleContextSentry.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/EDMException.h" #include "FWCore/Utilities/interface/transform.h" #include "FWCore/Utilities/interface/RandomNumberGenerator.h" #include "FWCore/ServiceRegistry/interface/InternalContext.h" #include "FWCore/ServiceRegistry/interface/ModuleCallingContext.h" #include "FWCore/ServiceRegistry/interface/ParentContext.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "SimDataFormats/CrossingFrame/interface/CrossingFramePlaybackInfoNew.h" #include "SimDataFormats/PileupSummaryInfo/interface/PileupSummaryInfo.h" #include "SimGeneral/MixingModule/interface/PileUpEventPrincipal.h" #include "SimGeneral/PreMixingModule/interface/PreMixingWorker.h" #include "SimGeneral/PreMixingModule/interface/PreMixingWorkerFactory.h" #include "PreMixingPileupCopy.h" #include <CLHEP/Random/RandomEngine.h> #include <functional> #include <vector> namespace edm { class PreMixingModule : public BMixingModule { public: PreMixingModule(const edm::ParameterSet& ps, MixingCache::Config const* globalConf); ~PreMixingModule() override = default; void checkSignal(const edm::Event& e) override{}; void createnewEDProduct() override {} void addSignals(const edm::Event& e, const edm::EventSetup& ES) override; void doPileUp(edm::Event& e, const edm::EventSetup& ES) override; void put(edm::Event& e, const edm::EventSetup& ES) override; void initializeEvent(edm::Event const& e, edm::EventSetup const& eventSetup) override; void beginRun(edm::Run const& run, edm::EventSetup const& eventSetup) override; void beginLuminosityBlock(LuminosityBlock const& l1, EventSetup const& c) override; void endLuminosityBlock(LuminosityBlock const& l1, EventSetup const& c) override; void endRun(const edm::Run& r, const edm::EventSetup& setup) override; private: class AdjustPileupDistribution { public: AdjustPileupDistribution(const edm::ParameterSet& ps) : firstRun_(ps.getParameter<unsigned int>("firstRun")), firstBinPileup_(ps.getParameter<unsigned int>("firstBinPileup")), pileupProbabilities_(ps.getParameter<std::vector<double>>("pileupProbabilities")) { for (double p : pileupProbabilities_) { if (p < 0. or p > 1.) { throw cms::Exception("Configuration") << "Invalid probability value " << p << " for firstRun " << firstRun_ << ". The probability must be >= 0. and <= 1."; } } } edm::RunNumber_t firstRun() const { return firstRun_; } double probability(float pileup) const { unsigned int bin = static_cast<unsigned int>(pileup); if (bin < firstBinPileup_ or bin >= firstBinPileup_ + pileupProbabilities_.size()) { edm::LogWarning("PreMixingModule") << "Got pileup event with true pileup " << pileup << " that is outside of the configured pileup adjustment bounds [" << firstBinPileup_ << ", " << firstBinPileup_ + pileupProbabilities_.size() - 1 << "]. Using probability 0."; return 0.; } return pileupProbabilities_[bin - firstBinPileup_]; } private: edm::RunNumber_t firstRun_; unsigned int firstBinPileup_; std::vector<double> pileupProbabilities_; }; bool pileWorker(const edm::EventPrincipal&, int bcr, int EventId, const edm::EventSetup& ES, ModuleCallingContext const*, AdjustPileupDistribution const* pileupAdjuster); PreMixingPileupCopy puWorker_; bool addedPileup_ = false; std::vector<AdjustPileupDistribution> pileupAdjusters_; std::vector<std::unique_ptr<PreMixingWorker>> workers_; }; PreMixingModule::PreMixingModule(const edm::ParameterSet& ps, MixingCache::Config const* globalConf) : BMixingModule(ps, globalConf), puWorker_(ps.getParameter<edm::ParameterSet>("workers").getParameter<edm::ParameterSet>("pileup"), producesCollector(), consumesCollector()), pileupAdjusters_( edm::vector_transform(ps.getParameter<std::vector<edm::ParameterSet>>("adjustPileupDistribution"), [](const auto& ps) { return AdjustPileupDistribution(ps); })) { std::sort(pileupAdjusters_.begin(), pileupAdjusters_.end(), [](const auto& a, const auto& b) { return a.firstRun() < b.firstRun(); }); const auto& workers = ps.getParameter<edm::ParameterSet>("workers"); std::vector<std::string> names = workers.getParameterNames(); // Hack to keep the random number sequence unchanged for migration // from DataMixingModule to PreMixingModule. To be removed in a // subsequent PR doing only that. { std::vector<std::string> tmp; auto hack = [&](const std::string& name) { auto i = std::find(names.begin(), names.end(), name); if (i != names.end()) { tmp.push_back(*i); names.erase(i); } }; hack("ecal"); hack("hcal"); hack("strip"); hack("pixel"); std::copy(names.begin(), names.end(), std::back_inserter(tmp)); names = std::move(tmp); } for (const auto& name : names) { if (name == "pileup") { continue; } const auto& pset = workers.getParameter<edm::ParameterSet>(name); std::string type = pset.getParameter<std::string>("workerType"); workers_.emplace_back( PreMixingWorkerFactory::get()->create(type, pset, producesCollector(), consumesCollector())); } } void PreMixingModule::initializeEvent(const edm::Event& e, const edm::EventSetup& ES) { for (auto& w : workers_) { w->initializeEvent(e, ES); } } void PreMixingModule::beginRun(edm::Run const& run, const edm::EventSetup& ES) { BMixingModule::beginRun(run, ES); for (auto& w : workers_) { w->beginRun(run, ES); } } void PreMixingModule::endRun(edm::Run const& run, const edm::EventSetup& ES) { for (auto& w : workers_) { w->endRun(); } BMixingModule::endRun(run, ES); } void PreMixingModule::addSignals(const edm::Event& e, const edm::EventSetup& ES) { // fill in maps of hits LogDebug("PreMixingModule") << "===============> adding MC signals for " << e.id(); for (auto& w : workers_) { w->addSignals(e, ES); } addedPileup_ = false; } bool PreMixingModule::pileWorker(const EventPrincipal& ep, int bcr, int eventNr, const edm::EventSetup& ES, edm::ModuleCallingContext const* mcc, AdjustPileupDistribution const* pileupAdjuster) { InternalContext internalContext(ep.id(), mcc); ParentContext parentContext(&internalContext); ModuleCallingContext moduleCallingContext(&moduleDescription()); ModuleContextSentry moduleContextSentry(&moduleCallingContext, parentContext); PileUpEventPrincipal pep(ep, &moduleCallingContext, bcr); if (pileupAdjuster) { float trueNumInteractions = puWorker_.getTrueNumInteractions(pep); double prob = pileupAdjuster->probability(static_cast<unsigned int>(trueNumInteractions)); edm::Service<edm::RandomNumberGenerator> rng; CLHEP::HepRandomEngine& engine = rng->getEngine(ep.streamID()); if (engine.flat() > prob) { // engine.flat() should give a double in ]0,1[ range // the choice above means that "prob = 1-ulp" is treatead as 1 return false; } } LogDebug("PreMixingModule") << "\n===============> adding pileups from event " << ep.id() << " for bunchcrossing " << bcr; // Note: setupPileUpEvent may modify the run and lumi numbers of the EventPrincipal to match that of the primary event. setupPileUpEvent(ES); // check and see if we need to copy the pileup information from // secondary stream to the output stream // We only have the pileup event here, so pick the first time and store the info if (!addedPileup_) { puWorker_.addPileupInfo(pep); addedPileup_ = true; } // fill in maps of hits; same code as addSignals, except now applied to the pileup events for (auto& w : workers_) { w->addPileups(pep, ES); } return true; } void PreMixingModule::doPileUp(edm::Event& e, const edm::EventSetup& ES) { using namespace std::placeholders; std::vector<edm::SecondaryEventIDAndFileInfo> recordEventID; std::vector<int> PileupList; TrueNumInteractions_.clear(); ModuleCallingContext const* mcc = e.moduleCallingContext(); AdjustPileupDistribution const* pileupAdjuster = nullptr; if (not pileupAdjusters_.empty()) { // Find the adjustment settings for the run of the signal event // the container should be small-enough to not really gain // anything with binary search auto it = std::find_if(pileupAdjusters_.rbegin(), pileupAdjusters_.rend(), [iRun = e.id().run()](const auto& elem) { return elem.firstRun() <= iRun; }); if (it == pileupAdjusters_.rend()) { throw cms::Exception("LogicError") << "Encountered run " << e.id().run() << ", but the first run available in the pileup adjustment configuration is " << pileupAdjusters_.front().firstRun() << ". Please fix the configuration."; } pileupAdjuster = &*it; } for (int bunchCrossing = minBunch_; bunchCrossing <= maxBunch_; ++bunchCrossing) { for (unsigned int isource = 0; isource < maxNbSources_; ++isource) { std::shared_ptr<PileUp> source = inputSources_[isource]; if (!source || !(source->doPileUp(bunchCrossing))) continue; if (isource == 0) source->CalculatePileup(minBunch_, maxBunch_, PileupList, TrueNumInteractions_, e.streamID()); int NumPU_Events = 0; if (isource == 0) { NumPU_Events = PileupList[bunchCrossing - minBunch_]; } else { // non-minbias pileup only gets one event for now. Fix later if desired. NumPU_Events = 1; } for (auto& w : workers_) { w->initializeBunchCrossing(e, ES, bunchCrossing); } source->readPileUp( e.id(), recordEventID, std::bind( &PreMixingModule::pileWorker, std::ref(*this), _1, bunchCrossing, _2, std::cref(ES), mcc, pileupAdjuster), NumPU_Events, e.streamID()); for (auto& w : workers_) { w->finalizeBunchCrossing(e, ES, bunchCrossing); } } } } void PreMixingModule::put(edm::Event& e, const edm::EventSetup& ES) { // individual workers... // move pileup first so we have access to the information for the put step const auto& ps = puWorker_.getPileupSummaryInfo(); int bunchSpacing = puWorker_.getBunchSpacing(); for (auto& w : workers_) { w->put(e, ES, ps, bunchSpacing); } puWorker_.putPileupInfo(e); } void PreMixingModule::beginLuminosityBlock(LuminosityBlock const& l1, EventSetup const& c) { BMixingModule::beginLuminosityBlock(l1, c); for (auto& w : workers_) { w->beginLuminosityBlock(l1, c); } } void PreMixingModule::endLuminosityBlock(LuminosityBlock const& l1, EventSetup const& c) { BMixingModule::endLuminosityBlock(l1, c); } } // namespace edm #include "FWCore/PluginManager/interface/PluginManager.h" #include "FWCore/Framework/interface/MakerMacros.h" using edm::PreMixingModule; DEFINE_FWK_MODULE(PreMixingModule);
5,126
394
<reponame>Blobanium/multiconnect package net.earthcomputer.multiconnect; public class TestingDummyMain { public static void main(String[] args) {} }
50
1,303
/**************************************************************************************** Copyright (C) 2015 Autodesk, Inc. All rights reserved. Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. ****************************************************************************************/ //! \file fbxfiletexture.h #ifndef _FBXSDK_SCENE_SHADING_TEXTURE_FILE_H_ #define _FBXSDK_SCENE_SHADING_TEXTURE_FILE_H_ #include <fbxsdk/fbxsdk_def.h> #include <fbxsdk/scene/shading/fbxtexture.h> #include <fbxsdk/fbxsdk_nsbegin.h> /** This class describes image mapping on top of geometry. * \note To apply a texture to geometry, first connect the * geometry to a FbxSurfaceMaterial object (e.g. FbxSurfaceLambert) * and then connect one of its properties (e.g. Diffuse) to the * FbxFileTexture object. * \see FbxSurfaceLambert * \see FbxSurfacePhong * \see FbxSurfaceMaterial * \note For some example code, see also the CreateTexture() function * in the ExportScene03 of FBX SDK examples. * \nosubgrouping */ class FBXSDK_DLL FbxFileTexture : public FbxTexture { FBXSDK_OBJECT_DECLARE(FbxFileTexture, FbxTexture); public: /** * \name Texture Properties */ //@{ /** This property handles the material use. * Default value is false. */ FbxPropertyT<FbxBool> UseMaterial; /** This property handles the Mipmap use. * Default value is false. */ FbxPropertyT<FbxBool> UseMipMap; /** Resets the default texture values. * \remarks The texture file name is not reset. */ void Reset(); /** Sets the associated texture file. * \param pName The absolute path of the texture file. * \return \c True if successful, returns \c false otherwise. * \remarks The texture file name must be valid, you cannot leave the name empty. */ bool SetFileName(const char* pName); /** Sets the associated texture file. * \param pName The relative path of the texture file. * \return \c True if successful, returns \c false otherwise. * \remarks The texture file name must be valid. */ bool SetRelativeFileName(const char* pName); /** Returns the absolute texture file path. * \return The absolute texture file path. * \remarks An empty string is returned if FbxFileTexture::SetFileName() has not been called before. */ const char* GetFileName () const; /** Returns the relative texture file path. * \return The relative texture file path. * \remarks An empty string is returned if FbxFileTexture::SetRelativeFileName() has not been called before. */ const char* GetRelativeFileName() const; /** \enum EMaterialUse Specify if texture uses model material. */ enum EMaterialUse { eModelMaterial, //! Texture uses model material. eDefaultMaterial //! Texture does not use model material. }; /** Sets the material use. * \param pMaterialUse Specify how texture uses model material. */ void SetMaterialUse(EMaterialUse pMaterialUse); /** Returns the material use. * \return How the texture uses model material. */ EMaterialUse GetMaterialUse() const; //@} /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS virtual FbxObject& Copy(const FbxObject& pObject); bool operator==(FbxFileTexture const& pTexture) const; FbxString& GetMediaName(); void SetMediaName(const char* pMediaName); protected: virtual void Construct(const FbxObject* pFrom); virtual void ConstructProperties(bool pForceSet); void Init(); void SyncVideoFileName(const char* pFileName); void SyncVideoRelativeFileName(const char* pFileName); FbxString mFileName; FbxString mRelativeFileName; FbxString mMediaName; // not a prop #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; #include <fbxsdk/fbxsdk_nsend.h> #endif /* _FBXSDK_SCENE_SHADING_TEXTURE_FILE_H_ */
1,565
3,680
// // Copyright 2021 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/imaging/hdSt/renderParam.h" PXR_NAMESPACE_OPEN_SCOPE HdStRenderParam::HdStRenderParam() : _drawBatchesVersion(1) , _materialTagsVersion(1) , _geomSubsetDrawItemsVersion(1) , _needsGarbageCollection(false) { } HdStRenderParam::~HdStRenderParam() = default; void HdStRenderParam::MarkDrawBatchesDirty() { ++_drawBatchesVersion; // uses std::memory_order_seq_cst } unsigned int HdStRenderParam::GetDrawBatchesVersion() const { // Can use relaxed ordering because render passes are expected to // only read the value, and that too in a single threaded fashion. return _drawBatchesVersion.load(std::memory_order_relaxed); } void HdStRenderParam::MarkMaterialTagsDirty() { ++_materialTagsVersion; // uses std::memory_order_seq_cst } unsigned int HdStRenderParam::GetMaterialTagsVersion() const { // Can use relaxed ordering because render passes are expected to // only read the value, and that too in a single threaded fashion. return _materialTagsVersion.load(std::memory_order_relaxed); } void HdStRenderParam::MarkGeomSubsetDrawItemsDirty() { ++_geomSubsetDrawItemsVersion; // uses std::memory_order_seq_cst } unsigned int HdStRenderParam::GetGeomSubsetDrawItemsVersion() const { // Can use relaxed ordering because render passes are expected to // only read the value, and that too in a single threaded fashion. return _geomSubsetDrawItemsVersion.load(std::memory_order_relaxed); } static bool _IsMaterialTagCounted(const TfToken &materialTag) { return !materialTag.IsEmpty(); } bool HdStRenderParam::HasMaterialTag(const TfToken &materialTag) const { if (!_IsMaterialTagCounted(materialTag)) { return true; } std::shared_lock<std::shared_timed_mutex> lock(_materialTagToCountMutex); const auto it = _materialTagToCount.find(materialTag); if (it == _materialTagToCount.end()) { return false; } return it->second > 0; } void HdStRenderParam::_AdjustMaterialTagCount(const TfToken &materialTag, const int i) { if (!_IsMaterialTagCounted(materialTag)) { return; } { // Map already had entry for materialTag. // Shared lock is sufficient because the entry's integer is atomic. std::shared_lock<std::shared_timed_mutex> l(_materialTagToCountMutex); const auto it = _materialTagToCount.find(materialTag); if (it != _materialTagToCount.end()) { it->second += i; return; } } { // Map had no entry for materialTag. std::unique_lock<std::shared_timed_mutex> l(_materialTagToCountMutex); _materialTagToCount[materialTag] += i; } } void HdStRenderParam::IncreaseMaterialTagCount(const TfToken &materialTag) { _AdjustMaterialTagCount(materialTag, +1); } void HdStRenderParam::DecreaseMaterialTagCount(const TfToken &materialTag) { _AdjustMaterialTagCount(materialTag, -1); // Note that it is difficult to remove zero entries from the map here during // multi-threaded access. // It is probably not worth implementing a garbage collection for this map. } PXR_NAMESPACE_CLOSE_SCOPE
1,469
4,071
<gh_stars>1000+ #include "core/ps_queue_hub/queue_work_item.hh" #include "service/network_context.hh" namespace ps { namespace network { SessionContext* SeastarWorkItem::GetSessionContext() const { return mNetworkContext->GetSessionOfId(mRemoteId); } } // namespace } // namespace
99
354
package com.steve.creact.powerfuladapter.presentation.viewholder; import android.view.View; import com.steve.creact.annotation.DataBean; import com.steve.creact.library.viewholder.BaseRecyclerViewHolder; import com.steve.creact.powerfuladapter.R; /** * @author:YJJ * @date:2016/3/30 * @email:<EMAIL> */ @DataBean(beanName = "CategoryBean",data = ICategory.class) public class CategoryViewHolder extends BaseRecyclerViewHolder<ICategory> { public static final int LAYOUT_ID = R.layout.item_book_catagory; public CategoryViewHolder(View itemView) { super(itemView); } @Override public void setData(ICategory category) { if (category == null) return; setText(R.id.book_category,category.getName()); } }
297
32,467
/* Generated from http://icu-project.org/apiref/icu4c/uchar_8h.html#ae40d616419e74ecc7c80a9febab03199 */ UPROPERTY(ALPHABETIC) UPROPERTY(BINARY_START) UPROPERTY(ASCII_HEX_DIGIT) UPROPERTY(BIDI_CONTROL) UPROPERTY(BIDI_MIRRORED) UPROPERTY(DASH) UPROPERTY(DEFAULT_IGNORABLE_CODE_POINT) UPROPERTY(DEPRECATED) UPROPERTY(DIACRITIC) UPROPERTY(EXTENDER) UPROPERTY(FULL_COMPOSITION_EXCLUSION) UPROPERTY(GRAPHEME_BASE) UPROPERTY(GRAPHEME_EXTEND) UPROPERTY(GRAPHEME_LINK) UPROPERTY(HEX_DIGIT) UPROPERTY(HYPHEN) UPROPERTY(ID_CONTINUE) UPROPERTY(ID_START) UPROPERTY(IDEOGRAPHIC) UPROPERTY(IDS_BINARY_OPERATOR) UPROPERTY(IDS_TRINARY_OPERATOR) UPROPERTY(JOIN_CONTROL) UPROPERTY(LOGICAL_ORDER_EXCEPTION) UPROPERTY(LOWERCASE) UPROPERTY(MATH) UPROPERTY(NONCHARACTER_CODE_POINT) UPROPERTY(QUOTATION_MARK) UPROPERTY(RADICAL) UPROPERTY(SOFT_DOTTED) UPROPERTY(TERMINAL_PUNCTUATION) UPROPERTY(UNIFIED_IDEOGRAPH) UPROPERTY(UPPERCASE) UPROPERTY(WHITE_SPACE) UPROPERTY(XID_CONTINUE) UPROPERTY(XID_START) UPROPERTY(CASE_SENSITIVE) UPROPERTY(S_TERM) UPROPERTY(VARIATION_SELECTOR) UPROPERTY(NFD_INERT) UPROPERTY(NFKD_INERT) UPROPERTY(NFC_INERT) UPROPERTY(NFKC_INERT) UPROPERTY(SEGMENT_STARTER) UPROPERTY(PATTERN_SYNTAX) UPROPERTY(PATTERN_WHITE_SPACE) UPROPERTY(POSIX_ALNUM) UPROPERTY(POSIX_BLANK) UPROPERTY(POSIX_GRAPH) UPROPERTY(POSIX_PRINT) UPROPERTY(POSIX_XDIGIT) UPROPERTY(CASED) UPROPERTY(CASE_IGNORABLE) UPROPERTY(CHANGES_WHEN_LOWERCASED) UPROPERTY(CHANGES_WHEN_UPPERCASED) UPROPERTY(CHANGES_WHEN_TITLECASED) UPROPERTY(CHANGES_WHEN_CASEFOLDED) UPROPERTY(CHANGES_WHEN_CASEMAPPED) UPROPERTY(CHANGES_WHEN_NFKC_CASEFOLDED) UPROPERTY(BINARY_LIMIT) UPROPERTY(BIDI_CLASS) UPROPERTY(INT_START) UPROPERTY(BLOCK) UPROPERTY(CANONICAL_COMBINING_CLASS) UPROPERTY(DECOMPOSITION_TYPE) UPROPERTY(EAST_ASIAN_WIDTH) UPROPERTY(GENERAL_CATEGORY) UPROPERTY(JOINING_GROUP) UPROPERTY(JOINING_TYPE) UPROPERTY(LINE_BREAK) UPROPERTY(NUMERIC_TYPE) UPROPERTY(SCRIPT) UPROPERTY(HANGUL_SYLLABLE_TYPE) UPROPERTY(NFD_QUICK_CHECK) UPROPERTY(NFKD_QUICK_CHECK) UPROPERTY(NFC_QUICK_CHECK) UPROPERTY(NFKC_QUICK_CHECK) UPROPERTY(LEAD_CANONICAL_COMBINING_CLASS) UPROPERTY(TRAIL_CANONICAL_COMBINING_CLASS) UPROPERTY(GRAPHEME_CLUSTER_BREAK) UPROPERTY(SENTENCE_BREAK) UPROPERTY(WORD_BREAK) #if U_ICU_VERSION_MAJOR_NUM >= 52 UPROPERTY(BIDI_PAIRED_BRACKET_TYPE) #endif /* ICU >= 52 */ UPROPERTY(INT_LIMIT) UPROPERTY(GENERAL_CATEGORY_MASK) UPROPERTY(MASK_START) UPROPERTY(MASK_LIMIT) UPROPERTY(NUMERIC_VALUE) UPROPERTY(DOUBLE_START) UPROPERTY(DOUBLE_LIMIT) UPROPERTY(AGE) UPROPERTY(STRING_START) UPROPERTY(BIDI_MIRRORING_GLYPH) UPROPERTY(CASE_FOLDING) UPROPERTY(ISO_COMMENT) UPROPERTY(LOWERCASE_MAPPING) UPROPERTY(NAME) UPROPERTY(SIMPLE_CASE_FOLDING) UPROPERTY(SIMPLE_LOWERCASE_MAPPING) UPROPERTY(SIMPLE_TITLECASE_MAPPING) UPROPERTY(SIMPLE_UPPERCASE_MAPPING) UPROPERTY(TITLECASE_MAPPING) UPROPERTY(UNICODE_1_NAME) UPROPERTY(UPPERCASE_MAPPING) #if U_ICU_VERSION_MAJOR_NUM >= 52 UPROPERTY(BIDI_PAIRED_BRACKET) #endif /* ICU >= 52 */ UPROPERTY(STRING_LIMIT) UPROPERTY(SCRIPT_EXTENSIONS) UPROPERTY(OTHER_PROPERTY_START) UPROPERTY(OTHER_PROPERTY_LIMIT) UPROPERTY(INVALID_CODE)
1,609
703
#pragma once /// \brief Base class for serialization contexts. A serialization context can be used to add high level logic to serialization, e.g. /// de-duplicating objects. /// /// Typically a context is created before any serialization happens and can then be accessed anywhere through the GetContext method. template <typename Derived> class ezSerializationContext { EZ_DISALLOW_COPY_AND_ASSIGN(ezSerializationContext); public: ezSerializationContext() { Derived::SetContext(this); } ~ezSerializationContext() { Derived::SetContext(nullptr); } /// \brief Set the context as active which means it can be accessed via GetContext in serialization methods. /// /// It can be useful to manually set a context as active if a serialization process is spread across multiple scopes /// and other serialization can happen in between. void SetActive(bool bActive) { Derived::SetContext(bActive ? this : nullptr); } }; /// \brief Declares the necessary functions to access a serialization context #define EZ_DECLARE_SERIALIZATION_CONTEXT(type) \ public: \ static type* GetContext(); \ \ protected: \ friend class ezSerializationContext<type>; \ static void SetContext(ezSerializationContext* pContext); /// \brief Implements the necessary functions to access a serialization context through GetContext. #define EZ_IMPLEMENT_SERIALIZATION_CONTEXT(type) \ thread_local type* EZ_CONCAT(s_pActiveContext, type); \ type* type::GetContext() { return EZ_CONCAT(s_pActiveContext, type); } \ void type::SetContext(ezSerializationContext* pContext) \ { \ EZ_ASSERT_DEV(pContext == nullptr || EZ_CONCAT(s_pActiveContext, type) == nullptr, "Only one context can be active at a time."); \ EZ_CONCAT(s_pActiveContext, type) = static_cast<type*>(pContext); \ }
1,164
2,333
// // UIImage+Blur.h // IOS-Categories (https://github.com/shaojiankui/iOS-Categories) // // Created by Jakey on 15/6/5. // Copyright (c) 2015年 www.skyfox.org. All rights reserved. // #import <UIKit/UIKit.h> FOUNDATION_EXPORT double ImageEffectsVersionNumber; FOUNDATION_EXPORT const unsigned char ImageEffectsVersionString[]; @interface UIImage (Blur) - (UIImage *)lightImage; - (UIImage *)extraLightImage; - (UIImage *)darkImage; - (UIImage *)tintedImageWithColor:(UIColor *)tintColor; - (UIImage *)blurredImageWithRadius:(CGFloat)blurRadius; - (UIImage *)blurredImageWithSize:(CGSize)blurSize; - (UIImage *)blurredImageWithSize:(CGSize)blurSize tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage; @end
334
886
/* * Copyright 2018 flow.ci * * 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.flowci.util; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.CollectionNode; import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.NodeTuple; import org.yaml.snakeyaml.nodes.SequenceNode; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; /** * @author yang */ public class YamlOrderedSkipEmptyRepresenter extends Representer { private final PropertySorter sorter = new PropertySorter(); private class PropertySorter implements Comparator<Property> { @Override public int compare(Property o1, Property o2) { Integer index1 = order.get(o1.getName()); Integer index2 = order.get(o2.getName()); if (Objects.isNull(index1) || Objects.isNull(index2)) { return 0; } return index1.compareTo(index2); } } private final Map<String, Integer> order; public YamlOrderedSkipEmptyRepresenter(Map<String, Integer> fieldsOrder) { this.order = fieldsOrder; } @Override protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { List<NodeTuple> value = new ArrayList<>(properties.size()); Tag tag; Tag customTag = classTags.get(javaBean.getClass()); tag = customTag != null ? customTag : new Tag(javaBean.getClass()); MappingNode node = new MappingNode(tag, value, FlowStyle.BLOCK); representedObjects.put(javaBean, node); List<Property> orderProperties = new ArrayList<>(properties); orderProperties.sort(sorter); for (Property property : orderProperties) { Object memberValue = property.get(javaBean); Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass()); NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag); if (tuple == null) { continue; } value.add(tuple); } return node; } @Override protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); org.yaml.snakeyaml.nodes.Node valueNode = tuple.getValueNode(); // skip 'null' values if (Tag.NULL.equals(valueNode.getTag())) { return null; } if (valueNode instanceof CollectionNode) { // skip empty lists if (Tag.SEQ.equals(valueNode.getTag())) { SequenceNode seq = (SequenceNode) valueNode; if (seq.getValue().isEmpty()) { return null; } } // skip empty maps if (Tag.MAP.equals(valueNode.getTag())) { MappingNode seq = (MappingNode) valueNode; if (seq.getValue().isEmpty()) { return null; } } } return tuple; } }
1,778
944
<gh_stars>100-1000 import pytest from tests.utils import PYTEST_6 pytest_plugins = "pytester" def pytest_generate_tests(metafunc): if "pytest_params" in metafunc.fixturenames: if PYTEST_6: parametrizations = [ pytest.param([], id="no-import-mode"), pytest.param(["--import-mode=prepend"], id="--import-mode=prepend"), pytest.param(["--import-mode=append"], id="--import-mode=append"), pytest.param(["--import-mode=importlib"], id="--import-mode=importlib"), ] else: parametrizations = [[]] metafunc.parametrize( "pytest_params", parametrizations, )
358
335
{ "word": "Minister", "definitions": [ "(in certain countries) a head of a government department.", "A member of the clergy, especially in the Presbyterian and Nonconformist Churches.", "The superior of some religious orders.", "A diplomatic agent, usually ranking below an ambassador, representing a state or sovereign in a foreign country.", "A person or thing used to achieve or convey something." ], "parts-of-speech": "Noun" }
154
14,668
// Copyright 2019 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 CHROME_BROWSER_ANDROID_BACKGROUND_TASK_SCHEDULER_CHROME_BACKGROUND_TASK_FACTORY_H_ #define CHROME_BROWSER_ANDROID_BACKGROUND_TASK_SCHEDULER_CHROME_BACKGROUND_TASK_FACTORY_H_ #include "components/background_task_scheduler/background_task.h" // Given a task id, creates the corresponding BackgroundTask. // Also provides methods to initialize the Java factory from native. class ChromeBackgroundTaskFactory { public: // Disable default constructor. ChromeBackgroundTaskFactory() = delete; // Disable copy (and move) semantics. ChromeBackgroundTaskFactory(const ChromeBackgroundTaskFactory&) = delete; ChromeBackgroundTaskFactory& operator=(const ChromeBackgroundTaskFactory&) = delete; ~ChromeBackgroundTaskFactory(); // Sets the ChromeBackgroundTaskFactory in Java. The C++ code // does not call ChromeApplication (java initializations), so this setting was // necessary for associating task ids with corresponding BackgroundTask // classes for BackgroundTaskScheduler. This method can be used to set the // default factory class to ChromeBackgroundTaskFactory. static void SetAsDefault(); // Creates and returns a BackgroundTask for the given |task_id|. static std::unique_ptr<background_task::BackgroundTask> GetNativeBackgroundTaskFromTaskId(int task_id); }; #endif // CHROME_BROWSER_ANDROID_BACKGROUND_TASK_SCHEDULER_CHROME_BACKGROUND_TASK_FACTORY_H_
452
382
<gh_stars>100-1000 package top.defaults.gradientdrawabletuner.db; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Parcel; import android.os.Parcelable; import android.util.SparseIntArray; import top.defaults.gradientdrawabletuner.R; import static top.defaults.drawabletoolbox.DrawableProperties.RADIUS_TYPE_PIXELS; public class DrawablePropertiesInRoom implements Parcelable { public int shape = GradientDrawable.RECTANGLE; // all dimens are in pixels public int innerRadius = -1; // when innerRadius == -1, innerRadiusRatio become effective public float innerRadiusRatio = 9f; public int thickness = -1; // when thickness == -1, thicknessRatio become effective public float thicknessRatio = 3f; private int cornerRadius = 0; // This is overridden for each corner by the following 4 properties public DrawablePropertiesInRoom() {} public DrawablePropertiesInRoom copy() { Parcel parcel = Parcel.obtain(); writeToParcel(parcel, 0); parcel.setDataPosition(0); DrawablePropertiesInRoom properties = DrawablePropertiesInRoom.CREATOR.createFromParcel(parcel); parcel.recycle(); return properties; } private DrawablePropertiesInRoom(Parcel in) { shape = in.readInt(); innerRadius = in.readInt(); innerRadiusRatio = in.readFloat(); thickness = in.readInt(); thicknessRatio = in.readFloat(); cornerRadius = in.readInt(); topLeftRadius = in.readInt(); topRightRadius = in.readInt(); bottomLeftRadius = in.readInt(); bottomRightRadius = in.readInt(); type = in.readInt(); useGradient = in.readByte() != 0; useCenterColor = in.readByte() != 0; angle = in.readInt(); centerX = in.readFloat(); centerY = in.readFloat(); startColor = in.readInt(); centerColor = in.readInt(); endColor = in.readInt(); gradientRadiusType = in.readInt(); gradientRadius = in.readFloat(); width = in.readInt(); height = in.readInt(); solidColor = in.readInt(); strokeWidth = in.readInt(); strokeColor = in.readInt(); dashWidth = in.readInt(); dashGap = in.readInt(); } public static final Creator<DrawablePropertiesInRoom> CREATOR = new Creator<DrawablePropertiesInRoom>() { @Override public DrawablePropertiesInRoom createFromParcel(Parcel in) { return new DrawablePropertiesInRoom(in); } @Override public DrawablePropertiesInRoom[] newArray(int size) { return new DrawablePropertiesInRoom[size]; } }; public int getCornerRadius() { return cornerRadius; } public void setCornerRadius(Integer cornerRadius) { if (cornerRadius == null) cornerRadius = 0; this.cornerRadius = cornerRadius; this.topLeftRadius = cornerRadius; this.topRightRadius = cornerRadius; this.bottomLeftRadius = cornerRadius; this.bottomRightRadius = cornerRadius; } public int topLeftRadius = 0; public int topRightRadius = 0; public int bottomLeftRadius = 0; public int bottomRightRadius = 0; public int type = GradientDrawable.RADIAL_GRADIENT; public boolean useGradient = false; public boolean useCenterColor = true; public int angle = 0; public float centerX = 0.5f; public float centerY = 0.5f; public int startColor = 0xFF2DCFCA; public int centerColor = Color.TRANSPARENT; public int endColor = 0x7FFFFFFF; public int gradientRadiusType = RADIUS_TYPE_PIXELS; public float gradientRadius = 200; public int width = 400; public int height = 400; public int solidColor = 0xFF2DCFCA; public int strokeWidth = 0; public int strokeColor = 0xFF24A5A1; public int dashWidth = 0; public int dashGap = 0; public boolean shouldEnableGradient() { return useGradient && shape != GradientDrawable.LINE; } public boolean shouldEnableCenterColor() { return useCenterColor && shouldEnableGradient(); } public boolean shouldEnableGradientRadius() { return type == GradientDrawable.RADIAL_GRADIENT && shouldEnableGradient(); } private static SparseIntArray shapeToIdMap = new SparseIntArray(); static { shapeToIdMap.put(GradientDrawable.RECTANGLE, R.id.rectangle); shapeToIdMap.put(GradientDrawable.OVAL, R.id.oval); shapeToIdMap.put(GradientDrawable.LINE, R.id.line); shapeToIdMap.put(GradientDrawable.RING, R.id.ring); } private static SparseIntArray idToShapeMap = new SparseIntArray(); static { idToShapeMap.put(R.id.rectangle, GradientDrawable.RECTANGLE); idToShapeMap.put(R.id.oval, GradientDrawable.OVAL); idToShapeMap.put(R.id.line, GradientDrawable.LINE); idToShapeMap.put(R.id.ring, GradientDrawable.RING); } public int getShapeId() { return shapeToIdMap.get(shape); } public void setShapeId(Integer id) { shape = idToShapeMap.get(id); } private static SparseIntArray typeToIdMap = new SparseIntArray(); static { typeToIdMap.put(GradientDrawable.LINEAR_GRADIENT, R.id.linear_gradient); typeToIdMap.put(GradientDrawable.RADIAL_GRADIENT, R.id.radial_gradient); typeToIdMap.put(GradientDrawable.SWEEP_GRADIENT, R.id.sweep_gradient); } private static SparseIntArray idToTypeMap = new SparseIntArray(); static { idToTypeMap.put(R.id.linear_gradient, GradientDrawable.LINEAR_GRADIENT); idToTypeMap.put(R.id.radial_gradient, GradientDrawable.RADIAL_GRADIENT); idToTypeMap.put(R.id.sweep_gradient, GradientDrawable.SWEEP_GRADIENT); } public int getTypeId() { return typeToIdMap.get(type); } public void setTypeId(Integer id) { type = idToTypeMap.get(id); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(shape); dest.writeInt(innerRadius); dest.writeFloat(innerRadiusRatio); dest.writeInt(thickness); dest.writeFloat(thicknessRatio); dest.writeInt(cornerRadius); dest.writeInt(topLeftRadius); dest.writeInt(topRightRadius); dest.writeInt(bottomLeftRadius); dest.writeInt(bottomRightRadius); dest.writeInt(type); dest.writeByte((byte) (useGradient ? 1 : 0)); dest.writeByte((byte) (useCenterColor ? 1 : 0)); dest.writeInt(angle); dest.writeFloat(centerX); dest.writeFloat(centerY); dest.writeInt(startColor); dest.writeInt(centerColor); dest.writeInt(endColor); dest.writeInt(gradientRadiusType); dest.writeFloat(gradientRadius); dest.writeInt(width); dest.writeInt(height); dest.writeInt(solidColor); dest.writeInt(strokeWidth); dest.writeInt(strokeColor); dest.writeInt(dashWidth); dest.writeInt(dashGap); } }
2,941
11,062
<reponame>chayward/libui<filename>_abort/windowevents/ui.h // uiWindowSetTitle _UI_EXTERN void uiWindowPosition(uiWindow *w, int *x, int *y); _UI_EXTERN void uiWindowSetPosition(uiWindow *w, int x, int y); _UI_EXTERN void uiWindowCenter(uiWindow *w); _UI_EXTERN void uiWindowOnPositionChanged(uiWindow *w, void (*f)(uiWindow *, void *), void *data); // uiWindowContentSize
139
1,011
<filename>utils/media_urls.py #!/usr/bin/env python """ Print out the URLs of images uploaded to Twitter in a tweet json stream. Useful for piping to wget or curl to mass download. In Bash: % wget $(./utils/image_urls.py tweets.jsonl) """ from __future__ import print_function import json import fileinput for line in fileinput.input(openhook=fileinput.hook_encoded("utf8")): tweet = json.loads(line) id = tweet["id_str"] if "media" in tweet["entities"]: for media in tweet["entities"]["media"]: if media["type"] == "photo": print(id, media["media_url_https"]) if "extended_entities" in tweet and "media" in tweet["extended_entities"]: for media in tweet["extended_entities"]["media"]: if media["type"] == "animated_gif": print(id, media["media_url_https"]) if "video_info" in media: for v in media["video_info"]["variants"]: print(id, v["url"])
417
787
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ <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. * * Author: * <NAME> (<EMAIL>) */ package io.jenetics.xml; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import io.jenetics.IntegerChromosome; import io.jenetics.IntegerGene; /** * @author <a href="mailto:<EMAIL>"><NAME></a> * @version 4.1 * @since 4.1 */ public class XMLStreamWriterTest { static void write(final IntegerChromosome ch, final XMLStreamWriter xml) throws XMLStreamException { xml.writeStartElement("int-chromosome"); xml.writeAttribute("length", Integer.toString(ch.length())); xml.writeStartElement("min"); xml.writeCharacters(ch.min().toString()); xml.writeEndElement(); xml.writeStartElement("max"); xml.writeCharacters(ch.max().toString()); xml.writeEndElement(); xml.writeStartElement("alleles"); for (IntegerGene gene : ch) { xml.writeStartElement("allele"); xml.writeCharacters(gene.allele().toString()); xml.writeEndElement(); } xml.writeEndElement(); xml.writeEndElement(); } public static void main(final String[] args) throws Exception { final IntegerChromosome ch = IntegerChromosome.of( Integer.MIN_VALUE, Integer.MAX_VALUE, 3 ); final XMLOutputFactory factory = XMLOutputFactory.newFactory(); final XMLStreamWriter xml = factory.createXMLStreamWriter(System.out); try { write(ch, xml); } finally { xml.close(); } } /* <int-chromosome length="3"> <min>-2147483648</min> <max>2147483647</max> <alleles> <allele>-1878762439</allele> <allele>-957346595</allele> <allele>-88668137</allele> </alleles> </int-chromosome> */ }
812
9,680
<gh_stars>1000+ import os.path from pathlib import Path from nni.experiment.config import ExperimentConfig, AlgorithmConfig, RemoteConfig, RemoteMachineConfig ## minimal config ## minimal_json = { 'searchSpace': {'a': 1}, 'trialCommand': 'python main.py', 'trialConcurrency': 2, 'tuner': { 'name': 'random', }, 'trainingService': { 'platform': 'remote', 'machine_list': [ { 'host': '1.2.3.4', 'user': 'test_user', 'password': '<PASSWORD>', }, ], }, } minimal_class = ExperimentConfig( search_space = {'a': 1}, trial_command = 'python main.py', trial_concurrency = 2, tuner = AlgorithmConfig( name = 'random', ), training_service = RemoteConfig( machine_list = [ RemoteMachineConfig( host = '1.2.3.4', user = 'test_user', password = '<PASSWORD>', ), ], ), ) minimal_canon = { 'searchSpace': {'a': 1}, 'trialCommand': 'python main.py', 'trialCodeDirectory': os.path.realpath('.'), 'trialConcurrency': 2, 'useAnnotation': False, 'debug': False, 'logLevel': 'info', 'experimentWorkingDirectory': str(Path.home() / 'nni-experiments'), 'tuner': { 'name': 'random', }, 'trainingService': { 'platform': 'remote', 'trialCommand': 'python main.py', 'trialCodeDirectory': os.path.realpath('.'), 'debug': False, 'machineList': [ { 'host': '1.2.3.4', 'port': 22, 'user': 'test_user', 'password': '<PASSWORD>', 'useActiveGpu': False, 'maxTrialNumberPerGpu': 1, } ], 'reuseMode': True, } } ## detailed config ## detailed_json = { 'searchSpace': {'a': 1}, 'trialCommand': 'python main.py', 'trialConcurrency': 2, 'trialGpuNumber': 1, 'nni_manager_ip': '1.2.3.0', 'tuner': { 'name': 'random', }, 'trainingService': { 'platform': 'remote', 'machine_list': [ { 'host': '1.2.3.4', 'user': 'test_user', 'password': '<PASSWORD>', }, { 'host': '1.2.3.5', 'user': 'test_user_2', 'password': '<PASSWORD>', 'use_active_gpu': True, 'max_trial_number_per_gpu': 2, 'gpu_indices': '0,1', 'python_path': '~/path', # don't do this in actual experiment }, ], }, } detailed_canon = { 'searchSpace': {'a': 1}, 'trialCommand': 'python main.py', 'trialCodeDirectory': os.path.realpath('.'), 'trialConcurrency': 2, 'trialGpuNumber': 1, 'nniManagerIp': '1.2.3.0', 'useAnnotation': False, 'debug': False, 'logLevel': 'info', 'experimentWorkingDirectory': str(Path.home() / 'nni-experiments'), 'tuner': {'name': 'random'}, 'trainingService': { 'platform': 'remote', 'trialCommand': 'python main.py', 'trialCodeDirectory': os.path.realpath('.'), 'trialGpuNumber': 1, 'nniManagerIp': '1.2.3.0', 'debug': False, 'machineList': [ { 'host': '1.2.3.4', 'port': 22, 'user': 'test_user', 'password': '<PASSWORD>', 'useActiveGpu': False, 'maxTrialNumberPerGpu': 1 }, { 'host': '1.2.3.5', 'port': 22, 'user': 'test_user_2', 'password': '<PASSWORD>', 'useActiveGpu': True, 'maxTrialNumberPerGpu': 2, 'gpuIndices': [0, 1], 'pythonPath': '~/path' } ], 'reuseMode': True, } } ## test function ## def test_remote(): config = ExperimentConfig(**minimal_json) assert config.json() == minimal_canon assert minimal_class.json() == minimal_canon config = ExperimentConfig(**detailed_json) assert config.json() == detailed_canon if __name__ == '__main__': test_remote()
2,276
1,874
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: authority_keys.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x14\x61uthority_keys.proto\x12!extensions.api.cast_channel.proto\"\x83\x01\n\rAuthorityKeys\x12\x42\n\x04keys\x18\x01 \x03(\x0b\x32\x34.extensions.api.cast_channel.proto.AuthorityKeys.Key\x1a.\n\x03Key\x12\x13\n\x0b\x66ingerprint\x18\x01 \x02(\x0c\x12\x12\n\npublic_key\x18\x02 \x02(\x0c\x42\x02H\x03') _AUTHORITYKEYS = DESCRIPTOR.message_types_by_name['AuthorityKeys'] _AUTHORITYKEYS_KEY = _AUTHORITYKEYS.nested_types_by_name['Key'] AuthorityKeys = _reflection.GeneratedProtocolMessageType('AuthorityKeys', (_message.Message,), { 'Key' : _reflection.GeneratedProtocolMessageType('Key', (_message.Message,), { 'DESCRIPTOR' : _AUTHORITYKEYS_KEY, '__module__' : 'authority_keys_pb2' # @@protoc_insertion_point(class_scope:extensions.api.cast_channel.proto.AuthorityKeys.Key) }) , 'DESCRIPTOR' : _AUTHORITYKEYS, '__module__' : 'authority_keys_pb2' # @@protoc_insertion_point(class_scope:extensions.api.cast_channel.proto.AuthorityKeys) }) _sym_db.RegisterMessage(AuthorityKeys) _sym_db.RegisterMessage(AuthorityKeys.Key) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'H\003' _AUTHORITYKEYS._serialized_start=60 _AUTHORITYKEYS._serialized_end=191 _AUTHORITYKEYS_KEY._serialized_start=145 _AUTHORITYKEYS_KEY._serialized_end=191 # @@protoc_insertion_point(module_scope)
762
1,230
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import with_statement import sys import os sys.path.insert(0, os.path.abspath('..')) from clint.textui import puts, indent lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' if __name__ == '__main__': puts('This is an example of text that is not indented. Awesome, eh?') puts('Lets quote some text.') with indent(4, quote='.'): puts('This is indented text.') with indent(3, quote=' >'): puts('This is quoted text.') puts(lorem) puts("And, we're back to the previous index level. That was easy.") with indent(12, quote=' |'): puts('This is massively indented text.') puts('This is massively indented text again.') puts("Now I'll show you how to negatively indent.") with indent(-5, quote='!! '): puts('NOTE: INCEPTION!') puts('And back to where we were.') puts('Back to level 1.') puts('Back to normal.')
502
692
#define boxbod_N 6 #define boxbod_P 2 #define boxbod_NTRIES 1 static double boxbod_x0[boxbod_P] = { 100.0, 0.75 }; static double boxbod_epsrel = 1.0e-7; static double boxbod_sigma[boxbod_P] = { 1.2354515176E+01, 1.0455993237E-01 }; static double boxbod_X[boxbod_N] = { 1.0, 2.0, 3.0, 5.0, 7.0, 10.0 }; static double boxbod_F[boxbod_N] = { 109.0, 149.0, 149.0, 191.0, 213.0, 224.0 }; static void boxbod_checksol(const double x[], const double sumsq, const double epsrel, const char *sname, const char *pname) { size_t i; const double sumsq_exact = 1.1680088766E+03; const double boxbod_x[boxbod_P] = { 2.1380940889E+02, 5.4723748542E-01 }; gsl_test_rel(sumsq, sumsq_exact, epsrel, "%s/%s sumsq", sname, pname); for (i = 0; i < boxbod_P; ++i) { gsl_test_rel(x[i], boxbod_x[i], epsrel, "%s/%s i=%zu", sname, pname, i); } } static int boxbod_f (const gsl_vector * x, void *params, gsl_vector * f) { double b[boxbod_P]; size_t i; for (i = 0; i < boxbod_P; i++) { b[i] = gsl_vector_get(x, i); } for (i = 0; i < boxbod_N; i++) { double xi = boxbod_X[i]; double yi; yi = b[0] * (1.0 - exp(-b[1] * xi)); gsl_vector_set (f, i, yi - boxbod_F[i]); } return GSL_SUCCESS; } static int boxbod_df (const gsl_vector * x, void *params, gsl_matrix * df) { double b[boxbod_P]; size_t i; for (i = 0; i < boxbod_P; i++) { b[i] = gsl_vector_get(x, i); } for (i = 0; i < boxbod_N; i++) { double xi = boxbod_X[i]; double term = exp(-b[1] * xi); gsl_matrix_set (df, i, 0, 1.0 - term); gsl_matrix_set (df, i, 1, b[0] * term * xi); } return GSL_SUCCESS; } static gsl_multifit_function_fdf boxbod_func = { &boxbod_f, &boxbod_df, NULL, boxbod_N, boxbod_P, NULL, 0, 0 }; static test_fdf_problem boxbod_problem = { "nist-boxbod", boxbod_x0, boxbod_sigma, &boxbod_epsrel, boxbod_NTRIES, &boxbod_checksol, &boxbod_func };
1,193
835
// THIS FILE IS AUTO-GENERATED. DO NOT EDIT package ai.verta.modeldb.versioning.autogenerated._public.modeldb.versioning.model; import ai.verta.modeldb.common.exceptions.ModelDBException; import ai.verta.modeldb.versioning.*; import ai.verta.modeldb.versioning.blob.diff.*; import ai.verta.modeldb.versioning.blob.diff.Function3; import ai.verta.modeldb.versioning.blob.visitors.Visitor; import com.pholser.junit.quickcheck.generator.*; import com.pholser.junit.quickcheck.random.*; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.function.Function; import org.apache.commons.codec.binary.Hex; public class AutogenContinuousHyperparameterSetConfigBlob implements ProtoType { private AutogenHyperparameterValuesConfigBlob IntervalBegin; private AutogenHyperparameterValuesConfigBlob IntervalEnd; private AutogenHyperparameterValuesConfigBlob IntervalStep; public AutogenContinuousHyperparameterSetConfigBlob() { this.IntervalBegin = null; this.IntervalEnd = null; this.IntervalStep = null; } public Boolean isEmpty() { if (this.IntervalBegin != null && !this.IntervalBegin.equals(null)) { return false; } if (this.IntervalEnd != null && !this.IntervalEnd.equals(null)) { return false; } if (this.IntervalStep != null && !this.IntervalStep.equals(null)) { return false; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{\"class\": \"AutogenContinuousHyperparameterSetConfigBlob\", \"fields\": {"); boolean first = true; if (this.IntervalBegin != null && !this.IntervalBegin.equals(null)) { if (!first) sb.append(", "); sb.append("\"IntervalBegin\": " + IntervalBegin); first = false; } if (this.IntervalEnd != null && !this.IntervalEnd.equals(null)) { if (!first) sb.append(", "); sb.append("\"IntervalEnd\": " + IntervalEnd); first = false; } if (this.IntervalStep != null && !this.IntervalStep.equals(null)) { if (!first) sb.append(", "); sb.append("\"IntervalStep\": " + IntervalStep); first = false; } sb.append("}}"); return sb.toString(); } // TODO: actually hash public String getSHA() throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(this.toString().getBytes(StandardCharsets.UTF_8)); return new String(new Hex().encode(hash)); } @Override public int hashCode() { return Objects.hash(this.toString()); } // TODO: not consider order on lists @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (!(o instanceof AutogenContinuousHyperparameterSetConfigBlob)) return false; AutogenContinuousHyperparameterSetConfigBlob other = (AutogenContinuousHyperparameterSetConfigBlob) o; { Function3< AutogenHyperparameterValuesConfigBlob, AutogenHyperparameterValuesConfigBlob, Boolean> f = (x, y) -> x.equals(y); if (this.IntervalBegin != null || other.IntervalBegin != null) { if (this.IntervalBegin == null && other.IntervalBegin != null) return false; if (this.IntervalBegin != null && other.IntervalBegin == null) return false; if (!f.apply(this.IntervalBegin, other.IntervalBegin)) return false; } } { Function3< AutogenHyperparameterValuesConfigBlob, AutogenHyperparameterValuesConfigBlob, Boolean> f = (x, y) -> x.equals(y); if (this.IntervalEnd != null || other.IntervalEnd != null) { if (this.IntervalEnd == null && other.IntervalEnd != null) return false; if (this.IntervalEnd != null && other.IntervalEnd == null) return false; if (!f.apply(this.IntervalEnd, other.IntervalEnd)) return false; } } { Function3< AutogenHyperparameterValuesConfigBlob, AutogenHyperparameterValuesConfigBlob, Boolean> f = (x, y) -> x.equals(y); if (this.IntervalStep != null || other.IntervalStep != null) { if (this.IntervalStep == null && other.IntervalStep != null) return false; if (this.IntervalStep != null && other.IntervalStep == null) return false; if (!f.apply(this.IntervalStep, other.IntervalStep)) return false; } } return true; } public AutogenContinuousHyperparameterSetConfigBlob setIntervalBegin( AutogenHyperparameterValuesConfigBlob value) { this.IntervalBegin = Utils.removeEmpty(value); return this; } public AutogenHyperparameterValuesConfigBlob getIntervalBegin() { return this.IntervalBegin; } public AutogenContinuousHyperparameterSetConfigBlob setIntervalEnd( AutogenHyperparameterValuesConfigBlob value) { this.IntervalEnd = Utils.removeEmpty(value); return this; } public AutogenHyperparameterValuesConfigBlob getIntervalEnd() { return this.IntervalEnd; } public AutogenContinuousHyperparameterSetConfigBlob setIntervalStep( AutogenHyperparameterValuesConfigBlob value) { this.IntervalStep = Utils.removeEmpty(value); return this; } public AutogenHyperparameterValuesConfigBlob getIntervalStep() { return this.IntervalStep; } public static AutogenContinuousHyperparameterSetConfigBlob fromProto( ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob blob) { if (blob == null) { return null; } AutogenContinuousHyperparameterSetConfigBlob obj = new AutogenContinuousHyperparameterSetConfigBlob(); { Function< ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob, AutogenHyperparameterValuesConfigBlob> f = x -> AutogenHyperparameterValuesConfigBlob.fromProto(blob.getIntervalBegin()); obj.setIntervalBegin(f.apply(blob)); } { Function< ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob, AutogenHyperparameterValuesConfigBlob> f = x -> AutogenHyperparameterValuesConfigBlob.fromProto(blob.getIntervalEnd()); obj.setIntervalEnd(f.apply(blob)); } { Function< ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob, AutogenHyperparameterValuesConfigBlob> f = x -> AutogenHyperparameterValuesConfigBlob.fromProto(blob.getIntervalStep()); obj.setIntervalStep(f.apply(blob)); } return obj; } public ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob.Builder toProto() { ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob.Builder builder = ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob.newBuilder(); { if (this.IntervalBegin != null && !this.IntervalBegin.equals(null)) { Function<ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob.Builder, Void> f = x -> { builder.setIntervalBegin(this.IntervalBegin.toProto()); return null; }; f.apply(builder); } } { if (this.IntervalEnd != null && !this.IntervalEnd.equals(null)) { Function<ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob.Builder, Void> f = x -> { builder.setIntervalEnd(this.IntervalEnd.toProto()); return null; }; f.apply(builder); } } { if (this.IntervalStep != null && !this.IntervalStep.equals(null)) { Function<ai.verta.modeldb.versioning.ContinuousHyperparameterSetConfigBlob.Builder, Void> f = x -> { builder.setIntervalStep(this.IntervalStep.toProto()); return null; }; f.apply(builder); } } return builder; } public void preVisitShallow(Visitor visitor) throws ModelDBException { visitor.preVisitAutogenContinuousHyperparameterSetConfigBlob(this); } public void preVisitDeep(Visitor visitor) throws ModelDBException { this.preVisitShallow(visitor); visitor.preVisitDeepAutogenHyperparameterValuesConfigBlob(this.IntervalBegin); visitor.preVisitDeepAutogenHyperparameterValuesConfigBlob(this.IntervalEnd); visitor.preVisitDeepAutogenHyperparameterValuesConfigBlob(this.IntervalStep); } public AutogenContinuousHyperparameterSetConfigBlob postVisitShallow(Visitor visitor) throws ModelDBException { return visitor.postVisitAutogenContinuousHyperparameterSetConfigBlob(this); } public AutogenContinuousHyperparameterSetConfigBlob postVisitDeep(Visitor visitor) throws ModelDBException { this.setIntervalBegin( visitor.postVisitDeepAutogenHyperparameterValuesConfigBlob(this.IntervalBegin)); this.setIntervalEnd( visitor.postVisitDeepAutogenHyperparameterValuesConfigBlob(this.IntervalEnd)); this.setIntervalStep( visitor.postVisitDeepAutogenHyperparameterValuesConfigBlob(this.IntervalStep)); return this.postVisitShallow(visitor); } }
3,618
14,668
// Copyright 2020 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. #include "fuchsia/runners/cast/create_web_message.h" #include "base/fuchsia/mem_buffer_util.h" #include "components/cast/message_port/fuchsia/message_port_fuchsia.h" fuchsia::web::WebMessage CreateWebMessage( base::StringPiece message, std::unique_ptr<cast_api_bindings::MessagePort> port) { fuchsia::web::WebMessage web_message; web_message.set_data(base::MemBufferFromString(message, "msg")); if (port) { fuchsia::web::OutgoingTransferable outgoing_transferable; outgoing_transferable.set_message_port( cast_api_bindings::MessagePortFuchsia::FromMessagePort(port.get()) ->TakeServiceRequest()); std::vector<fuchsia::web::OutgoingTransferable> outgoing_transferables; outgoing_transferables.push_back(std::move(outgoing_transferable)); web_message.set_outgoing_transfer(std::move(outgoing_transferables)); } return web_message; }
364
322
/* * 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.eagle.jpm.spark.entity; import org.apache.eagle.jpm.util.Constants; import org.apache.eagle.log.base.taggedlog.TaggedLogAPIEntity; import org.apache.eagle.log.entity.meta.*; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Table("eglesprk_jobs") @ColumnFamily("f") @Prefix("sprkjob") @Service(Constants.SPARK_JOB_SERVICE_ENDPOINT_NAME) @JsonIgnoreProperties(ignoreUnknown = true) @TimeSeries(true) @Tags({"site","sprkAppId", "sprkAppAttemptId", "sprkAppName", "normSprkAppName", "jobId","user", "queue"}) @Partition({"site"}) public class SparkJob extends TaggedLogAPIEntity { @Column("a") private long submissionTime; @Column("b") private long completionTime; @Column("c") private int numStages = 0; @Column("d") private String status; @Column("e") private int numTask = 0; @Column("f") private int numActiveTasks = 0; @Column("g") private int numCompletedTasks = 0; @Column("h") private int numSkippedTasks = 0; @Column("i") private int numFailedTasks = 0; @Column("j") private int numActiveStages = 0; @Column("k") private int numCompletedStages = 0; @Column("l") private int numSkippedStages = 0; @Column("m") private int numFailedStages = 0; public long getSubmissionTime() { return submissionTime; } public long getCompletionTime() { return completionTime; } public int getNumStages() { return numStages; } public String getStatus() { return status; } public int getNumTask() { return numTask; } public int getNumActiveTasks() { return numActiveTasks; } public int getNumCompletedTasks() { return numCompletedTasks; } public int getNumSkippedTasks() { return numSkippedTasks; } public int getNumFailedTasks() { return numFailedTasks; } public int getNumActiveStages() { return numActiveStages; } public int getNumCompletedStages() { return numCompletedStages; } public int getNumSkippedStages() { return numSkippedStages; } public int getNumFailedStages() { return numFailedStages; } public void setSubmissionTime(long submissionTime) { this.submissionTime = submissionTime; this.valueChanged("submissionTime"); } public void setCompletionTime(long completionTime) { this.completionTime = completionTime; this.valueChanged("completionTime"); } public void setNumStages(int numStages) { this.numStages = numStages; this.valueChanged("numStages"); } public void setStatus(String status) { this.status = status; this.valueChanged("status"); } public void setNumTask(int numTask) { this.numTask = numTask; this.valueChanged("numTask"); } public void setNumActiveTasks(int numActiveTasks) { this.numActiveTasks = numActiveTasks; this.valueChanged("numActiveTasks"); } public void setNumCompletedTasks(int numCompletedTasks) { this.numCompletedTasks = numCompletedTasks; this.valueChanged("numCompletedTasks"); } public void setNumSkippedTasks(int numSkippedTasks) { this.numSkippedTasks = numSkippedTasks; this.valueChanged("numSkippedTasks"); } public void setNumFailedTasks(int numFailedTasks) { this.numFailedTasks = numFailedTasks; this.valueChanged("numFailedTasks"); } public void setNumActiveStages(int numActiveStages) { this.numActiveStages = numActiveStages; this.valueChanged("numActiveStages"); } public void setNumCompletedStages(int numCompletedStages) { this.numCompletedStages = numCompletedStages; this.valueChanged("numCompletedStages"); } public void setNumSkippedStages(int numSkippedStages) { this.numSkippedStages = numSkippedStages; this.valueChanged("numSkippedStages"); } public void setNumFailedStages(int numFailedStages) { this.numFailedStages = numFailedStages; this.valueChanged("numFailedStages"); } }
1,908
903
package org.develnext.jphp.core.tokenizer.token; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.develnext.jphp.core.tokenizer.TokenMeta; @RunWith(JUnit4.class) public class TokenMetaTest { @Test public void testSimple() throws Exception { TokenMeta meta = new TokenMeta("foobar", 1, 2, 3, 4); Assert.assertEquals("foobar", meta.getWord()); Assert.assertEquals(1, meta.getStartLine()); Assert.assertEquals(2, meta.getEndLine()); Assert.assertEquals(3, meta.getStartPosition()); Assert.assertEquals(4, meta.getEndPosition()); } }
268
5,267
<gh_stars>1000+ package io.swagger.v3.core.util; import com.google.common.collect.ImmutableMap; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.media.Schema; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.Serializable; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URL; import java.util.Date; import java.util.Map; import java.util.Optional; import java.util.UUID; public class AnnotationsUtilsTest { @DataProvider private Object[][] expectedSchemaFromTypes() { return new Object[][]{ {String.class, ImmutableMap.of("type", "string")}, {Character.class, ImmutableMap.of("type", "string")}, {Boolean.class, ImmutableMap.of("type", "boolean")}, {Byte.class, ImmutableMap.of("type", "string", "format", "byte")}, {URI.class, ImmutableMap.of("type", "string", "format", "uri")}, {URL.class, ImmutableMap.of("type", "string", "format", "url")}, {UUID.class, ImmutableMap.of("type", "string", "format", "uuid")}, {Short.class, ImmutableMap.of("type", "integer", "format", "int32")}, {Integer.class, ImmutableMap.of("type", "integer", "format", "int32")}, {Long.class, ImmutableMap.of("type", "integer", "format", "int64")}, {Float.class, ImmutableMap.of("type", "number", "format", "float")}, {Double.class, ImmutableMap.of("type", "number", "format", "double")}, {BigInteger.class, ImmutableMap.of("type", "integer")}, {BigDecimal.class, ImmutableMap.of("type", "number")}, {Number.class, ImmutableMap.of("type", "number")}, {Date.class, ImmutableMap.of("type", "string", "format", "date-time")}, {File.class, ImmutableMap.of("type", "string", "format", "binary")}, {Object.class, ImmutableMap.of("type", "object")}, {DummyClass.class, ImmutableMap.of("$ref", "#/components/schemas/DummyClass")} }; } @Test(dataProvider = "expectedSchemaFromTypes") public void resolveSchemaFromType(Class<?> aClass, Map<String, Object> expected) { Schema schema = AnnotationsUtils.resolveSchemaFromType(aClass, new Components(), null); Assert.assertEquals(schema.getType(), expected.get("type")); Assert.assertEquals(schema.getFormat(), expected.get("format")); Assert.assertEquals(schema.get$ref(), expected.get("$ref")); } @DataProvider private Object[][] expectedSchemaFromTypeAndFormat() { return new Object[][]{ {"byteType", ImmutableMap.of("type", "string", "format", "byte")}, {"binaryType", ImmutableMap.of("type", "string", "format", "binary")}, {"emailType", ImmutableMap.of("type", "string", "format", "email")}, {"dummyType", ImmutableMap.of("$ref", "#/components/schemas/DummyClass")} }; } @Test(dataProvider = "expectedSchemaFromTypeAndFormat") public void getSchema(String methodName, Map<String, Object> expected) throws NoSuchMethodException { final Method method = getClass().getDeclaredMethod(methodName); Content annotationContent = method.getAnnotation(ApiResponse.class).content()[0]; Optional<? extends Schema> schema = AnnotationsUtils.getSchema(annotationContent, new Components(), null); Assert.assertTrue(schema.isPresent()); Assert.assertEquals(schema.get().getType(), expected.get("type")); Assert.assertEquals(schema.get().getFormat(), expected.get("format")); Assert.assertEquals(schema.get().get$ref(), expected.get("$ref")); } @ApiResponse(content = @Content(schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = Byte.class))) private void byteType() { } @ApiResponse(content = @Content(schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = Byte.class, format = "binary"))) private void binaryType() { } @ApiResponse(content = @Content(schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = String.class, format = "email"))) private void emailType() { } @ApiResponse(content = @Content(schema = @io.swagger.v3.oas.annotations.media.Schema(implementation = DummyClass.class))) private void dummyType() { } class DummyClass implements Serializable {} }
1,919
404
// Copyright (c) 2014-2019 K Team. All Rights Reserved. package org.kframework.main; import com.beust.jcommander.Parameter; import com.google.inject.Inject; import org.kframework.utils.errorsystem.KEMException; import org.kframework.utils.errorsystem.KException.ExceptionType; import org.kframework.utils.options.BaseEnumConverter; import org.kframework.utils.options.DurationConverter; import java.time.Duration; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; public final class GlobalOptions { public GlobalOptions() {} //TODO(dwightguth): remove in Guice 4.0 /** * Prevents instantiation by Guice when not explicitly configured in a Module. */ @Inject public GlobalOptions(Void v) {} public GlobalOptions(boolean debug, Warnings warnings, boolean verbose) { this.debug = debug; this.warnings = warnings; this.verbose = verbose; } public GlobalOptions(boolean debug, Warnings warnings, boolean verbose, boolean warnings2errors) { this.debug = debug; this.warnings = warnings; this.verbose = verbose; this.warnings2errors = warnings2errors; } public static enum Warnings { /** * All warnings and errors */ ALL(EnumSet.allOf(ExceptionType.class)), /** * All warnings and errors except hidden warnings */ NORMAL(EnumSet.range(ExceptionType.ERROR, ExceptionType.FIRST_HIDDEN)), /** * No warnings, only errors */ NONE(EnumSet.of(ExceptionType.ERROR)); private Warnings(Set<ExceptionType> types) { typesIncluded = types; } private Set<ExceptionType> typesIncluded; public Set<ExceptionType> getTypesIncluded() { return typesIncluded; } } public static class WarningsConverter extends BaseEnumConverter<Warnings> { public WarningsConverter(String optionName) { super(optionName); } @Override public Class<Warnings> enumClass() { return Warnings.class; } } public static class ExceptionTypeConverter extends BaseEnumConverter<ExceptionType> { public ExceptionTypeConverter(String optionName) { super(optionName); } @Override public Class<ExceptionType> enumClass() { return ExceptionType.class; } } private Set<ExceptionType> typesIncluded; public boolean includesExceptionType(ExceptionType e) { Set<ExceptionType> t = typesIncluded; if (t == null) { t = new HashSet<>(warnings.getTypesIncluded()); t.addAll(enableWarnings); t.removeAll(disableWarnings); if (!t.contains(ExceptionType.ERROR)) { throw KEMException.criticalError("Cannot disable errors with -Wno."); } typesIncluded = t; } return t.contains(e); } @Parameter(names={"--help", "-h"}, description="Print this help message", help = true) public boolean help = false; @Parameter(names="--version", description="Print version information") public boolean version = false; @Parameter(names={"--verbose", "-v"}, description="Print verbose output messages") public boolean verbose = false; @Parameter(names="--debug", description="Print debugging output messages and error stack traces") private boolean debug = false; @Parameter(names="--debug-warnings", description="Print debugging output messages and error/warning stack traces") public boolean debugWarnings = false; @Parameter(names={"--warnings", "-w"}, converter=WarningsConverter.class, description="Warning level. Values: [all|normal|none]") public Warnings warnings = Warnings.NORMAL; @Parameter(names="-W", description="Enable specific warning categories. Values: [non-exhaustive-match|undeleted-temp-dir|missing-hook-ocaml|missing-hook-java|missing-syntax-module|invalid-exit-code|deprecated-backend|invalid-config-var|future-error|unused-var|proof-lint|useless-rule|unresolved-function-symbol|malformed-markdown|invalidated-cache|unused-symbol]", converter=ExceptionTypeConverter.class) public List<ExceptionType> enableWarnings = Collections.emptyList(); @Parameter(names="-Wno", description="Disable specific warning categories.", converter=ExceptionTypeConverter.class) public List<ExceptionType> disableWarnings = Collections.emptyList(); @Parameter(names={"--warnings-to-errors", "-w2e"}, description="Convert warnings to errors.") public boolean warnings2errors = false; @Parameter(names = {"--shutdown-wait-time"}, converter = DurationConverter.class, description = "If option is set, a shutdown hook will be registered " + "that, once invoked, interrupts the main thread and waits its termination. " + "The wait time is the argument of this option, in format like 10ms/10s/10m/10h. " + "Useful if K is interrupted by Ctrl+C, because it allows the backend to detect " + "interruption and print diagnostics information. Currently interruption detection is implemented " + "in Java Backend. If K is invoked from KServer (e.g. Nailgun), the option is ignored.") public Duration shutdownWaitTime; @Parameter(names = {"--timeout"}, converter = DurationConverter.class, description = "If option is set, timeout for this process, in format like 10ms/10s/10m/10h. " + "Using this option is preferred compared to bash timeout command, which has known limitations " + "when invoked from scripts.") public Duration timeout; @Parameter(names={"--no-exc-wrap"}, description="Do not wrap exception messages to 80 chars. Keep long lines.") public boolean noExcWrap = false; public boolean debug() { return debug || debugWarnings; } }
2,198
939
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A Resnet implementation from `Realistic Evaluation of Deep SSL Algorithms`. Following this paper from Google Brain: https://papers.nips.cc/paper/7585-realistic-evaluation-of-deep-semi-supervised-learning-algorithms and this Github repository: https://github.com/brain-research/realistic-ssl-evaluation """ from .models_base import Model import numpy as np import tensorflow as tf def fast_flip(images, is_training): """Flips the input images when training.""" def func(inp): batch_size = tf.shape(inp)[0] flips = tf.to_float( tf.random_uniform([batch_size, 1, 1, 1], 0, 2, tf.int32)) flipped_inp = tf.reverse(inp, [2]) return flips * flipped_inp + (1 - flips) * images return tf.cond(is_training, lambda: func(images), lambda: images) class WideResnet(Model): """Resnet implementation from `Realistic Evaluation of Deep SSL Algorithms`. Attributes: num_classes: Integer representing the number of classes. lrelu_leakiness: A float representing the weight of the Leaky Relu parameter. horizontal_flip: A boolean specifying whether we do random horizontal flips of the training data, for data augmentation. random_translation: A boolean specifying whether we do random translations of the training data, for data augmentation. gaussian_noise: Boolean specifying whether to add Gaussian noise to the inputs. width: Integer representing the size of the convolutional filter. num_residual_units: Integer representing the number of residual units. name: String representing the model name. aggregation: String representing an aggregation operation that could be applied to the inputs. See superclass attributes for details. hidden_aggregation: A tuple or list of integers representing the number of units in each layer of aggregation multilayer percepron. After the inputs are passed through the encoding layers, before aggregation they are passed through a fully connected network with these numbers of hidden units in each layer. activation: An activation function to be applied to the outputs of each fully connected layer in the aggregation network. is_binary_classification: Boolean specifying if this is model for binary classification. If so, it uses a different loss function and returns predictions with a single dimension, batch size. """ def __init__(self, num_classes, lrelu_leakiness, horizontal_flip, random_translation, gaussian_noise, width, num_residual_units, name="wide_resnet", ema_factor=None, is_binary_classification=False, aggregation=None, activation=tf.nn.leaky_relu, hidden_aggregation=()): super(WideResnet, self).__init__( aggregation=aggregation, hidden_aggregation=hidden_aggregation, activation=activation) self.name = name self.num_classes = num_classes self.is_binary_classification = is_binary_classification self.lrelu_leakiness = lrelu_leakiness self.horizontal_flip = horizontal_flip self.random_translation = random_translation self.gaussian_noise = gaussian_noise self.width = width self.num_residual_units = num_residual_units self.ema_factor = ema_factor def get_encoding_and_params(self, inputs, is_train, update_batch_stats=True, **unused_kwargs): """Creates the model hidden representations and prediction ops. For this model, the hidden representation is the last layer before the logit computation. The predictions are unnormalized logits. Args: inputs: A tensor containing the model inputs. The first dimension is the batch size. is_train: A placeholder representing a boolean value that specifies if this model will be used for training or for test. update_batch_stats: Boolean specifying whether to update the batch norm statistics. **unused_kwargs: Other unused keyword arguments. Returns: encoding: A tensor containing an encoded batch of samples. The first dimension corresponds to the batch size. all_vars: A dictionary mapping from variable name to TensorFlow op containing all variables used in this model. reg_params: A dictionary mapping from a variable name to a Tensor of parameters which will be used for regularization. """ # Build layers. with tf.variable_scope(self.name): if isinstance(inputs, (list, tuple)): with tf.variable_scope("encoding"): left = self._get_encoding(inputs[0], is_train, update_batch_stats) with tf.variable_scope("encoding", reuse=True): right = self._get_encoding(inputs[1], is_train, update_batch_stats) encoding = self._aggregate((left, right)) else: with tf.variable_scope("encoding"): encoding = self._get_encoding(inputs, is_train, update_batch_stats) # Store model variables for easy access. variables = tf.get_collection( tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_default_graph().get_name_scope()) all_vars = {var.name: var for var in variables} reg_params = {} return encoding, all_vars, reg_params def get_predictions_and_params(self, encoding, is_train, **kwargs): """Creates the model prediction op. For this model, the hidden representation is the last layer of the MLP, before the logit computation. The predictions are unnormalized logits. Args: encoding: A tensor containing the model inputs. The first dimension is the batch size. is_train: A placeholder representing a boolean value that specifies if this model will be used for training or for test. **kwargs: Other keyword arguments. Returns: logits: A tensor of logits. For multiclass classification its shape is (num_samples, num_classes), where the second dimension contains a logit per class. For binary classification, its shape is (num_samples,), where each element is the probability of class 1 for that sample. all_vars: A dictionary mapping from variable name to TensorFlow op containing all variables used in this model. reg_params: A dictionary mapping from a variable name to a Tensor of parameters which will be used for regularization. """ # Logits layer. with tf.variable_scope(self.name + "/prediction"): w_init = tf.glorot_normal_initializer() logits = tf.layers.dense( encoding, self.num_classes, kernel_initializer=w_init) if self.is_binary_classification: logits = logits[:, 0] # Store model variables for easy access. variables = tf.get_collection( tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_default_graph().get_name_scope()) all_vars = {var.name: var for var in variables} # No regularization parameters. reg_params = {} return logits, all_vars, reg_params def _get_encoding(self, inputs, is_train, update_batch_stats, **kwargs): """Creates the model hidden representations and prediction ops. For this model, the hidden representation is the last layer before the logit computation. The predictions are unnormalized logits. Args: inputs: A tensor containing the model inputs. The first dimension is the batch size. is_train: A placeholder representing a boolean value that specifies if this model will be used for training or for test. update_batch_stats: Boolean specifying whether to update the batch norm statistics. **kwargs: Other keyword arguments. Returns: encoding: A tensor containing an encoded batch of samples. The first dimension corresponds to the batch size. all_vars: A dictionary mapping from variable name to TensorFlow op containing all variables used in this model. reg_params: A dictionary mapping from a variable name to a Tensor of parameters which will be used for regularization. """ # Helper functions def _conv(name, x, filter_size, in_filters, out_filters, strides): """Convolution.""" with tf.variable_scope(name): n = filter_size * filter_size * out_filters kernel = tf.get_variable( "DW", [filter_size, filter_size, in_filters, out_filters], tf.float32, initializer=tf.random_normal_initializer(stddev=np.sqrt(2.0 / n)), ) return tf.nn.conv2d(x, kernel, strides, padding="SAME") def _relu(x, leakiness=0.0): """Relu, with optional leaky support.""" return tf.where(tf.less(x, 0.0), leakiness * x, x, name="leaky_relu") def _residual(x, in_filter, out_filter, stride, activate_before_residual=False): """Residual unit with 2 sub layers.""" if activate_before_residual: with tf.variable_scope("shared_activation"): x = tf.layers.batch_normalization( x, axis=1, scale=True, training=is_train) x = _relu(x, self.lrelu_leakiness) orig_x = x else: with tf.variable_scope("residual_only_activation"): orig_x = x x = tf.layers.batch_normalization( x, axis=1, scale=True, training=is_train) x = _relu(x, self.lrelu_leakiness) with tf.variable_scope("sub1"): x = _conv("conv1", x, 3, in_filter, out_filter, stride) with tf.variable_scope("sub2"): x = tf.layers.batch_normalization( x, axis=1, scale=True, training=is_train) x = _relu(x, self.lrelu_leakiness) x = _conv("conv2", x, 3, out_filter, out_filter, [1, 1, 1, 1]) with tf.variable_scope("sub_add"): if in_filter != out_filter: orig_x = _conv("conv1x1", orig_x, 1, in_filter, out_filter, stride) x += orig_x return x x = inputs tf.summary.image("images_in_net", x) if self.horizontal_flip: x = fast_flip(x, is_training=is_train) if self.random_translation: raise NotImplementedError("Random translations are not implemented yet.") if self.gaussian_noise: x = tf.cond(is_train, lambda: x + tf.random_normal(tf.shape(x)) * 0.15, lambda: x) x = _conv("init_conv", x, 3, 3, 16, [1, 1, 1, 1]) activate_before_residual = [True, False, False] res_func = _residual filters = [16, 16 * self.width, 32 * self.width, 64 * self.width] with tf.variable_scope("unit_1_0"): x = res_func(x, filters[0], filters[1], [1, 1, 1, 1], activate_before_residual[0]) for i in range(1, self.num_residual_units): with tf.variable_scope("unit_1_%d" % i): x = res_func(x, filters[1], filters[1], [1, 1, 1, 1], False) with tf.variable_scope("unit_2_0"): x = res_func(x, filters[1], filters[2], [1, 2, 2, 1], activate_before_residual[1]) for i in range(1, self.num_residual_units): with tf.variable_scope("unit_2_%d" % i): x = res_func(x, filters[2], filters[2], [1, 1, 1, 1], False) with tf.variable_scope("unit_3_0"): x = res_func(x, filters[2], filters[3], [1, 2, 2, 1], activate_before_residual[2]) for i in range(1, self.num_residual_units): with tf.variable_scope("unit_3_%d" % i): x = res_func(x, filters[3], filters[3], [1, 1, 1, 1], False) with tf.variable_scope("unit_last"): x = tf.layers.batch_normalization( x, axis=1, scale=True, training=is_train) x = _relu(x, self.lrelu_leakiness) # Global average pooling. x = tf.reduce_mean(x, [1, 2]) return x def get_loss(self, predictions, targets, name_scope="loss", reg_params=None, **kwargs): weight_decay = kwargs["weight_decay"] if "weight_decay" in kwargs else 0.0 with tf.name_scope(name_scope): if self.is_binary_classification: loss = tf.reduce_sum( tf.nn.sigmoid_cross_entropy_with_logits( labels=targets, logits=predictions)) else: # Cross entropy error loss = tf.reduce_mean( tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( labels=targets, logits=predictions), axis=-1)) # Weight decay loss if reg_params: for var in reg_params.values(): loss += weight_decay * tf.nn.l2_loss(var) return loss def normalize_predictions(self, predictions): if self.is_binary_classification: return tf.nn.sigmoid(predictions) return tf.nn.softmax(predictions, axis=-1)
5,410
8,747
<reponame>cablelabs/esp-idf<gh_stars>1000+ /* * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ /** * NOTE: this is not the original header file from the hal component. It is a stripped-down copy to support mocking. */ #pragma once /** * @brief Enum with the three SPI peripherals that are software-accessible in it */ typedef enum { // SPI_HOST (SPI1_HOST) is not supported by the SPI Master and SPI Slave driver on ESP32-S2 SPI1_HOST=0, ///< SPI1 SPI2_HOST=1, ///< SPI2 SPI3_HOST=2, ///< SPI3 SPI_HOST_MAX=3, ///< invalid host value } spi_host_device_t;
256
4,223
<gh_stars>1000+ // // Created by <NAME> on 10/21/14. // Copyright (c) 2014 nplexity, LLC. All rights reserved. // #import <Foundation/Foundation.h> #import "XMPPFileTransfer.h" @interface XMPPOutgoingFileTransfer : XMPPFileTransfer /** * (Required) * * The data being sent to the recipient. * * If you're using startFileTransfer:, you *MUST* set this prior to calling * startFileTransfer:. */ @property (nonatomic, strong) NSData *outgoingData; /** * (Required) * * The recipient of your file transfer. * * If you're using startFileTransfer:, you *MUST* set this prior to calling * startFileTransfer:. */ @property (nonatomic, strong) XMPPJID *recipientJID; /** * (Optional) * * The name of the file you're sending. * * If you don't provide a filename, one will be generated for you. */ @property (nonatomic, copy) NSString *outgoingFileName; /** * (Optional) * * The description of the file you're sending. */ @property (nonatomic, copy) NSString *outgoingFileDescription; /** * (Optional) * * Specifies whether or not a random name should be generated instead of the * filename provided. The randomly generated name will retain the same file * extension as the original name if one was provided * * The default is NO; set to YES to generate a random name. */ @property (nonatomic, assign) BOOL shouldGenerateRandomName; /** * (Optional) * * Specifies the default block-size when using IBB file transfers. The default * value is 4096 (Bytes). If the file recipient requests a smaller block-size, * it will be halved. */ @property (nonatomic, assign) int32_t blockSize; #pragma mark - Public Methods /** * Starts the file transfer. This assumes that at a minimum a recipientJID and * outgoingData have already been provided. * * @param errPtr The address of an error which will be contain a description of * the problem if there is one (optional). * * @return Returns NO if there is something blatantly wrong (not authorized, no * recipientJID, no outgoingData); YES otherwise. */ - (BOOL)startFileTransfer:(NSError **)errPtr; /** * Sends the provided data to the provided recipient. Use of this method is not * recommended, as there is no error handling, but you're free to make your own * choices. */ - (BOOL)sendData:(NSData *)data toRecipient:(XMPPJID *)recipient; /** * Sends the provided data to the provided recipient. Pass nil for params you * don't care about. * * @param data The data you wish to send (required). * @param name The filename of the file you're sending (optional). * @param recipient The recipient of your file transfer (required). Note that a * resource must also be included in the JID. * @param description The description of the file you're sending (optional). * @param errPtr The address of an error which will contain a description of the * problem if there is one (optional). */ - (BOOL)sendData:(NSData *)data named:(NSString *)name toRecipient:(XMPPJID *)recipient description:(NSString *)description error:(NSError **)errPtr; @end #pragma mark - XMPPOutgoingFileTransferDelegate @protocol XMPPOutgoingFileTransferDelegate @optional /** * Implement this method when calling startFileTransfer: or sendData:(variants). * It will be invoked if the file transfer fails to execute properly. More * information will be given in the error. * * @param sender XMPPOutgoingFileTransfer object invoking this delegate method. * @param error NSError containing more details of the failure. */ - (void)xmppOutgoingFileTransfer:(XMPPOutgoingFileTransfer *)sender didFailWithError:(NSError *)error; /** * Implement this method when calling startFileTransfer: or sendData:(variants). * It will be invoked if the outgoing file transfer was completed successfully. * * @param sender XMPPOutgoingFileTransfer object invoking this delegate method. */ - (void)xmppOutgoingFileTransferDidSucceed:(XMPPOutgoingFileTransfer *)sender; /** * Not really sure why you would want this information, but hey, when I get * information, I'm happy to share. */ - (void)xmppOutgoingFileTransferIBBClosed:(XMPPOutgoingFileTransfer *)sender; @end
1,270
2,151
package org.robolectric.annotation.processing; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Maps.newTreeMap; import static com.google.common.collect.Sets.newTreeSet; import com.google.common.base.Equivalence; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Multimaps; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.AnnotationValueVisitor; import javax.lang.model.element.Element; import javax.lang.model.element.ElementVisitor; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVisitor; import javax.lang.model.util.Elements; import javax.lang.model.util.SimpleAnnotationValueVisitor6; import javax.lang.model.util.SimpleElementVisitor6; import javax.lang.model.util.SimpleTypeVisitor6; import javax.lang.model.util.Types; import org.robolectric.annotation.Implements; import org.robolectric.annotation.processing.validator.ImplementsValidator; /** * Model describing the Robolectric source file. */ public class RobolectricModel { private static FQComparator fqComparator = new FQComparator(); private static SimpleComparator comparator = new SimpleComparator(); /** TypeElement representing the Robolectric.Anything interface, or null if the element isn't found. */ final TypeElement ANYTHING; /** TypeMirror representing the Robolectric.Anything interface, or null if the element isn't found. */ public final TypeMirror ANYTHING_MIRROR; /** TypeMirror representing the Object class. */ final TypeMirror OBJECT_MIRROR; /** TypeElement representing the @Implements annotation. */ final TypeElement IMPLEMENTS; /** PackageElement representing the java.lang package. */ final PackageElement JAVA_LANG; /** Convenience reference for the processing environment's elements utilities. */ private final Elements elements; /** Convenience reference for the processing environment's types utilities. */ private final Types types; private HashMap<TypeElement,String> referentMap = newHashMap(); private HashMultimap<String,TypeElement> typeMap = HashMultimap.create(); private HashMap<TypeElement,TypeElement> importMap = newHashMap(); private TreeMap<TypeElement,TypeElement> shadowTypes = newTreeMap(fqComparator); private TreeMap<String, String> extraShadowTypes = newTreeMap(); private TreeSet<String> imports = newTreeSet(); private TreeMap<TypeElement,ExecutableElement> resetterMap = newTreeMap(comparator); private final Map<String, DocumentedPackage> documentedPackages = new TreeMap<>(); public Collection<DocumentedPackage> getDocumentedPackages() { return documentedPackages.values(); } public void documentPackage(String name, String documentation) { getDocumentedPackage(name).setDocumentation(documentation); } private DocumentedPackage getDocumentedPackage(String name) { DocumentedPackage documentedPackage = documentedPackages.get(name); if (documentedPackage == null) { documentedPackage = new DocumentedPackage(name); documentedPackages.put(name, documentedPackage); } return documentedPackage; } private DocumentedPackage getDocumentedPackage(TypeElement type) { Element pkgElement = type.getEnclosingElement(); return getDocumentedPackage(pkgElement.toString()); } public void documentType(TypeElement type, String documentation, List<String> imports) { DocumentedType documentedType = getDocumentedType(type); documentedType.setDocumentation(documentation); documentedType.imports = imports; } private DocumentedType getDocumentedType(TypeElement type) { DocumentedPackage documentedPackage = getDocumentedPackage(type); return documentedPackage.getDocumentedType(type.getQualifiedName().toString()); } public void documentMethod(TypeElement shadowClass, DocumentedMethod documentedMethod) { DocumentedType documentedType = getDocumentedType(shadowClass); documentedType.methods.put(documentedMethod.getName(), documentedMethod); } private static class FQComparator implements Comparator<TypeElement> { @Override public int compare(TypeElement o1, TypeElement o2) { return o1.getQualifiedName().toString().compareTo(o2.getQualifiedName().toString()); } } private static class SimpleComparator implements Comparator<Element> { @Override public int compare(Element o1, Element o2) { return o1.getSimpleName().toString().compareTo(o2.getSimpleName().toString()); } } public RobolectricModel(Elements elements, Types types) { this.elements = elements; this.types = types; ANYTHING = elements.getTypeElement("org.robolectric.Robolectric.Anything"); ANYTHING_MIRROR = ANYTHING == null ? null : ANYTHING.asType(); // FIXME: check this type lookup for NPEs (and also the ones in the // validators) IMPLEMENTS = elements.getTypeElement(ImplementsValidator.IMPLEMENTS_CLASS); JAVA_LANG = elements.getPackageElement("java.lang"); OBJECT_MIRROR = elements.getTypeElement(Object.class.getCanonicalName()).asType(); notObject = new Predicate<TypeMirror>() { @Override public boolean apply(TypeMirror t) { return !RobolectricModel.this.types.isSameType(t, OBJECT_MIRROR); } }; } public AnnotationMirror getAnnotationMirror(Element element, TypeElement annotation) { TypeMirror expectedType = annotation.asType(); for (AnnotationMirror m : element.getAnnotationMirrors()) { if (types.isSameType(expectedType, m.getAnnotationType())) { return m; } } return null; } public static ElementVisitor<TypeElement,Void> typeVisitor = new SimpleElementVisitor6<TypeElement,Void>() { @Override public TypeElement visitType(TypeElement e, Void p) { return e; } }; public static AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String key) { for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet() ) { if (entry.getKey().getSimpleName().toString().equals(key)) { return entry.getValue(); } } return null; } public static AnnotationValueVisitor<TypeMirror,Void> valueVisitor = new SimpleAnnotationValueVisitor6<TypeMirror,Void>() { @Override public TypeMirror visitType(TypeMirror t, Void arg) { return t; } }; public static AnnotationValueVisitor<String, Void> classNameVisitor = new SimpleAnnotationValueVisitor6<String, Void>() { @Override public String visitString(String s, Void arg) { return s; } }; public static AnnotationValueVisitor<Integer, Void> intVisitor = new SimpleAnnotationValueVisitor6<Integer, Void>() { @Override public Integer visitInt(int i, Void aVoid) { return i; } }; public AnnotationMirror getImplementsMirror(Element elem) { return getAnnotationMirror(elem, IMPLEMENTS); } private TypeMirror getImplementedClassName(AnnotationMirror am) { AnnotationValue className = getAnnotationValue(am, "className"); if (className == null) { return null; } String classNameString = classNameVisitor.visit(className); if (classNameString == null) { return null; } TypeElement impElement = elements.getTypeElement(classNameString.replace('$', '.')); if (impElement == null) { return null; } return impElement.asType(); } public TypeMirror getImplementedClass(AnnotationMirror am) { if (am == null) { return null; } // RobolectricWiringTest prefers className (if provided) to value, so we do the same here. TypeMirror impType = getImplementedClassName(am); if (impType != null) { return impType; } AnnotationValue av = getAnnotationValue(am, "value"); if (av == null) { return null; } TypeMirror type = valueVisitor.visit(av); if (type == null) { return null; } // If the class is Robolectric.Anything, treat as if it wasn't specified at all. if (ANYTHING_MIRROR != null && types.isSameType(type, ANYTHING_MIRROR)) { return null; } return type; } private static ElementVisitor<TypeElement,Void> typeElementVisitor = new SimpleElementVisitor6<TypeElement,Void>() { @Override public TypeElement visitType(TypeElement e, Void p) { return e; } }; private void registerType(TypeElement type) { if (!Objects.equal(ANYTHING, type) && !importMap.containsKey(type)) { typeMap.put(type.getSimpleName().toString(), type); importMap.put(type, type); for (TypeParameterElement typeParam : type.getTypeParameters()) { for (TypeMirror bound : typeParam.getBounds()) { // FIXME: get rid of cast using a visitor TypeElement boundElement = typeElementVisitor.visit(types.asElement(bound)); registerType(boundElement); } } } } /** * Prepares the various derived parts of the model based on the class mappings * that have been registered to date. */ public void prepare() { for (Map.Entry<TypeElement,TypeElement> entry : getVisibleShadowTypes().entrySet()) { final TypeElement shadowType = entry.getKey(); registerType(shadowType); final TypeElement solidType = entry.getValue(); registerType(solidType); } for (Map.Entry<TypeElement,TypeElement> entry : getResetterShadowTypes().entrySet()) { final TypeElement shadowType = entry.getKey(); registerType(shadowType); } while (!typeMap.isEmpty()) { final HashMultimap<String,TypeElement> nextRound = HashMultimap.create(); for (Map.Entry<String, Set<TypeElement>> referents : Multimaps.asMap(typeMap).entrySet()) { final Set<TypeElement> c = referents.getValue(); // If there is only one type left with the given simple // name, then if (c.size() == 1) { final TypeElement type = c.iterator().next(); referentMap.put(type, referents.getKey()); } else { for (TypeElement type : c) { SimpleElementVisitor6<Void,TypeElement> visitor = new SimpleElementVisitor6<Void,TypeElement>() { @Override public Void visitType(TypeElement parent, TypeElement type) { nextRound.put(parent.getSimpleName() + "." + type.getSimpleName(), type); importMap.put(type, parent); return null; } @Override public Void visitPackage(PackageElement parent, TypeElement type) { referentMap.put(type, type.getQualifiedName().toString()); importMap.remove(type); return null; } }; visitor.visit(importMap.get(type).getEnclosingElement(), type); } } } typeMap = nextRound; } for (TypeElement imp: importMap.values()) { if (imp.getModifiers().contains(Modifier.PUBLIC) && !JAVA_LANG.equals(imp.getEnclosingElement())) { imports.add(imp.getQualifiedName().toString()); } } // Other imports that the generated class needs imports.add("java.util.Map"); imports.add("java.util.HashMap"); imports.add("javax.annotation.Generated"); imports.add("org.robolectric.internal.ShadowProvider"); imports.add("org.robolectric.shadow.api.Shadow"); } public void addShadowType(TypeElement elem, TypeElement type) { shadowTypes.put(elem, type); } public void addExtraShadow(String sdkClassName, String shadowClassName) { extraShadowTypes.put(shadowClassName, sdkClassName); } public void addResetter(TypeElement parent, ExecutableElement elem) { resetterMap.put(parent, elem); } public Map<TypeElement, ExecutableElement> getResetters() { return resetterMap; } public Set<String> getImports() { return imports; } public Map<TypeElement, TypeElement> getAllShadowTypes() { return shadowTypes; } public Map<String, String> getExtraShadowTypes() { return extraShadowTypes; } public Map<TypeElement, TypeElement> getResetterShadowTypes() { return Maps.filterEntries(shadowTypes, new Predicate<Entry<TypeElement, TypeElement>>() { @Override public boolean apply(Entry<TypeElement, TypeElement> entry) { return resetterMap.containsKey(entry.getKey()); } }); } public Map<TypeElement, TypeElement> getVisibleShadowTypes() { return Maps.filterEntries(shadowTypes, new Predicate<Entry<TypeElement, TypeElement>>() { @Override public boolean apply(Entry<TypeElement, TypeElement> entry) { return entry.getKey().getAnnotation(Implements.class).isInAndroidSdk(); } }); } public Map<TypeElement, TypeElement> getShadowOfMap() { return Maps.filterEntries(getVisibleShadowTypes(), new Predicate<Entry<TypeElement,TypeElement>> () { @Override public boolean apply(Entry<TypeElement, TypeElement> entry) { return !Objects.equal(ANYTHING, entry.getValue()); } }); } public Collection<String> getShadowedPackages() { Set<String> packages = new TreeSet<>(); for (TypeElement element : shadowTypes.values()) { String packageName = elements.getPackageOf(element).toString(); // org.robolectric.* should never be instrumented if (packageName.matches("org.robolectric(\\..*)?")) { continue; } packages.add("\"" + packageName + "\""); } return packages; } private Predicate<TypeMirror> notObject; public List<TypeMirror> getExplicitBounds(TypeParameterElement typeParam) { return newArrayList(Iterables.filter(typeParam.getBounds(), notObject)); } /** * Returns a plain string to be used in the generated source * to identify the given type. The returned string will have * sufficient level of qualification in order to make the referent * unique for the source file. * @param type * @return */ public String getReferentFor(TypeElement type) { return referentMap.get(type); } private TypeVisitor<String,Void> findReferent = new SimpleTypeVisitor6<String,Void>() { @Override public String visitDeclared(DeclaredType t, Void p) { return referentMap.get(t.asElement()); } }; public String getReferentFor(TypeMirror type) { return findReferent.visit(type); } private Equivalence<TypeMirror> typeMirrorEq = new Equivalence<TypeMirror>() { @Override protected boolean doEquivalent(TypeMirror a, TypeMirror b) { return types.isSameType(a, b); } @Override protected int doHash(TypeMirror t) { // We're not using the hash. return 0; } }; private Equivalence<TypeParameterElement> typeEq = new Equivalence<TypeParameterElement>() { @Override @SuppressWarnings({"unchecked"}) protected boolean doEquivalent(TypeParameterElement arg0, TypeParameterElement arg1) { // Casts are necessary due to flaw in pairwise equivalence implementation. return typeMirrorEq.pairwise().equivalent((List<TypeMirror>)arg0.getBounds(), (List<TypeMirror>)arg1.getBounds()); } @Override protected int doHash(TypeParameterElement arg0) { // We don't use the hash code. return 0; } }; public void appendParameterList(StringBuilder message, List<? extends TypeParameterElement> tpeList) { boolean first = true; for (TypeParameterElement tpe : tpeList) { if (first) { first = false; } else { message.append(','); } message.append(tpe.toString()); boolean iFirst = true; for (TypeMirror bound : getExplicitBounds(tpe)) { if (iFirst) { message.append(" extends "); iFirst = false; } else { message.append(','); } message.append(bound); } } } @SuppressWarnings({"unchecked"}) public boolean isSameParameterList(List<? extends TypeParameterElement> l1, List<? extends TypeParameterElement> l2) { // Cast is necessary because of a flaw in the API design of "PairwiseEquivalent", // a flaw that is even acknowledged in the source. // Our casts are safe because we're not trying to add elements to the list // and therefore can't violate the constraint. return typeEq.pairwise().equivalent((List<TypeParameterElement>)l1, (List<TypeParameterElement>)l2); } }
6,078
14,668
<reponame>zealoussnow/chromium // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/base/webui/web_ui_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" TEST(WebUIUtilTest, ParsePathAndScale) { std::string path; float factor = 0; GURL url("http://some/random/username@email/and/more"); webui::ParsePathAndScale(url, &path, &factor); EXPECT_EQ("random/username@email/and/more", path); EXPECT_EQ(1.0f, factor); factor = 0; GURL url2("http://some/random/username/and/more"); webui::ParsePathAndScale(url2, &path, &factor); EXPECT_EQ("random/username/and/more", path); EXPECT_EQ(1.0f, factor); factor = 0; GURL url3("http://some/random/username/and/more@2ax"); webui::ParsePathAndScale(url3, &path, &factor); EXPECT_EQ("random/username/and/more@2ax", path); EXPECT_EQ(1.0f, factor); factor = 0; GURL url4("http://some/random/username/and/more@x"); webui::ParsePathAndScale(url4, &path, &factor); EXPECT_EQ("random/username/and/more@x", path); EXPECT_EQ(1.0f, factor); factor = 0; GURL url5("http://some/random/username@email/and/more@2x"); webui::ParsePathAndScale(url5, &path, &factor); EXPECT_EQ("random/username@email/and/more", path); EXPECT_EQ(2.0f, factor); factor = 0; GURL url6("http://some/random/username/and/[email protected]"); webui::ParsePathAndScale(url6, &path, &factor); EXPECT_EQ("random/username/and/more", path); EXPECT_EQ(1.4f, factor); factor = 0; GURL url7("http://some/random/username/and/[email protected]"); webui::ParsePathAndScale(url7, &path, &factor); EXPECT_EQ("random/username/and/more", path); EXPECT_EQ(1.3f, factor); } TEST(WebUIUtilTest, ParsePathAndImageSpec) { std::string path; float factor = 0; int index = -2; GURL url("http://[::192.9.5.5]/some/random/username@email/and/more"); webui::ParsePathAndImageSpec(url, &path, &factor, &index); EXPECT_EQ("some/random/username@email/and/more", path); EXPECT_EQ(1.0f, factor); EXPECT_EQ(-1, index); factor = 0; index = -2; GURL url2("http://host/some/random/username/and/more"); webui::ParsePathAndImageSpec(url2, &path, &factor, &index); EXPECT_EQ("some/random/username/and/more", path); EXPECT_EQ(1.0f, factor); EXPECT_EQ(-1, index); factor = 0; index = -2; GURL url3("http://host/some/random/username/and/more[0]@2x"); webui::ParsePathAndImageSpec(url3, &path, &factor, &index); EXPECT_EQ("some/random/username/and/more", path); EXPECT_EQ(2.0f, factor); EXPECT_EQ(0, index); factor = 0; index = -2; GURL url4("http://[::192.9.5.5]/some/random/username@email/and/more[1]@1.5x"); webui::ParsePathAndImageSpec(url4, &path, &factor, &index); EXPECT_EQ("some/random/username@email/and/more", path); EXPECT_EQ(1.5f, factor); EXPECT_EQ(1, index); } TEST(WebUIUtilTest, GetPngDataUrl_Basic) { // The input doesn't have to be a valid image. std::vector<unsigned char> in = {1, 2, 3, 4}; std::string out = webui::GetPngDataUrl(in.data(), in.size()); EXPECT_EQ("data:image/png;base64,AQIDBA==", out); } TEST(WebUIUtilTest, GetPngDataUrl_EmptyInput) { std::vector<unsigned char> in; webui::GetPngDataUrl(in.data(), in.size()); // No crash. }
1,360
562
from crocs.regex import Pattern, ConsumeBack e = ConsumeBack('Isaac ', 'Asimov', neg=True) e.test() e.hits()
43
2,209
// // Created by qlu on 2019/8/1. // #ifndef KUNGFU_POLLER_EPOLL_H #define KUNGFU_POLLER_EPOLL_H #include "poller.h" #include <sys/epoll.h> #include <spdlog/spdlog.h> namespace kungfu { namespace yijinjing { namespace socket { class poller { public: poller(): live_(false) { epoll_fd_ = epoll_create1(0); if (epoll_fd_ == -1) { SPDLOG_ERROR("epoll_create1 error, errno: {}, error msg: {}", errno, strerror(errno)); } } bool live() const { return live_; } void stop() { live_ = false; } void poll(std::vector<poll_event> events) { for (size_t idx =0; idx < events.size(); idx ++) { const poll_event& poll_ev = events[idx]; SPDLOG_DEBUG("add event, idx: {}, fd: {}, events: {}", idx, poll_ev.fd, poll_ev.events); struct epoll_event epoll_ev; epoll_ev.data.u64 = idx; if (poll_ev.events & POLL_IN_EVENT) { epoll_ev.events |= EPOLLIN; } if (poll_ev.events & POLL_OUT_EVENT) { epoll_ev.events |= EPOLLOUT; } int s = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, poll_ev.fd, &epoll_ev); if(s == -1) { SPDLOG_ERROR("epoll_ctl error, epfd: {}, errno: {}, error msg: {}", epoll_fd_, errno, strerror(errno)); } } live_ = true; while (live_) { int n = epoll_wait(epoll_fd_, epoll_events_, MAX_EVENTS, 0); for (size_t idx = 0; idx < n; idx++) { const epoll_event& epoll_ev = epoll_events_[idx]; if (epoll_ev.events & EPOLLIN) { const poll_event& poll_ev = events.at(epoll_ev.data.u64); memset(buffer_, 0, sizeof(buffer_)); size_t data_length = read(poll_ev.fd, buffer_, RCV_BUFFER_SIZE); if (data_length > 0) { poll_ev.rcv_handler(buffer_, data_length); } } } } } private: bool live_; char buffer_[RCV_BUFFER_SIZE]; int epoll_fd_; struct epoll_event epoll_events_[MAX_EVENTS]; }; } } } #endif //KUNGFU_POLLER_EPOLL_H
2,097
1,085
/* * Copyright (C) 2017-2019 Dremio 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. */ package com.dremio.common.types; import static com.dremio.common.expression.CompleteType.BIGINT; import static com.dremio.common.expression.CompleteType.BIT; import static com.dremio.common.expression.CompleteType.DATE; import static com.dremio.common.expression.CompleteType.DECIMAL; import static com.dremio.common.expression.CompleteType.DOUBLE; import static com.dremio.common.expression.CompleteType.FLOAT; import static com.dremio.common.expression.CompleteType.INT; import static com.dremio.common.expression.CompleteType.LIST; import static com.dremio.common.expression.CompleteType.STRUCT; import static com.dremio.common.expression.CompleteType.TIME; import static com.dremio.common.expression.CompleteType.TIMESTAMP; import static com.dremio.common.expression.CompleteType.VARCHAR; import static com.dremio.common.types.TypeCoercionRules.getResultantType; import static org.apache.arrow.vector.types.pojo.ArrowType.Decimal.createDecimal; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.Optional; import java.util.function.Supplier; import org.junit.Test; import com.dremio.common.expression.CompleteType; public class TypeCoercionRulesTest { private static final CompleteType DEC_10_5 = new CompleteType(createDecimal(10, 5, null)); private static final CompleteType DEC_18_18 = new CompleteType(createDecimal(18, 18, null)); private static final CompleteType DEC_38_0 = new CompleteType(createDecimal(38, 0, null)); private static final CompleteType DEC_100_50 = new CompleteType(createDecimal(100, 50, null)); @Test public void testGetResultantType() { assertThat(getType(INT, BIGINT), is(BIGINT)); assertThat(getType(INT, FLOAT), is(DOUBLE)); assertThat(getType(INT, DOUBLE), is(DOUBLE)); assertThat(getType(INT, DECIMAL), is(DECIMAL)); assertThat(getType(INT, DEC_18_18), is(DEC_18_18)); assertThat(getType(INT, DEC_38_0), is(DEC_38_0)); assertThat(getType(INT, DEC_10_5), is(DEC_10_5)); assertThat(getType(BIGINT, DECIMAL), is(DECIMAL)); assertThat(getType(BIGINT, DEC_18_18), is(DEC_18_18)); assertThat(getType(BIGINT, DEC_38_0), is(DEC_38_0)); assertThat(getType(BIGINT, DEC_10_5), is(DEC_10_5)); assertThat(getType(FLOAT, DECIMAL), is(DECIMAL)); assertThat(getType(FLOAT, DEC_18_18), is(DEC_18_18)); assertThat(getType(FLOAT, DEC_38_0), is(DEC_38_0)); assertThat(getType(FLOAT, DEC_10_5), is(DEC_10_5)); assertThat(getType(INT, VARCHAR), is(VARCHAR)); assertThat(getType(BIT, VARCHAR), is(VARCHAR)); assertThat(getType(BIGINT, VARCHAR), is(VARCHAR)); assertThat(getType(FLOAT, VARCHAR), is(VARCHAR)); assertThat(getType(DOUBLE, VARCHAR), is(VARCHAR)); assertThat(getType(DATE, VARCHAR), is(VARCHAR)); assertThat(getType(TIME, VARCHAR), is(VARCHAR)); assertThat(getType(TIMESTAMP, VARCHAR), is(VARCHAR)); assertThat(getType(DECIMAL, VARCHAR), is(VARCHAR)); assertThat(getType(DEC_18_18, VARCHAR), is(VARCHAR)); assertThat(getType(DEC_38_0, VARCHAR), is(VARCHAR)); assertThat(getType(DEC_10_5, VARCHAR), is(VARCHAR)); assertThat(getType(FLOAT, DOUBLE), is(DOUBLE)); assertThat(getType(BIGINT, FLOAT), is(DOUBLE)); assertThat(getType(BIGINT, DOUBLE), is(DOUBLE)); assertThat(getType(DECIMAL, DECIMAL), is(DECIMAL)); assertThat(getType(DECIMAL, DOUBLE), is(DOUBLE)); assertThat(getType(DEC_18_18, DOUBLE), is(DOUBLE)); assertThat(getType(DEC_38_0, DOUBLE), is(DOUBLE)); assertThat(getType(DEC_10_5, DOUBLE), is(DOUBLE)); } @Test public void testAsymmetryOfRules() { assertThat(getResultantType(BIGINT, INT), is(Optional.empty())); assertThat(getResultantType(FLOAT, INT), is(Optional.empty())); assertThat(getResultantType(DOUBLE, INT), is(Optional.empty())); assertThat(getResultantType(DOUBLE, FLOAT), is(Optional.empty())); assertThat(getResultantType(DOUBLE, BIGINT), is(Optional.empty())); assertThat(getResultantType(DOUBLE, DECIMAL), is(Optional.empty())); assertThat(getResultantType(FLOAT, BIGINT), is(Optional.empty())); assertThat(getResultantType(DECIMAL, INT), is(Optional.empty())); assertThat(getResultantType(DEC_10_5, INT), is(Optional.empty())); assertThat(getResultantType(DEC_18_18, INT), is(Optional.empty())); assertThat(getResultantType(DEC_38_0, INT), is(Optional.empty())); assertThat(getResultantType(DECIMAL, BIGINT), is(Optional.empty())); assertThat(getResultantType(DEC_10_5, BIGINT), is(Optional.empty())); assertThat(getResultantType(DEC_18_18, BIGINT), is(Optional.empty())); assertThat(getResultantType(DEC_38_0, BIGINT), is(Optional.empty())); assertThat(getResultantType(DECIMAL, FLOAT), is(Optional.empty())); assertThat(getResultantType(DEC_10_5, FLOAT), is(Optional.empty())); assertThat(getResultantType(DEC_18_18, FLOAT), is(Optional.empty())); assertThat(getResultantType(DEC_38_0, FLOAT), is(Optional.empty())); assertThat(getResultantType(VARCHAR, BIT), is(Optional.empty())); assertThat(getResultantType(VARCHAR, BIGINT), is(Optional.empty())); assertThat(getResultantType(VARCHAR, FLOAT), is(Optional.empty())); assertThat(getResultantType(VARCHAR, DOUBLE), is(Optional.empty())); assertThat(getResultantType(VARCHAR, DATE), is(Optional.empty())); assertThat(getResultantType(VARCHAR, TIME), is(Optional.empty())); assertThat(getResultantType(VARCHAR, TIMESTAMP), is(Optional.empty())); assertThat(getResultantType(VARCHAR, DECIMAL), is(Optional.empty())); assertThat(getResultantType(VARCHAR, DEC_10_5), is(Optional.empty())); assertThat(getResultantType(VARCHAR, DEC_18_18), is(Optional.empty())); assertThat(getResultantType(VARCHAR, DEC_38_0), is(Optional.empty())); } @Test public void testConversionBetweenDecimals() { assertThat(getType(DECIMAL, DEC_10_5), is(DEC_10_5)); assertThat(getType(DECIMAL, DEC_18_18), is(DEC_18_18)); assertThat(getType(DECIMAL, DEC_38_0), is(DEC_38_0)); assertThat(getType(DEC_10_5, DECIMAL), is(DECIMAL)); assertThat(getType(DEC_10_5, DEC_18_18), is(DEC_18_18)); assertThat(getType(DEC_10_5, DEC_38_0), is(DEC_38_0)); assertThat(getType(DEC_18_18, DECIMAL), is(DECIMAL)); assertThat(getType(DEC_18_18, DEC_10_5), is(DEC_10_5)); assertThat(getType(DEC_18_18, DEC_38_0), is(DEC_38_0)); assertThat(getType(DEC_38_0, DECIMAL), is(DECIMAL)); assertThat(getType(DEC_38_0, DEC_10_5), is(DEC_10_5)); assertThat(getType(DEC_38_0, DEC_18_18), is(DEC_18_18)); } @Test public void testErrorForComplexTypes() { assertThat(getResultantType(LIST, STRUCT), is(Optional.empty())); assertThat(getResultantType(STRUCT, LIST), is(Optional.empty())); assertThat(getResultantType(STRUCT, INT), is(Optional.empty())); assertThat(getResultantType(INT, STRUCT), is(Optional.empty())); assertThat(getResultantType(LIST, INT), is(Optional.empty())); assertThat(getResultantType(INT, LIST), is(Optional.empty())); } @Test public void testUnsupportedDecimals() { expectException(() -> getResultantType(DEC_10_5, DEC_100_50)); expectException(() -> getResultantType(DEC_100_50, DEC_10_5)); expectException(() -> getResultantType(DEC_100_50, DEC_100_50)); } private void expectException(Supplier<Optional<CompleteType>> supplier) { try { supplier.get(); fail("Expected exception"); } catch (Exception e) { assertThat(e, instanceOf(IllegalArgumentException.class)); assertThat(e.getMessage(), containsString("Max supported precision is 38")); } } private CompleteType getType(CompleteType fileType, CompleteType tableType) { return getResultantType(fileType, tableType).get(); } }
3,173
778
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: <NAME> // #ifndef KRATOS_CALCULATE_DIVERGENCE_PROCESS_H #define KRATOS_CALCULATE_DIVERGENCE_PROCESS_H // System includes // External includes // Project includes #include "includes/model_part.h" #include "processes/process.h" // Application includes namespace Kratos { ///@addtogroup ExaquteSandboxApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Process to compute divergence /** * This process computes the divergence and the seminorm of the velocity field. * We define VELOCITY_H1_SEMINORM as: \left \| \nabla u_{h} \right \|_{L^2(K)}^2 , * and DIVERGENCE as \left \| \nabla \cdot u_{h} \right \|_{L^2(K)}^2 , * where u is the velocity field and K an element of the domain \Omega. */ class KRATOS_API(EXAQUTE_SANDBOX_APPLICATION) CalculateDivergenceProcess : public Process { public: ///@name Type Definitions ///@{ /// Pointer definition of Process KRATOS_CLASS_POINTER_DEFINITION(CalculateDivergenceProcess); ///@} ///@name Life Cycle ///@{ /// Default constructor /** * @brief Construct CalculateDivergenceProcess object * @param rModelPart Model part the process is applied to * @param ThisParameters The input parameters */ CalculateDivergenceProcess( ModelPart& rModelPart, Parameters ThisParameters = Parameters(R"({})")); /// Destructor. ~CalculateDivergenceProcess() override = default; /// Assignment operator. CalculateDivergenceProcess& operator=(CalculateDivergenceProcess const& rOther) = delete; ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Function initializing the process */ void ExecuteInitialize() override; /** * @brief Function computing quantities at each time step */ void ExecuteBeforeOutputStep() override; ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override; /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override; /// Print object's data. void PrintData(std::ostream& rOStream) const override; ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ const ModelPart& mrModelPart; ///@} ///@name Private Operations ///@{ /** * @brief Function computing divergence at element level */ double ComputeAuxiliaryElementDivergence(Vector& grad_x, Vector& grad_y, Vector& grad_z); /** * @brief Function computing velocity seminorm at element level */ double ComputeAuxiliaryElementVelocitySeminorm(Vector& grad_x, Vector& grad_y, Vector& grad_z); ///@} ///@name Un accessible methods ///@{ /// Copy constructor. CalculateDivergenceProcess(CalculateDivergenceProcess const& rOther) = delete;; ///@} }; // Class Process ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function inline std::istream& operator >> (std::istream& rIStream, CalculateDivergenceProcess& rThis); /// output stream function inline std::ostream& operator << (std::ostream& rOStream, const CalculateDivergenceProcess& rThis); ///@} } // namespace Kratos #endif // KRATOS_CALCULATE_DIVERGENCE_PROCESS_H
2,256
16,461
<reponame>zakharchenkoAndrii/expo // Copyright © 2018 650 Industries. All rights reserved. #import <Foundation/Foundation.h> #import <ABI43_0_0ExpoModulesCore/ABI43_0_0EXDefines.h> #import <ABI43_0_0ExpoModulesCore/ABI43_0_0EXExportedModule.h> @protocol ABI43_0_0EXEventEmitterService - (void)sendEventWithName:(NSString *)name body:(id)body; @end
145
852
import FWCore.ParameterSet.Config as cms CastorDbProducer = cms.ESProducer( "CastorDbProducer", appendToDataLabel = cms.string( "" ) )
117
2,151
<filename>third_party/blink/renderer/core/frame/performance_monitor.cc<gh_stars>1000+ // Copyright 2016 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. #include "third_party/blink/renderer/core/frame/performance_monitor.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/bindings/core/v8/scheduled_action.h" #include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h" #include "third_party/blink/renderer/bindings/core/v8/source_location.h" #include "third_party/blink/renderer/core/CoreProbeSink.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/events/event_listener.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/frame.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/html/parser/html_document_parser.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/platform/histogram.h" #include "third_party/blink/renderer/platform/wtf/time.h" namespace blink { namespace { constexpr auto kLongTaskSubTaskThreshold = TimeDelta::FromMilliseconds(12); } // namespace void PerformanceMonitor::BypassLongCompileThresholdOnceForTesting() { bypass_long_compile_threshold_ = true; }; // static double PerformanceMonitor::Threshold(ExecutionContext* context, Violation violation) { PerformanceMonitor* monitor = PerformanceMonitor::InstrumentingMonitor(context); return monitor ? monitor->thresholds_[violation] : 0; } // static void PerformanceMonitor::ReportGenericViolation( ExecutionContext* context, Violation violation, const String& text, double time, std::unique_ptr<SourceLocation> location) { PerformanceMonitor* monitor = PerformanceMonitor::InstrumentingMonitor(context); if (!monitor) return; monitor->InnerReportGenericViolation(context, violation, text, time, std::move(location)); } // static PerformanceMonitor* PerformanceMonitor::Monitor( const ExecutionContext* context) { if (!context || !context->IsDocument()) return nullptr; LocalFrame* frame = ToDocument(context)->GetFrame(); if (!frame) return nullptr; return frame->GetPerformanceMonitor(); } // static PerformanceMonitor* PerformanceMonitor::InstrumentingMonitor( const ExecutionContext* context) { PerformanceMonitor* monitor = PerformanceMonitor::Monitor(context); return monitor && monitor->enabled_ ? monitor : nullptr; } PerformanceMonitor::PerformanceMonitor(LocalFrame* local_root) : local_root_(local_root) { std::fill(std::begin(thresholds_), std::end(thresholds_), 0); Platform::Current()->CurrentThread()->AddTaskTimeObserver(this); local_root_->GetProbeSink()->addPerformanceMonitor(this); } PerformanceMonitor::~PerformanceMonitor() { DCHECK(!local_root_); } void PerformanceMonitor::Subscribe(Violation violation, double threshold, Client* client) { DCHECK(violation < kAfterLast); ClientThresholds* client_thresholds = subscriptions_.at(violation); if (!client_thresholds) { client_thresholds = new ClientThresholds(); subscriptions_.Set(violation, client_thresholds); } client_thresholds->Set(client, threshold); UpdateInstrumentation(); } void PerformanceMonitor::UnsubscribeAll(Client* client) { for (const auto& it : subscriptions_) it.value->erase(client); UpdateInstrumentation(); } void PerformanceMonitor::Shutdown() { if (!local_root_) return; subscriptions_.clear(); UpdateInstrumentation(); Platform::Current()->CurrentThread()->RemoveTaskTimeObserver(this); local_root_->GetProbeSink()->removePerformanceMonitor(this); local_root_ = nullptr; } void PerformanceMonitor::UpdateInstrumentation() { std::fill(std::begin(thresholds_), std::end(thresholds_), 0); for (const auto& it : subscriptions_) { Violation violation = static_cast<Violation>(it.key); ClientThresholds* client_thresholds = it.value; for (const auto& client_threshold : *client_thresholds) { if (!thresholds_[violation] || thresholds_[violation] > client_threshold.value) thresholds_[violation] = client_threshold.value; } } enabled_ = std::count(std::begin(thresholds_), std::end(thresholds_), 0) < static_cast<int>(kAfterLast); } void PerformanceMonitor::WillExecuteScript(ExecutionContext* context) { // Heuristic for minimal frame context attribution: note the frame context // for each script execution. When a long task is encountered, // if there is only one frame context involved, then report it. // Otherwise don't report frame context. // NOTE: This heuristic is imperfect and will be improved in V2 API. // In V2, timing of script execution along with style & layout updates will be // accounted for detailed and more accurate attribution. ++script_depth_; UpdateTaskAttribution(context); } void PerformanceMonitor::DidExecuteScript() { --script_depth_; } void PerformanceMonitor::UpdateTaskAttribution(ExecutionContext* context) { // If |context| is not a document, unable to attribute a frame context. if (!context || !context->IsDocument()) return; UpdateTaskShouldBeReported(ToDocument(context)->GetFrame()); if (!task_execution_context_) task_execution_context_ = context; else if (task_execution_context_ != context) task_has_multiple_contexts_ = true; } void PerformanceMonitor::UpdateTaskShouldBeReported(LocalFrame* frame) { if (frame && local_root_ == &(frame->LocalFrameRoot())) task_should_be_reported_ = true; } void PerformanceMonitor::Will(const probe::RecalculateStyle& probe) { UpdateTaskShouldBeReported(probe.document ? probe.document->GetFrame() : nullptr); if (enabled_ && thresholds_[kLongLayout] && script_depth_) probe.CaptureStartTime(); } void PerformanceMonitor::Did(const probe::RecalculateStyle& probe) { if (enabled_ && script_depth_ && thresholds_[kLongLayout]) per_task_style_and_layout_time_ += probe.Duration(); } void PerformanceMonitor::Will(const probe::UpdateLayout& probe) { UpdateTaskShouldBeReported(probe.document ? probe.document->GetFrame() : nullptr); ++layout_depth_; if (!enabled_) return; if (layout_depth_ > 1 || !script_depth_ || !thresholds_[kLongLayout]) return; probe.CaptureStartTime(); } void PerformanceMonitor::Did(const probe::UpdateLayout& probe) { --layout_depth_; if (!enabled_) return; if (thresholds_[kLongLayout] && script_depth_ && !layout_depth_) per_task_style_and_layout_time_ += probe.Duration(); } void PerformanceMonitor::Will(const probe::ExecuteScript& probe) { WillExecuteScript(probe.context); probe.CaptureStartTime(); } void PerformanceMonitor::Did(const probe::ExecuteScript& probe) { DidExecuteScript(); if (!enabled_ || !thresholds_[kLongTask]) return; if (probe.Duration() <= kLongTaskSubTaskThreshold) return; std::unique_ptr<SubTaskAttribution> sub_task_attribution = SubTaskAttribution::Create(String("script-run"), probe.context->Url().GetString(), probe.CaptureStartTime(), probe.Duration()); sub_task_attributions_.push_back(std::move(sub_task_attribution)); } void PerformanceMonitor::Will(const probe::CallFunction& probe) { WillExecuteScript(probe.context); if (user_callback_) probe.CaptureStartTime(); } void PerformanceMonitor::Did(const probe::CallFunction& probe) { DidExecuteScript(); if (!enabled_ || !user_callback_) return; // Working around Oilpan - probes are STACK_ALLOCATED. const probe::UserCallback* user_callback = static_cast<const probe::UserCallback*>(user_callback_); Violation handler_type = user_callback->recurring ? kRecurringHandler : kHandler; double threshold = thresholds_[handler_type]; double duration = probe.Duration().InSecondsF(); if (!threshold || duration < threshold) return; String name = user_callback->name ? String(user_callback->name) : String(user_callback->atomicName); String text = String::Format("'%s' handler took %ldms", name.Utf8().data(), lround(duration * 1000)); InnerReportGenericViolation(probe.context, handler_type, text, duration, SourceLocation::FromFunction(probe.function)); } void PerformanceMonitor::Will(const probe::V8Compile& probe) { UpdateTaskAttribution(probe.context); if (!enabled_ || !thresholds_[kLongTask]) return; v8_compile_start_time_ = probe.CaptureStartTime(); } void PerformanceMonitor::Did(const probe::V8Compile& probe) { if (!enabled_ || !thresholds_[kLongTask]) return; TimeDelta v8_compile_duration = probe.Duration(); if (bypass_long_compile_threshold_) { bypass_long_compile_threshold_ = false; } else { if (v8_compile_duration <= kLongTaskSubTaskThreshold) return; } std::unique_ptr<SubTaskAttribution> sub_task_attribution = SubTaskAttribution::Create( String("script-compile"), String::Format("%s(%d, %d)", probe.file_name.Utf8().data(), probe.line, probe.column), v8_compile_start_time_, v8_compile_duration); sub_task_attributions_.push_back(std::move(sub_task_attribution)); } void PerformanceMonitor::Will(const probe::UserCallback& probe) { ++user_callback_depth_; UpdateTaskAttribution(probe.context); if (!enabled_ || user_callback_depth_ != 1 || !thresholds_[probe.recurring ? kRecurringHandler : kHandler]) return; DCHECK(!user_callback_); user_callback_ = &probe; } void PerformanceMonitor::Did(const probe::UserCallback& probe) { --user_callback_depth_; if (!user_callback_depth_) user_callback_ = nullptr; DCHECK(user_callback_ != &probe); } void PerformanceMonitor::DocumentWriteFetchScript(Document* document) { if (!enabled_) return; String text = "Parser was blocked due to document.write(<script>)"; InnerReportGenericViolation(document, kBlockedParser, text, 0, nullptr); } void PerformanceMonitor::WillProcessTask(double start_time) { // Reset m_taskExecutionContext. We don't clear this in didProcessTask // as it is needed in ReportTaskTime which occurs after didProcessTask. task_execution_context_ = nullptr; task_has_multiple_contexts_ = false; task_should_be_reported_ = false; if (!enabled_) return; // Reset everything for regular and nested tasks. script_depth_ = 0; layout_depth_ = 0; per_task_style_and_layout_time_ = TimeDelta(); user_callback_ = nullptr; v8_compile_start_time_ = TimeTicks(); sub_task_attributions_.clear(); } void PerformanceMonitor::DidProcessTask(double start_time, double end_time) { if (!enabled_ || !task_should_be_reported_) return; double layout_threshold = thresholds_[kLongLayout]; double layout_time = per_task_style_and_layout_time_.InSecondsF(); if (layout_threshold && layout_time > layout_threshold) { ClientThresholds* client_thresholds = subscriptions_.at(kLongLayout); DCHECK(client_thresholds); for (const auto& it : *client_thresholds) { if (it.value < layout_time) it.key->ReportLongLayout(layout_time); } } double task_time = end_time - start_time; if (thresholds_[kLongTask] && task_time > thresholds_[kLongTask]) { ClientThresholds* client_thresholds = subscriptions_.at(kLongTask); for (const auto& it : *client_thresholds) { if (it.value < task_time) { it.key->ReportLongTask( start_time, end_time, task_has_multiple_contexts_ ? nullptr : task_execution_context_, task_has_multiple_contexts_, sub_task_attributions_); } } } } void PerformanceMonitor::InnerReportGenericViolation( ExecutionContext* context, Violation violation, const String& text, double time, std::unique_ptr<SourceLocation> location) { ClientThresholds* client_thresholds = subscriptions_.at(violation); if (!client_thresholds) return; if (!location) location = SourceLocation::Capture(context); for (const auto& it : *client_thresholds) { if (it.value < time) it.key->ReportGenericViolation(violation, text, time, location.get()); } } void PerformanceMonitor::Trace(blink::Visitor* visitor) { visitor->Trace(local_root_); visitor->Trace(task_execution_context_); visitor->Trace(subscriptions_); } } // namespace blink
4,549
4,054
<reponame>Anlon-Burke/vespa<gh_stars>1000+ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "arithmeticvalueupdate.h" #include <vespa/document/base/field.h> #include <vespa/document/fieldvalue/fieldvalues.h> #include <vespa/vespalib/objects/nbostream.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/xmlstream.h> #include <ostream> using vespalib::IllegalArgumentException; using vespalib::IllegalStateException; using namespace vespalib::xml; namespace document { IMPLEMENT_IDENTIFIABLE(ArithmeticValueUpdate, ValueUpdate); // Declare string representations for operator names. static const char * operatorName[] = { "add", "div", "mul", "sub" }; static const char * operatorNameC[] = { "Add", "Div", "Mul", "Sub" }; bool ArithmeticValueUpdate::operator==(const ValueUpdate& other) const { if (other.getClass().id() != ArithmeticValueUpdate::classId) return false; const ArithmeticValueUpdate& o(static_cast<const ArithmeticValueUpdate&>(other)); if (_operator != o._operator) return false; if (_operand != o._operand) return false; return true; } // Ensure that this update is compatible with given field. void ArithmeticValueUpdate::checkCompatibility(const Field& field) const { if ( ! field.getDataType().inherits(NumericDataType::classId)) { throw IllegalArgumentException(vespalib::make_string( "Can not perform arithmetic update on non-numeric field '%s'.", field.getName().data()), VESPA_STRLOC); } } // Apply this update. bool ArithmeticValueUpdate::applyTo(FieldValue& value) const { if (value.inherits(ByteFieldValue::classId)) { ByteFieldValue& bValue = static_cast<ByteFieldValue&>(value); bValue.setValue((int)applyTo(static_cast<int64_t>(bValue.getAsInt()))); } else if (value.inherits(DoubleFieldValue::classId)) { DoubleFieldValue& dValue = static_cast<DoubleFieldValue&>(value); dValue.setValue(applyTo(dValue.getAsDouble())); } else if (value.inherits(FloatFieldValue::classId)) { FloatFieldValue& fValue = static_cast<FloatFieldValue&>(value); fValue.setValue((float)applyTo(fValue.getAsFloat())); } else if (value.inherits(IntFieldValue::classId)) { IntFieldValue& iValue = static_cast<IntFieldValue&>(value); iValue.setValue((int)applyTo(static_cast<int64_t>(iValue.getAsInt()))); } else if (value.inherits(LongFieldValue::classId)) { LongFieldValue& lValue = static_cast<LongFieldValue&>(value); lValue.setValue(applyTo(lValue.getAsLong())); } else { std::string err = vespalib::make_string( "Unable to perform an arithmetic update on a \"%s\" field " "value.", value.getClass().name()); throw IllegalStateException(err, VESPA_STRLOC); } return true; } // Perform the contained operation on the given value. double ArithmeticValueUpdate::applyTo(double value) const { switch(_operator) { case Add: return value + _operand; case Div: return value / _operand; case Mul: return value * _operand; case Sub: return value - _operand; default: return 0; } } // Perform the contained operation on the given value. long ArithmeticValueUpdate::applyTo(int64_t value) const { switch(_operator) { case Add: return (long)(value + _operand); case Div: return (long)(value / _operand); case Mul: return (long)(value * _operand); case Sub: return (long)(value - _operand); default: return 0; } } // Perform the contained operation on the given value. std::string ArithmeticValueUpdate::applyTo(const std::string & value) const { return value; } // Print this update as a human readable string. void ArithmeticValueUpdate::print(std::ostream& out, bool, const std::string& indent) const { out << indent << "ArithmeticValueUpdate(" << operatorNameC[_operator] << " " << _operand << ")"; } void ArithmeticValueUpdate::printXml(XmlOutputStream& xos) const { xos << XmlTag(operatorName[_operator]) << XmlAttribute("by", _operand) << XmlEndTag(); } // Deserialize this update from the given buffer. void ArithmeticValueUpdate::deserialize(const DocumentTypeRepo&, const DataType&, nbostream & stream) { int32_t opt; stream >> opt >>_operand; _operator = static_cast<ArithmeticValueUpdate::Operator>(opt); } } // document
1,682
14,668
<reponame>zealoussnow/chromium // Copyright 2019 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. #include "components/permissions/android/nfc/mock_nfc_system_level_setting.h" namespace { static bool nfc_access_is_possible_ = false; static bool is_nfc_setting_enabled_ = false; static bool has_shown_nfc_setting_prompt_ = false; } // namespace namespace permissions { MockNfcSystemLevelSetting::MockNfcSystemLevelSetting() : NfcSystemLevelSetting() {} MockNfcSystemLevelSetting::~MockNfcSystemLevelSetting() {} void MockNfcSystemLevelSetting::SetNfcAccessIsPossible(bool is_possible) { nfc_access_is_possible_ = is_possible; } void MockNfcSystemLevelSetting::SetNfcSystemLevelSettingEnabled( bool is_enabled) { is_nfc_setting_enabled_ = is_enabled; } bool MockNfcSystemLevelSetting::HasShownNfcSettingPrompt() { return has_shown_nfc_setting_prompt_; } void MockNfcSystemLevelSetting::ClearHasShownNfcSettingPrompt() { has_shown_nfc_setting_prompt_ = false; } bool MockNfcSystemLevelSetting::IsNfcAccessPossible() { return nfc_access_is_possible_; } bool MockNfcSystemLevelSetting::IsNfcSystemLevelSettingEnabled() { return is_nfc_setting_enabled_; } void MockNfcSystemLevelSetting::PromptToEnableNfcSystemLevelSetting( content::WebContents* web_contents, base::OnceClosure prompt_completed_callback) { has_shown_nfc_setting_prompt_ = true; std::move(prompt_completed_callback).Run(); } } // namespace permissions
530
442
#include <Bindings/obe/Engine/Engine.hpp> #include <Engine/Engine.hpp> #include <Engine/ResourceManager.hpp> #include <Bindings/Config.hpp> namespace obe::Engine::Bindings { void LoadClassEngine(sol::state_view state) { sol::table EngineNamespace = state["obe"]["Engine"].get<sol::table>(); sol::usertype<obe::Engine::Engine> bindEngine = EngineNamespace.new_usertype<obe::Engine::Engine>( "Engine", sol::call_constructor, sol::constructors<obe::Engine::Engine()>()); bindEngine["init"] = &obe::Engine::Engine::init; bindEngine["run"] = &obe::Engine::Engine::run; bindEngine["Audio"] = sol::property(&obe::Engine::Engine::getAudioManager); bindEngine["Configuration"] = sol::property(&obe::Engine::Engine::getConfigurationManager); bindEngine["Resources"] = sol::property(&obe::Engine::Engine::getResourceManager); bindEngine["Input"] = sol::property(&obe::Engine::Engine::getInputManager); bindEngine["Framerate"] = sol::property(&obe::Engine::Engine::getFramerateManager); bindEngine["Events"] = sol::property(&obe::Engine::Engine::getEventManager); bindEngine["Scene"] = sol::property(&obe::Engine::Engine::getScene); bindEngine["Cursor"] = sol::property(&obe::Engine::Engine::getCursor); bindEngine["Window"] = sol::property(&obe::Engine::Engine::getWindow); } void LoadClassResourceManagedObject(sol::state_view state) { sol::table EngineNamespace = state["obe"]["Engine"].get<sol::table>(); sol::usertype<obe::Engine::ResourceManagedObject> bindResourceManagedObject = EngineNamespace.new_usertype<obe::Engine::ResourceManagedObject>( "ResourceManagedObject", sol::call_constructor, sol::default_constructor); bindResourceManagedObject["removeResourceManager"] = &obe::Engine::ResourceManagedObject::removeResourceManager; bindResourceManagedObject["attachResourceManager"] = &obe::Engine::ResourceManagedObject::attachResourceManager; } void LoadClassResourceManager(sol::state_view state) { sol::table EngineNamespace = state["obe"]["Engine"].get<sol::table>(); sol::usertype<obe::Engine::ResourceManager> bindResourceManager = EngineNamespace.new_usertype<obe::Engine::ResourceManager>("ResourceManager", sol::call_constructor, sol::constructors<obe::Engine::ResourceManager()>()); bindResourceManager["getFont"] = &obe::Engine::ResourceManager::getFont; bindResourceManager["getTexture"] = sol::overload(static_cast<const obe::Graphics::Texture& ( obe::Engine::ResourceManager::*)(const obe::System::Path&, bool)>( &obe::Engine::ResourceManager::getTexture), static_cast<const obe::Graphics::Texture& ( obe::Engine::ResourceManager::*)(const obe::System::Path&)>( &obe::Engine::ResourceManager::getTexture)); bindResourceManager["clean"] = &obe::Engine::ResourceManager::clean; bindResourceManager["defaultAntiAliasing"] = &obe::Engine::ResourceManager::defaultAntiAliasing; } };
1,293
1,006
<gh_stars>1000+ /**************************************************************************** * arch/arm/src/imxrt/imxrt_wdog.h * * 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. * ****************************************************************************/ #ifndef __ARCH_ARM_SRC_IMXRT_IMXRT_WDOG_H #define __ARCH_ARM_SRC_IMXRT_IMXRT_WDOG_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <nuttx/compiler.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include "arm_internal.h" #include "chip.h" #include "hardware/imxrt_wdog.h" /**************************************************************************** * Public Types ****************************************************************************/ /**************************************************************************** * Public Function Prototypes ****************************************************************************/ #if defined(CONFIG_WATCHDOG) && defined(CONFIG_IMXRT_WDOG) /**************************************************************************** * Name: imxrt_wdog_initialize * * Description: * Initialize the watchdog time. The watchdog timer is initialized and * registered at devpath. The initial state of the watchdog time is * disabled. * * Input Parameters: * devpath - The full path to the watchdog. This should be of the form * /dev/watchdog0 * * Returned Values: * None * ****************************************************************************/ void imxrt_wdog_initialize(void); #endif /* CONFIG_WATCHDOG && CONFIG_IMXRT_WDOG */ /**************************************************************************** * Name: imxrt_wdog_disable * * Description: * Called at the very beginning of _start. Disables all watchdogs * ****************************************************************************/ void imxrt_wdog_disable_all(void); #endif /* __ARCH_ARM_SRC_IMXRT_IMXRT_WDOG_H */
694
3,897
<reponame>mcheah-bose/mbed-os<gh_stars>1000+ /* mbed Microcontroller Library * Copyright (c) 2015-2018 ARM Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #ifndef COMMON_RTC_H #define COMMON_RTC_H #include "nrf_rtc.h" #define RTC_COUNTER_BITS 24u #define RTC_FREQ 32768u // Instance 0 is reserved for SoftDevice. // Instance 1 is used as a common one for lp_ticker and (in case // of NRF51) as an alternative tick source for RTOS. #define COMMON_RTC_INSTANCE NRF_RTC1 #define COMMON_RTC_IRQ_HANDLER RTC1_IRQHandler #define OS_TICK_CC_CHANNEL 0 #define LP_TICKER_CC_CHANNEL 1 #define COMMON_RTC_EVENT_COMPARE(channel) \ CONCAT_2(NRF_RTC_EVENT_COMPARE_, channel) #define COMMON_RTC_INT_COMPARE_MASK(channel) \ CONCAT_3(NRF_RTC_INT_COMPARE, channel, _MASK) #define OS_TICK_EVENT COMMON_RTC_EVENT_COMPARE(OS_TICK_CC_CHANNEL) #define OS_TICK_INT_MASK COMMON_RTC_INT_COMPARE_MASK(OS_TICK_CC_CHANNEL) #define LP_TICKER_EVENT COMMON_RTC_EVENT_COMPARE(LP_TICKER_CC_CHANNEL) #define LP_TICKER_INT_MASK COMMON_RTC_INT_COMPARE_MASK(LP_TICKER_CC_CHANNEL) extern bool m_common_rtc_enabled; extern uint32_t volatile m_common_rtc_overflows; extern bool volatile lp_ticker_interrupt_fire; void common_rtc_free(void); void common_rtc_init(void); uint32_t common_rtc_32bit_ticks_get(void); uint64_t common_rtc_64bit_us_get(void); void common_rtc_set_interrupt(uint32_t us_timestamp, uint32_t cc_channel, uint32_t int_mask); #endif // COMMON_RTC_H
897
424
<reponame>mablanchard/Fastor #ifndef SIMD_VECTOR_DOUBLE_H #define SIMD_VECTOR_DOUBLE_H #include "Fastor/simd_vector/simd_vector_base.h" namespace Fastor { // AVX512 VERSION //-------------------------------------------------------------------------------------------------- #ifdef FASTOR_AVX512_IMPL template <> struct SIMDVector<double, simd_abi::avx512> { using value_type = __m512d; using scalar_value_type = double; using abi_type = simd_abi::avx512; static constexpr FASTOR_INDEX Size = internal::get_simd_vector_size<SIMDVector<double,simd_abi::avx512>>::value; static constexpr FASTOR_INLINE FASTOR_INDEX size() {return internal::get_simd_vector_size<SIMDVector<double,simd_abi::avx512>>::value;} FASTOR_INLINE SIMDVector() : value(_mm512_setzero_pd()) {} FASTOR_INLINE SIMDVector(double num) : value(_mm512_set1_pd(num)) {} FASTOR_INLINE SIMDVector(__m512d regi) : value(regi) {} FASTOR_INLINE SIMDVector(const double *data, bool Aligned=true) { if (Aligned) value =_mm512_load_pd(data); else value = _mm512_loadu_pd(data); } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator=(double num) { value = _mm512_set1_pd(num); return *this; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator=(__m512d regi) { value = regi; return *this; } FASTOR_INLINE void load(const double *data, bool Aligned=true) { if (Aligned) value =_mm512_load_pd(data); else value = _mm512_loadu_pd(data); } FASTOR_INLINE void store(double *data, bool Aligned=true) const { if (Aligned) _mm512_store_pd(data,value); else _mm512_storeu_pd(data,value); } FASTOR_INLINE void aligned_load(const double *data) { value =_mm512_load_pd(data); } FASTOR_INLINE void aligned_store(double *data) const { _mm512_store_pd(data,value); } FASTOR_INLINE void mask_load(const scalar_value_type *a, uint8_t mask, bool Aligned=false) { #ifdef FASTOR_HAS_AVX512_MASKS if (!Aligned) value = _mm512_mask_loadu_pd(value, mask, a); else value = _mm512_mask_load_pd(value, mask, a); #else // perhaps very inefficient but they never get used int maska[Size]; mask_to_array(mask,maska); value = _mm512_setzero_pd(); for (FASTOR_INDEX i=0; i<Size; ++i) { if (maska[i] == -1) { ((scalar_value_type*)&value)[Size - i - 1] = a[Size - i - 1]; } } unused(Aligned); #endif } FASTOR_INLINE void mask_store(scalar_value_type *a, uint8_t mask, bool Aligned=false) const { #ifdef FASTOR_HAS_AVX512_MASKS if (!Aligned) _mm512_mask_storeu_pd(a, mask, value); else _mm512_mask_store_pd(a, mask, value); #else // perhaps very inefficient but they never get used int maska[Size]; mask_to_array(mask,maska); for (FASTOR_INDEX i=0; i<Size; ++i) { if (maska[i] == -1) { a[Size - i - 1] = ((const scalar_value_type*)&value)[Size - i - 1]; } else { a[Size - i - 1] = 0; } } unused(Aligned); #endif } FASTOR_INLINE double operator[](FASTOR_INDEX i) const {return reinterpret_cast<const double*>(&value)[i];} FASTOR_INLINE double operator()(FASTOR_INDEX i) const {return reinterpret_cast<const double*>(&value)[i];} FASTOR_INLINE void set(double num) { value = _mm512_set1_pd(num); } FASTOR_INLINE void set(double num0, double num1, double num2, double num3, double num4, double num5, double num6, double num7) { value = _mm512_set_pd(num0,num1,num2,num3,num4,num5,num6,num7); } FASTOR_INLINE void set_sequential(double num0) { value = _mm512_setr_pd(num0,num0+1.0,num0+2.0,num0+3.0,num0+4.0,num0+5.0,num0+6.0,num0+7.0); } FASTOR_INLINE void broadcast(const double *data) { // value = _mm512_broadcast_sd(data); } // In-place operators FASTOR_INLINE void operator+=(double num) { value = _mm512_add_pd(value,_mm512_set1_pd(num)); } FASTOR_INLINE void operator+=(__m512d regi) { value = _mm512_add_pd(value,regi); } FASTOR_INLINE void operator+=(const SIMDVector<double,simd_abi::avx512> &a) { value = _mm512_add_pd(value,a.value); } FASTOR_INLINE void operator-=(double num) { value = _mm512_sub_pd(value,_mm512_set1_pd(num)); } FASTOR_INLINE void operator-=(__m512d regi) { value = _mm512_sub_pd(value,regi); } FASTOR_INLINE void operator-=(const SIMDVector<double,simd_abi::avx512> &a) { value = _mm512_sub_pd(value,a.value); } FASTOR_INLINE void operator*=(double num) { value = _mm512_mul_pd(value,_mm512_set1_pd(num)); } FASTOR_INLINE void operator*=(__m512d regi) { value = _mm512_mul_pd(value,regi); } FASTOR_INLINE void operator*=(const SIMDVector<double,simd_abi::avx512> &a) { value = _mm512_mul_pd(value,a.value); } FASTOR_INLINE void operator/=(double num) { value = _mm512_div_pd(value,_mm512_set1_pd(num)); } FASTOR_INLINE void operator/=(__m512d regi) { value = _mm512_div_pd(value,regi); } FASTOR_INLINE void operator/=(const SIMDVector<double,simd_abi::avx512> &a) { value = _mm512_div_pd(value,a.value); } // end of in-place operators // FASTOR_INLINE SIMDVector<double,simd_abi::avx512> shift(FASTOR_INDEX i) { // SIMDVector<double,simd_abi::avx512> out; // if (i==1) // out.value = _mm512_shift1_pd(value); // else if (i==2) // out.value = _mm512_shift2_pd(value); // else if (i==3) // out.value = _mm512_shift3_pd(value); // return out; // } FASTOR_INLINE double sum() { #ifdef FASTOR_HAS_AVX512_REDUCE_ADD return _mm512_reduce_add_pd(value); #else __m256d low = _mm512_castpd512_pd256(value); __m256d high = _mm512_extractf64x4_pd(value,0x1); return _mm256_sum_pd(_mm256_add_pd(low,high)); #endif } FASTOR_INLINE double product() { __m256d low = _mm512_castpd512_pd256(value); __m256d high = _mm512_extractf64x4_pd(value,1); return _mm256_prod_pd(_mm256_mul_pd(low,high)); } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> reverse() { return _mm512_reverse_pd(value); } // FASTOR_INLINE double minimum() {return _mm512_hmin_pd(value);} // FASTOR_INLINE double maximum() {return _mm512_hmax_pd(value);} FASTOR_INLINE double dot(const SIMDVector<double,simd_abi::avx512> &other) { __m512d res = _mm512_mul_pd(value,other.value); __m256d low = _mm512_castpd512_pd256(res); __m256d high = _mm512_extractf64x4_pd(res,1); return _mm256_sum_pd(_mm256_add_pd(low,high)); } __m512d value; }; FASTOR_HINT_INLINE std::ostream& operator<<(std::ostream &os, SIMDVector<double,simd_abi::avx512> a) { // ICC crashes without a copy const __m512d v = a.value; const double* value = reinterpret_cast<const double*>(&v); os << "[" << value[0] << " " << value[1] << " " << value[2] << " " << value[3] << " " << value[4] << " " << value[5] << " " << value[6] << " " << value[7] << "]\n"; return os; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator+( const SIMDVector<double,simd_abi::avx512> &a, const SIMDVector<double,simd_abi::avx512> &b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_add_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator+(const SIMDVector<double,simd_abi::avx512> &a, double b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_add_pd(a.value,_mm512_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator+(double a, const SIMDVector<double,simd_abi::avx512> &b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_add_pd(_mm512_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator+(const SIMDVector<double,simd_abi::avx512> &b) { return b; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator-( const SIMDVector<double,simd_abi::avx512> &a, const SIMDVector<double,simd_abi::avx512> &b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_sub_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator-(const SIMDVector<double,simd_abi::avx512> &a, double b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_sub_pd(a.value,_mm512_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator-(double a, const SIMDVector<double,simd_abi::avx512> &b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_sub_pd(_mm512_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator-(const SIMDVector<double,simd_abi::avx512> &b) { return _mm512_neg_pd(b.value); } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator*( const SIMDVector<double,simd_abi::avx512> &a, const SIMDVector<double,simd_abi::avx512> &b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_mul_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator*(const SIMDVector<double,simd_abi::avx512> &a, double b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_mul_pd(a.value,_mm512_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator*(double a, const SIMDVector<double,simd_abi::avx512> &b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_mul_pd(_mm512_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator/( const SIMDVector<double,simd_abi::avx512> &a, const SIMDVector<double,simd_abi::avx512> &b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_div_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator/(const SIMDVector<double,simd_abi::avx512> &a, double b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_div_pd(a.value,_mm512_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> operator/(double a, const SIMDVector<double,simd_abi::avx512> &b) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_div_pd(_mm512_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> rcp(const SIMDVector<double,simd_abi::avx512> &a) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_rcp14_pd(a.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> sqrt(const SIMDVector<double,simd_abi::avx512> &a) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_sqrt_pd(a.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> rsqrt(const SIMDVector<double,simd_abi::avx512> &a) { SIMDVector<double,simd_abi::avx512> out; out.value = _mm512_rsqrt14_pd(a.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx512> abs(const SIMDVector<double,simd_abi::avx512> &a) { SIMDVector<double,simd_abi::avx512> out; #ifdef FASTOR_HAS_AVX512_ABS out.value = _mm512_abs_pd(a.value); #else for (FASTOR_INDEX i=0UL; i<8UL; ++i) { ((double*)&out.value)[i] = std::abs(((double*)&a.value)[i]); } #endif return out; } #endif // AVX VERSION //-------------------------------------------------------------------------------------------------- #ifdef FASTOR_AVX_IMPL template <> struct SIMDVector<double, simd_abi::avx> { using value_type = __m256d; using scalar_value_type = double; using abi_type = simd_abi::avx; static constexpr FASTOR_INDEX Size = internal::get_simd_vector_size<SIMDVector<double,simd_abi::avx>>::value; static constexpr FASTOR_INLINE FASTOR_INDEX size() {return internal::get_simd_vector_size<SIMDVector<double,simd_abi::avx>>::value;} FASTOR_INLINE SIMDVector() : value(_mm256_setzero_pd()) {} FASTOR_INLINE SIMDVector(double num) : value(_mm256_set1_pd(num)) {} FASTOR_INLINE SIMDVector(__m256d regi) : value(regi) {} FASTOR_INLINE SIMDVector(const double *data, bool Aligned=true) { if (Aligned) value =_mm256_load_pd(data); else value = _mm256_loadu_pd(data); } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator=(double num) { value = _mm256_set1_pd(num); return *this; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator=(__m256d regi) { value = regi; return *this; } FASTOR_INLINE void load(const double *data, bool Aligned=true) { if (Aligned) value =_mm256_load_pd(data); else value = _mm256_loadu_pd(data); } FASTOR_INLINE void store(double *data, bool Aligned=true) const { if (Aligned) _mm256_store_pd(data,value); else _mm256_storeu_pd(data,value); } FASTOR_INLINE void aligned_load(const double *data) { value =_mm256_load_pd(data); } FASTOR_INLINE void aligned_store(double *data) const { _mm256_store_pd(data,value); } FASTOR_INLINE void mask_load(const scalar_value_type *a, uint8_t mask, bool Aligned=false) { #ifdef FASTOR_HAS_AVX512_MASKS if (!Aligned) value = _mm256_mask_loadu_pd(value, mask, a); else value = _mm256_mask_load_pd(value, mask, a); #else // perhaps very inefficient but they never get used int maska[Size]; mask_to_array(mask,maska); value = _mm256_setzero_pd(); for (FASTOR_INDEX i=0; i<Size; ++i) { if (maska[i] == -1) { ((scalar_value_type*)&value)[Size - i - 1] = a[Size - i - 1]; } } unused(Aligned); #endif } FASTOR_INLINE void mask_store(scalar_value_type *a, uint8_t mask, bool Aligned=false) const { #ifdef FASTOR_HAS_AVX512_MASKS if (!Aligned) _mm256_mask_storeu_pd(a, mask, value); else _mm256_mask_store_pd(a, mask, value); #else // perhaps very inefficient but they never get used int maska[Size]; mask_to_array(mask,maska); for (FASTOR_INDEX i=0; i<Size; ++i) { if (maska[i] == -1) { a[Size - i - 1] = ((const scalar_value_type*)&value)[Size - i - 1]; } else { a[Size - i - 1] = 0; } } unused(Aligned); #endif } FASTOR_INLINE double operator[](FASTOR_INDEX i) const {return reinterpret_cast<const double*>(&value)[i];} FASTOR_INLINE double operator()(FASTOR_INDEX i) const {return reinterpret_cast<const double*>(&value)[i];} FASTOR_INLINE void set(double num) { value = _mm256_set1_pd(num); } FASTOR_INLINE void set(double num0, double num1, double num2, double num3) { value = _mm256_set_pd(num0,num1,num2,num3); } FASTOR_INLINE void set_sequential(double num0) { value = _mm256_setr_pd(num0,num0+1.0,num0+2.0,num0+3.0); } FASTOR_INLINE void broadcast(const double *data) { value = _mm256_broadcast_sd(data); } // In-place operators FASTOR_INLINE void operator+=(double num) { value = _mm256_add_pd(value,_mm256_set1_pd(num)); } FASTOR_INLINE void operator+=(__m256d regi) { value = _mm256_add_pd(value,regi); } FASTOR_INLINE void operator+=(const SIMDVector<double,simd_abi::avx> &a) { value = _mm256_add_pd(value,a.value); } FASTOR_INLINE void operator-=(double num) { value = _mm256_sub_pd(value,_mm256_set1_pd(num)); } FASTOR_INLINE void operator-=(__m256d regi) { value = _mm256_sub_pd(value,regi); } FASTOR_INLINE void operator-=(const SIMDVector<double,simd_abi::avx> &a) { value = _mm256_sub_pd(value,a.value); } FASTOR_INLINE void operator*=(double num) { value = _mm256_mul_pd(value,_mm256_set1_pd(num)); } FASTOR_INLINE void operator*=(__m256d regi) { value = _mm256_mul_pd(value,regi); } FASTOR_INLINE void operator*=(const SIMDVector<double,simd_abi::avx> &a) { value = _mm256_mul_pd(value,a.value); } FASTOR_INLINE void operator/=(double num) { value = _mm256_div_pd(value,_mm256_set1_pd(num)); } FASTOR_INLINE void operator/=(__m256d regi) { value = _mm256_div_pd(value,regi); } FASTOR_INLINE void operator/=(const SIMDVector<double,simd_abi::avx> &a) { value = _mm256_div_pd(value,a.value); } // end of in-place operators FASTOR_INLINE SIMDVector<double,simd_abi::avx> shift(FASTOR_INDEX i) { SIMDVector<double,simd_abi::avx> out; if (i==1) out.value = _mm256_shift1_pd(value); else if (i==2) out.value = _mm256_shift2_pd(value); else if (i==3) out.value = _mm256_shift3_pd(value); return out; } FASTOR_INLINE double sum() {return _mm256_sum_pd(value);} FASTOR_INLINE double product() {return _mm256_prod_pd(value);} FASTOR_INLINE SIMDVector<double,simd_abi::avx> reverse() { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_reverse_pd(value); return out; } FASTOR_INLINE double minimum() {return _mm256_hmin_pd(value);} FASTOR_INLINE double maximum() {return _mm256_hmax_pd(value);} FASTOR_INLINE double dot(const SIMDVector<double,simd_abi::avx> &other) { return _mm_cvtsd_f64(_mm256_dp_pd(value,other.value)); } __m256d value; }; FASTOR_HINT_INLINE std::ostream& operator<<(std::ostream &os, SIMDVector<double,simd_abi::avx> a) { // ICC crashes without a copy const __m256d v = a.value; const double* value = reinterpret_cast<const double*>(&v); os << "[" << value[0] << " " << value[1] << " " << value[2] << " " << value[3] << "]\n"; return os; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator+(const SIMDVector<double,simd_abi::avx> &a, const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_add_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator+(const SIMDVector<double,simd_abi::avx> &a, double b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_add_pd(a.value,_mm256_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator+(double a, const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_add_pd(_mm256_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator+(const SIMDVector<double,simd_abi::avx> &b) { return b; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator-(const SIMDVector<double,simd_abi::avx> &a, const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_sub_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator-(const SIMDVector<double,simd_abi::avx> &a, double b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_sub_pd(a.value,_mm256_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator-(double a, const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_sub_pd(_mm256_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator-(const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_neg_pd(b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator*(const SIMDVector<double,simd_abi::avx> &a, const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_mul_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator*(const SIMDVector<double,simd_abi::avx> &a, double b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_mul_pd(a.value,_mm256_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator*(double a, const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_mul_pd(_mm256_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator/(const SIMDVector<double,simd_abi::avx> &a, const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_div_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator/(const SIMDVector<double,simd_abi::avx> &a, double b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_div_pd(a.value,_mm256_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> operator/(double a, const SIMDVector<double,simd_abi::avx> &b) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_div_pd(_mm256_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> rcp(const SIMDVector<double,simd_abi::avx> &a) { SIMDVector<double,simd_abi::avx> out; // This is very inaccurate for double precision out.value = _mm256_cvtps_pd(_mm_rcp_ps(_mm256_cvtpd_ps(a.value))); return out; // // For making it more accurate using Newton Raphson use this // __m128d xmm0 = _mm256_cvtps_pd(_mm_rcp_ps(_mm256_cvtpd_ps(a.value))); // xmm0 = _mm256_mul_pd(xmm0,_mm256_sub_pd(VTWOPD,_mm256_mul_pd(x,xmm0))); // out.value = _mm256_mul_pd(xmm0,_mm256_sub_pd(VTWOPD,_mm256_mul_pd(x,xmm0))); // return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> sqrt(const SIMDVector<double,simd_abi::avx> &a) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_sqrt_pd(a.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> rsqrt(const SIMDVector<double,simd_abi::avx> &a) { SIMDVector<double,simd_abi::avx> out; // This is very inaccurate for double precision out.value = _mm256_cvtps_pd(_mm_rsqrt_ps(_mm256_cvtpd_ps(a.value))); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::avx> abs(const SIMDVector<double,simd_abi::avx> &a) { SIMDVector<double,simd_abi::avx> out; out.value = _mm256_abs_pd(a.value); return out; } #endif // SSE VERSION //------------------------------------------------------------------------------------------------------------ #ifdef FASTOR_SSE2_IMPL template <> struct SIMDVector<double, simd_abi::sse> { using value_type = __m128d; using scalar_value_type = double; using abi_type = simd_abi::sse; static constexpr FASTOR_INDEX Size = internal::get_simd_vector_size<SIMDVector<double,simd_abi::sse>>::value; static constexpr FASTOR_INLINE FASTOR_INDEX size() {return internal::get_simd_vector_size<SIMDVector<double,simd_abi::sse>>::value;} FASTOR_INLINE SIMDVector() : value(_mm_setzero_pd()) {} FASTOR_INLINE SIMDVector(double num) : value(_mm_set1_pd(num)) {} FASTOR_INLINE SIMDVector(__m128d regi) : value(regi) {} FASTOR_INLINE SIMDVector(const double *data, bool Aligned=true) { if (Aligned) value =_mm_load_pd(data); else value = _mm_loadu_pd(data); } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator=(double num) { value = _mm_set1_pd(num); return *this; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator=(__m128d regi) { value = regi; return *this; } FASTOR_INLINE void load(const double *data, bool Aligned=true) { if (Aligned) value =_mm_load_pd(data); else value = _mm_loadu_pd(data); } FASTOR_INLINE void store(double *data, bool Aligned=true) const { if (Aligned) _mm_store_pd(data,value); else _mm_storeu_pd(data,value); } FASTOR_INLINE void aligned_load(const double *data) { value =_mm_load_pd(data); } FASTOR_INLINE void aligned_store(double *data) const { _mm_store_pd(data,value); } FASTOR_INLINE void mask_load(const scalar_value_type *a, uint8_t mask, bool Aligned=false) { #ifdef FASTOR_HAS_AVX512_MASKS if (!Aligned) value = _mm_mask_loadu_pd(value, mask, a); else value = _mm_mask_load_pd(value, mask, a); #else // perhaps very inefficient but they never get used int maska[Size]; mask_to_array(mask,maska); value = _mm_setzero_pd(); for (FASTOR_INDEX i=0; i<Size; ++i) { if (maska[i] == -1) { ((scalar_value_type*)&value)[Size - i - 1] = a[Size - i - 1]; } } unused(Aligned); #endif } FASTOR_INLINE void mask_store(scalar_value_type *a, uint8_t mask, bool Aligned=false) const { #ifdef FASTOR_HAS_AVX512_MASKS if (!Aligned) _mm_mask_storeu_pd(a, mask, value); else _mm_mask_store_pd(a, mask, value); #else // perhaps very inefficient but they never get used int maska[Size]; mask_to_array(mask,maska); for (FASTOR_INDEX i=0; i<Size; ++i) { if (maska[i] == -1) { a[Size - i - 1] = ((const scalar_value_type*)&value)[Size - i - 1]; } else { a[Size - i - 1] = 0; } } unused(Aligned); #endif } FASTOR_INLINE double operator[](FASTOR_INDEX i) const {return reinterpret_cast<const double*>(&value)[i];} FASTOR_INLINE double operator()(FASTOR_INDEX i) const {return reinterpret_cast<const double*>(&value)[i];} FASTOR_INLINE void set(double num) { value = _mm_set1_pd(num); } FASTOR_INLINE void set(double num0, double num1) { value = _mm_set_pd(num0,num1); } FASTOR_INLINE void set_sequential(double num0) { value = _mm_setr_pd(num0,num0+1.0); } FASTOR_INLINE void broadcast(const double *data) { value = _mm_load1_pd(data); } // In-place operators FASTOR_INLINE void operator+=(double num) { value = _mm_add_pd(value,_mm_set1_pd(num)); } FASTOR_INLINE void operator+=(__m128d regi) { value = _mm_add_pd(value,regi); } FASTOR_INLINE void operator+=(const SIMDVector<double,simd_abi::sse> &a) { value = _mm_add_pd(value,a.value); } FASTOR_INLINE void operator-=(double num) { value = _mm_sub_pd(value,_mm_set1_pd(num)); } FASTOR_INLINE void operator-=(__m128d regi) { value = _mm_sub_pd(value,regi); } FASTOR_INLINE void operator-=(const SIMDVector<double,simd_abi::sse> &a) { value = _mm_sub_pd(value,a.value); } FASTOR_INLINE void operator*=(double num) { value = _mm_mul_pd(value,_mm_set1_pd(num)); } FASTOR_INLINE void operator*=(__m128d regi) { value = _mm_mul_pd(value,regi); } FASTOR_INLINE void operator*=(const SIMDVector<double,simd_abi::sse> &a) { value = _mm_mul_pd(value,a.value); } FASTOR_INLINE void operator/=(double num) { value = _mm_div_pd(value,_mm_set1_pd(num)); } FASTOR_INLINE void operator/=(__m128d regi) { value = _mm_div_pd(value,regi); } FASTOR_INLINE void operator/=(const SIMDVector<double,simd_abi::sse> &a) { value = _mm_div_pd(value,a.value); } // end of in-place operators FASTOR_INLINE SIMDVector<double,simd_abi::sse> shift(FASTOR_INDEX i) { SIMDVector<double,simd_abi::sse> out; FASTOR_ASSERT(i==1,"INCORRECT SHIFT INDEX"); out.value = _mm_shift1_pd(value); return out; } FASTOR_INLINE double sum() {return _mm_sum_pd(value);} FASTOR_INLINE double product() {return _mm_prod_pd(value);} FASTOR_INLINE SIMDVector<double,simd_abi::sse> reverse() { SIMDVector<double,simd_abi::sse> out; out.value = _mm_reverse_pd(value); return out; } FASTOR_INLINE double minimum() {return _mm_hmin_pd(value);} FASTOR_INLINE double maximum() {return _mm_hmax_pd(value);} FASTOR_INLINE double dot(const SIMDVector<double,simd_abi::sse> &other) { #ifdef FASTOR_SSE4_1_IMPL return _mm_cvtsd_f64(_mm_dp_pd(value,other.value,0xff)); #else return _mm_sum_pd(_mm_mul_pd(value,other.value)); #endif } __m128d value; }; FASTOR_HINT_INLINE std::ostream& operator<<(std::ostream &os, SIMDVector<double,simd_abi::sse> a) { // ICC crashes without a copy const __m128d v = a.value; const double* value = reinterpret_cast<const double*>(&v); os << "[" << value[0] << " " << value[1] << "]\n"; return os; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator+(const SIMDVector<double,simd_abi::sse> &a, const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_add_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator+(const SIMDVector<double,simd_abi::sse> &a, double b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_add_pd(a.value,_mm_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator+(double a, const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_add_pd(_mm_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator+(const SIMDVector<double,simd_abi::sse> &b) { return b; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator-(const SIMDVector<double,simd_abi::sse> &a, const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_sub_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator-(const SIMDVector<double,simd_abi::sse> &a, double b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_sub_pd(a.value,_mm_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator-(double a, const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_sub_pd(_mm_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator-(const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_neg_pd(b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator*(const SIMDVector<double,simd_abi::sse> &a, const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_mul_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator*(const SIMDVector<double,simd_abi::sse> &a, double b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_mul_pd(a.value,_mm_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator*(double a, const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_mul_pd(_mm_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator/(const SIMDVector<double,simd_abi::sse> &a, const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_div_pd(a.value,b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator/(const SIMDVector<double,simd_abi::sse> &a, double b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_div_pd(a.value,_mm_set1_pd(b)); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> operator/(double a, const SIMDVector<double,simd_abi::sse> &b) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_div_pd(_mm_set1_pd(a),b.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> rcp(const SIMDVector<double,simd_abi::sse> &a) { SIMDVector<double,simd_abi::sse> out; // This is very inaccurate for double precision out.value = _mm_cvtps_pd(_mm_rcp_ps(_mm_cvtpd_ps(a.value))); return out; /* // For making it more accurate using Newton Raphson use this __m128d xmm0 = _mm_cvtps_pd(_mm_rcp_ps(_mm_cvtpd_ps(a.value))); xmm0 = _mm_mul_pd(xmm0,_mm_sub_pd(TWOPD,_mm_mul_pd(x,xmm0))); out.value = _mm_mul_pd(xmm0,_mm_sub_pd(TWOPD,_mm_mul_pd(x,xmm0))); return out; */ } FASTOR_INLINE SIMDVector<double,simd_abi::sse> sqrt(const SIMDVector<double,simd_abi::sse> &a) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_sqrt_pd(a.value); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> rsqrt(const SIMDVector<double,simd_abi::sse> &a) { SIMDVector<double,simd_abi::sse> out; // This is very inaccurate for double precision out.value = _mm_cvtps_pd(_mm_rsqrt_ps(_mm_cvtpd_ps(a.value))); return out; } FASTOR_INLINE SIMDVector<double,simd_abi::sse> abs(const SIMDVector<double,simd_abi::sse> &a) { SIMDVector<double,simd_abi::sse> out; out.value = _mm_abs_pd(a.value); return out; } #endif } // end of namespace Fastor #endif // // SIMD_VECTOR_DOUBLE_H
15,817
2,151
// 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 DEVICE_USB_USB_DEVICE_WIN_H_ #define DEVICE_USB_USB_DEVICE_WIN_H_ #include <string> #include "base/macros.h" #include "base/threading/thread_checker.h" #include "device/usb/usb_device.h" namespace base { class SequencedTaskRunner; } namespace device { struct UsbDeviceDescriptor; class UsbDeviceWin : public UsbDevice { public: // UsbDevice implementation: void Open(OpenCallback callback) override; protected: friend class UsbServiceWin; friend class UsbDeviceHandleWin; // Called by UsbServiceWin only; UsbDeviceWin(const std::string& device_path, const std::string& hub_path, int port_number, const std::string& driver_name, scoped_refptr<base::SequencedTaskRunner> task_runner); ~UsbDeviceWin() override; const std::string& device_path() const { return device_path_; } int port_number() const { return port_number_; } const std::string& driver_name() const { return driver_name_; } // Opens the device's parent hub in order to read the device, configuration // and string descriptors. void ReadDescriptors(base::OnceCallback<void(bool)> callback); private: void OnReadDescriptors(base::OnceCallback<void(bool)> callback, scoped_refptr<UsbDeviceHandle> device_handle, std::unique_ptr<UsbDeviceDescriptor> descriptor); void OnReadStringDescriptors( base::OnceCallback<void(bool)> callback, scoped_refptr<UsbDeviceHandle> device_handle, std::unique_ptr<std::map<uint8_t, base::string16>> string_map); void OnOpenedToReadWebUsbDescriptors( base::OnceCallback<void(bool)> callback, scoped_refptr<UsbDeviceHandle> device_handle); void OnReadWebUsbDescriptors(base::OnceCallback<void(bool)> callback, scoped_refptr<UsbDeviceHandle> device_handle, const GURL& landing_page); private: base::ThreadChecker thread_checker_; const std::string device_path_; const std::string hub_path_; const int port_number_; const std::string driver_name_; scoped_refptr<base::SequencedTaskRunner> task_runner_; scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; DISALLOW_COPY_AND_ASSIGN(UsbDeviceWin); }; } // namespace device #endif // DEVICE_USB_USB_DEVICE_WIN_H_
949
311
# coding=utf-8 """ The List Webhooks API endpoint Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/webhooks/ Schema: https://api.mailchimp.com/schema/3.0/Lists/Webhooks/Instance.json """ from __future__ import unicode_literals from mailchimp3.baseapi import BaseApi from mailchimp3.helpers import check_url class ListWebhooks(BaseApi): """ Manage webhooks for a specific MailChimp list. """ def __init__(self, *args, **kwargs): """ Initialize the endpoint """ super(ListWebhooks, self).__init__(*args, **kwargs) self.endpoint = 'lists' self.list_id = None self.webhook_id = None def create(self, list_id, data): """ Create a new webhook for a specific list. The documentation does not include any required request body parameters but the url parameter is being listed here as a required parameter in documentation and error-checking based on the description of the method :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { "url": string* } """ self.list_id = list_id if 'url' not in data: raise KeyError('The list webhook must have a url') check_url(data['url']) response = self._mc_client._post(url=self._build_path(list_id, 'webhooks'), data=data) if response is not None: self.webhook_id = response['id'] else: self.webhook_id = None return response def all(self, list_id): """ Get information about all webhooks for a specific list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` """ self.list_id = list_id self.webhook_id = None return self._mc_client._get(url=self._build_path(list_id, 'webhooks')) def get(self, list_id, webhook_id): """ Get information about a specific webhook. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param webhook_id: The unique id for the webhook. :type webhook_id: :py:class:`str` """ self.list_id = list_id self.webhook_id = webhook_id return self._mc_client._get(url=self._build_path(list_id, 'webhooks', webhook_id)) def update(self, list_id, webhook_id, data): """ Update the settings for an existing webhook. :param list_id: The unique id for the list :type list_id: :py:class:`str` :param webhook_id: The unique id for the webhook :type webhook_id: :py:class:`str` """ self.list_id = list_id self.webhook_id = webhook_id return self._mc_client._patch(url=self._build_path(list_id, 'webhooks', webhook_id), data=data) def delete(self, list_id, webhook_id): """ Delete a specific webhook in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param webhook_id: The unique id for the webhook. :type webhook_id: :py:class:`str` """ self.list_id = list_id self.webhook_id = webhook_id return self._mc_client._delete(url=self._build_path(list_id, 'webhooks', webhook_id))
1,526
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. * *************************************************************/ #ifndef SC_CHART2UNO_HXX #define SC_CHART2UNO_HXX #include "cellsuno.hxx" // for XModifyListenerArr_Impl / ScLinkListener #include "rangelst.hxx" #include "externalrefmgr.hxx" #include "token.hxx" #include "chartlis.hxx" #include <svl/lstner.hxx> #include <com/sun/star/chart/ChartDataRowSource.hpp> #include <com/sun/star/chart2/data/XDataProvider.hpp> #include <com/sun/star/chart2/data/XRangeXMLConversion.hpp> #include <com/sun/star/chart2/data/XDataSource.hpp> #include <com/sun/star/chart2/data/XDataSequence.hpp> #include <com/sun/star/chart2/data/XTextualDataSequence.hpp> #include <com/sun/star/chart2/data/XNumericalDataSequence.hpp> #include <com/sun/star/chart2/data/XLabeledDataSequence.hpp> #include <com/sun/star/chart2/data/DataSequenceRole.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/util/XCloneable.hpp> #include <com/sun/star/util/XModifyBroadcaster.hpp> // #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ // #include <com/sun/star/lang/XUnoTunnel.hpp> // #endif #include <cppuhelper/implbase2.hxx> #include <cppuhelper/implbase4.hxx> #include <cppuhelper/implbase6.hxx> #include <cppuhelper/implbase7.hxx> #include <rtl/ustring.hxx> #include <svl/itemprop.hxx> #include <hash_set> #include <list> #include <vector> #include <memory> #include <boost/shared_ptr.hpp> #define USE_CHART2_EMPTYDATASEQUENCE 0 class ScDocument; // DataProvider ============================================================== class ScChart2DataProvider : public ::cppu::WeakImplHelper4< ::com::sun::star::chart2::data::XDataProvider, ::com::sun::star::chart2::data::XRangeXMLConversion, ::com::sun::star::beans::XPropertySet, ::com::sun::star::lang::XServiceInfo>, SfxListener { public: explicit ScChart2DataProvider( ScDocument* pDoc ); virtual ~ScChart2DataProvider(); virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); // XDataProvider --------------------------------------------------------- virtual ::sal_Bool SAL_CALL createDataSourcePossible( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArguments ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSource > SAL_CALL createDataSource( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArguments ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL detectArguments( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSource >& xDataSource ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL createDataSequenceByRangeRepresentationPossible( const ::rtl::OUString& aRangeRepresentation ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSequence > SAL_CALL createDataSequenceByRangeRepresentation( const ::rtl::OUString& aRangeRepresentation ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XRangeSelection > SAL_CALL getRangeSelection() throw (::com::sun::star::uno::RuntimeException); /* virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > SAL_CALL getNumberFormatsSupplier() throw (::com::sun::star::uno::RuntimeException);*/ // XRangeXMLConversion --------------------------------------------------- virtual ::rtl::OUString SAL_CALL convertRangeToXML( const ::rtl::OUString& sRangeRepresentation ) throw ( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); virtual ::rtl::OUString SAL_CALL convertRangeFromXML( const ::rtl::OUString& sXMLRange ) throw ( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); // XPropertySet ---------------------------------------------------------- virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Any& rValue) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& rPropertyName) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>& xListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XServiceInfo ---------------------------------------------------------- virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName) throw( ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException); private: ScDocument* m_pDocument; SfxItemPropertySet m_aPropSet; sal_Bool m_bIncludeHiddenCells; }; // DataSource ================================================================ class ScChart2DataSource : public ::cppu::WeakImplHelper2< ::com::sun::star::chart2::data::XDataSource, ::com::sun::star::lang::XServiceInfo>, SfxListener { public: explicit ScChart2DataSource( ScDocument* pDoc); virtual ~ScChart2DataSource(); virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); // XDataSource ----------------------------------------------------------- virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence > > SAL_CALL getDataSequences() throw (::com::sun::star::uno::RuntimeException); // XServiceInfo ---------------------------------------------------------- virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName) throw( ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException); // implementation void AddLabeledSequence(const com::sun::star::uno::Reference < com::sun::star::chart2::data::XLabeledDataSequence >& xNew); private: ScDocument* m_pDocument; typedef std::list < com::sun::star::uno::Reference< com::sun::star::chart2::data::XLabeledDataSequence > > LabeledList; LabeledList m_aLabeledSequences; }; // DataSequence ============================================================== class ScChart2DataSequence : public ::cppu::WeakImplHelper7< ::com::sun::star::chart2::data::XDataSequence, ::com::sun::star::chart2::data::XTextualDataSequence, ::com::sun::star::chart2::data::XNumericalDataSequence, ::com::sun::star::util::XCloneable, ::com::sun::star::util::XModifyBroadcaster, ::com::sun::star::beans::XPropertySet, // ::com::sun::star::lang::XUnoTunnel, ::com::sun::star::lang::XServiceInfo>, SfxListener { public: explicit ScChart2DataSequence( ScDocument* pDoc, const com::sun::star::uno::Reference< com::sun::star::chart2::data::XDataProvider >& xDP, ::std::vector<ScSharedTokenRef>* pTokens, bool bIncludeHiddenCells ); virtual ~ScChart2DataSequence(); virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); // XDataSequence --------------------------------------------------------- virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL getData() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getSourceRangeRepresentation() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL generateLabel(::com::sun::star::chart2::data::LabelOrigin nOrigin) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getNumberFormatKeyByIndex( ::sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XNumericalDataSequence -------------------------------------------------- virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getNumericalData( ) throw (::com::sun::star::uno::RuntimeException); // XTextualDataSequence -------------------------------------------------- virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getTextualData( ) throw (::com::sun::star::uno::RuntimeException); // XPropertySet ---------------------------------------------------------- virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Any& rValue) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& rPropertyName) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>& xListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XCloneable ------------------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone() throw (::com::sun::star::uno::RuntimeException); // XModifyBroadcaster ---------------------------------------------------- virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo ---------------------------------------------------------- virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName) throw( ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException); // XUnoTunnel ------------------------------------------------------------ // virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< // sal_Int8 >& aIdentifier ) // throw(::com::sun::star::uno::RuntimeException); // static const com::sun::star::uno::Sequence<sal_Int8>& getUnoTunnelId(); // static ScChart2DataSequence* getImplementation( const com::sun::star::uno::Reference< // com::sun::star::uno::XInterface> xObj ); private: void setDataChangedHint(bool b); // Implementation -------------------------------------------------------- void RefChanged(); DECL_LINK( ValueListenerHdl, SfxHint* ); private: ScChart2DataSequence(); // disabled ScChart2DataSequence(const ScChart2DataSequence& r); // disabled class ExternalRefListener : public ScExternalRefManager::LinkListener { public: ExternalRefListener(ScChart2DataSequence& rParent, ScDocument* pDoc); virtual ~ExternalRefListener(); virtual void notify(sal_uInt16 nFileId, ScExternalRefManager::LinkUpdateType eType); void addFileId(sal_uInt16 nFileId); void removeFileId(sal_uInt16 nFileId); const ::std::hash_set<sal_uInt16>& getAllFileIds(); private: ExternalRefListener(); ExternalRefListener(const ExternalRefListener& r); ScChart2DataSequence& mrParent; ::std::hash_set<sal_uInt16> maFileIds; ScDocument* mpDoc; }; /** * Build an internal data array to cache the data ranges, and other * information such as hidden values. */ void BuildDataCache(); void RebuildDataCache(); sal_Int32 FillCacheFromExternalRef(const ScSharedTokenRef& pToken); void UpdateTokensFromRanges(const ScRangeList& rRanges); ExternalRefListener* GetExtRefListener(); void StopListeningToAllExternalRefs(); void CopyData(const ScChart2DataSequence& r); private: // data array struct Item { double mfValue; ::rtl::OUString maString; bool mbIsValue; Item(); }; class HiddenRangeListener : public ScChartHiddenRangeListener { public: HiddenRangeListener(ScChart2DataSequence& rParent); virtual ~HiddenRangeListener(); virtual void notify(); private: ScChart2DataSequence& mrParent; }; ::std::list<Item> m_aDataArray; /** * Cached data for getData. We may also need to cache data for the * numerical and textural data series if they turn out to be bottlenecks * under certain scenarios. */ ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > m_aMixedDataCache; ::com::sun::star::uno::Sequence<sal_Int32> m_aHiddenValues; // properties ::com::sun::star::chart2::data::DataSequenceRole m_aRole; sal_Bool m_bIncludeHiddenCells; // internals typedef ::std::auto_ptr< ::std::vector<ScSharedTokenRef> > TokenListPtr; typedef ::std::auto_ptr< ::std::vector<sal_uInt32> > RangeIndexMapPtr; typedef ::std::auto_ptr<ExternalRefListener> ExtRefListenerPtr; sal_Int64 m_nObjectId; ScDocument* m_pDocument; TokenListPtr m_pTokens; RangeIndexMapPtr m_pRangeIndices; ExtRefListenerPtr m_pExtRefListener; com::sun::star::uno::Reference < com::sun::star::chart2::data::XDataProvider > m_xDataProvider; SfxItemPropertySet m_aPropSet; ::std::auto_ptr<HiddenRangeListener> m_pHiddenListener; ScLinkListener* m_pValueListener; XModifyListenerArr_Impl m_aValueListeners; bool m_bGotDataChangedHint; bool m_bExtDataRebuildQueued; }; #if USE_CHART2_EMPTYDATASEQUENCE // DataSequence ============================================================== class ScChart2EmptyDataSequence : public ::cppu::WeakImplHelper6< ::com::sun::star::chart2::data::XDataSequence, ::com::sun::star::chart2::data::XTextualDataSequence, ::com::sun::star::util::XCloneable, ::com::sun::star::util::XModifyBroadcaster, ::com::sun::star::beans::XPropertySet, // ::com::sun::star::lang::XUnoTunnel, ::com::sun::star::lang::XServiceInfo>, SfxListener { public: explicit ScChart2EmptyDataSequence( ScDocument* pDoc, const com::sun::star::uno::Reference< com::sun::star::chart2::data::XDataProvider >& xDP, const ScRangeListRef& rRangeList, sal_Bool bColumn ); virtual ~ScChart2EmptyDataSequence(); virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); // XDataSequence --------------------------------------------------------- virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL getData() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getSourceRangeRepresentation() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL generateLabel(::com::sun::star::chart2::data::LabelOrigin nOrigin) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getNumberFormatKeyByIndex( ::sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XTextualDataSequence -------------------------------------------------- virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getTextualData( ) throw (::com::sun::star::uno::RuntimeException); // XPropertySet ---------------------------------------------------------- virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Any& rValue) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& rPropertyName) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>& xListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener>& rListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XCloneable ------------------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone() throw (::com::sun::star::uno::RuntimeException); // XModifyBroadcaster ---------------------------------------------------- virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo ---------------------------------------------------------- virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName) throw( ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException); // XUnoTunnel ------------------------------------------------------------ // virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< // sal_Int8 >& aIdentifier ) // throw(::com::sun::star::uno::RuntimeException); // static const com::sun::star::uno::Sequence<sal_Int8>& getUnoTunnelId(); // static ScChart2DataSequence* getImplementation( const com::sun::star::uno::Reference< // com::sun::star::uno::XInterface> xObj ); // Implementation -------------------------------------------------------- ScRangeListRef GetRangeList() { return m_xRanges; } private: // properties ::com::sun::star::chart2::data::DataSequenceRole m_aRole; sal_Bool m_bIncludeHiddenCells; // internals ScRangeListRef m_xRanges; ScDocument* m_pDocument; com::sun::star::uno::Reference < com::sun::star::chart2::data::XDataProvider > m_xDataProvider; SfxItemPropertySet m_aPropSet; sal_Bool m_bColumn; // defines the orientation to create the right labels }; #endif #endif // SC_CHART2UNO_HXX
10,802
3,426
<reponame>toinouH/Geyser /* * Copyright (c) 2019-2020 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */ package org.geysermc.connector.network.translators.java; import com.github.steveice10.mc.protocol.packet.ingame.client.ClientPluginMessagePacket; import com.github.steveice10.mc.protocol.packet.ingame.server.ServerPluginMessagePacket; import com.google.common.base.Charsets; import com.nukkitx.protocol.bedrock.packet.TransferPacket; import org.geysermc.connector.GeyserConnector; import org.geysermc.connector.GeyserLogger; import org.geysermc.connector.common.AuthType; import org.geysermc.connector.network.session.GeyserSession; import org.geysermc.connector.network.translators.PacketTranslator; import org.geysermc.connector.network.translators.Translator; import org.geysermc.cumulus.Form; import org.geysermc.cumulus.Forms; import org.geysermc.cumulus.util.FormType; import java.nio.charset.StandardCharsets; @Translator(packet = ServerPluginMessagePacket.class) public class JavaPluginMessageTranslator extends PacketTranslator<ServerPluginMessagePacket> { private final GeyserLogger logger = GeyserConnector.getInstance().getLogger(); @Override public void translate(GeyserSession session, ServerPluginMessagePacket packet) { // The only plugin messages it has to listen for are Floodgate plugin messages if (session.getRemoteAuthType() != AuthType.FLOODGATE) { return; } String channel = packet.getChannel(); if (channel.equals("floodgate:form")) { byte[] data = packet.getData(); // receive: first byte is form type, second and third are the id, remaining is the form data // respond: first and second byte id, remaining is form response data FormType type = FormType.getByOrdinal(data[0]); if (type == null) { throw new NullPointerException( "Got type " + data[0] + " which isn't a valid form type!"); } String dataString = new String(data, 3, data.length - 3, Charsets.UTF_8); Form form = Forms.fromJson(dataString, type); form.setResponseHandler(response -> { byte[] raw = response.getBytes(StandardCharsets.UTF_8); byte[] finalData = new byte[raw.length + 2]; finalData[0] = data[1]; finalData[1] = data[2]; System.arraycopy(raw, 0, finalData, 2, raw.length); session.sendDownstreamPacket(new ClientPluginMessagePacket(channel, finalData)); }); session.sendForm(form); } else if (channel.equals("floodgate:transfer")) { byte[] data = packet.getData(); // port, 4 bytes. remaining data, address. if (data.length < 5) { throw new NullPointerException("Transfer data should be at least 5 bytes long"); } int port = data[0] << 24 | (data[1] & 0xFF) << 16 | (data[2] & 0xFF) << 8 | data[3] & 0xFF; String address = new String(data, 4, data.length - 4); if (logger.isDebug()) { logger.info("Transferring client to: " + address + ":" + port); } TransferPacket transferPacket = new TransferPacket(); transferPacket.setAddress(address); transferPacket.setPort(port); session.sendUpstreamPacket(transferPacket); } } }
1,743
1,986
#ifndef MAIN_SOCKSERV_H_ #define MAIN_SOCKSERV_H_ #include <stdint.h> #include <string> #include <set> #include "Socket.h" #include "FreeRTOS.h" #include <freertos/FreeRTOS.h> #include <freertos/queue.h> /** * @brief Provide a socket listener and the ability to send data to connected partners. * * We use this class to listen on a given socket and accept connections from partners. * When we call one of the sendData() methods, the data passed as parameters is then sent * to the connected partners. * * Here is an example code fragment that uses the class: * * @code{.cpp} * SockServ mySockServer = SockServ(9876); * mySockServer.start(); * * // Later ... * mySockServer.sendData(data, dataLen); * @endcode * */ class SockServ { private: static void acceptTask(void*); uint16_t m_port; Socket m_serverSocket; FreeRTOS::Semaphore m_clientSemaphore = FreeRTOS::Semaphore("clientSemaphore"); std::set<Socket> m_clientSet; QueueHandle_t m_acceptQueue; bool m_useSSL; public: SockServ(uint16_t port); SockServ(); ~SockServ(); int connectedCount(); void disconnect(Socket s); bool getSSL(); size_t receiveData(Socket s, void* pData, size_t maxData); void sendData(uint8_t* data, size_t length); void sendData(std::string str); void setPort(uint16_t port); void setSSL(bool use = true); void start(); void stop(); Socket waitForData(std::set<Socket>& socketSet); Socket waitForNewClient(); }; #endif /* MAIN_SOCKSERV_H_ */
590
1,025
package com.baidu.unbiz.fluentvalidator.group; /** * @author zhangxu */ public class CheckManufacturer { }
40
391
<reponame>weblucas/mseg-semantic #!/usr/bin/python3 from pathlib import Path from types import SimpleNamespace from mseg_semantic.scripts.collect_results import parse_result_file from mseg_semantic.tool.test_oracle_tax import test_oracle_taxonomy_model REPO_ROOT_ = Path(__file__).resolve().parent.parent # Replace this variables with your own path to run integration tests. INTEGRATION_TEST_OUTPUT_DIR = '/srv/scratch/jlambert30/MSeg/mseg-semantic/integration_test_data' # Copy the mseg-3m-1080p model there CAMVID_MODEL_PATH = f'{INTEGRATION_TEST_OUTPUT_DIR}/camvid-11-1m.pth' def test_evaluate_oracle_tax_model(): """ Ensure oracle model testing script works correctly. base_sizes=( #360 720 #1080 python -u mseg_semantic/tool/test_oracle_tax.py --config=${config_fpath} dataset ${dataset_name} model_path ${model_fpath} model_name ${model_name} """ base_size = 1080 d = { 'dataset': 'camvid-11', 'config': f'{REPO_ROOT_}/mseg_semantic/config/test/default_config_${base_size}_ss.yaml', 'model_path': CAMVID_MODEL_PATH, 'model_name': 'mseg-3m-1080p', 'input_file': 'default', 'base_size': base_size, 'test_h': 713, 'test_w': 713, 'scales': [1.0], 'save_folder': 'default', 'arch': 'hrnet', 'index_start': 0, 'index_step': 0, 'workers': 16, 'has_prediction': False, 'split': 'val', 'vis_freq': 20 } args = SimpleNamespace(**d) use_gpu = True test_oracle_taxonomy_model(args, use_gpu) # Ensure that results match paper result_file_path = INTEGRATION_TEST_OUTPUT_DIR result_file_path += f'/camvid-11-1m/camvid-11/{base_size}/ss/results.txt' assert Path(result_file_path).exists() mIoU = parse_result_file(result_file_path) print(f"mIoU: {mIoU}") # single-scale result assert mIoU == 78.79 OKGREEN = '\033[92m' ENDC = '\033[0m' print(OKGREEN + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>" + ENDC) print(OKGREEN + 'Oracle model evalution passed successfully' + ENDC) print(OKGREEN + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>" + ENDC) if __name__ == '__main__': test_evaluate_oracle_tax_model()
880
809
/** * @file * @brief CPU Information Library * * @date 19.03.2020 * @author <NAME> */ #ifndef LIB_CPU_INFO_H_ #define LIB_CPU_INFO_H_ #define FEATURE_NAME_LEN 32 #define MAX_NUM_FEATURES 5 #include <stdint.h> #include <module/embox/arch/cpu_info.h> struct cpu_feature { char name[FEATURE_NAME_LEN]; unsigned int val; }; struct cpu_info { char vendor_id[FEATURE_NAME_LEN]; struct cpu_feature feature[MAX_NUM_FEATURES]; unsigned int feature_count; }; extern void set_feature_val(struct cpu_info *info, const char *name, unsigned int val); extern struct cpu_info *get_cpu_info(void); extern uint64_t get_cpu_counter(void); #endif /* LIB_CPU_INFO_H_ */
257
348
<filename>docs/data/leg-t2/082/08202154.json {"nom":"Saint-Amans-de-Pellagal","circ":"2ème circonscription","dpt":"Tarn-et-Garonne","inscrits":179,"abs":69,"votants":110,"blancs":6,"nuls":2,"exp":102,"res":[{"nuance":"FN","nom":"<NAME>","voix":54},{"nuance":"RDG","nom":"Mme <NAME>","voix":48}]}
126
17,481
<reponame>marcin-kozinski/dagger /* * Copyright (C) 2019 The Dagger 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 dagger.hilt.android.processor.internal.androidentrypoint; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import dagger.hilt.android.processor.internal.AndroidClassNames; import dagger.hilt.processor.internal.Processors; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.lang.model.util.ElementFilter; /** Generates an Hilt Service class for the @AndroidEntryPoint annotated class. */ public final class ServiceGenerator { private final ProcessingEnvironment env; private final AndroidEntryPointMetadata metadata; private final ClassName generatedClassName; public ServiceGenerator(ProcessingEnvironment env, AndroidEntryPointMetadata metadata) { this.env = env; this.metadata = metadata; generatedClassName = metadata.generatedClassName(); } // @Generated("ServiceGenerator") // abstract class Hilt_$CLASS extends $BASE { // ... // } public void generate() throws IOException { TypeSpec.Builder builder = TypeSpec.classBuilder(generatedClassName.simpleName()) .addOriginatingElement(metadata.element()) .superclass(metadata.baseClassName()) .addModifiers(metadata.generatedClassModifiers()) .addMethods(baseClassConstructors()) .addMethod(onCreateMethod()); Generators.addGeneratedBaseClassJavadoc(builder, AndroidClassNames.ANDROID_ENTRY_POINT); Processors.addGeneratedAnnotation(builder, env, getClass()); Generators.copyLintAnnotations(metadata.element(), builder); Generators.copySuppressAnnotations(metadata.element(), builder); metadata.baseElement().getTypeParameters().stream() .map(TypeVariableName::get) .forEachOrdered(builder::addTypeVariable); Generators.addInjectionMethods(metadata, builder); Generators.addComponentOverride(metadata, builder); JavaFile.builder(generatedClassName.packageName(), builder.build()) .build().writeTo(env.getFiler()); } private List<MethodSpec> baseClassConstructors() { return ElementFilter.constructorsIn(metadata.baseElement().getEnclosedElements()) .stream() .map((constructor) -> { List<ParameterSpec> params = constructor.getParameters() .stream() .map(p -> ParameterSpec.builder(TypeName.get(p.asType()), p.toString()).build()) .collect(Collectors.toList()); return MethodSpec.constructorBuilder() .addParameters(params) .addStatement( "super($L)", params.stream().map(p -> p.name).collect(Collectors.joining(","))) .build(); }) .collect(Collectors.toList()); } // @CallSuper // @Override // protected void onCreate() { // inject(); // super.onCreate(); // } private MethodSpec onCreateMethod() throws IOException { return MethodSpec.methodBuilder("onCreate") .addAnnotation(AndroidClassNames.CALL_SUPER) .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addStatement("inject()") .addStatement("super.onCreate()") .build(); } }
1,452
892
{ "schema_version": "1.2.0", "id": "GHSA-2cfp-qxgv-mqcq", "modified": "2022-02-25T00:01:20Z", "published": "2022-02-18T00:00:32Z", "aliases": [ "CVE-2014-8597" ], "details": "A reflected cross-site scripting (XSS) vulnerability in PHP-Fusion 7.02.07 allows remote attackers to inject arbitrary web script or HTML via the status parameter in the CMS admin panel.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2014-8597" }, { "type": "WEB", "url": "https://www.xlabs.com.br/blog/cve-2014-8597-php-fusion-xss-injection-reflected/" } ], "database_specific": { "cwe_ids": [ "CWE-79" ], "severity": "MODERATE", "github_reviewed": false } }
367
72,551
//===--- Once.cpp - Runtime support for lazy initialization ---------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Swift runtime functions in support of lazy initialization. // //===----------------------------------------------------------------------===// #include "Private.h" #include "swift/Runtime/Once.h" #include "swift/Runtime/Debug.h" #include <type_traits> using namespace swift; #ifdef SWIFT_STDLIB_SINGLE_THREADED_RUNTIME // No dependencies on single-threaded environments. #elif defined(__APPLE__) // On macOS and iOS, swift_once is implemented using GCD. // The compiler emits an inline check matching the barrier-free inline fast // path of dispatch_once(). See SwiftTargetInfo.OnceDonePredicateValue. #include <dispatch/dispatch.h> static_assert(std::is_same<swift_once_t, dispatch_once_t>::value, "swift_once_t and dispatch_once_t must stay in sync"); #else // On non-Darwin platforms we do not assume any barrier-free inline path // and SwiftTargetInfo.OnceDonePredicateValue is unset in the compiler. #endif // The compiler generates the swift_once_t values as word-sized zero-initialized // variables, so we want to make sure swift_once_t isn't larger than the // platform word or the function below might overwrite something it shouldn't. static_assert(sizeof(swift_once_t) <= sizeof(void*), "swift_once_t must be no larger than the platform word"); /// Runs the given function with the given context argument exactly once. /// The predicate argument must point to a global or static variable of static /// extent of type swift_once_t. void swift::swift_once(swift_once_t *predicate, void (*fn)(void *), void *context) { #ifdef SWIFT_STDLIB_SINGLE_THREADED_RUNTIME if (! *predicate) { *predicate = true; fn(context); } #elif defined(__APPLE__) dispatch_once_f(predicate, context, fn); #elif defined(__CYGWIN__) _swift_once_f(predicate, context, fn); #else std::call_once(*predicate, [fn, context]() { fn(context); }); #endif }
747
459
<gh_stars>100-1000 /** * @file oglplus/transform_feedback_mode.hpp * @brief TransformFeedbackMode enumeration * * @author <NAME> * * Copyright 2010-2015 <NAME>. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #pragma once #ifndef OGLPLUS_TRANSFORM_FEEDBACK_MODE_1107121519_HPP #define OGLPLUS_TRANSFORM_FEEDBACK_MODE_1107121519_HPP #include <oglplus/enums/transform_feedback_mode.hpp> #endif // include guard
204
1,356
<reponame>GrandArc/cardboard /* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sensors/lowpass_filter.h" #include <cmath> namespace { const double kSecondsFromNanoseconds = 1e-9; // Minimum time step between sensor updates. This corresponds to 1000 Hz. const double kMinTimestepS = 0.001f; // Maximum time step between sensor updates. This corresponds to 1 Hz. const double kMaxTimestepS = 1.00f; } // namespace namespace cardboard { LowpassFilter::LowpassFilter(double cutoff_freq_hz) : cutoff_time_constant_(1.0 / (2.0 * M_PI * cutoff_freq_hz)), initialized_(false) { Reset(); } void LowpassFilter::AddSample(const Vector3& sample, uint64_t timestamp_ns) { AddWeightedSample(sample, timestamp_ns, 1.0); } void LowpassFilter::AddWeightedSample(const Vector3& sample, uint64_t timestamp_ns, double weight) { if (!initialized_) { // Initialize filter state filtered_data_ = {sample[0], sample[1], sample[2]}; timestamp_most_recent_update_ns_ = timestamp_ns; initialized_ = true; return; } if (timestamp_ns < timestamp_most_recent_update_ns_) { timestamp_most_recent_update_ns_ = timestamp_ns; return; } const double delta_s = static_cast<double>(timestamp_ns - timestamp_most_recent_update_ns_) * kSecondsFromNanoseconds; if (delta_s <= kMinTimestepS || delta_s > kMaxTimestepS) { timestamp_most_recent_update_ns_ = timestamp_ns; return; } const double weighted_delta_secs = weight * delta_s; const double alpha = weighted_delta_secs / (cutoff_time_constant_ + weighted_delta_secs); for (int i = 0; i < 3; ++i) { filtered_data_[i] = (1.0 - alpha) * filtered_data_[i] + alpha * sample[i]; } timestamp_most_recent_update_ns_ = timestamp_ns; } void LowpassFilter::Reset() { initialized_ = false; filtered_data_ = {0, 0, 0}; } } // namespace cardboard
869
809
/** * @file * * @date 20.01.2017 * @author <NAME> */ #include <errno.h> #include <stddef.h> #include <stdint.h> #include <assert.h> #include <sys/mman.h> #include <util/log.h> #include <embox/unit.h> #include <hal/reg.h> #include <drivers/common/memory.h> #include <drivers/gpio/gpio_driver.h> #define GPIO_CHIP_ID OPTION_GET(NUMBER,gpio_chip_id) #define BASE_CTRL_ADDR(i) \ ((uintptr_t) OPTION_GET(NUMBER,base_addr) + (i) * 0x1000) #define DWAPB_GPIO_PORTS_COUNT OPTION_GET(NUMBER,gpio_ports) EMBOX_UNIT_INIT(dwapb_gpio_init); struct gpio_dwapb_port { uint32_t dr; /* data */ uint32_t ddr; /* direction */ uint32_t ctl; }; static int dwapb_gpio_setup_mode(unsigned char port, gpio_mask_t mask, int mode) { struct gpio_dwapb_port *gpio_port; uint32_t direction; uint32_t ctl; gpio_port = (struct gpio_dwapb_port *) BASE_CTRL_ADDR(port); log_debug("port %d mask 0x%X mode %d", port, mask, mode); ctl = REG32_LOAD(&gpio_port->ctl); ctl &= ~mask; REG32_STORE(&gpio_port->ctl, ctl); /* all hardware pins */ switch (mode) { case GPIO_MODE_OUTPUT: break; default: log_error("wrong gpio mode"); return -EINVAL; } direction = REG32_LOAD(&gpio_port->ddr); REG32_STORE(&gpio_port->ddr, direction | mask); return 0; } static void dwapb_gpio_set(unsigned char port, gpio_mask_t mask, char level) { struct gpio_dwapb_port *gpio_port; uint32_t dr; gpio_port = (struct gpio_dwapb_port *) BASE_CTRL_ADDR(port); dr = REG32_LOAD(&gpio_port->dr); if (level) { dr |= mask; } else { dr &= ~mask; } log_debug("%d mask 0x%X mode %d", port, mask, level); REG32_STORE(&gpio_port->dr, dr); } static gpio_mask_t dwapb_gpio_get(unsigned char port, gpio_mask_t mask) { struct gpio_dwapb_port *gpio_port; uint32_t dr; gpio_port = (struct gpio_dwapb_port *) BASE_CTRL_ADDR(port); dr = REG32_LOAD(&gpio_port->dr); return dr & mask; } static struct gpio_chip dwapb_gpio_chip = { .setup_mode = dwapb_gpio_setup_mode, .get = dwapb_gpio_get, .set = dwapb_gpio_set, .nports = DWAPB_GPIO_PORTS_COUNT }; static int dwapb_gpio_init(void) { return gpio_register_chip(&dwapb_gpio_chip, GPIO_CHIP_ID); } PERIPH_MEMORY_DEFINE(arasan, BASE_CTRL_ADDR(0), 0x1000 * DWAPB_GPIO_PORTS_COUNT);
1,019
591
[ {"circleVillage_forest/_circleVillage_forest.json": true }, {"v_1/_v_1.json": true }, {"empty_test/_empty_test.json": true }, {"road_test/_road_test.json": true }, {"rockMaze/_rockMaze.json": true } ]
98
2,692
#!/usr/bin/env python # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import sys from typing import Any, Dict, cast import setuptools def get_version() -> str: onefuzz: Dict[str, Any] = {} with open("onefuzz/__version__.py") as fh: # Exec our own __version__.py to pull out version string # without import exec(fh.read(), onefuzz) # nosec version = onefuzz["__version__"] if "-v" in sys.argv: index = sys.argv.index("-v") sys.argv.pop(index) version += ".dev" + sys.argv.pop(index) return cast(str, version) with open("requirements.txt") as f: requirements = f.read().splitlines() # remove any installer options (see pydantic example) requirements = [x.split(" ")[0] for x in requirements] setuptools.setup( name="onefuzz", version=get_version(), description="Onefuzz Client Library for Python", long_description=open("README.md").read(), long_description_content_type="text/markdown", url="https://github.com/microsoft/onefuzz/", author="<NAME>", author_email="<EMAIL>", license="MIT", packages=setuptools.find_packages(), entry_points={"console_scripts": ["onefuzz = onefuzz.__main__:main"]}, install_requires=requirements, zip_safe=False, include_package_data=True, package_data={ "": ["*.md", "*.txt", "onefuzz/data/licenses.json", "onefuzz/data/privacy.txt"] }, )
571
377
<reponame>sirAgg/nebula //------------------------------------------------------------------------------ // scriptserver.cc // (C) 2006 Radon Labs GmbH // (C) 2013-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "foundation/stdneb.h" #include "scripting/scriptserver.h" #include "io/console.h" namespace Scripting { __ImplementClass(Scripting::ScriptServer, 'SCRS', Core::RefCounted); __ImplementSingleton(Scripting::ScriptServer); using namespace Util; using namespace IO; //------------------------------------------------------------------------------ /** */ ScriptServer::ScriptServer() : isOpen(false), debug(true) { __ConstructSingleton; } //------------------------------------------------------------------------------ /** */ ScriptServer::~ScriptServer() { n_assert(!this->isOpen); __DestructSingleton; } //------------------------------------------------------------------------------ /** */ bool ScriptServer::Open() { n_assert(!this->isOpen); this->isOpen = true; return true; } //------------------------------------------------------------------------------ /** */ void ScriptServer::Close() { n_assert(this->isOpen); this->isOpen = false; } } // namespace Scripting
346
703
#pragma once #include <RendererFoundation/Device/Pass.h> struct ezGALCommandEncoderRenderState; class ezGALRenderCommandEncoder; class ezGALComputeCommandEncoder; class ezGALCommandEncoderImplVulkan; class ezGALPassVulkan : public ezGALPass { protected: friend class ezGALDeviceVulkan; friend class ezMemoryUtils; virtual ezGALRenderCommandEncoder* BeginRenderingPlatform(const ezGALRenderingSetup& renderingSetup, const char* szName) override; virtual void EndRenderingPlatform(ezGALRenderCommandEncoder* pCommandEncoder) override; virtual ezGALComputeCommandEncoder* BeginComputePlatform(const char* szName) override; virtual void EndComputePlatform(ezGALComputeCommandEncoder* pCommandEncoder) override; ezGALPassVulkan(ezGALDevice& device); virtual ~ezGALPassVulkan(); void BeginPass(const char* szName); void EndPass(); private: ezUniquePtr<ezGALCommandEncoderRenderState> m_pCommandEncoderState; ezUniquePtr<ezGALCommandEncoderImplVulkan> m_pCommandEncoderImpl; ezUniquePtr<ezGALRenderCommandEncoder> m_pRenderCommandEncoder; ezUniquePtr<ezGALComputeCommandEncoder> m_pComputeCommandEncoder; };
385
2,085
def test(): assert ( "patterns = list(nlp.pipe(people))" in __solution__ ), "Utilises-tu nlp.pipe enveloppé dans une liste ?" __msg__.good( "Bon boulot ! Passons à un exemple pratique qui utilise nlp.pipe " "pour traiter des documents avec des métadonnées supplémentaires." )
139
1,968
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// package com.ansca.corona.input; /** * Stores an axis input's value and timestamp. * <p> * Instances of this class are immutable. */ public class AxisDataPoint { /** The axis value that was recorded. */ private float fValue; /** The time the axis data was recorded on in milliseconds since bootup. */ private long fTimestamp; /** * Creates a new axis data point set to current time. * @param value The axis value that was recorded. */ public AxisDataPoint(float value) { this(value, android.os.SystemClock.uptimeMillis()); } /** * Creates a new axis data point. * @param value The axis value that was recorded. * @param timestamp The time the axis event occurred in milliseconds since bootup. * <p> * This value should be taken from MotionEvent.getEventTime() or SystemClock.uptimeMillis(). */ public AxisDataPoint(float value, long timestamp) { fValue = value; fTimestamp = timestamp; } /** * Gets the axis value that was recorded. * @return Returns the axis value. */ public float getValue() { return fValue; } /** * Gets the time when the axis event occurred. * @return Returns a timestamp in milliseconds since bootup. * <p> * Can be compared against the value returned by MotionEvent.getEventTime() * or SystemClock.uptimeMillis(). */ public long getTimestamp() { return fTimestamp; } /** * Gets this axis data in human readable string form. * @return Returns a non-localized string of this axis data point. */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("("); builder.append(Float.toString(fValue)); builder.append(", "); builder.append(Long.toString(fTimestamp)); builder.append(")"); return builder.toString(); } }
670
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.pdmodel.common; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary; import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode; import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification; import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile; import org.junit.jupiter.api.Test; class TestEmbeddedFiles { @Test void testNullEmbeddedFile() throws IOException { PDEmbeddedFile embeddedFile = null; boolean ok = false; try { PDDocument doc = Loader.loadPDF(TestEmbeddedFiles.class .getResourceAsStream( "null_PDComplexFileSpecification.pdf")); PDDocumentCatalog catalog = doc.getDocumentCatalog(); PDDocumentNameDictionary names = catalog.getNames(); assertEquals(2, names.getEmbeddedFiles().getNames().size(), "expected two files"); PDEmbeddedFilesNameTreeNode embeddedFiles = names.getEmbeddedFiles(); PDComplexFileSpecification spec = embeddedFiles.getNames().get("non-existent-file.docx"); if (spec != null) { embeddedFile = spec.getEmbeddedFile(); ok = true; } //now test for actual attachment spec = embeddedFiles.getNames().get("My first attachment"); assertNotNull(spec, "one attachment actually exists"); assertEquals(17660, spec.getEmbeddedFile().getLength(), "existing file length"); spec = embeddedFiles.getNames().get("non-existent-file.docx"); } catch (NullPointerException e) { fail("null pointer exception"); } assertTrue(ok, "Was able to get file without exception"); assertNull(embeddedFile, "EmbeddedFile was correctly null"); } @Test void testOSSpecificAttachments() throws IOException { PDEmbeddedFile nonOSFile = null; PDEmbeddedFile macFile = null; PDEmbeddedFile dosFile = null; PDEmbeddedFile unixFile = null; PDDocument doc = Loader.loadPDF( TestEmbeddedFiles.class .getResourceAsStream("testPDF_multiFormatEmbFiles.pdf")); PDDocumentCatalog catalog = doc.getDocumentCatalog(); PDDocumentNameDictionary names = catalog.getNames(); PDEmbeddedFilesNameTreeNode treeNode = names.getEmbeddedFiles(); List<PDNameTreeNode<PDComplexFileSpecification>> kids = treeNode.getKids(); for (PDNameTreeNode<PDComplexFileSpecification> kid : kids) { Map<String, PDComplexFileSpecification> tmpNames = kid.getNames(); COSObjectable obj = tmpNames.get("My first attachment"); PDComplexFileSpecification spec = (PDComplexFileSpecification) obj; nonOSFile = spec.getEmbeddedFile(); macFile = spec.getEmbeddedFileMac(); dosFile = spec.getEmbeddedFileDos(); unixFile = spec.getEmbeddedFileUnix(); } assertTrue(byteArrayContainsLC("non os specific", nonOSFile.toByteArray(), "ISO-8859-1"), "non os specific"); assertTrue(byteArrayContainsLC("mac embedded", macFile.toByteArray(), "ISO-8859-1"), "mac"); assertTrue(byteArrayContainsLC("dos embedded", dosFile.toByteArray(), "ISO-8859-1"), "dos"); assertTrue(byteArrayContainsLC("unix embedded", unixFile.toByteArray(), "ISO-8859-1"), "unix"); } private boolean byteArrayContainsLC(String target, byte[] bytes, String encoding) throws UnsupportedEncodingException { String s = new String(bytes, encoding); return s.toLowerCase().contains(target); } }
1,931
12,347
import os from pathlib import Path import pytest from poetry.utils.env import EnvManager @pytest.fixture def venv_name(app): return EnvManager.generate_env_name("simple-project", str(app.poetry.file.parent)) @pytest.fixture def venv_cache(tmp_dir): return Path(tmp_dir) @pytest.fixture(scope="module") def python_versions(): return ["3.6", "3.7"] @pytest.fixture def venvs_in_cache_config(app, venv_cache): app.poetry.config.merge({"virtualenvs": {"path": str(venv_cache)}}) @pytest.fixture def venvs_in_cache_dirs( app, venvs_in_cache_config, venv_name, venv_cache, python_versions ): directories = [] for version in python_versions: directory = venv_cache.joinpath("{}-py{}".format(venv_name, version)) directory.mkdir(parents=True, exist_ok=True) directories.append(directory.name) return directories @pytest.fixture def venvs_in_project_dir(app): os.environ.pop("VIRTUAL_ENV", None) venv_dir = app.poetry.file.parent.joinpath(".venv") venv_dir.mkdir(exist_ok=True) app.poetry.config.merge({"virtualenvs": {"in-project": True}}) try: yield venv_dir finally: venv_dir.rmdir()
496
2,406
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" #include "util/type_prop.hpp" using namespace std; using namespace ngraph; TEST(type_prop, selu_basic_inference_f32_3D) { const auto param = make_shared<op::Parameter>(element::f32, Shape{1, 32, 32}); const auto alpha = make_shared<op::Parameter>(element::f32, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::f32, Shape{1}); const auto selu = make_shared<op::Selu>(param, alpha, lambda); ASSERT_EQ(selu->get_element_type(), element::f32); ASSERT_EQ(selu->get_shape(), (Shape{1, 32, 32})); } TEST(type_prop, selu_basic_inference_f16_3D) { const auto param = make_shared<op::Parameter>(element::f16, Shape{1, 32, 32}); const auto alpha = make_shared<op::Parameter>(element::f16, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::f16, Shape{1}); const auto selu = make_shared<op::Selu>(param, alpha, lambda); ASSERT_EQ(selu->get_element_type(), element::f16); ASSERT_EQ(selu->get_shape(), (Shape{1, 32, 32})); } TEST(type_prop, selu_basic_inference_f32_5D) { const auto param = make_shared<op::Parameter>(element::f32, Shape{12, 135, 221, 31, 15}); const auto alpha = make_shared<op::Parameter>(element::f32, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::f32, Shape{1}); const auto selu = make_shared<op::Selu>(param, alpha, lambda); ASSERT_EQ(selu->get_element_type(), element::f32); ASSERT_EQ(selu->get_shape(), (Shape{12, 135, 221, 31, 15})); } TEST(type_prop, selu_basic_inference_f16_5D) { const auto param = make_shared<op::Parameter>(element::f16, Shape{12, 135, 221, 31, 15}); const auto alpha = make_shared<op::Parameter>(element::f16, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::f16, Shape{1}); const auto selu = make_shared<op::Selu>(param, alpha, lambda); ASSERT_EQ(selu->get_element_type(), element::f16); ASSERT_EQ(selu->get_shape(), (Shape{12, 135, 221, 31, 15})); } TEST(type_prop, selu_incompatible_input_type_boolean) { // Invalid data input element type try { auto data = make_shared<op::Parameter>(element::boolean, Shape{1, 2, 3, 4}); const auto alpha = make_shared<op::Parameter>(element::boolean, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::boolean, Shape{1}); auto selu = make_shared<op::Selu>(data, alpha, lambda); // Data input expected to be of numeric type FAIL() << "Invalid input type not detected"; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input element types must be floating-point")); } catch (...) { FAIL() << "Input type check failed for unexpected reason"; } } TEST(type_prop, selu_incompatible_input_type_i32) { // Invalid data input element type try { auto data = make_shared<op::Parameter>(element::i32, Shape{1, 2, 3, 4}); const auto alpha = make_shared<op::Parameter>(element::i32, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::i32, Shape{1}); auto selu = make_shared<op::Selu>(data, alpha, lambda); // Data input expected to be of numeric type FAIL() << "Invalid input type not detected"; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input element types must be floating-point")); } catch (...) { FAIL() << "Input type check failed for unexpected reason"; } } TEST(type_prop, selu_incompatible_input_type_u16) { // Invalid data input element type try { auto data = make_shared<op::Parameter>(element::u16, Shape{1, 2, 3, 4}); const auto alpha = make_shared<op::Parameter>(element::u16, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::u16, Shape{1}); auto selu = make_shared<op::Selu>(data, alpha, lambda); // Data input expected to be of numeric type FAIL() << "Invalid input type not detected"; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input element types must be floating-point")); } catch (...) { FAIL() << "Input type check failed for unexpected reason"; } } TEST(type_prop, selu_incompatible_input_types) { // Invalid data input element type try { auto data = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); const auto alpha = make_shared<op::Parameter>(element::f32, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::u16, Shape{1}); auto selu = make_shared<op::Selu>(data, alpha, lambda); // Data input expected to be of numeric type FAIL() << "Inavlid input types not detected"; } catch (const NodeValidationFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("Input element types do not match")); } catch (...) { FAIL() << "Input type check failed for unexpected reason"; } } TEST(type_prop, selu_dynamic_rank_input_shape_2D) { const PartialShape param_shape{Dimension::dynamic(), 10}; const auto param = std::make_shared<op::Parameter>(element::f32, param_shape); const auto alpha = make_shared<op::Parameter>(element::f32, Shape{2, 1}); const auto lambda = make_shared<op::Parameter>(element::f32, Shape{1}); const auto op = std::make_shared<op::Selu>(param, alpha, lambda); ASSERT_TRUE(op->get_output_partial_shape(0).same_scheme(PartialShape{Dimension(), 10})); } TEST(type_prop, selu_dynamic_rank_input_shape_3D) { const PartialShape param_shape{100, Dimension::dynamic(), 58}; const auto param = std::make_shared<op::Parameter>(element::f32, param_shape); const auto alpha = make_shared<op::Parameter>(element::f32, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::f32, Shape{1}); const auto op = std::make_shared<op::Selu>(param, alpha, lambda); ASSERT_TRUE(op->get_output_partial_shape(0).same_scheme(PartialShape{100, Dimension(), 58})); } TEST(type_prop, selu_dynamic_rank_input_shape_full) { const auto param = std::make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); const auto alpha = make_shared<op::Parameter>(element::f32, Shape{1}); const auto lambda = make_shared<op::Parameter>(element::f32, Shape{1}); const auto op = std::make_shared<op::Selu>(param, alpha, lambda); ASSERT_TRUE(op->get_output_partial_shape(0).same_scheme(PartialShape::dynamic())); }
2,486
788
/* * 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.usergrid.persistence.core.astyanax; import java.util.HashSet; import java.util.Set; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.netflix.astyanax.AstyanaxConfiguration; import com.netflix.astyanax.AstyanaxContext; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; import com.netflix.astyanax.connectionpool.NodeDiscoveryType; import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl; import com.netflix.astyanax.connectionpool.impl.Slf4jConnectionPoolMonitorImpl; import com.netflix.astyanax.impl.AstyanaxConfigurationImpl; import com.netflix.astyanax.thrift.ThriftFamilyFactory; /** * TODO. Provide the ability to do a service hook for realtime tuning without the need of a JVM restart This could be * done with governator and service discovery * * @author tnine */ @Singleton public class AstyanaxKeyspaceProvider implements Provider<Keyspace> { private final CassandraCluster cassandraCluster; @Inject public AstyanaxKeyspaceProvider( final CassandraCluster cassandraCluster) { this.cassandraCluster = cassandraCluster; } @Override public Keyspace get() { return cassandraCluster.getApplicationKeyspace(); } }
612
1,590
{ "parameters": { "subscriptionId": "daefabc0-95b4-48b3-b645-8a753a63c4fa", "resourceGroupName": "resourceGroup1", "hostPoolName": "hostPool1", "sessionHostName": "sessionHost1.microsoft.com", "userSessionId": "1", "api-version": "2021-09-03-preview" }, "responses": { "200": { "body": { "name": "1", "id": "/subscriptions/daefabc0-95b4-48b3-b645-8a753a63c4fa/resourceGroups/resourceGroup1/providers/Microsoft.DesktopVirtualization/hostPools/hostPool1/sessionHosts/sessionHost1.microsoft.com/userSessions/1", "type": "Microsoft.DesktopVirtualization/hostPools/sessionHosts/userSessions", "systemData": { "createdBy": "user1", "createdByType": "User", "createdAt": "2020-01-01T17:18:19.1234567Z", "lastModifiedBy": "user2", "lastModifiedByType": "User", "lastModifiedAt": "2020-01-02T17:18:19.1234567Z" }, "properties": { "objectId": "7877fb31-4bde-49fd-9df3-c046e0ec5325", "userPrincipalName": "<EMAIL>", "applicationType": "Desktop", "sessionState": "Active", "activeDirectoryUserName": "WVDARM\\user1", "createTime": "2008-09-22T14:01:54.9571247Z" } } } } }
631
337
<reponame>shyamjangid07/Reverse-Engineering<filename>mailspam/mailspam_dec.py<gh_stars>100-1000 # uncompyle6 version 3.7.3 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.16 (default, Oct 10 2019, 22:02:15) # [GCC 8.3.0] # Embedded file name: <script> # Compiled at: 2020-08-30 16:51:23 W = '\x1b[1;37m' N = '\x1b[0m' R = '\x1b[1;37m\x1b[31m' B = '\x1b[1;37m\x1b[34m' G = '\x1b[1;32m' Y = '\x1b[1;33;40m' SR = W + '[' + R + '*' + W + ']' SG = W + '[' + G + '*' + W + ']' SRO = W + '(' + R + '>' + W + ')' SGO = W + '(' + G + '>' + W + ')' newlin = '\n' SBG = '\x1b[1;37m(\x1b[1;32m\xe2\x97\x8f\x1b[1;37m)' SBR = '\x1b[1;37m(\x1b[1;37m\x1b[31m\xe2\x97\x8f\x1b[1;37m)' banner = '\n\n ______________________________________\n ________| |_______\n \\ | {} Email Spammer V2.0 {} | / \n \\ | {} Dev : {}Nasir Ali {} | /\n / |______________________________________| \\\x01 \n /__________) (_________\\ \n \n\n{}------------------------------------------------\n{}Follow on Instagram :{} @nasir.xoz\n{}Youtube :{} Youtube.com/TheDarkSec\n{}Facebook :{} fb.com/nasir.xo\n{}Github :{} github.com/nasirxo\n{}------------------------------------------------\n\n' from base64 import * import os, time try: from requests import * from bs4 import * except: print SBR + ' Installing Dependencies.....' os.system('pip2 install requests') os.system('pip2 install bs4') print SBG + ' Dependencies Installed.....' os.system('clear') os.system('clear') print W + banner.format(G, W, G, Y, W, R, W, G, W, G, W, G, W, G, R) def mailspoof(fromemail, toemail, ammount, subject, text): try: mail_site = b64decode('<KEY>') mail = {'to': str(toemail), 'nhost': str(fromemail), 'nom': str(ammount), 'subj': str(subject), 'Comments': str(text), 'submit': 'Send Mail Strm '} stat = post(mail_site, data=mail) return stat.status_code except: return 0 def mailspoofhost(fromhost, toemail, ammount, subject, text): try: mail_site = b64decode('<KEY> mail = {'to': str(toemail), 'nhost': str(fromhost), 'nom': str(ammount), 'subj': str(subject), 'Comments': str(text), 'submit': 'Send Mail Strm '} stat = post(mail_site, data=mail) return stat.status_code except: return 0 while True: try: print SBR + ' Get License Key from Darksec Youtube Channel' tok = raw_input(SBG + ' Enter License Key : ' + G) r = get('https://mbasic.facebook.com/nasir.xo') bs = BeautifulSoup(r.content, 'html.parser') if tok == bs.find_all('span', dir='ltr')[0].get_text()[:9]: print SBG + ' Mail Spam Activated *_* ' time.sleep(2) break else: print SBR + ' Invalid License Key ! :(' except: print SBR + ' No Internet Connection ! :( ' exit() while True: os.system('clear') print ('\n\n {} ---- [ {}MailSpam V2.0{} ] ----\n {} DEV :{} Nasir Ali\n\n {} (1) {} Send from Gmail Server.\n {} (2) {} Send from Yahoo Server.\n {} (3) {} Send from Outlook Server.\n {} (4) {} Send from Facebook Server.\n {} (5) {} Send from Nhacker Server. {}({}Stable{})\n\n {} ---|{} Select Any Option {}|---\n \n ').format(Y, G, Y, W, G, G, SBG, G, SBG, G, SBG, G, SBG, G, SBG, G, R, G, G, W, G, W) try: option = raw_input(SBG + ' Option : ' + G) if int(option) == 1: target = raw_input(SBG + ' Target-Email : ' + G) num = raw_input(SBG + ' Ammount : ' + G) msg = raw_input(SBG + ' Message : ' + G) if int(num) <= 999999: try: os.system('clear') print ('\n {} ====|{} Status {}|====\n\n \n ').format(W, G, W) print W + '==' * 20 status = mailspoofhost('gmail.com', target, num, 'xyz', msg) if int(status) == 200: for i in range(1, int(num) + 1): time.sleep(0.5) print SBG + ('{}--> {}({}{}) {} SENDED ').format(Y, G, W, i, G, W) else: print SBR + ' No internet Connection ! :( ' print W + '==' * 20 except: SBR + ' Error ! :( ' else: print SBR + G + ' Max-Sending Limit Execeeded !' if int(option) == 2: target = raw_input(SBG + ' Target-Email : ' + G) num = raw_input(SBG + ' Ammount : ' + G) msg = raw_input(SBG + ' Message : ' + G) if int(num) <= 999999: try: os.system('clear') print ('\n {} ====|{} Status {}|====\n \n \n ').format(W, G, W) print W + '==' * 20 status = mailspoofhost('yahoo.com', target, num, 'xyz', msg) if int(status) == 200: for i in range(1, int(num) + 1): time.sleep(0.5) print SBG + ('{}--> {}({}{}) {} SENDED ').format(Y, G, W, i, G, W) else: print SBR + ' No internet Connection ! :( ' print W + '==' * 20 except: SBR + ' Error ! :( ' else: print SBR + G + ' Max-Sending Limit Execeeded !' if int(option) == 3: target = raw_input(SBG + ' Target-Email : ' + G) num = raw_input(SBG + ' Ammount : ' + G) msg = raw_input(SBG + ' Message : ' + G) if int(num) <= 999999: try: os.system('clear') print ('\n {} ====|{} Status {}|====\n \n \n ').format(W, G, W) print W + '==' * 20 status = mailspoofhost('outlook.com', target, num, 'xyz', msg) if int(status) == 200: for i in range(1, int(num) + 1): time.sleep(0.5) print SBG + ('{}--> {}({}{}) {} SENDED ').format(Y, G, W, i, G, W) else: print SBR + ' No internet Connection ! :( ' print W + '==' * 20 except: SBR + ' Error ! :( ' else: print SBR + G + ' Max-Sending Limit Execeeded !' if int(option) == 4: target = raw_input(SBG + ' Target-Email : ' + G) num = raw_input(SBG + ' Ammount : ' + G) msg = raw_input(SBG + ' Message : ' + G) if int(num) <= 999999: try: os.system('clear') print ('\n {} ====|{} Status {}|====\n \n \n ').format(W, G, W) print W + '==' * 20 status = mailspoofhost('facebook.com', target, num, 'xyz', msg) if int(status) == 200: for i in range(1, int(num) + 1): time.sleep(0.5) print SBG + ('{}--> {}({}{}) {} SENDED ').format(Y, G, W, i, G, W) else: print SBR + ' No internet Connection ! :( ' print W + '==' * 20 except: SBR + ' Error ! :( ' else: print SBR + G + ' Max-Sending Limit Execeeded !' if int(option) == 5: target = raw_input(SBG + ' Target-Email : ' + G) num = raw_input(SBG + ' Ammount : ' + G) msg = raw_input(SBG + ' Message : ' + G) if int(num) <= 999999: try: os.system('clear') print ('\n {} ====|{} Status {}|====\n \n \n ').format(W, G, W) print W + '==' * 20 status = mailspoofhost('nhacker.com', target, num, 'xyz', msg) if int(status) == 200: for i in range(1, int(num) + 1): time.sleep(0.5) print SBG + ('{}--> {}({}{}) {} SENDED ').format(Y, G, W, i, G, W) else: print SBR + ' No internet Connection ! :( ' print W + '==' * 20 except: SBR + ' Error ! :( ' else: print SBR + G + ' Max-Sending Limit Execeeded !' else: print SBR + ' Invalid Option :( ' except: pass # okay decompiling patched.pyc
5,298
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.debugger.jpda.jsui.vars.models; import java.awt.datatransfer.Transferable; import java.io.IOException; import java.util.List; import org.netbeans.api.annotations.common.StaticResource; import org.netbeans.api.debugger.jpda.Field; import org.netbeans.api.debugger.jpda.InvalidExpressionException; import org.netbeans.api.debugger.jpda.JPDAClassType; import org.netbeans.api.debugger.jpda.ObjectVariable; import org.netbeans.api.debugger.jpda.Super; import org.netbeans.api.debugger.jpda.This; import org.netbeans.api.debugger.jpda.Variable; import org.netbeans.modules.debugger.jpda.js.vars.JSThis; import org.netbeans.modules.debugger.jpda.js.vars.JSVariable; import org.netbeans.modules.debugger.jpda.js.vars.ScopeVariable; import org.netbeans.spi.debugger.DebuggerServiceRegistration; import org.netbeans.spi.debugger.DebuggerServiceRegistrations; import org.netbeans.spi.viewmodel.ExtendedNodeModel; import org.netbeans.spi.viewmodel.ExtendedNodeModelFilter; import org.netbeans.spi.viewmodel.ModelListener; import org.netbeans.spi.viewmodel.NodeModel; import org.netbeans.spi.viewmodel.UnknownTypeException; import org.openide.util.datatransfer.PasteType; /** * * @author Martin */ @DebuggerServiceRegistrations({ @DebuggerServiceRegistration(path="netbeans-JPDASession/JS/LocalsView", types=ExtendedNodeModelFilter.class), @DebuggerServiceRegistration(path="netbeans-JPDASession/JS/ResultsView", types=ExtendedNodeModelFilter.class), @DebuggerServiceRegistration(path="netbeans-JPDASession/JS/ToolTipView", types=ExtendedNodeModelFilter.class, position = 500), @DebuggerServiceRegistration(path="netbeans-JPDASession/JS/WatchesView", types=ExtendedNodeModelFilter.class, position = 250), }) public class VariablesJSNodeModel implements ExtendedNodeModelFilter { @StaticResource(searchClasspath = true) private static final String GLOBAL = "org/netbeans/modules/javascript2/debug/ui/resources/global_variable_16.png"; // NOI18N @Override public boolean canRename(ExtendedNodeModel original, Object node) throws UnknownTypeException { return original.canRename(node); } @Override public boolean canCopy(ExtendedNodeModel original, Object node) throws UnknownTypeException { return original.canCopy(node); } @Override public boolean canCut(ExtendedNodeModel original, Object node) throws UnknownTypeException { return original.canCut(node); } @Override public Transferable clipboardCopy(ExtendedNodeModel original, Object node) throws IOException, UnknownTypeException { return original.clipboardCopy(node); } @Override public Transferable clipboardCut(ExtendedNodeModel original, Object node) throws IOException, UnknownTypeException { return original.clipboardCut(node); } @Override public PasteType[] getPasteTypes(ExtendedNodeModel original, Object node, Transferable t) throws UnknownTypeException { return original.getPasteTypes(node, t); } @Override public void setName(ExtendedNodeModel original, Object node, String name) throws UnknownTypeException { original.setName(node, name); } @Override public String getIconBaseWithExtension(ExtendedNodeModel original, Object node) throws UnknownTypeException { if (node instanceof JSThis) { return original.getIconBaseWithExtension(new EmptyThis()); } if (node instanceof JSVariable) { return original.getIconBaseWithExtension(new EmptyVar()); } if (node instanceof JSWatchVar) { return original.getIconBaseWithExtension(((JSWatchVar) node).getWatch()); } if (node instanceof ScopeVariable) { return GLOBAL; } return original.getIconBaseWithExtension(node); } @Override public String getDisplayName(NodeModel original, Object node) throws UnknownTypeException { if (node instanceof JSVariable) { return ((JSVariable) node).getKey(); } if (node instanceof ScopeVariable) { return ((ScopeVariable) node).getName(); } if (node instanceof JSWatchVar) { JSWatchVar jswv = (JSWatchVar) node; node = jswv.getWatch(); } return original.getDisplayName(node); } @Override public String getIconBase(NodeModel original, Object node) throws UnknownTypeException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String getShortDescription(NodeModel original, Object node) throws UnknownTypeException { if (node instanceof JSVariable) { JSVariable var = (JSVariable) node; return var.getKey() + " = " + var.getValue(); } if (node instanceof ScopeVariable) { return ((ScopeVariable) node).getName(); } if (node instanceof JSWatchVar) { JSWatchVar jswv = (JSWatchVar) node; JSVariable jsVar = jswv.getJSVar(); if (jsVar != null) { return jswv.getWatch().getExpression() + " = " + jsVar.getValue(); } else { node = jswv.getWatch(); } } return original.getShortDescription(node); } @Override public void addModelListener(ModelListener l) { } @Override public void removeModelListener(ModelListener l) { } private static final class EmptyThis implements This { @Override public String getToStringValue() throws InvalidExpressionException { return "empty"; } @Override public Variable invokeMethod(String methodName, String signature, Variable[] arguments) throws NoSuchMethodException, InvalidExpressionException { throw new UnsupportedOperationException("Not supported."); } @Override public int getFieldsCount() { return 0; } @Override public Field getField(String name) { return null; } @Override public Field[] getFields(int from, int to) { return null; } @Override public Field[] getAllStaticFields(int from, int to) { return null; } @Override public Field[] getInheritedFields(int from, int to) { return null; } @Override public List<ObjectVariable> getReferringObjects(long maxReferrers) throws UnsupportedOperationException { return null; } @Override public Super getSuper() { return null; } @Override public JPDAClassType getClassType() { return null; } @Override public long getUniqueID() { return 0l; } @Override public String getType() { return "empty"; } @Override public String getValue() { return ""; } @Override public Object createMirrorObject() { return null; } } private static final class EmptyVar implements Variable { @Override public String getType() { return "empty"; } @Override public String getValue() { return ""; } @Override public Object createMirrorObject() { return null; } } }
2,912
912
// https://man7.org/linux/man-pages/man3/getline.3.html #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *stream = fopen(argv[1], "r"); char *line = malloc(100); size_t len = 0; ssize_t nread; int line_nb = 5; while ((nread = getline(&line, &len, stream)) != -1 && --line_nb) ; fwrite(line, nread, 1, stdout); free(line); fclose(stream); }
199
1,201
/************************************************************************* * * Copyright 2016 Realm 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. * **************************************************************************/ #ifndef REALM_COLUMN_TIMESTAMP_HPP #define REALM_COLUMN_TIMESTAMP_HPP #include <realm/column.hpp> #include <realm/timestamp.hpp> namespace realm { // Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the // column type class TimestampColumn : public ColumnBaseSimple { public: TimestampColumn(bool nullable, Allocator& alloc, ref_type ref, size_t col_ndx = npos); static ref_type create(Allocator& alloc, size_t size, bool nullable); static size_t get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept; /// Get the number of entries in this column. This operation is relatively /// slow. size_t size() const noexcept override; /// Whether or not this column is nullable. bool is_nullable() const noexcept override; /// Whether or not the value at \a row_ndx is NULL. If the column is not /// nullable, always returns false. bool is_null(size_t row_ndx) const noexcept override; /// Sets the value at \a row_ndx to be NULL. /// \throw LogicError Thrown if this column is not nullable. void set_null(size_t row_ndx) override; void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override; void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool broken_reciprocal_backlinks) override; void move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool broken_reciprocal_backlinks) override; void clear(size_t num_rows, bool broken_reciprocal_backlinks) override; void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; void destroy() noexcept override; bool has_search_index() const noexcept final { return bool(m_search_index); } StringIndex* get_search_index() noexcept final { return m_search_index.get(); } StringIndex* get_search_index() const noexcept final { return m_search_index.get(); } void destroy_search_index() noexcept override; void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent) final; void populate_search_index(); StringIndex* create_search_index() override; bool supports_search_index() const noexcept final { return true; } StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override; ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override; void update_from_parent(size_t old_baseline) noexcept override; void set_ndx_in_parent(size_t ndx) noexcept override; void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override; void verify() const override; void to_dot(std::ostream&, StringData title = StringData()) const override; void do_dump_node_structure(std::ostream&, int level) const override; void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; void add(const Timestamp& ts = Timestamp{}); Timestamp get(size_t row_ndx) const noexcept; void set(size_t row_ndx, const Timestamp& ts); bool compare(const TimestampColumn& c) const noexcept; int compare_values(size_t row1, size_t row2) const noexcept override; Timestamp maximum(size_t* result_index) const; Timestamp minimum(size_t* result_index) const; size_t count(Timestamp) const; void erase(size_t row_ndx, bool is_last); template <class Condition> size_t find(Timestamp value, size_t begin, size_t end) const noexcept { // FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match // check nanoseconds, etc. Lots of possibilities. Below code is naive and slow but works. Condition cond; for (size_t t = begin; t < end; t++) { Timestamp ts = get(t); if (cond(ts, value, ts.is_null(), value.is_null())) return t; } return npos; } typedef Timestamp value_type; private: std::unique_ptr<BpTree<util::Optional<int64_t>>> m_seconds; std::unique_ptr<BpTree<int64_t>> m_nanoseconds; std::unique_ptr<StringIndex> m_search_index; bool m_nullable; template <class BT> class CreateHandler; template <class Condition> Timestamp minmax(size_t* result_index) const noexcept { // Condition is realm::Greater for maximum and realm::Less for minimum. Any non-null value is both larger // and smaller than a null value. if (size() == 0) { if (result_index) *result_index = npos; return Timestamp{}; } Timestamp best = get(0); size_t best_index = best.is_null() ? npos : 0; for (size_t i = 1; i < size(); ++i) { Timestamp candidate = get(i); // Condition() will return false if any of the two values are null. if ((best.is_null() && !candidate.is_null()) || Condition()(candidate, best, candidate.is_null(), best.is_null())) { best = candidate; best_index = i; } } if (result_index) *result_index = best_index; return best; } }; } // namespace realm #endif // REALM_COLUMN_TIMESTAMP_HPP
2,252
477
from django.conf import settings from django.db.models import Max, Count from biostar.forum.util import now from biostar.planet.models import Blog, BlogPost from django.core.management.base import BaseCommand import os import logging from biostar.planet import auth logger = logging.getLogger('engine') def abspath(*args): """Generates absolute paths""" return os.path.abspath(os.path.join(*args)) def dropall(): Blog.objects.all().delete() logger.info("deleted all blogs.") return def init_local(update): """ Creates a local blog """ blog, created = Blog.objects.get_or_create(title="Local blog", remote=False) for step in range(update): logger.info("adding local blog post") BlogPost.objects.create(blog=blog, title='Local blog post', content="Lorem ipsum", creation_date=now()) class Command(BaseCommand): help = 'Create search index for the forum app.' def add_arguments(self, parser): parser.add_argument('--add', dest='add', help='adds blogs to the database') parser.add_argument('--download', dest='download', action="store_true", default=False, help='downloads latest feeds') parser.add_argument('--report', action='store_true', default=False, help="Reports on the content of the index.") parser.add_argument('--update', dest='update', default=0, type=int, help='updates existing blogs with latest feeds') parser.add_argument('--local', dest='local', action="store_true", default=False, help='Creates a local blog') parser.add_argument('--drop', dest='drop', action="store_true", default=False, help='Delete repeated blogs in database.') def handle(self, *args, **options): # Create the planet directory if it is missing os.makedirs(settings.PLANET_DIR, exist_ok=True) fname = options['add'] update = options['update'] download = options['download'] drop = options['drop'] local = options['local'] if local: init_local(update=update) return if drop: dropall() if fname: auth.add_blogs(fname) if download: auth.download_blogs() if update: auth.update_entries(update)
899
4,922
package razerdp.demo.ui; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.just.agentweb.AgentWeb; import androidx.viewbinding.ViewBinding; import razerdp.basepopup.databinding.ActivityUpdateLogBinding; import razerdp.demo.base.baseactivity.BaseActivity; import razerdp.demo.base.baseactivity.BaseBindingActivity; import razerdp.demo.utils.DescBuilder; /** * Created by 大灯泡 on 2019/9/23. */ public class UpdateLogActivity extends BaseBindingActivity<ActivityUpdateLogBinding> { public static final String DESC = DescBuilder.get() .append("更新日志") .build(); AgentWeb mAgentWeb; @Override protected void onHandleIntent(Intent intent) { } @Override public ActivityUpdateLogBinding onCreateViewBinding(LayoutInflater layoutInflater) { return ActivityUpdateLogBinding.inflate(layoutInflater); } @Override protected void onInitView(View decorView) { mAgentWeb = AgentWeb.with(this) .setAgentWebParent(mBinding.webViewContainer, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) .useDefaultIndicator() .createAgentWeb() .ready() .go("https://www.yuque.com/razerdp/basepopup/uyrsxx"); mAgentWeb.getAgentWebSettings().getWebSettings().setUseWideViewPort(true); mAgentWeb.getAgentWebSettings().getWebSettings().setLoadWithOverviewMode(true); } @Override public void onTitleLeftClick(View view) { if (!mAgentWeb.back()) { super.onTitleLeftClick(view); } } }
868
5,766
// // EscapeHTMLStream.h // // Library: Net // Package: HTTP // Module: EscapeHTMLStream // // Definition of the EscapeHTMLStream class. // // Copyright (c) 1029, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef Net_EscapeHTMLStream_INCLUDED #define Net_EscapeHTMLStream_INCLUDED #include "Poco/Net/Net.h" #include "Poco/UnbufferedStreamBuf.h" #include <ostream> namespace Poco { namespace Net { class Net_API EscapeHTMLStreamBuf: public Poco::UnbufferedStreamBuf /// This stream buffer replaces all occurrences of special HTML /// characters < > " & with their respective character /// entities &lt; &gt; &quot; &amp;. { public: EscapeHTMLStreamBuf(std::ostream& ostr); /// Creates the EscapeHTMLStreamBuf and connects it /// to the given output stream. ~EscapeHTMLStreamBuf(); /// Destroys the EscapeHTMLStreamBuf. protected: int readFromDevice(); int writeToDevice(char c); private: std::ostream* _pOstr; }; class Net_API EscapeHTMLIOS: public virtual std::ios /// The base class for EscapeHTMLOutputStream. { public: EscapeHTMLIOS(std::ostream& ostr); /// Creates the MailIOS and connects it /// to the given output stream. ~EscapeHTMLIOS(); /// Destroys the stream. EscapeHTMLStreamBuf* rdbuf(); /// Returns a pointer to the underlying streambuf. protected: EscapeHTMLStreamBuf _buf; }; class Net_API EscapeHTMLOutputStream: public EscapeHTMLIOS, public std::ostream /// This stream replaces all occurrences of special HTML /// characters < > " & with their respective character /// entities &lt; &gt; &quot; &amp;. { public: EscapeHTMLOutputStream(std::ostream& ostr); /// Creates the MailOutputStream and connects it /// to the given input stream. ~EscapeHTMLOutputStream(); /// Destroys the MailOutputStream. }; } } // namespace Poco::Net #endif // Net_EscapeHTMLStream_INCLUDED
627
2,151
//===---------------------- catch_array_01.cpp ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Can you have a catch clause of array type that catches anything? // GCC incorrectly allows array types to be caught by reference. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69372 // XFAIL: gcc // UNSUPPORTED: libcxxabi-no-exceptions #include <cassert> int main() { typedef char Array[4]; Array a = {'H', 'i', '!', 0}; try { throw a; // converts to char* assert(false); } catch (Array& b) // can't catch char* { assert(false); } catch (...) { } }
313
451
#include "Console.h" Console::Console() : QWidget() { this->setWindowFlags(Qt::WindowStaysOnTopHint); setWindowModality(Qt::ApplicationModal); //IMPORTANT, permet que ta fenêtre reste active setWindowTitle("Console"); QVBoxLayout *boxLayoutV = new QVBoxLayout; QLabel *labelCmd = new QLabel(this); labelCmd->setText("Commande"); boxLayoutV->addWidget(labelCmd); this->setGeometry(100,100,800,600); lab = new QTextEdit; boxLayoutV->addWidget(lab); this->setLayout(boxLayoutV); } void Console::setLabCons(){ }
217
335
<filename>J/Jean_noun.json<gh_stars>100-1000 { "word": "Jean", "definitions": [ "Heavy twilled cotton cloth, especially denim." ], "parts-of-speech": "Noun" }
80
1,019
package com.roncoo.education.course.service.dao.impl.mapper.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class FileStorageExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; protected int limitStart = -1; protected int pageSize = -1; public FileStorageExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } public void setLimitStart(int limitStart) { this.limitStart=limitStart; } public int getLimitStart() { return limitStart; } public void setPageSize(int pageSize) { this.pageSize=pageSize; } public int getPageSize() { return pageSize; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andGmtCreateIsNull() { addCriterion("gmt_create is null"); return (Criteria) this; } public Criteria andGmtCreateIsNotNull() { addCriterion("gmt_create is not null"); return (Criteria) this; } public Criteria andGmtCreateEqualTo(Date value) { addCriterion("gmt_create =", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotEqualTo(Date value) { addCriterion("gmt_create <>", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateGreaterThan(Date value) { addCriterion("gmt_create >", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateGreaterThanOrEqualTo(Date value) { addCriterion("gmt_create >=", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateLessThan(Date value) { addCriterion("gmt_create <", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateLessThanOrEqualTo(Date value) { addCriterion("gmt_create <=", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateIn(List<Date> values) { addCriterion("gmt_create in", values, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotIn(List<Date> values) { addCriterion("gmt_create not in", values, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateBetween(Date value1, Date value2) { addCriterion("gmt_create between", value1, value2, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotBetween(Date value1, Date value2) { addCriterion("gmt_create not between", value1, value2, "gmtCreate"); return (Criteria) this; } public Criteria andFileNoIsNull() { addCriterion("file_no is null"); return (Criteria) this; } public Criteria andFileNoIsNotNull() { addCriterion("file_no is not null"); return (Criteria) this; } public Criteria andFileNoEqualTo(Long value) { addCriterion("file_no =", value, "fileNo"); return (Criteria) this; } public Criteria andFileNoNotEqualTo(Long value) { addCriterion("file_no <>", value, "fileNo"); return (Criteria) this; } public Criteria andFileNoGreaterThan(Long value) { addCriterion("file_no >", value, "fileNo"); return (Criteria) this; } public Criteria andFileNoGreaterThanOrEqualTo(Long value) { addCriterion("file_no >=", value, "fileNo"); return (Criteria) this; } public Criteria andFileNoLessThan(Long value) { addCriterion("file_no <", value, "fileNo"); return (Criteria) this; } public Criteria andFileNoLessThanOrEqualTo(Long value) { addCriterion("file_no <=", value, "fileNo"); return (Criteria) this; } public Criteria andFileNoIn(List<Long> values) { addCriterion("file_no in", values, "fileNo"); return (Criteria) this; } public Criteria andFileNoNotIn(List<Long> values) { addCriterion("file_no not in", values, "fileNo"); return (Criteria) this; } public Criteria andFileNoBetween(Long value1, Long value2) { addCriterion("file_no between", value1, value2, "fileNo"); return (Criteria) this; } public Criteria andFileNoNotBetween(Long value1, Long value2) { addCriterion("file_no not between", value1, value2, "fileNo"); return (Criteria) this; } public Criteria andFileNameIsNull() { addCriterion("file_name is null"); return (Criteria) this; } public Criteria andFileNameIsNotNull() { addCriterion("file_name is not null"); return (Criteria) this; } public Criteria andFileNameEqualTo(String value) { addCriterion("file_name =", value, "fileName"); return (Criteria) this; } public Criteria andFileNameNotEqualTo(String value) { addCriterion("file_name <>", value, "fileName"); return (Criteria) this; } public Criteria andFileNameGreaterThan(String value) { addCriterion("file_name >", value, "fileName"); return (Criteria) this; } public Criteria andFileNameGreaterThanOrEqualTo(String value) { addCriterion("file_name >=", value, "fileName"); return (Criteria) this; } public Criteria andFileNameLessThan(String value) { addCriterion("file_name <", value, "fileName"); return (Criteria) this; } public Criteria andFileNameLessThanOrEqualTo(String value) { addCriterion("file_name <=", value, "fileName"); return (Criteria) this; } public Criteria andFileNameLike(String value) { addCriterion("file_name like", value, "fileName"); return (Criteria) this; } public Criteria andFileNameNotLike(String value) { addCriterion("file_name not like", value, "fileName"); return (Criteria) this; } public Criteria andFileNameIn(List<String> values) { addCriterion("file_name in", values, "fileName"); return (Criteria) this; } public Criteria andFileNameNotIn(List<String> values) { addCriterion("file_name not in", values, "fileName"); return (Criteria) this; } public Criteria andFileNameBetween(String value1, String value2) { addCriterion("file_name between", value1, value2, "fileName"); return (Criteria) this; } public Criteria andFileNameNotBetween(String value1, String value2) { addCriterion("file_name not between", value1, value2, "fileName"); return (Criteria) this; } public Criteria andFileUrlIsNull() { addCriterion("file_url is null"); return (Criteria) this; } public Criteria andFileUrlIsNotNull() { addCriterion("file_url is not null"); return (Criteria) this; } public Criteria andFileUrlEqualTo(String value) { addCriterion("file_url =", value, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlNotEqualTo(String value) { addCriterion("file_url <>", value, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlGreaterThan(String value) { addCriterion("file_url >", value, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlGreaterThanOrEqualTo(String value) { addCriterion("file_url >=", value, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlLessThan(String value) { addCriterion("file_url <", value, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlLessThanOrEqualTo(String value) { addCriterion("file_url <=", value, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlLike(String value) { addCriterion("file_url like", value, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlNotLike(String value) { addCriterion("file_url not like", value, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlIn(List<String> values) { addCriterion("file_url in", values, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlNotIn(List<String> values) { addCriterion("file_url not in", values, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlBetween(String value1, String value2) { addCriterion("file_url between", value1, value2, "fileUrl"); return (Criteria) this; } public Criteria andFileUrlNotBetween(String value1, String value2) { addCriterion("file_url not between", value1, value2, "fileUrl"); return (Criteria) this; } public Criteria andFileTypeIsNull() { addCriterion("file_type is null"); return (Criteria) this; } public Criteria andFileTypeIsNotNull() { addCriterion("file_type is not null"); return (Criteria) this; } public Criteria andFileTypeEqualTo(Integer value) { addCriterion("file_type =", value, "fileType"); return (Criteria) this; } public Criteria andFileTypeNotEqualTo(Integer value) { addCriterion("file_type <>", value, "fileType"); return (Criteria) this; } public Criteria andFileTypeGreaterThan(Integer value) { addCriterion("file_type >", value, "fileType"); return (Criteria) this; } public Criteria andFileTypeGreaterThanOrEqualTo(Integer value) { addCriterion("file_type >=", value, "fileType"); return (Criteria) this; } public Criteria andFileTypeLessThan(Integer value) { addCriterion("file_type <", value, "fileType"); return (Criteria) this; } public Criteria andFileTypeLessThanOrEqualTo(Integer value) { addCriterion("file_type <=", value, "fileType"); return (Criteria) this; } public Criteria andFileTypeIn(List<Integer> values) { addCriterion("file_type in", values, "fileType"); return (Criteria) this; } public Criteria andFileTypeNotIn(List<Integer> values) { addCriterion("file_type not in", values, "fileType"); return (Criteria) this; } public Criteria andFileTypeBetween(Integer value1, Integer value2) { addCriterion("file_type between", value1, value2, "fileType"); return (Criteria) this; } public Criteria andFileTypeNotBetween(Integer value1, Integer value2) { addCriterion("file_type not between", value1, value2, "fileType"); return (Criteria) this; } public Criteria andFileSizeIsNull() { addCriterion("file_size is null"); return (Criteria) this; } public Criteria andFileSizeIsNotNull() { addCriterion("file_size is not null"); return (Criteria) this; } public Criteria andFileSizeEqualTo(Long value) { addCriterion("file_size =", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeNotEqualTo(Long value) { addCriterion("file_size <>", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeGreaterThan(Long value) { addCriterion("file_size >", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeGreaterThanOrEqualTo(Long value) { addCriterion("file_size >=", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeLessThan(Long value) { addCriterion("file_size <", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeLessThanOrEqualTo(Long value) { addCriterion("file_size <=", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeIn(List<Long> values) { addCriterion("file_size in", values, "fileSize"); return (Criteria) this; } public Criteria andFileSizeNotIn(List<Long> values) { addCriterion("file_size not in", values, "fileSize"); return (Criteria) this; } public Criteria andFileSizeBetween(Long value1, Long value2) { addCriterion("file_size between", value1, value2, "fileSize"); return (Criteria) this; } public Criteria andFileSizeNotBetween(Long value1, Long value2) { addCriterion("file_size not between", value1, value2, "fileSize"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
9,241
852
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "DQMOffline/Trigger/interface/EgHLTTrigCodes.h" TEST_CASE("EgHLTTrigCodes", "[EgHLTTrigCodes]") { std::vector<std::string> names = {{"Foo"}, {"Bar"}, {"Ish"}, {"Tar"}, {"ash"}}; constexpr unsigned int kFoo = 0b1; constexpr unsigned int kBar = 0b10; constexpr unsigned int kIsh = 0b100; constexpr unsigned int kTar = 0b1000; constexpr unsigned int kash = 0b10000; using bits = egHLT::TrigCodes::TrigBitSet; SECTION("Sorted") { //This will sort to // ash, Bar, Foo Ish Tar std::unique_ptr<egHLT::TrigCodes> codes(egHLT::TrigCodes::makeCodes(names)); REQUIRE(codes->getCode("ash") == bits(kash)); REQUIRE(codes->getCode("Bar") == bits(kBar)); REQUIRE(codes->getCode("Foo") == bits(kFoo)); REQUIRE(codes->getCode("Ish") == bits(kIsh)); REQUIRE(codes->getCode("Tar") == bits(kTar)); } SECTION("Select multiple") { std::unique_ptr<egHLT::TrigCodes> codes(egHLT::TrigCodes::makeCodes(names)); REQUIRE(codes->getCode("ash:Ish") == bits(kash | kIsh)); REQUIRE(codes->getCode("Bar:Foo:Tar") == bits(kBar | kFoo | kTar)); REQUIRE(codes->getCode("Tar:Foo:Bar") == bits(kTar | kFoo | kBar)); } SECTION("Missing") { std::unique_ptr<egHLT::TrigCodes> codes(egHLT::TrigCodes::makeCodes(names)); REQUIRE(codes->getCode("BAD") == bits()); REQUIRE(codes->getCode("Tar:BAD:Bar") == bits(kTar | kBar)); //no partial match REQUIRE(codes->getCode("as") == bits()); REQUIRE(codes->getCode("ashton") == bits()); } }
639
8,772
<filename>support/cas-server-support-actions-core/src/main/java/org/apereo/cas/web/flow/login/RedirectUnauthorizedServiceUrlAction.java package org.apereo.cas.web.flow.login; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.util.scripting.ScriptingUtils; import org.apereo.cas.web.support.WebUtils; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.springframework.context.ApplicationContext; import org.springframework.webflow.action.AbstractAction; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; import java.net.URI; /** * This is {@link RedirectUnauthorizedServiceUrlAction}. * * @author <NAME> * @since 5.3.0 */ @Slf4j @RequiredArgsConstructor @Getter public class RedirectUnauthorizedServiceUrlAction extends AbstractAction { private final ServicesManager servicesManager; private final ApplicationContext applicationContext; @Override public Event doExecute(final RequestContext context) { var redirectUrl = determineUnauthorizedServiceRedirectUrl(context); val url = redirectUrl.toString(); if (ScriptingUtils.isExternalGroovyScript(url)) { val scriptResource = applicationContext.getResource(url); val registeredService = WebUtils.getRegisteredService(context); val args = new Object[]{registeredService, context, this.applicationContext, LOGGER}; redirectUrl = ScriptingUtils.executeGroovyScript(scriptResource, args, URI.class, true); } LOGGER.debug("Redirecting to unauthorized redirect URL [{}]", redirectUrl); WebUtils.putUnauthorizedRedirectUrlIntoFlowScope(context, redirectUrl); return null; } /** * Determine unauthorized service redirect url. * * @param context the context * @return the uri */ protected URI determineUnauthorizedServiceRedirectUrl(final RequestContext context) { val redirectUrl = WebUtils.getUnauthorizedRedirectUrlFromFlowScope(context); val currentEvent = context.getCurrentEvent(); val eventAttributes = currentEvent.getAttributes(); LOGGER.debug("Finalizing the unauthorized redirect URL [{}] when processing event [{}] with attributes [{}]", redirectUrl, currentEvent.getId(), eventAttributes); return redirectUrl; } }
834
2,151
// Copyright 2015 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. #include "chrome/browser/chromeos/extensions/file_manager/job_event_router.h" #include <stddef.h> #include <stdint.h> #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "testing/gtest/include/gtest/gtest.h" namespace file_manager { namespace { class JobEventRouterImpl : public JobEventRouter { public: JobEventRouterImpl() : JobEventRouter(base::TimeDelta::FromMilliseconds(0)) { listener_extension_ids_.insert("extension_a"); } std::vector<std::unique_ptr<base::DictionaryValue>> events; void SetListenerExtensionIds(std::set<std::string> extension_ids) { listener_extension_ids_ = extension_ids; } protected: std::set<std::string> GetFileTransfersUpdateEventListenerExtensionIds() override { return listener_extension_ids_; } GURL ConvertDrivePathToFileSystemUrl( const base::FilePath& file_path, const std::string& extension_id) override { std::string url; url.append("filesystem:chrome-extension://"); url.append(extension_id); url.append(file_path.value()); return GURL(url); } void DispatchEventToExtension( const std::string& extension_id, extensions::events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> event_args) override { const base::DictionaryValue* event; event_args->GetDictionary(0, &event); events.push_back(base::WrapUnique(event->DeepCopy())); } private: std::set<std::string> listener_extension_ids_; DISALLOW_COPY_AND_ASSIGN(JobEventRouterImpl); }; class JobEventRouterTest : public testing::Test { protected: void SetUp() override { job_event_router.reset(new JobEventRouterImpl()); } drive::JobInfo CreateJobInfo(drive::JobID id, int64_t num_completed_bytes, int64_t num_total_bytes, const base::FilePath& file_path) { drive::JobInfo job(drive::TYPE_DOWNLOAD_FILE); job.job_id = id; job.num_total_bytes = num_total_bytes; job.num_completed_bytes = num_completed_bytes; job.file_path = file_path; return job; } std::string GetEventString(size_t index, const std::string& name) { std::string value; job_event_router->events[index]->GetString(name, &value); return value; } double GetEventDouble(size_t index, const std::string& name) { double value = NAN; job_event_router->events[index]->GetDouble(name, &value); return value; } std::unique_ptr<JobEventRouterImpl> job_event_router; private: base::MessageLoop message_loop_; }; TEST_F(JobEventRouterTest, Basic) { // Add a job. job_event_router->OnJobAdded( CreateJobInfo(0, 0, 100, base::FilePath("/test/a"))); // Event should be throttled. ASSERT_EQ(0u, job_event_router->events.size()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(1u, job_event_router->events.size()); EXPECT_EQ("in_progress", GetEventString(0, "transferState")); EXPECT_EQ(0.0f, GetEventDouble(0, "processed")); EXPECT_EQ(100.0f, GetEventDouble(0, "total")); job_event_router->events.clear(); // Job is updated. job_event_router->OnJobUpdated( CreateJobInfo(0, 50, 100, base::FilePath("/test/a"))); job_event_router->OnJobUpdated( CreateJobInfo(0, 100, 100, base::FilePath("/test/a"))); // Event should be throttled. ASSERT_EQ(0u, job_event_router->events.size()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(1u, job_event_router->events.size()); EXPECT_EQ("in_progress", GetEventString(0, "transferState")); EXPECT_EQ(100.0f, GetEventDouble(0, "processed")); EXPECT_EQ(100.0f, GetEventDouble(0, "total")); job_event_router->events.clear(); // Complete first job. job_event_router->OnJobDone( CreateJobInfo(0, 100, 100, base::FilePath("/test/a")), drive::FILE_ERROR_OK); // Complete event should not be throttled. ASSERT_EQ(1u, job_event_router->events.size()); EXPECT_EQ("completed", GetEventString(0, "transferState")); EXPECT_EQ(100.0f, GetEventDouble(0, "processed")); EXPECT_EQ(100.0f, GetEventDouble(0, "total")); job_event_router->events.clear(); } TEST_F(JobEventRouterTest, CompleteWithInvalidCompletedBytes) { job_event_router->OnJobDone( CreateJobInfo(0, 50, 100, base::FilePath("/test/a")), drive::FILE_ERROR_OK); ASSERT_EQ(1u, job_event_router->events.size()); EXPECT_EQ("completed", GetEventString(0, "transferState")); EXPECT_EQ(100.0f, GetEventDouble(0, "processed")); EXPECT_EQ(100.0f, GetEventDouble(0, "total")); } TEST_F(JobEventRouterTest, AnotherJobAddedBeforeComplete) { job_event_router->OnJobAdded( CreateJobInfo(0, 0, 100, base::FilePath("/test/a"))); job_event_router->OnJobUpdated( CreateJobInfo(0, 50, 100, base::FilePath("/test/a"))); job_event_router->OnJobAdded( CreateJobInfo(1, 0, 100, base::FilePath("/test/b"))); // Event should be throttled. ASSERT_EQ(0u, job_event_router->events.size()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(1u, job_event_router->events.size()); EXPECT_EQ("in_progress", GetEventString(0, "transferState")); EXPECT_EQ(50.0f, GetEventDouble(0, "processed")); EXPECT_EQ(200.0f, GetEventDouble(0, "total")); job_event_router->events.clear(); job_event_router->OnJobDone( CreateJobInfo(0, 100, 100, base::FilePath("/test/a")), drive::FILE_ERROR_OK); job_event_router->OnJobDone( CreateJobInfo(1, 100, 100, base::FilePath("/test/b")), drive::FILE_ERROR_OK); // Complete event should not be throttled. ASSERT_EQ(2u, job_event_router->events.size()); EXPECT_EQ("completed", GetEventString(0, "transferState")); EXPECT_EQ(100.0f, GetEventDouble(0, "processed")); EXPECT_EQ(200.0f, GetEventDouble(0, "total")); EXPECT_EQ("completed", GetEventString(1, "transferState")); EXPECT_EQ(200.0f, GetEventDouble(1, "processed")); EXPECT_EQ(200.0f, GetEventDouble(1, "total")); } TEST_F(JobEventRouterTest, AnotherJobAddedAfterComplete) { job_event_router->OnJobAdded( CreateJobInfo(0, 0, 100, base::FilePath("/test/a"))); job_event_router->OnJobUpdated( CreateJobInfo(0, 50, 100, base::FilePath("/test/a"))); job_event_router->OnJobDone( CreateJobInfo(0, 100, 100, base::FilePath("/test/a")), drive::FILE_ERROR_OK); job_event_router->OnJobAdded( CreateJobInfo(1, 0, 100, base::FilePath("/test/b"))); job_event_router->OnJobDone( CreateJobInfo(1, 100, 100, base::FilePath("/test/b")), drive::FILE_ERROR_OK); // Complete event should not be throttled. ASSERT_EQ(2u, job_event_router->events.size()); EXPECT_EQ("completed", GetEventString(0, "transferState")); EXPECT_EQ(100.0f, GetEventDouble(0, "processed")); // Total byte shold be reset when all tasks complete. EXPECT_EQ(100.0f, GetEventDouble(0, "total")); EXPECT_EQ("completed", GetEventString(1, "transferState")); EXPECT_EQ(100.0f, GetEventDouble(1, "processed")); EXPECT_EQ(100.0f, GetEventDouble(1, "total")); } TEST_F(JobEventRouterTest, UpdateTotalSizeAfterAdded) { job_event_router->OnJobAdded( CreateJobInfo(0, 0, 0, base::FilePath("/test/a"))); base::RunLoop().RunUntilIdle(); job_event_router->OnJobUpdated( CreateJobInfo(0, 0, 100, base::FilePath("/test/a"))); base::RunLoop().RunUntilIdle(); ASSERT_EQ(2u, job_event_router->events.size()); EXPECT_EQ("in_progress", GetEventString(0, "transferState")); EXPECT_EQ(0.0f, GetEventDouble(0, "processed")); EXPECT_EQ(0.0f, GetEventDouble(0, "total")); EXPECT_EQ("in_progress", GetEventString(1, "transferState")); EXPECT_EQ(0.0f, GetEventDouble(1, "processed")); EXPECT_EQ(100.0f, GetEventDouble(1, "total")); } TEST_F(JobEventRouterTest, MultipleListenerExtensions) { std::set<std::string> extension_ids; extension_ids.insert("extension_a"); extension_ids.insert("extension_b"); job_event_router->SetListenerExtensionIds(extension_ids); // Add a job. job_event_router->OnJobAdded( CreateJobInfo(0, 0, 100, base::FilePath("/test/a"))); base::RunLoop().RunUntilIdle(); ASSERT_EQ(2u, job_event_router->events.size()); // Check event for extension_a. EXPECT_EQ("in_progress", GetEventString(0, "transferState")); EXPECT_EQ(0.0f, GetEventDouble(0, "processed")); EXPECT_EQ(100.0f, GetEventDouble(0, "total")); EXPECT_EQ("filesystem:chrome-extension://extension_a/test/a", GetEventString(0, "fileUrl")); // Check event for extension_b. EXPECT_EQ("in_progress", GetEventString(1, "transferState")); EXPECT_EQ(0.0f, GetEventDouble(1, "processed")); EXPECT_EQ(100.0f, GetEventDouble(1, "total")); EXPECT_EQ("filesystem:chrome-extension://extension_b/test/a", GetEventString(1, "fileUrl")); } } // namespace } // namespace file_manager
3,600
19,438
/* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibGUI/Action.h> #include <LibGUI/ActionGroup.h> namespace GUI { void ActionGroup::add_action(Action& action) { action.set_group({}, this); m_actions.set(&action); } void ActionGroup::remove_action(Action& action) { action.set_group({}, nullptr); m_actions.remove(&action); } }
160
1,251
package cn.dblearn.blog.portal.operation.service; import cn.dblearn.blog.entity.operation.Tag; import cn.dblearn.blog.entity.operation.vo.TagVO; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * TagService * * @author bobbi * @date 2019/02/22 16:34 * @email <EMAIL> * @description */ public interface TagService extends IService<Tag> { /** * 获取tagVoList * @return */ List<TagVO> listTagVo(); }
190
760
/** * Licensed to DigitalPebble Ltd under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * DigitalPebble 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 com.digitalpebble.stormcrawler.parse; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.digitalpebble.stormcrawler.Constants; import com.digitalpebble.stormcrawler.Metadata; import com.digitalpebble.stormcrawler.bolt.JSoupParserBolt; /** @see https://github.com/DigitalPebble/storm-crawler/pull/653 **/ public class StackOverflowTest extends ParsingTester { @Before public void setupParserBolt() { bolt = new JSoupParserBolt(); setupParserBolt(bolt); } @Test public void testStackOverflow() throws IOException { prepareParserBolt("test.parsefilters.json"); Metadata metadata = new Metadata(); parse("http://polloxniner.blogspot.com", "stackexception.html", metadata); Assert.assertEquals(164, output.getEmitted(Constants.StatusStreamName) .size()); } /** @see https://github.com/DigitalPebble/storm-crawler/issues/666 **/ @Test public void testNamespaceExtraction() throws IOException { prepareParserBolt("test.parsefilters.json"); Metadata metadata = new Metadata(); parse("http://polloxniner.<EMAIL>", "stackexception.html", metadata); Assert.assertEquals(1, output.getEmitted().size()); List<Object> obj = output.getEmitted().get(0); Metadata m = (Metadata) obj.get(2); assertNotNull(m.getFirstValue("title")); } }
809
590
<filename>Tools/EditorFramework/DataSelectorManager.cpp /*! @file @author <NAME> @date 07/2012 */ #include "Precompiled.h" #include "DataSelectorManager.h" #include "DataTypeManager.h" namespace tools { DataSelectorManager* DataSelectorManager::mInstance = nullptr; DataSelectorManager::DataSelectorManager() { mInstance = this; } DataSelectorManager::~DataSelectorManager() { mInstance = nullptr; } DataSelectorManager& DataSelectorManager::getInstance() { return *mInstance; } DataSelectorManager* DataSelectorManager::getInstancePtr() { return mInstance; } void DataSelectorManager::initialise() { } void DataSelectorManager::shutdown() { clear(); } void DataSelectorManager::clear() { for (MapEvent::iterator event = mEvents.begin(); event != mEvents.end(); event ++) delete (*event).second; mEvents.clear(); } DataSelectorManager::EventType* DataSelectorManager::getEvent(const std::string& _dataType) { MapEvent::iterator event = mEvents.find(_dataType); if (event != mEvents.end()) return (*event).second; EventType* type = new EventType(); mEvents[_dataType] = type; return type; } void DataSelectorManager::changeParent(DataPtr _parent) { onChangeData(_parent, _parent->getType(), false); } void DataSelectorManager::changeParentSelection(DataPtr _parent, DataPtr _selectedChild) { _parent->setChildSelected(_selectedChild); onChangeData(_parent, _parent->getType(), true); } void DataSelectorManager::onChangeData(DataPtr _parent, DataTypePtr _type, bool _changeOnlySelection) { EventType* event = getEvent(_type->getName()); if (event != nullptr) { event->operator()(_parent, _changeOnlySelection); } DataPtr childSelected = nullptr; if (_parent != nullptr) childSelected = _parent->getChildSelected(); const DataType::VectorString& childs = _type->getChilds(); for (DataType::VectorString::const_iterator childName = childs.begin(); childName != childs.end(); childName ++) { DataTypePtr childType = DataTypeManager::getInstance().getType(*childName); if (childType != nullptr) { DataPtr child = childSelected; if (child != nullptr && child->getType() != childType) child = nullptr; if (child != nullptr) { DataPtr subChildSelected = child->getChildSelected(); if (subChildSelected == nullptr) { if (child->getChilds().size() != 0) { DataPtr childData = child->getChildByIndex(0); child->setChildSelected(childData); } } } onChangeData(child, childType, false); } } } }
959
1,244
<reponame>caokun8008/ckeos<filename>externals/binaryen/test/emscripten/system/lib/libc/musl/src/unistd/pipe.c<gh_stars>1000+ #include <unistd.h> #include "syscall.h" int pipe(int fd[2]) { return syscall(SYS_pipe, fd); }
106
467
{ "actor": { "avatar_url": "https://avatars.githubusercontent.com/u/5858395?", "display_login": "Diwahars", "gravatar_id": "", "id": 5858395.0, "login": "Diwahars", "url": "https://api.github.com/users/Diwahars" }, "created_at": "2016-06-02T17:59:59Z", "id": "4095565518", "payload": { "description": "", "master_branch": "master", "pusher_type": "user", "ref": null, "ref_type": "repository" }, "public": true, "repo": { "id": 60285881.0, "name": "Diwahars/twitter", "url": "https://api.github.com/repos/Diwahars/twitter" }, "type": "CreateEvent", "a_structure": "{description:,master_branch:,pusher_type:,ref:,ref_type:}" }
325
1,338
#include <../private/package/hpkg/PackageWriterImpl.h>
18
319
<filename>demos/sandbox/src/main/java/org/openimaj/image/neardups/SimulationDriver.java /** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Southampton nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openimaj.image.neardups; import java.io.File; import java.io.IOException; import org.openimaj.image.DisplayUtilities; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.neardups.sim.ComboSimulation; import org.openimaj.image.neardups.sim.CompressSimulation; import org.openimaj.image.neardups.sim.CropSimulation; import org.openimaj.image.neardups.sim.Rotate90Simulation; import org.openimaj.image.neardups.sim.Simulation; import org.openimaj.image.neardups.sim.WatermarkSimulation; public class SimulationDriver { public static void main(String[] args) throws IOException { final int seed = 43; final MBFImage input = ImageUtilities.readMBF(new File("/Users/jsh2/Data/ukbench/full/ukbench00000.jpg")); // Simulation sim = new CropSimulation(seed); // Simulation sim = new ArbitaryRotateSimulation(seed); // Simulation sim = new Rotate90Simulation(seed); // Simulation sim = new CompressSimulation(seed); // Simulation sim = new UniformScaleSimulation(seed); // Simulation sim = new ArbitaryStretchSimulation(seed); // Simulation sim = new GreyscaleSimulation(seed); // Simulation sim = new WatermarkSimulation(seed); final Simulation sim = new ComboSimulation(seed, new Rotate90Simulation(seed), new CropSimulation(seed), new WatermarkSimulation(seed), new CompressSimulation(seed) ); for (int i = 0; i < 10; i++) { DisplayUtilities.display(sim.applySimulation(input)); } } }
994
459
<filename>include/oglplus/math/vector_3.ipp<gh_stars>100-1000 /** * .file oglplus/math/vector_3.ipp * .brief Specialization of Vector for 3D vectors * * @author <NAME> * * Copyright 2010-2014 <NAME>. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ template <typename T> class Vector<T, 3> : public VectorBase<T, 3> { private: typedef VectorBase<T, 3> Base; typedef typename Base::Unit_ Unit_; public: Vector(void) { } template <typename U, std::size_t M> Vector(const Vector<U, M>& vector) : Base(vector) { } Vector(const T (&v)[3]) : Base(v) { } Vector(const T* v, std::size_t n) : Base(v, n) { } explicit Vector(T v0) : Base(v0) { } Vector(T v0, T v1, T v2) : Base(oglplus::Nothing()) { this->_elem[0] = v0; this->_elem[1] = v1; this->_elem[2] = v2; } template <typename U> Vector(const Vector<U, 1>& v, T v1, T v2) : Base(oglplus::Nothing()) { this->_elem[0] = T(v[0]); this->_elem[1] = v1; this->_elem[2] = v2; } template <typename U> Vector(const Vector<U, 2>& v, T v2) : Base(oglplus::Nothing()) { this->_elem[0] = T(v[0]); this->_elem[1] = T(v[1]); this->_elem[2] = v2; } Vector(Unit_, std::size_t axis) { assert(axis < 3); this->_elem[axis] = T(1); } static Vector Unit(std::size_t axis) { return Vector(Unit_(), axis); } explicit Vector(const Matrix<T, 1, 3>& matrix) : Base(matrix) { } explicit Vector(const Matrix<T, 3, 1>& matrix) : Base(matrix) { } T x(void) const { return this->At(0); } T y(void) const { return this->At(1); } T z(void) const { return this->At(2); } Vector<T, 2> xy(void) const { return Vector<T, 2>(this->At(0), this->At(1)); } friend Vector Negated(const Vector& a) { return Vector(-a[0], -a[1], -a[2]); } friend Vector Added(const Vector& a, const Vector& b) { return Vector(a[0]+b[0], a[1]+b[1], a[2]+b[2]); } Vector& operator += (const Vector& v) { this->Add(v); return *this; } friend Vector Subtracted(const Vector& a, const Vector& b) { return Vector(a[0]-b[0], a[1]-b[1], a[2]-b[2]); } Vector& operator -= (const Vector& v) { this->Subtract(v); return *this; } friend Vector Multiplied(const Vector& a, T v) { return Vector(a[0]*v, a[1]*v, a[2]*v); } Vector& operator *= (T v) { this->Multiply(v); return *this; } Vector& operator *= (const Vector& v) { this->Multiply(v); return *this; } friend Vector Divided(const Vector& a, T v) { return Vector(a[0]/v, a[1]/v, a[2]/v); } Vector& operator /= (T v) { this->Divide(v); return *this; } };
1,254
1,144
<filename>backend/de.metas.adempiere.adempiere/base/src/main/java-legacy/org/compiere/print/PrintDataElement.java<gh_stars>1000+ /****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via <EMAIL> or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.print; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.model.MLocation; import org.compiere.util.DisplayType; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; import org.compiere.util.NamePair; import de.metas.i18n.Language; /** * Print Data Element * * @author <NAME> * @version $Id: PrintDataElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $ */ public class PrintDataElement { /** * Print Data Element Constructor * @param columnName name * @param value display value * @param displayType optional displayType * @param isPKey is primary key * @param isPageBreak if true force page break */ public PrintDataElement (String columnName, Object value, int displayType, boolean isPKey, boolean isPageBreak, String format) { if (columnName == null) throw new IllegalArgumentException("PrintDataElement - Name cannot be null"); m_columnName = columnName; m_value = value; m_displayType = displayType; m_isPKey = isPKey; m_isPageBreak = isPageBreak; m_formatPattern = format; } // PrintDataElement /** * Print Data Element Constructor * @param columnName name * @param value display value * @param pattern Number/date format pattern * @param displayType optional displayType */ public PrintDataElement(String columnName, Object value, int displayType, String pattern) { this (columnName, value, displayType, false, false, pattern); } // PrintDataElement /** Data Name */ private String m_columnName; /** Data Value */ private Object m_value; /** Display Type */ private int m_displayType; /** Is Primary Key */ private boolean m_isPKey; /** Is Page Break */ private boolean m_isPageBreak; /** Value format pattern */ private String m_formatPattern; /** XML Element Name */ public static final String XML_TAG = "element"; /** XML Attribute Name */ public static final String XML_ATTRIBUTE_NAME = "name"; /** XML Attribute Key */ public static final String XML_ATTRIBUTE_KEY = "key"; /** * Get Name * @return name */ public String getColumnName() { return m_columnName; } // getName /** * Get Node Value * @return value */ public Object getValue() { return m_value; } // getValue /** * Get Function Value * @return length or numeric value */ public BigDecimal getFunctionValue() { if (m_value == null) return Env.ZERO; // Numbers - return number value if (m_value instanceof BigDecimal) return (BigDecimal)m_value; if (m_value instanceof Number) return new BigDecimal(((Number)m_value).doubleValue()); // Boolean - return 1 for true 0 for false if (m_value instanceof Boolean) { if (((Boolean)m_value).booleanValue()) return Env.ONE; else return Env.ZERO; } // Return Length String s = m_value.toString(); return new BigDecimal(s.length()); } // getFunctionValue /** * Get Node Value Display * @param language optional language - if null numbers/dates are not formatted * @return display value optionally formatted */ public String getValueDisplay (Language language) { if (m_value == null) return ""; String retValue = m_value.toString(); if (m_displayType == DisplayType.Location) return getValueDisplay_Location(); // ID columns should be printed as ID numbers - teo_sarca [ 1673363 ] else if (DisplayType.ID == m_displayType && m_value instanceof KeyNamePair) return ((KeyNamePair)m_value).getID(); else if (m_columnName.equals("C_BPartner_Location_ID") || m_columnName.equals("Bill_Location_ID")) return getValueDisplay_BPLocation(); else if (m_displayType == 0 || m_value instanceof String || m_value instanceof NamePair) ; else if (language != null) // Optional formatting of Numbers and Dates { if (DisplayType.isNumeric(m_displayType)) { retValue = DisplayType.getNumberFormat(m_displayType, language, m_formatPattern).format(m_value); } else if (DisplayType.isDate(m_displayType)) retValue = DisplayType.getDateFormat(m_displayType, language, m_formatPattern).format(m_value); } return retValue; } // getValueDisplay /** * Get Node Data Value as String * @return data value */ public String getValueAsString() { if (m_value == null) return ""; String retValue = m_value.toString(); if (m_value instanceof NamePair) retValue = ((NamePair)m_value).getID(); return retValue; } // getValueDisplay /** * Return Address String not just name * @return Address String */ private String getValueDisplay_BPLocation () { try { int C_BPartner_Location_ID = Integer.parseInt (getValueKey ()); if (C_BPartner_Location_ID != 0) { MLocation loc = MLocation.getBPLocation(Env.getCtx(), C_BPartner_Location_ID, null); if (loc != null) return loc.toStringCR(); } } catch (Exception ex) { } return m_value.toString(); } // getValueDisplay_BPLocation /** * Return Address String not just City * @return Address String */ private String getValueDisplay_Location () { try { int C_Location_ID = Integer.parseInt (getValueKey ()); if (C_Location_ID != 0) { MLocation loc = new MLocation (Env.getCtx(), C_Location_ID, null); if (loc != null) return loc.toStringCR(); } } catch (Exception ex) { } return m_value.toString(); } // getValueDisplay_Location /** * Get Node Value Key * @return key */ public String getValueKey() { if (m_value == null) return ""; if (m_value instanceof NamePair) return ((NamePair)m_value).getID(); return ""; } // getValueKey /** * Is Value Null * @return true if value is null */ public boolean isNull() { return m_value == null; } // isNull /*************************************************************************/ /** * Get Display Type * @return Display Type */ public int getDisplayType() { return m_displayType; } // getDisplayType /** * Is Value numeric * @return true if value is a numeric */ public boolean isNumeric() { if (m_displayType == 0) return m_value instanceof BigDecimal; return DisplayType.isNumeric(m_displayType); } // isNumeric /** * Is Value a date * @return true if value is a date */ public boolean isDate() { if (m_displayType == 0) return m_value instanceof Timestamp; return DisplayType.isDate(m_displayType); } // isDate /** * Is Value an ID * @return true if value is an ID */ public boolean isID() { // ID columns are considered numbers - teo_sarca [ 1673363 ] if (DisplayType.ID == m_displayType) return false; return DisplayType.isID(m_displayType); } // isID /** * Is Value boolean * @return true if value is a boolean */ public boolean isYesNo() { if (m_displayType == 0) return m_value instanceof Boolean; return DisplayType.YesNo == m_displayType; } // isYesNo /** * Is Value the primary key of row * @return true if value is the PK */ public boolean isPKey() { return m_isPKey; } // isPKey /** * Column value forces page break * @return true if page break */ public boolean isPageBreak() { return m_isPageBreak; } // isPageBreak /*************************************************************************/ /** * HashCode * @return hash code */ public int hashCode() { if (m_value == null) return m_columnName.hashCode(); return m_columnName.hashCode() + m_value.hashCode(); } // hashCode /** * Equals * @param compare compare object * @return true if equals */ public boolean equals (Object compare) { if (compare instanceof PrintDataElement) { PrintDataElement pde = (PrintDataElement)compare; if (pde.getColumnName().equals(m_columnName)) { if (pde.getValue() != null && pde.getValue().equals(m_value)) return true; if (pde.getValue() == null && m_value == null) return true; } } return false; } // equals /** * String representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer(m_columnName).append("=").append(m_value); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } // toString /** * Value Has Key * @return true if value has a key */ public boolean hasKey() { return m_value instanceof NamePair; } // hasKey /** * String representation with key info * @return info */ public String toStringX() { if (m_value instanceof NamePair) { NamePair pp = (NamePair)m_value; StringBuffer sb = new StringBuffer(m_columnName); sb.append("(").append(pp.getID()).append(")") .append("=").append(pp.getName()); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } else return toString(); } // toStringX public String getM_formatPattern() { return m_formatPattern; } public void setM_formatPattern(String pattern) { m_formatPattern = pattern; } } // PrintDataElement
3,822