max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,671
/** * Copyright 2016 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.github.ambry.tools.perf; import com.codahale.metrics.MetricRegistry; import com.github.ambry.clustermap.ClusterAgentsFactory; import com.github.ambry.clustermap.ClusterMap; import com.github.ambry.clustermap.ReplicaId; import com.github.ambry.commons.BlobId; import com.github.ambry.server.ServerErrorCode; import com.github.ambry.config.ClusterMapConfig; import com.github.ambry.config.ConnectionPoolConfig; import com.github.ambry.config.SSLConfig; import com.github.ambry.config.VerifiableProperties; import com.github.ambry.messageformat.BlobData; import com.github.ambry.messageformat.BlobProperties; import com.github.ambry.messageformat.MessageFormatFlags; import com.github.ambry.messageformat.MessageFormatRecord; import com.github.ambry.network.BlockingChannelConnectionPool; import com.github.ambry.network.ConnectedChannel; import com.github.ambry.network.ConnectionPool; import com.github.ambry.network.Port; import com.github.ambry.protocol.DeleteRequest; import com.github.ambry.protocol.DeleteResponse; import com.github.ambry.protocol.GetOption; import com.github.ambry.protocol.GetRequest; import com.github.ambry.protocol.GetResponse; import com.github.ambry.protocol.PartitionRequestInfo; import com.github.ambry.tools.util.ToolUtils; import com.github.ambry.utils.ByteBufferOutputStream; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Throttler; import com.github.ambry.utils.Utils; import io.netty.buffer.ByteBuf; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.nio.ByteBuffer; import java.rmi.UnexpectedException; import java.util.ArrayList; import java.util.Collections; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import joptsimple.ArgumentAcceptingOptionSpec; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; /** * */ public class ServerReadPerformance { public static void main(String args[]) { ConnectionPool connectionPool = null; FileWriter writer = null; try { OptionParser parser = new OptionParser(); ArgumentAcceptingOptionSpec<String> logToReadOpt = parser.accepts("logToRead", "The log that needs to be replayed for traffic") .withRequiredArg() .describedAs("log_to_read") .ofType(String.class); ArgumentAcceptingOptionSpec<String> hardwareLayoutOpt = parser.accepts("hardwareLayout", "The path of the hardware layout file") .withRequiredArg() .describedAs("hardware_layout") .ofType(String.class); ArgumentAcceptingOptionSpec<String> partitionLayoutOpt = parser.accepts("partitionLayout", "The path of the partition layout file") .withRequiredArg() .describedAs("partition_layout") .ofType(String.class); ArgumentAcceptingOptionSpec<Integer> readsPerSecondOpt = parser.accepts("readsPerSecond", "The rate at which reads need to be performed") .withRequiredArg() .describedAs("The number of reads per second") .ofType(Integer.class) .defaultsTo(1000); ArgumentAcceptingOptionSpec<Long> measurementIntervalOpt = parser.accepts("measurementInterval", "The interval in second to report performance result") .withOptionalArg() .describedAs("The CPU time spent for getting blobs, not wall time") .ofType(Long.class) .defaultsTo(300L); ArgumentAcceptingOptionSpec<Boolean> verboseLoggingOpt = parser.accepts("enableVerboseLogging", "Enables verbose logging") .withOptionalArg() .describedAs("Enable verbose logging") .ofType(Boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<String> sslEnabledDatacentersOpt = parser.accepts("sslEnabledDatacenters", "Datacenters to which ssl should be enabled") .withOptionalArg() .describedAs("Comma separated list") .ofType(String.class) .defaultsTo(""); ArgumentAcceptingOptionSpec<String> sslKeystorePathOpt = parser.accepts("sslKeystorePath", "SSL key store path") .withOptionalArg() .describedAs("The file path of SSL key store") .defaultsTo("") .ofType(String.class); ArgumentAcceptingOptionSpec<String> sslKeystoreTypeOpt = parser.accepts("sslKeystoreType", "SSL key store type") .withOptionalArg() .describedAs("The type of SSL key store") .defaultsTo("") .ofType(String.class); ArgumentAcceptingOptionSpec<String> sslTruststorePathOpt = parser.accepts("sslTruststorePath", "SSL trust store path") .withOptionalArg() .describedAs("The file path of SSL trust store") .defaultsTo("") .ofType(String.class); ArgumentAcceptingOptionSpec<String> sslKeystorePasswordOpt = parser.accepts("sslKeystorePassword", "SSL key store password") .withOptionalArg() .describedAs("The password of SSL key store") .defaultsTo("") .ofType(String.class); ArgumentAcceptingOptionSpec<String> sslKeyPasswordOpt = parser.accepts("sslKeyPassword", "SSL key password") .withOptionalArg() .describedAs("The password of SSL private key") .defaultsTo("") .ofType(String.class); ArgumentAcceptingOptionSpec<String> sslTruststorePasswordOpt = parser.accepts("sslTruststorePassword", "SSL trust store password") .withOptionalArg() .describedAs("The password of SSL trust store") .defaultsTo("") .ofType(String.class); ArgumentAcceptingOptionSpec<String> sslCipherSuitesOpt = parser.accepts("sslCipherSuites", "SSL enabled cipher suites") .withOptionalArg() .describedAs("Comma separated list") .defaultsTo("TLS_RSA_WITH_AES_128_CBC_SHA") .ofType(String.class); OptionSet options = parser.parse(args); ArrayList<OptionSpec> listOpt = new ArrayList<>(); listOpt.add(logToReadOpt); listOpt.add(hardwareLayoutOpt); listOpt.add(partitionLayoutOpt); ToolUtils.ensureOrExit(listOpt, options, parser); long measurementIntervalNs = options.valueOf(measurementIntervalOpt) * SystemTime.NsPerSec; ToolUtils.validateSSLOptions(options, parser, sslEnabledDatacentersOpt, sslKeystorePathOpt, sslKeystoreTypeOpt, sslTruststorePathOpt, sslKeystorePasswordOpt, sslKeyPasswordOpt, sslTruststorePasswordOpt); String sslEnabledDatacenters = options.valueOf(sslEnabledDatacentersOpt); Properties sslProperties; if (sslEnabledDatacenters.length() != 0) { sslProperties = ToolUtils.createSSLProperties(sslEnabledDatacenters, options.valueOf(sslKeystorePathOpt), options.valueOf(sslKeystoreTypeOpt), options.valueOf(sslKeystorePasswordOpt), options.valueOf(sslKeyPasswordOpt), options.valueOf(sslTruststorePathOpt), options.valueOf(sslTruststorePasswordOpt), options.valueOf(sslCipherSuitesOpt)); } else { sslProperties = new Properties(); } ToolUtils.addClusterMapProperties(sslProperties); String logToRead = options.valueOf(logToReadOpt); int readsPerSecond = options.valueOf(readsPerSecondOpt); boolean enableVerboseLogging = options.has(verboseLoggingOpt); if (enableVerboseLogging) { System.out.println("Enabled verbose logging"); } File logFile = new File(System.getProperty("user.dir"), "readperfresult"); writer = new FileWriter(logFile); String hardwareLayoutPath = options.valueOf(hardwareLayoutOpt); String partitionLayoutPath = options.valueOf(partitionLayoutOpt); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(new VerifiableProperties(sslProperties)); ClusterMap map = ((ClusterAgentsFactory) Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, hardwareLayoutPath, partitionLayoutPath)).getClusterMap(); final AtomicLong totalTimeTaken = new AtomicLong(0); final AtomicLong totalReads = new AtomicLong(0); final AtomicBoolean shutdown = new AtomicBoolean(false); // attach shutdown handler to catch control-c Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { System.out.println("Shutdown invoked"); shutdown.set(true); String message = "Total reads : " + totalReads.get() + " Total time taken : " + totalTimeTaken.get() + " Nano Seconds Average time taken per read " + ((double) totalTimeTaken.get()) / SystemTime.NsPerSec / totalReads.get() + " Seconds"; System.out.println(message); } catch (Exception e) { System.out.println("Error while shutting down " + e); } } }); final BufferedReader br = new BufferedReader(new FileReader(logToRead)); Throttler throttler = new Throttler(readsPerSecond, 100, true, SystemTime.getInstance()); String line; ConnectedChannel channel = null; ConnectionPoolConfig connectionPoolConfig = new ConnectionPoolConfig(new VerifiableProperties(new Properties())); VerifiableProperties vProps = new VerifiableProperties(sslProperties); SSLConfig sslConfig = new SSLConfig(vProps); clusterMapConfig = new ClusterMapConfig(vProps); connectionPool = new BlockingChannelConnectionPool(connectionPoolConfig, sslConfig, clusterMapConfig, new MetricRegistry()); long totalNumberOfGetBlobs = 0; long totalLatencyForGetBlobs = 0; ArrayList<Long> latenciesForGetBlobs = new ArrayList<Long>(); long maxLatencyForGetBlobs = 0; long minLatencyForGetBlobs = Long.MAX_VALUE; while ((line = br.readLine()) != null) { String[] id = line.split("-"); BlobData blobData = null; BlobId blobId = new BlobId(id[1], map); ArrayList<BlobId> blobIds = new ArrayList<BlobId>(); blobIds.add(blobId); for (ReplicaId replicaId : blobId.getPartition().getReplicaIds()) { long startTimeGetBlob = 0; ArrayList<PartitionRequestInfo> partitionRequestInfoList = new ArrayList<PartitionRequestInfo>(); try { partitionRequestInfoList.clear(); PartitionRequestInfo partitionRequestInfo = new PartitionRequestInfo(blobId.getPartition(), blobIds); partitionRequestInfoList.add(partitionRequestInfo); GetRequest getRequest = new GetRequest(1, "getperf", MessageFormatFlags.Blob, partitionRequestInfoList, GetOption.None); Port port = replicaId.getDataNodeId().getPortToConnectTo(); channel = connectionPool.checkOutConnection(replicaId.getDataNodeId().getHostname(), port, 10000); startTimeGetBlob = SystemTime.getInstance().nanoseconds(); channel.send(getRequest); DataInputStream receiveStream = channel.receive().getInputStream(); GetResponse getResponse = GetResponse.readFrom(receiveStream, map); blobData = MessageFormatRecord.deserializeBlob(getResponse.getInputStream()); long sizeRead = 0; byte[] outputBuffer = new byte[(int) blobData.getSize()]; ByteBufferOutputStream streamOut = new ByteBufferOutputStream(ByteBuffer.wrap(outputBuffer)); ByteBuf buffer = blobData.content(); try { buffer.readBytes(streamOut, (int) blobData.getSize()); } finally { buffer.release(); } long latencyPerBlob = SystemTime.getInstance().nanoseconds() - startTimeGetBlob; totalTimeTaken.addAndGet(latencyPerBlob); latenciesForGetBlobs.add(latencyPerBlob); totalReads.incrementAndGet(); totalNumberOfGetBlobs++; totalLatencyForGetBlobs += latencyPerBlob; if (enableVerboseLogging) { System.out.println( "Time taken to get blob id " + blobId + " in ms " + latencyPerBlob / SystemTime.NsPerMs); } if (latencyPerBlob > maxLatencyForGetBlobs) { maxLatencyForGetBlobs = latencyPerBlob; } if (latencyPerBlob < minLatencyForGetBlobs) { minLatencyForGetBlobs = latencyPerBlob; } if (totalLatencyForGetBlobs >= measurementIntervalNs) { Collections.sort(latenciesForGetBlobs); int index99 = (int) (latenciesForGetBlobs.size() * 0.99) - 1; int index95 = (int) (latenciesForGetBlobs.size() * 0.95) - 1; String message = totalNumberOfGetBlobs + "," + (double) latenciesForGetBlobs.get(index99) / SystemTime.NsPerSec + "," + (double) latenciesForGetBlobs.get(index95) / SystemTime.NsPerSec + "," + ( (double) totalLatencyForGetBlobs / SystemTime.NsPerSec / totalNumberOfGetBlobs); System.out.println(message); writer.write(message + "\n"); totalLatencyForGetBlobs = 0; latenciesForGetBlobs.clear(); totalNumberOfGetBlobs = 0; maxLatencyForGetBlobs = 0; minLatencyForGetBlobs = Long.MAX_VALUE; } partitionRequestInfoList.clear(); partitionRequestInfo = new PartitionRequestInfo(blobId.getPartition(), blobIds); partitionRequestInfoList.add(partitionRequestInfo); GetRequest getRequestProperties = new GetRequest(1, "getperf", MessageFormatFlags.BlobProperties, partitionRequestInfoList, GetOption.None); long startTimeGetBlobProperties = SystemTime.getInstance().nanoseconds(); channel.send(getRequestProperties); DataInputStream receivePropertyStream = channel.receive().getInputStream(); GetResponse getResponseProperty = GetResponse.readFrom(receivePropertyStream, map); BlobProperties blobProperties = MessageFormatRecord.deserializeBlobProperties(getResponseProperty.getInputStream()); long endTimeGetBlobProperties = SystemTime.getInstance().nanoseconds() - startTimeGetBlobProperties; partitionRequestInfoList.clear(); partitionRequestInfo = new PartitionRequestInfo(blobId.getPartition(), blobIds); partitionRequestInfoList.add(partitionRequestInfo); GetRequest getRequestUserMetadata = new GetRequest(1, "getperf", MessageFormatFlags.BlobUserMetadata, partitionRequestInfoList, GetOption.None); long startTimeGetBlobUserMetadata = SystemTime.getInstance().nanoseconds(); channel.send(getRequestUserMetadata); DataInputStream receiveUserMetadataStream = channel.receive().getInputStream(); GetResponse getResponseUserMetadata = GetResponse.readFrom(receiveUserMetadataStream, map); ByteBuffer userMetadata = MessageFormatRecord.deserializeUserMetadata(getResponseUserMetadata.getInputStream()); long endTimeGetBlobUserMetadata = SystemTime.getInstance().nanoseconds() - startTimeGetBlobUserMetadata; // delete the blob DeleteRequest deleteRequest = new DeleteRequest(0, "perf", blobId, System.currentTimeMillis()); channel.send(deleteRequest); DeleteResponse deleteResponse = DeleteResponse.readFrom(channel.receive().getInputStream()); if (deleteResponse.getError() != ServerErrorCode.No_Error) { throw new UnexpectedException("error " + deleteResponse.getError()); } throttler.maybeThrottle(1); } finally { if (channel != null) { connectionPool.checkInConnection(channel); channel = null; } } } } } catch (Exception e) { e.printStackTrace(); System.out.println("Error in server read performance " + e); } finally { if (writer != null) { try { writer.close(); } catch (Exception e) { System.out.println("Error when closing writer"); } } if (connectionPool != null) { connectionPool.shutdown(); } } } }
6,978
1,953
package grails.util; public class Triple<A, B, C> { final A aValue; final B bValue; final C cValue; public Triple(A aValue, B bValue, C cValue) { this.aValue = aValue; this.bValue = bValue; this.cValue = cValue; } public A getaValue() { return aValue; } public B getbValue() { return bValue; } public C getcValue() { return cValue; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((aValue == null) ? 0 : aValue.hashCode()); result = prime * result + ((bValue == null) ? 0 : bValue.hashCode()); result = prime * result + ((cValue == null) ? 0 : cValue.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Triple other = (Triple)obj; if (aValue == null) { if (other.aValue != null) return false; } else if (!aValue.equals(other.aValue)) return false; if (bValue == null) { if (other.bValue != null) return false; } else if (!bValue.equals(other.bValue)) return false; if (cValue == null) { if (other.cValue != null) return false; } else if (!cValue.equals(other.cValue)) return false; return true; } @Override public String toString() { return "Triple [aValue=" + aValue + ", bValue=" + bValue + ", cValue=" + cValue + "]"; } }
861
3,006
<gh_stars>1000+ package com.nightonke.wowoviewpagerexample; import android.annotation.SuppressLint; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; /** * Created by <NAME> at 15:37 on 2016/3/3 * For Personal Open Source * Contact me at <EMAIL> or <EMAIL> * For more projects: https://github.com/Nightonke * */ class SetEaseTypeAdapter extends BaseAdapter { private Context mContext; SetEaseTypeAdapter(Context mContext) { this.mContext = mContext; } @Override public int getCount() { return mContext.getResources().getStringArray(R.array.ease_types).length; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @SuppressLint("ViewHolder") @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = LayoutInflater.from(mContext).inflate(R.layout.item_ease_type, parent, false); ((TextView)convertView.findViewById(R.id.textview)).setText( mContext.getResources().getStringArray(R.array.ease_types)[position]); return convertView; } }
495
349
<reponame>AntonDyukarev/wiremock /* * Copyright (C) 2017-2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.tomakehurst.wiremock.verification.diff; import static java.lang.System.lineSeparator; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import static org.apache.commons.lang3.StringUtils.repeat; import static org.apache.commons.lang3.StringUtils.rightPad; import com.github.tomakehurst.wiremock.common.Strings; import com.github.tomakehurst.wiremock.matching.RequestMatcherExtension; import java.util.Map; public class PlainTextDiffRenderer { private final String SEPARATOR = lineSeparator(); private final int consoleWidth; private final Map<String, RequestMatcherExtension> customMatcherExtensions; public PlainTextDiffRenderer(Map<String, RequestMatcherExtension> customMatcherExtensions) { this(customMatcherExtensions, 119); } public PlainTextDiffRenderer( Map<String, RequestMatcherExtension> customMatcherExtensions, int consoleWidth) { this.customMatcherExtensions = customMatcherExtensions; this.consoleWidth = consoleWidth; } public String render(Diff diff) { StringBuilder sb = new StringBuilder(); header(sb); if (diff.getStubMappingName() != null) { writeLine(sb, diff.getStubMappingName(), "", null); writeBlankLine(sb); } for (DiffLine<?> line : diff.getLines(customMatcherExtensions)) { boolean isBodyLine = line.getRequestAttribute().equals("Body"); if (!isBodyLine || line.isForNonMatch()) { writeLine( sb, line.getPrintedPatternValue(), line.getActual().toString(), line.getMessage()); } } writeBlankLine(sb); footer(sb); return sb.toString(); } private void header(StringBuilder sb) { String titleLine = "Request was not matched"; int middle = getMiddle(); int titleLinePaddingLeft = middle - (titleLine.length() / 2); sb.append(SEPARATOR) .append(repeat(' ', titleLinePaddingLeft)) .append(titleLine) .append(SEPARATOR) .append(repeat(' ', titleLinePaddingLeft)) .append(repeat('=', titleLine.length())) .append(SEPARATOR) .append(SEPARATOR) .append(repeat('-', consoleWidth)) .append(SEPARATOR) .append('|') .append(rightPad(" Closest stub", middle)) .append('|') .append(rightPad(" Request", middle, ' ')) .append('|') .append(SEPARATOR) .append(repeat('-', consoleWidth)) .append(SEPARATOR); writeBlankLine(sb); } private void footer(StringBuilder sb) { sb.append(repeat('-', consoleWidth)).append(SEPARATOR); } private void writeLine(StringBuilder sb, String left, String right, String message) { String[] leftLines = wrap(left).split(SEPARATOR); String[] rightLines = wrap(right).split(SEPARATOR); int maxLines = Math.max(leftLines.length, rightLines.length); writeSingleLine(sb, leftLines[0], rightLines[0], message); if (maxLines > 1) { for (int i = 1; i < maxLines; i++) { String leftPart = leftLines.length > i ? leftLines[i] : ""; String rightPart = rightLines.length > i ? rightLines[i] : ""; writeSingleLine(sb, leftPart, rightPart, null); } } } private void writeBlankLine(StringBuilder sb) { writeSingleLine(sb, "", null, null); } private void writeSingleLine(StringBuilder sb, String left, String right, String message) { sb.append("").append(rightPad(left, getMiddle() + 1, " ")).append("|"); if (isNotEmpty(right)) { sb.append(" "); if (isNotEmpty(message)) { sb.append(rightPad(right, getMiddle() - 6, " ")).append("<<<<< ").append(message); } else { sb.append(right); } } else { if (isNotEmpty(message)) { sb.append(rightPad(right, getMiddle() - 5, " ")).append("<<<<< ").append(message); } } sb.append(SEPARATOR); } private String wrap(String s) { String safeString = s == null ? "" : s; return Strings.wrapIfLongestLineExceedsLimit(safeString, getColumnWidth()); } private int getColumnWidth() { return (consoleWidth / 2) - 2; } private int getMiddle() { return (consoleWidth / 2) - 1; } }
1,775
1,239
<reponame>1050368550/tiantiCMS package com.jeff.tianti.common.service; import java.io.Serializable; import java.util.Collection; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import com.jeff.tianti.common.dao.CommonDao; /** * 基础Service的定义 * @author <NAME> * @since 2015-12-09 * @param <E> * @param <ID> */ public abstract class CommonService<E,ID extends Serializable> { protected CommonDao<E,ID> commonDao; public void setCommonDao(CommonDao<E, ID> commonDao) { this.commonDao = commonDao; } public CommonDao<E, ID> getCommonDao() { return commonDao; } /** * 根据ID获取某个Entity * @param id * @return */ public E get(ID id) { return commonDao.getOne(id); } /** * 根据ID查找某个Entity(建议使用) * @param id * @return */ public E find(ID id) { return commonDao.findOne(id); } /** * 获取所有的Entity列表 * @return */ public List<E> getAll() { return commonDao.findAll(); } /** * 获取Entity的总数 * @return */ public Long getTotalCount() { return commonDao.count(); } /** * 保存Entity * @param entity * @return */ public E save(E entity) { return commonDao.save(entity); } /** * 修改Entity * @param entity * @return */ public E update(E entity) { return commonDao.save(entity); } /** * 删除Entity * @param entity */ public void delete(E entity) { commonDao.delete(entity); } /** * 根据Id删除某个Entity * @param id */ public void delete(ID id) { commonDao.delete(id); } /** * 删除Entity的集合类 * @param entities */ public void delete(Collection<E> entities) { commonDao.delete(entities); } /** * 清空缓存,提交持久化 */ public void flush() { commonDao.flush(); } /** * 根据查询信息获取某个Entity的列表 * @param spec * @return */ public List<E> findAll(Specification<E> spec) { return commonDao.findAll(spec); } /** * 获取Entity的分页信息 * @param pageable * @return */ public Page<E> findAll(Pageable pageable){ return commonDao.findAll(pageable); } /** * 根据查询条件和分页信息获取某个结果的分页信息 * @param spec * @param pageable * @return */ public Page<E> findAll(Specification<E> spec, Pageable pageable) { return commonDao.findAll(spec, pageable); } /** * 根据查询条件和排序条件获取某个结果集列表 * @param spec * @param sort * @return */ public List<E> findAll(Specification<E> spec, Sort sort) { return commonDao.findAll(spec); } /** * 查询某个条件的结果数集 * @param spec * @return */ public long count(Specification<E> spec) { return commonDao.count(spec); } }
1,502
1,916
<reponame>e-schumann/simbody<filename>Simbody/Visualizer/src/VisualizerProtocol.h #ifndef SimTK_SIMBODY_VISUALIZER_PROTOCOL_H_ #define SimTK_SIMBODY_VISUALIZER_PROTOCOL_H_ /* -------------------------------------------------------------------------- * * Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2011-14 Stanford University and the Authors. * * Authors: <NAME> * * Contributors: <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. * * -------------------------------------------------------------------------- */ #include "simbody/internal/common.h" #include "simbody/internal/Visualizer.h" #include <utility> #include <map> #include <atomic> /** @file * This file defines commands that are used for communication between the * simulation application and the visualization GUI. */ // Increment this every time you make *any* change to the protocol; // we insist on an exact match. static const unsigned ProtocolVersion = 34; // The visualizer has several predefined cached meshes for common // shapes so that we don't have to send them. These are the mesh // indices for them; they must start with zero. static const unsigned short MeshBox = 0; static const unsigned short MeshEllipsoid = 1; // works for sphere static const unsigned short MeshCylinder = 2; static const unsigned short MeshCircle = 3; // This serves as the first index number for unique meshes that are // defined during this run. static const unsigned short NumPredefinedMeshes = 4; // Commands sent to the GUI. // This should always be command #1 so we can reliably check whether // we're talking to a compatible protocol. static const unsigned char StartupHandshake = 1; static const unsigned char StartOfScene = 2; static const unsigned char EndOfScene = 3; static const unsigned char AddSolidMesh = 4; static const unsigned char AddPointMesh = 5; static const unsigned char AddWireframeMesh = 6; static const unsigned char AddLine = 7; static const unsigned char AddText = 8; static const unsigned char AddCoords = 9; static const unsigned char DefineMesh = 10; static const unsigned char DefineMenu = 11; static const unsigned char DefineSlider = 12; static const unsigned char SetSliderValue = 13; static const unsigned char SetSliderRange = 14; static const unsigned char SetCamera = 15; static const unsigned char ZoomCamera = 16; static const unsigned char LookAt = 17; static const unsigned char SetFieldOfView = 18; static const unsigned char SetClipPlanes = 19; static const unsigned char SetSystemUpDirection = 20; static const unsigned char SetGroundHeight = 21; static const unsigned char SetWindowTitle = 22; static const unsigned char SetMaxFrameRate = 23; static const unsigned char SetBackgroundColor = 24; static const unsigned char SetShowShadows = 25; static const unsigned char SetBackgroundType = 26; static const unsigned char SetShowFrameRate = 27; static const unsigned char SetShowSimTime = 28; static const unsigned char SetShowFrameNumber = 29; static const unsigned char Shutdown = 30; static const unsigned char StopCommunication = 31; // Events sent from the GUI back to the simulation application. // This should always be command #1 so we can reliably check whether // we're talking to a compatible protocol. static const unsigned char ReturnHandshake = 1; static const unsigned char KeyPressed = 2; static const unsigned char MenuSelected = 3; static const unsigned char SliderMoved = 4; namespace SimTK { class VisualizerProtocol { public: VisualizerProtocol(Visualizer& visualizer, const Array_<String>& searchPath); ~VisualizerProtocol(); void shakeHandsWithGUI(int toGUIPipe, int fromGUIPipe); void shutdownGUI(); void stopListeningIfNecessary(); void beginScene(Real simTime); void finishScene(); void drawBox(const Transform& transform, const Vec3& scale, const Vec4& color, int representation); void drawEllipsoid(const Transform& transform, const Vec3& scale, const Vec4& color, int representation, unsigned short resolution); void drawCylinder(const Transform& transform, const Vec3& scale, const Vec4& color, int representation, unsigned short resolution); void drawCircle(const Transform& transform, const Vec3& scale, const Vec4& color, int representation, unsigned short resolution); void drawPolygonalMesh(const PolygonalMesh& mesh, const Transform& transform, const Vec3& scale, const Vec4& color, int representation); void drawLine(const Vec3& end1, const Vec3& end2, const Vec4& color, Real thickness); void drawText(const Transform& transform, const Vec3& scale, const Vec4& color, const std::string& string, bool faceCamera, bool isScreenText); void drawCoords(const Transform& transform, const Vec3& axisLengths, const Vec4& color); void addMenu(const String& title, int id, const Array_<std::pair<String, int> >& items); void addSlider(const String& title, int id, Real min, Real max, Real value); void setSliderValue(int id, Real newValue) const; void setSliderRange(int id, Real newMin, Real newMax) const; void setSystemUpDirection(const CoordinateDirection& upDir); void setGroundHeight(Real height); void setWindowTitle(const String& title) const; void setMaxFrameRate(Real rateInFPS) const; void setBackgroundColor(const Vec3& color) const; void setShowShadows(bool showShadows) const; void setShowFrameRate(bool showFrameRate) const; void setShowSimTime(bool showSimTime) const; void setShowFrameNumber(bool showFrameNumber) const; void setBackgroundType(Visualizer::BackgroundType type) const; void setCameraTransform(const Transform& transform) const; void zoomCamera() const; void lookAt(const Vec3& point, const Vec3& upDirection) const; void setFieldOfView(Real fov) const; void setClippingPlanes(Real near, Real far) const; private: void drawMesh(const Transform& transform, const Vec3& scale, const Vec4& color, short representation, unsigned short meshIndex, unsigned short resolution); int outPipe; // For user-defined meshes, map their unique memory addresses to the // assigned visualizer cache index. mutable std::map<const void*, unsigned short> meshes; mutable std::mutex sceneMutex; // This lock should only be used in beginScene() and finishScene(). std::unique_lock<std::mutex> sceneLockBeginFinishScene {sceneMutex, std::defer_lock}; mutable std::thread eventListenerThread; }; } #endif // SimTK_SIMBODY_VISUALIZER_PROTOCOL_H_
3,244
330
package com.alphawallet.app.entity; /** * Created by James on 18/07/2019. * Stormbird in Sydney */ public interface BackupTokenCallback { void BackupClick(Wallet wallet); void remindMeLater(Wallet wallet); }
69
807
#include <glog/logging.h> #include <gtest/gtest.h> #include <string> #include "merkletree/verifiable_map.h" #include "util/status_test_util.h" #include "util/testing.h" #include "util/util.h" namespace cert_trans { namespace { using std::array; using std::string; using std::unique_ptr; using util::StatusOr; using util::testing::StatusIs; using util::ToBase64; class VerifiableMapTest : public testing::Test { public: VerifiableMapTest() : map_(new Sha256Hasher()) { } protected: VerifiableMap map_; }; TEST_F(VerifiableMapTest, TestGetNotFound) { const string kKey("unknown_key"); const StatusOr<string> retrieved(map_.Get(kKey)); EXPECT_THAT(retrieved.status(), StatusIs(util::error::NOT_FOUND)); } TEST_F(VerifiableMapTest, TestSetGet) { const string kKey("key"); const string kValue("value"); map_.Set(kKey, kValue); const StatusOr<string> retrieved(map_.Get(kKey)); EXPECT_OK(retrieved); EXPECT_EQ(kValue, retrieved.ValueOrDie()); } // TODO(alcutter): Lots and lots more tests. } // namespace } // namespace cert_trans int main(int argc, char** argv) { cert_trans::test::InitTesting(argv[0], &argc, &argv, true); return RUN_ALL_TESTS(); }
437
1,439
<filename>galen-core/src/main/java/com/galenframework/generator/SpecGenerator.java /******************************************************************************* * Copyright 2018 <NAME> http://galenframework.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.galenframework.generator; import com.galenframework.generator.builders.SpecGeneratorOptions; import com.galenframework.generator.model.GmPageSpec; import com.galenframework.page.Point; import com.galenframework.page.Rect; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.List; import java.util.stream.Collectors; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; public class SpecGenerator { private PageItemJsonMapper piJsonMapper = new PageItemJsonMapper(); public PageSpecGenerationResult generate(InputStream stream, SpecGeneratorOptions specGeneratorOptions) throws IOException { List<PageItem> pageItems = piJsonMapper.loadItems(stream); return generate(pageItems, specGeneratorOptions); } private PageSpecGenerationResult generate(List<PageItem> pageItems, SpecGeneratorOptions specGeneratorOptions) { Set<String> allObjectNames = extractItemNamesOnAllPages(pageItems); return generate(pageItems, allObjectNames, specGeneratorOptions); } private Set<String> extractItemNamesOnAllPages(List<PageItem> pageItems) { return pageItems.stream().map(PageItem::getName).distinct().collect(Collectors.toSet()); } private PageSpecGenerationResult generate(List<PageItem> pageItems, Set<String> allObjectNames, SpecGeneratorOptions specGeneratorOptions) { List<PageItem> convertedItems = new LinkedList<>(); PageItem screenItem = null; Size largestSize = new Size(); for (PageItem pageItem : pageItems) { if (!"viewport".equals(pageItem.getName())) { convertedItems.add(pageItem); if (screenItem == null && "screen".equals(pageItem.getName())) { screenItem = pageItem; } if (largestSize.width < pageItem.getArea().getWidth()) { largestSize.width = pageItem.getArea().getWidth(); largestSize.height = pageItem.getArea().getHeight(); } } } // Sorting items by size first and then by location convertedItems.sort(bySizeAndLocation()); removeDuplicatedElements(convertedItems); List<PageItemNode> rootPins = restructurePageItems(convertedItems); List<String> objectNamesPerPage = new LinkedList<>(); rootPins.forEach(p -> p.visitTree(pin -> { objectNamesPerPage.add(pin.getPageItem().getName()); if (pin.getChildren() != null) { sortPinsHorizontally(pin.getChildren()); } })); SuggestionTestResult results = new SuggestionTestResult(); rootPins.forEach(p -> p.visitTree(pin -> results.merge(proposeSpecsFor(pin, objectNamesPerPage, specGeneratorOptions)))); List<String> missingObjects = proposeAbsenseSpecs(results, pageItems, allObjectNames); // adding missing objects to pins. For now we will put missing objects inside a first root pin missingObjects.forEach(missingObjectName -> { new PageItemNode(new PageItem(missingObjectName)).moveToParent(rootPins.get(0)); objectNamesPerPage.add(missingObjectName); }); return new PageSpecGenerationResult(largestSize, objectNamesPerPage, rootPins, results); } private List<String> proposeAbsenseSpecs(SuggestionTestResult results, List<PageItem> pageItems, Set<String> allObjectNames) { Set<String> allItemsOnCurrentPage = pageItems.stream().map(PageItem::getName).collect(Collectors.toSet()); List<String> missingObjectNames = new LinkedList<>(); allObjectNames.stream().filter(itemName -> !allItemsOnCurrentPage.contains(itemName)).forEach(itemName -> { results.getGeneratedObjectSpecs().put(itemName, singletonList(new SpecStatement("absent"))); missingObjectNames.add(itemName); }); return missingObjectNames; } private void removeDuplicatedElements(List<PageItem> convertedItems) { ListIterator<PageItem> it = convertedItems.listIterator(); if (it.hasNext()) { PageItem item = it.next(); while (it.hasNext()) { PageItem nextItem = it.next(); if (nextItem.getArea().equals(item.getArea())) { it.remove(); } else { item = nextItem; } } } } private Comparator<PageItem> bySizeAndLocation() { return (a, b) -> { int size = a.getArea().getWidth() * a.getArea().getHeight() - b.getArea().getWidth() * b.getArea().getHeight(); if (size != 0) { return size; } else { int diff = a.getArea().getLeft() - b.getArea().getLeft(); if (diff != 0) { return diff; } else { return a.getArea().getTop() - b.getArea().getTop(); } } }; } /** * Orders page items into a tree by their area. Tries to fit one item inside another * @param items * @return A list of pins which are root elements (don't have a parent) */ private List<PageItemNode> restructurePageItems(List<PageItem> items) { List<PageItemNode> pins = items.stream().map(PageItemNode::new).collect(toList()); for (PageItemNode pinA : pins) { for (PageItemNode pinB: pins) { if (pinA != pinB) { if (isInside(pinA.getPageItem().getArea(), pinB.getPageItem().getArea())) { if (pinB.getParent() == pinA) { throw new RuntimeException(format("The following objects have identical areas: %s, %s. Please remove one of the objects", pinA.getPageItem().getName(), pinB.getPageItem().getName())); } pinA.moveToParent(pinB); break; } } } } return pins.stream().filter(pin -> pin.getParent() == null && pin.getChildren().size() > 0).collect(toList()); } private SuggestionTestResult proposeSpecsFor(PageItemNode pin, List<String> objectNamesPerPage, SpecGeneratorOptions specGeneratorOptions) { SuggestionTestResult allResults = new SuggestionTestResult(); SpecSuggester specSuggester = new SpecSuggester(new SuggestionOptions(objectNamesPerPage)); if (pin.getParent() != null) { allResults.merge(specSuggester.suggestSpecsForTwoObjects(asList(pin.getParent(), pin), SpecSuggester.parentSuggestions, specGeneratorOptions)); } if (pin.getChildren() != null && !pin.getChildren().isEmpty()) { List<PageItemNode> horizontallySortedPins = pin.getChildren(); List<PageItemNode> verticallySortedPins = copySortedVertically(pin.getChildren()); if (specGeneratorOptions.isUseGalenExtras()) { allResults.merge(specSuggester.suggestSpecsForMultipleObjects(horizontallySortedPins, SpecSuggester.horizontallyOrderComplexRulesSuggestions, specGeneratorOptions)); allResults.merge(specSuggester.suggestSpecsForMultipleObjects(verticallySortedPins, SpecSuggester.verticallyOrderComplexRulesSuggestions, specGeneratorOptions)); } allResults.merge(specSuggester.suggestSpecsRayCasting(pin, horizontallySortedPins, specGeneratorOptions)); allResults.merge(specSuggester.suggestSpecsForSingleObject(horizontallySortedPins, SpecSuggester.singleItemSuggestions, specGeneratorOptions)); } return allResults; } private void sortPinsHorizontally(List<PageItemNode> pins) { Collections.sort(pins, (a,b) -> { int ax = a.getPageItem().getArea().getLeft(); int ay = a.getPageItem().getArea().getTop(); int bx = b.getPageItem().getArea().getLeft(); int by = b.getPageItem().getArea().getTop(); if (ax != bx) { return ax - bx; } else { return ay - by; } }); } private List<PageItemNode> copySortedVertically(List<PageItemNode> pins) { ArrayList<PageItemNode> sortedPins = new ArrayList<>(pins); Collections.sort(sortedPins, (a,b) -> { int ax = a.getPageItem().getArea().getLeft(); int ay = a.getPageItem().getArea().getTop(); int bx = b.getPageItem().getArea().getLeft(); int by = b.getPageItem().getArea().getTop(); if (ay != by) { return ay - by; } else { return ax - bx; } }); return sortedPins; } private boolean isInside(Rect area, Rect areaParent) { for (Point p : area.getPoints()) { if (!areaParent.contains(p)) { return false; } } return true; } public static String generateSpecSections(PageSpecGenerationResult result) { StringBuilder finalSpec = new StringBuilder(); GmPageSpec pageSpecGM = GmPageSpec.create(result); finalSpec.append(pageSpecGM.render()); return finalSpec.toString(); } public static String generatePageSpec(PageSpecGenerationResult result, SpecGeneratorOptions specGeneratorOptions) { StringBuilder builder = new StringBuilder(); if (specGeneratorOptions.isUseGalenExtras()) { builder.append("@lib galen-extras\n\n"); } return builder.append(SpecGenerator.generateSpecSections(result)) .toString(); } }
4,349
364
package rsc.publisher; import java.util.ArrayDeque; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.function.BooleanSupplier; import org.reactivestreams.*; import rsc.documentation.BackpressureMode; import rsc.documentation.BackpressureSupport; import rsc.documentation.FusionMode; import rsc.documentation.FusionSupport; import rsc.flow.*; import rsc.publisher.PublisherTakeLastOne.PublisherTakeLastOneSubscriber; import rsc.flow.Trackable; import rsc.subscriber.SubscriptionHelper; import rsc.util.*; /** * Emits the last N values the source emitted before its completion. * * @param <T> the value type */ @BackpressureSupport(input = BackpressureMode.UNBOUNDED, output = BackpressureMode.BOUNDED) @FusionSupport(input = { FusionMode.NONE }, output = { FusionMode.ASYNC }) public final class PublisherTakeLast<T> extends PublisherSource<T, T> implements Fuseable { final int n; public PublisherTakeLast(Publisher<? extends T> source, int n) { super(source); if (n < 0) { throw new IllegalArgumentException("n >= required but it was " + n); } this.n = n; } @Override public void subscribe(Subscriber<? super T> s) { if (n == 0) { source.subscribe(new PublisherTakeLastZeroSubscriber<>(s)); } else if (n == 1) { source.subscribe(new PublisherTakeLastOneSubscriber<>(s)); } else { source.subscribe(new PublisherTakeLastManySubscriber<>(s, n)); } } @Override public long getPrefetch() { return Long.MAX_VALUE; } static final class PublisherTakeLastZeroSubscriber<T> implements Subscriber<T>, Producer, Subscription, Receiver { final Subscriber<? super T> actual; Subscription s; public PublisherTakeLastZeroSubscriber(Subscriber<? super T> actual) { this.actual = actual; } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.s, s)) { this.s = s; actual.onSubscribe(this); s.request(Long.MAX_VALUE); } } @Override public void onNext(T t) { // ignoring all values } @Override public void onError(Throwable t) { actual.onError(t); } @Override public void onComplete() { actual.onComplete(); } @Override public Object downstream() { return actual; } @Override public void request(long n) { s.request(n); } @Override public void cancel() { s.cancel(); } @Override public Object upstream() { return s; } } static final class PublisherTakeLastManySubscriber<T> implements Subscriber<T>, Subscription, BooleanSupplier, Producer, Trackable, Receiver { final Subscriber<? super T> actual; final int n; volatile boolean cancelled; Subscription s; final ArrayDeque<T> buffer; volatile long requested; @SuppressWarnings("rawtypes") static final AtomicLongFieldUpdater<PublisherTakeLastManySubscriber> REQUESTED = AtomicLongFieldUpdater.newUpdater(PublisherTakeLastManySubscriber.class, "requested"); public PublisherTakeLastManySubscriber(Subscriber<? super T> actual, int n) { this.actual = actual; this.n = n; this.buffer = new ArrayDeque<>(); } @Override public boolean getAsBoolean() { return cancelled; } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { DrainHelper.postCompleteRequest(n, actual, buffer, REQUESTED, this, this); } } @Override public void cancel() { cancelled = true; s.cancel(); } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.s, s)) { this.s = s; actual.onSubscribe(this); s.request(Long.MAX_VALUE); } } @Override public void onNext(T t) { ArrayDeque<T> bs = buffer; if (bs.size() == n) { bs.poll(); } bs.offer(t); } @Override public void onError(Throwable t) { actual.onError(t); } @Override public void onComplete() { DrainHelper.postComplete(actual, buffer, REQUESTED, this, this); } @Override public Object upstream() { return s; } @Override public boolean isCancelled() { return cancelled; } @Override public long getPending() { return buffer.size(); } @Override public long getCapacity() { return n; } @Override public Object downstream() { return actual; } } }
2,528
14,668
// Copyright (c) 2012 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 CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_AURA_H_ #define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_AURA_H_ #include <stddef.h> #include <stdint.h> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/callback.h" #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_piece.h" #include "base/time/time.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "cc/layers/deadline_policy.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/frame_sinks/begin_frame_source.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/compositor/image_transport_factory.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/renderer_host/render_widget_host_view_event_handler.h" #include "content/browser/renderer_host/text_input_manager.h" #include "content/browser/renderer_host/virtual_keyboard_controller_win.h" #include "content/common/content_export.h" #include "content/common/cursors/webcursor.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/visibility.h" #include "third_party/blink/public/mojom/widget/record_content_to_visible_time_request.mojom-forward.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/aura/client/cursor_client_observer.h" #include "ui/aura/client/focus_change_observer.h" #include "ui/aura/client/window_types.h" #include "ui/aura/window_delegate.h" #include "ui/aura/window_tree_host_observer.h" #include "ui/base/ime/text_input_client.h" #include "ui/display/display_observer.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/selection_bound.h" #include "ui/wm/public/activation_delegate.h" namespace wm { class ScopedTooltipDisabler; } namespace gfx { class Display; class Point; class Rect; } namespace ui { enum class DomCode; class InputMethod; class LocatedEvent; } namespace content { #if defined(OS_WIN) class LegacyRenderWidgetHostHWND; class DirectManipulationBrowserTestBase; #endif class CursorManager; class DelegatedFrameHost; class DelegatedFrameHostClient; class MouseWheelPhaseHandler; class RenderFrameHostImpl; class RenderWidgetHostView; class TouchSelectionControllerClientAura; // RenderWidgetHostView class hierarchy described in render_widget_host_view.h. class CONTENT_EXPORT RenderWidgetHostViewAura : public RenderWidgetHostViewBase, public RenderWidgetHostViewEventHandler::Delegate, public RenderFrameMetadataProvider::Observer, public TextInputManager::Observer, public ui::TextInputClient, public display::DisplayObserver, public aura::WindowTreeHostObserver, public aura::WindowDelegate, public wm::ActivationDelegate, public aura::client::FocusChangeObserver, public aura::client::CursorClientObserver { public: explicit RenderWidgetHostViewAura(RenderWidgetHost* host); RenderWidgetHostViewAura(const RenderWidgetHostViewAura&) = delete; RenderWidgetHostViewAura& operator=(const RenderWidgetHostViewAura&) = delete; // RenderWidgetHostView implementation. void InitAsChild(gfx::NativeView parent_view) override; void SetSize(const gfx::Size& size) override; void SetBounds(const gfx::Rect& rect) override; gfx::NativeView GetNativeView() override; gfx::NativeViewAccessible GetNativeViewAccessible() override; ui::TextInputClient* GetTextInputClient() override; bool HasFocus() override; void Hide() override; bool IsShowing() override; void WasUnOccluded() override; void WasOccluded() override; gfx::Rect GetViewBounds() override; bool IsMouseLocked() override; gfx::Size GetVisibleViewportSize() override; void SetInsets(const gfx::Insets& insets) override; TouchSelectionControllerClientManager* GetTouchSelectionControllerClientManager() override; bool ShouldVirtualKeyboardOverlayContent() override; void NotifyVirtualKeyboardOverlayRect( const gfx::Rect& keyboard_rect) override; bool IsHTMLFormPopup() const override; // Overridden from RenderWidgetHostViewBase: void InitAsPopup(RenderWidgetHostView* parent_host_view, const gfx::Rect& pos, const gfx::Rect& anchor_rect) override; void Focus() override; void UpdateCursor(const WebCursor& cursor) override; void DisplayCursor(const WebCursor& cursor) override; CursorManager* GetCursorManager() override; void SetIsLoading(bool is_loading) override; void RenderProcessGone() override; void ShowWithVisibility(PageVisibilityState page_visibility) final; void Destroy() override; void UpdateTooltipUnderCursor(const std::u16string& tooltip_text) override; void UpdateTooltip(const std::u16string& tooltip_text) override; void UpdateTooltipFromKeyboard(const std::u16string& tooltip_text, const gfx::Rect& bounds) override; void ClearKeyboardTriggeredTooltip() override; uint32_t GetCaptureSequenceNumber() const override; bool IsSurfaceAvailableForCopy() override; void CopyFromSurface( const gfx::Rect& src_rect, const gfx::Size& output_size, base::OnceCallback<void(const SkBitmap&)> callback) override; void EnsureSurfaceSynchronizedForWebTest() override; void TransformPointToRootSurface(gfx::PointF* point) override; gfx::Rect GetBoundsInRootWindow() override; void WheelEventAck(const blink::WebMouseWheelEvent& event, blink::mojom::InputEventResultState ack_result) override; void GestureEventAck(const blink::WebGestureEvent& event, blink::mojom::InputEventResultState ack_result) override; void DidOverscroll(const ui::DidOverscrollParams& params) override; void ProcessAckedTouchEvent( const TouchEventWithLatencyInfo& touch, blink::mojom::InputEventResultState ack_result) override; std::unique_ptr<SyntheticGestureTarget> CreateSyntheticGestureTarget() override; blink::mojom::InputEventResultState FilterInputEvent( const blink::WebInputEvent& input_event) override; gfx::AcceleratedWidget AccessibilityGetAcceleratedWidget() override; gfx::NativeViewAccessible AccessibilityGetNativeViewAccessible() override; void SetMainFrameAXTreeID(ui::AXTreeID id) override; blink::mojom::PointerLockResult LockMouse( bool request_unadjusted_movement) override; blink::mojom::PointerLockResult ChangeMouseLock( bool request_unadjusted_movement) override; void UnlockMouse() override; bool GetIsMouseLockedUnadjustedMovementForTesting() override; bool LockKeyboard(absl::optional<base::flat_set<ui::DomCode>> codes) override; void UnlockKeyboard() override; bool IsKeyboardLocked() override; base::flat_map<std::string, std::string> GetKeyboardLayoutMap() override; void ClearFallbackSurfaceForCommitPending() override; void ResetFallbackToFirstNavigationSurface() override; bool RequestRepaintForTesting() override; void DidStopFlinging() override; void OnDidNavigateMainFrameToNewPage() override; const viz::FrameSinkId& GetFrameSinkId() const override; const viz::LocalSurfaceId& GetLocalSurfaceId() const override; bool TransformPointToCoordSpaceForView( const gfx::PointF& point, RenderWidgetHostViewBase* target_view, gfx::PointF* transformed_point) override; viz::FrameSinkId GetRootFrameSinkId() override; viz::SurfaceId GetCurrentSurfaceId() const override; void FocusedNodeChanged(bool is_editable_node, const gfx::Rect& node_bounds_in_screen) override; void OnSynchronizedDisplayPropertiesChanged(bool rotation = false) override; viz::ScopedSurfaceIdAllocator DidUpdateVisualProperties( const cc::RenderFrameMetadata& metadata) override; void DidNavigate() override; void TakeFallbackContentFrom(RenderWidgetHostView* view) override; bool CanSynchronizeVisualProperties() override; std::vector<std::unique_ptr<ui::TouchEvent>> ExtractAndCancelActiveTouches() override; void TransferTouches( const std::vector<std::unique_ptr<ui::TouchEvent>>& touches) override; // TODO(lanwei): Use TestApi interface to write functions that are used in // tests and remove FRIEND_TEST_ALL_PREFIXES. void SetLastPointerType(ui::EventPointerType last_pointer_type) override; // Overridden from ui::TextInputClient: void SetCompositionText(const ui::CompositionText& composition) override; uint32_t ConfirmCompositionText(bool keep_selection) override; void ClearCompositionText() override; void InsertText(const std::u16string& text, InsertTextCursorBehavior cursor_behavior) override; void InsertChar(const ui::KeyEvent& event) override; ui::TextInputType GetTextInputType() const override; ui::TextInputMode GetTextInputMode() const override; base::i18n::TextDirection GetTextDirection() const override; int GetTextInputFlags() const override; bool CanComposeInline() const override; gfx::Rect GetCaretBounds() const override; gfx::Rect GetSelectionBoundingBox() const override; bool GetCompositionCharacterBounds(uint32_t index, gfx::Rect* rect) const override; bool HasCompositionText() const override; ui::TextInputClient::FocusReason GetFocusReason() const override; bool GetTextRange(gfx::Range* range) const override; bool GetCompositionTextRange(gfx::Range* range) const override; bool GetEditableSelectionRange(gfx::Range* range) const override; bool SetEditableSelectionRange(const gfx::Range& range) override; bool DeleteRange(const gfx::Range& range) override; bool GetTextFromRange(const gfx::Range& range, std::u16string* text) const override; void OnInputMethodChanged() override; bool ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection direction) override; void ExtendSelectionAndDelete(size_t before, size_t after) override; void EnsureCaretNotInRect(const gfx::Rect& rect) override; bool IsTextEditCommandEnabled(ui::TextEditCommand command) const override; void SetTextEditCommandForNextKeyEvent(ui::TextEditCommand command) override; ukm::SourceId GetClientSourceForMetrics() const override; bool ShouldDoLearning() override; #if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) bool SetCompositionFromExistingText( const gfx::Range& range, const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) override; #endif #if BUILDFLAG(IS_CHROMEOS_ASH) gfx::Range GetAutocorrectRange() const override; gfx::Rect GetAutocorrectCharacterBounds() const override; bool SetAutocorrectRange(const gfx::Range& range) override; absl::optional<ui::GrammarFragment> GetGrammarFragment( const gfx::Range& range) override; bool ClearGrammarFragments(const gfx::Range& range) override; bool AddGrammarFragments( const std::vector<ui::GrammarFragment>& fragments) override; #endif #if defined(OS_WIN) || defined(OS_CHROMEOS) // Returns the control and selection bounds of the EditContext or control // bounds of the active editable element. This is used to report the layout // bounds of the text input control to TSF on Windows. void GetActiveTextInputControlLayoutBounds( absl::optional<gfx::Rect>* control_bounds, absl::optional<gfx::Rect>* selection_bounds) override; #endif #if defined(OS_WIN) // API to notify accessibility whether there is an active composition // from TSF or not. // It notifies the composition range, composition text and whether the // composition has been committed or not. void SetActiveCompositionForAccessibility( const gfx::Range& range, const std::u16string& active_composition_text, bool is_composition_committed) override; #endif // Overridden from display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t metrics) override; // Overridden from aura::WindowDelegate: gfx::Size GetMinimumSize() const override; gfx::Size GetMaximumSize() const override; void OnBoundsChanged(const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) override; gfx::NativeCursor GetCursor(const gfx::Point& point) override; int GetNonClientComponent(const gfx::Point& point) const override; bool ShouldDescendIntoChildForEventHandling( aura::Window* child, const gfx::Point& location) override; bool CanFocus() override; void OnCaptureLost() override; void OnPaint(const ui::PaintContext& context) override; void OnDeviceScaleFactorChanged(float old_device_scale_factor, float new_device_scale_factor) override; void OnWindowDestroying(aura::Window* window) override; void OnWindowDestroyed(aura::Window* window) override; void OnWindowTargetVisibilityChanged(bool visible) override; bool HasHitTestMask() const override; void GetHitTestMask(SkPath* mask) const override; bool RequiresDoubleTapGestureEvents() const override; // Overridden from ui::EventHandler: void OnKeyEvent(ui::KeyEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; void OnScrollEvent(ui::ScrollEvent* event) override; void OnTouchEvent(ui::TouchEvent* event) override; void OnGestureEvent(ui::GestureEvent* event) override; base::StringPiece GetLogContext() const override; // Overridden from wm::ActivationDelegate: bool ShouldActivate() const override; // Overridden from aura::client::CursorClientObserver: void OnCursorVisibilityChanged(bool is_visible) override; // Overridden from aura::client::FocusChangeObserver: void OnWindowFocused(aura::Window* gained_focus, aura::Window* lost_focus) override; // Overridden from aura::WindowTreeHostObserver: void OnHostMovedInPixels(aura::WindowTreeHost* host, const gfx::Point& new_origin_in_pixels) override; // RenderFrameMetadataProvider::Observer implementation. void OnRenderFrameMetadataChangedBeforeActivation( const cc::RenderFrameMetadata& metadata) override {} void OnRenderFrameMetadataChangedAfterActivation( base::TimeTicks activation_time) override; void OnRenderFrameSubmission() override {} void OnLocalSurfaceIdChanged( const cc::RenderFrameMetadata& metadata) override {} #if defined(OS_WIN) // Gets the HWND of the host window. HWND GetHostWindowHWND() const; // Updates the cursor clip region. Used for mouse locking. void UpdateMouseLockRegion(); // Notification that the LegacyRenderWidgetHostHWND was destroyed. void OnLegacyWindowDestroyed(); #endif gfx::NativeViewAccessible GetParentNativeViewAccessible(); // Method to indicate if this instance is shutting down or closing. // TODO(shrikant): Discuss around to see if it makes sense to add this method // as part of RenderWidgetHostView. bool IsClosing() const { return in_shutdown_; } // Sets whether the overscroll controller should be enabled for this page. void SetOverscrollControllerEnabled(bool enabled); void SnapToPhysicalPixelBoundary(); // Used in tests to set a mock client for touch selection controller. It will // create a new touch selection controller for the new client. void SetSelectionControllerClientForTest( std::unique_ptr<TouchSelectionControllerClientAura> client); // RenderWidgetHostViewEventHandler::Delegate: gfx::Rect ConvertRectToScreen(const gfx::Rect& rect) const override; void ForwardKeyboardEventWithLatencyInfo(const NativeWebKeyboardEvent& event, const ui::LatencyInfo& latency, bool* update_event) override; RenderFrameHostImpl* GetFocusedFrame() const; bool NeedsMouseCapture() override; void SetTooltipsEnabled(bool enable) override; void Shutdown() override; bool FocusedFrameHasStickyActivation() const; RenderWidgetHostViewEventHandler* event_handler() { return event_handler_.get(); } void ScrollFocusedEditableNodeIntoRect(const gfx::Rect& rect); ui::EventPointerType GetLastPointerType() const { return last_pointer_type_; } MouseWheelPhaseHandler* GetMouseWheelPhaseHandler() override; ui::Compositor* GetCompositor() override; protected: ~RenderWidgetHostViewAura() override; // Exposed for tests. aura::Window* window() { return window_; } DelegatedFrameHost* GetDelegatedFrameHost() const { return delegated_frame_host_.get(); } // RenderWidgetHostViewBase: void UpdateBackgroundColor() override; bool HasFallbackSurface() const override; absl::optional<DisplayFeature> GetDisplayFeature() override; void SetDisplayFeatureForTesting( const DisplayFeature* display_feature) override; void NotifyHostAndDelegateOnWasShown( blink::mojom::RecordContentToVisibleTimeRequestPtr visible_time_request) final; void RequestPresentationTimeFromHostOrDelegate( blink::mojom::RecordContentToVisibleTimeRequestPtr visible_time_request) final; void CancelPresentationTimeRequestForHostAndDelegate() final; private: friend class DelegatedFrameHostClientAura; friend class FakeRenderWidgetHostViewAura; friend class InputMethodAuraTestBase; friend class RenderWidgetHostViewAuraTest; friend class RenderWidgetHostViewAuraBrowserTest; friend class RenderWidgetHostViewAuraDevtoolsBrowserTest; friend class RenderWidgetHostViewAuraCopyRequestTest; friend class TestInputMethodObserver; #if defined(OS_WIN) friend class AccessibilityObjectLifetimeWinBrowserTest; friend class AccessibilityTreeLinkageWinBrowserTest; friend class DirectManipulationBrowserTestBase; #endif FRIEND_TEST_ALL_PREFIXES(InputMethodResultAuraTest, FinishImeCompositionSession); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, PopupRetainsCaptureAfterMouseRelease); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, SetCompositionText); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, FocusedNodeChanged); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, TouchEventState); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, TouchEventPositionsArentRounded); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, TouchEventSyncAsync); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, Resize); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, SwapNotifiesWindow); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, MirrorLayers); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, SkippedDelegatedFrames); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, ResizeAfterReceivingFrame); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, ChildGeneratedResizeRoutesLocalSurfaceId); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, MissingFramesDontLock); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, OutputSurfaceIdChange); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, DiscardDelegatedFrames); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, DiscardDelegatedFramesWithLocking); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, SoftwareDPIChange); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, UpdateCursorIfOverSelf); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, VisibleViewportTest); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, OverscrollResetsOnBlur); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, FinishCompositionByMouse); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, ForwardsBeginFrameAcks); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, VirtualKeyboardFocusEnsureCaretInRect); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, DiscardDelegatedFramesWithMemoryPressure); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraInputMethodTest, OnCaretBoundsChanged); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraInputMethodTest, OnCaretBoundsChangedInputModeNone); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraInputMethodFocusTest, OnFocusLost); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraKeyboardTest, KeyboardObserverDestroyed); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraKeyboardTest, NoKeyboardObserverForMouseInput); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraKeyboardTest, KeyboardObserverForOnlyTouchInput); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraKeyboardTest, KeyboardObserverForFocusedNodeChanged); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraKeyboardTest, KeyboardObserverForPenInput); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraKeyboardTest, KeyboardObserverDetachDuringWindowDestroy); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, DropFallbackWhenHidden); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, CompositorFrameSinkChange); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, SurfaceChanges); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, DeviceScaleFactorChanges); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, HideThenShow); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, DropFallbackIfResizedWhileHidden); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, DontDropFallbackIfNotResizedWhileHidden); FRIEND_TEST_ALL_PREFIXES(SitePerProcessHitTestBrowserTest, PopupMenuTest); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, NewContentRenderingTimeout); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, AllocateLocalSurfaceIdOnEviction); FRIEND_TEST_ALL_PREFIXES(WebContentsViewAuraTest, WebContentsViewReparent); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, TakeFallbackContent); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, TakeFallbackContentForPrerender); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, DiscardDelegatedFrames); FRIEND_TEST_ALL_PREFIXES(SitePerProcessHitTestBrowserTest, ScrollOOPIFEditableElement); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, OcclusionHidesTooltip); FRIEND_TEST_ALL_PREFIXES(RenderWidgetHostViewAuraTest, UpdateInsetsWithVirtualKeyboardEnabled); class WindowObserver; friend class WindowObserver; class WindowAncestorObserver; friend class WindowAncestorObserver; friend void VerifyStaleContentOnFrameEviction( RenderWidgetHostView* render_widget_host_view); void CreateAuraWindow(aura::client::WindowType type); // Returns true if a stale frame content needs to be set for the current RWHV. // This is primarily useful during various CrOS animations to prevent showing // a white screen and instead showing a snapshot of the frame content that // was most recently evicted. bool ShouldShowStaleContentOnEviction(); void CreateDelegatedFrameHostClient(); void UpdateCursorIfOverSelf(); bool SynchronizeVisualProperties( const cc::DeadlinePolicy& deadline_policy, const absl::optional<viz::LocalSurfaceId>& child_local_surface_id); void OnDidUpdateVisualPropertiesComplete( const cc::RenderFrameMetadata& metadata); // Set the bounds of the window and handle size changes. Assumes the caller // has already adjusted the origin of |rect| to conform to whatever coordinate // space is required by the aura::Window. void InternalSetBounds(const gfx::Rect& rect); // Update the insets for bounds change when the virtual keyboard is shown. void UpdateInsetsWithVirtualKeyboardEnabled(); #if defined(OS_WIN) // Creates and/or updates the legacy dummy window which corresponds to // the bounds of the webcontents. It is needed for accessibility and // for scrolling to work in legacy drivers for trackpoints/trackpads, etc. void UpdateLegacyWin(); bool UsesNativeWindowFrame() const; #endif ui::InputMethod* GetInputMethod() const; // Get the focused view that should be used for retrieving the text selection. RenderWidgetHostViewBase* GetFocusedViewForTextSelection() const; // Returns whether the widget needs an input grab to work properly. bool NeedsInputGrab(); // Sends an IPC to the renderer process to communicate whether or not // the mouse cursor is visible anywhere on the screen. void NotifyRendererOfCursorVisibilityState(bool is_visible); // Called after |window_| is parented to a WindowEventDispatcher. void AddedToRootWindow(); // Called prior to removing |window_| from a WindowEventDispatcher. void RemovingFromRootWindow(); // TextInputManager::Observer implementation. void OnUpdateTextInputStateCalled(TextInputManager* text_input_manager, RenderWidgetHostViewBase* updated_view, bool did_update_state) override; void OnImeCancelComposition(TextInputManager* text_input_manager, RenderWidgetHostViewBase* updated_view) override; void OnSelectionBoundsChanged( TextInputManager* text_input_manager, RenderWidgetHostViewBase* updated_view) override; void OnTextSelectionChanged(TextInputManager* text_input_mangager, RenderWidgetHostViewBase* updated_view) override; // Detaches |this| from the input method object. // is_removed flag is true if this is called while the window is // getting removed/destroyed, false, otherwise. void DetachFromInputMethod(bool is_removed); // Dismisses a Web Popup on a mouse or touch press outside the popup and its // parent. void ApplyEventObserverForPopupExit(const ui::LocatedEvent& event); // Converts |rect| from screen coordinate to window coordinate. gfx::Rect ConvertRectFromScreen(const gfx::Rect& rect) const; // Called when the parent window bounds change. void HandleParentBoundsChanged(); // Called when the parent window hierarchy for our window changes. void ParentHierarchyChanged(); // Helper function to create a selection controller. void CreateSelectionController(); // Used to set the |popup_child_host_view_| on the |popup_parent_host_view_| // and to notify the |event_handler_|. void SetPopupChild(RenderWidgetHostViewAura* popup_child_host_view); // Called when the window title is changed. void WindowTitleChanged(); void InvalidateLocalSurfaceIdOnEviction(); // Called to process a display metrics change. void ProcessDisplayMetricsChanged(); void CancelActiveTouches(); // Common part of UnOccluded() and Show(). void ShowImpl(PageVisibilityState page_visibility); // Common part of Occluded() and Hide(). void HideImpl(); blink::mojom::FrameWidgetInputHandler* GetFrameWidgetInputHandlerForFocusedWidget(); void SetTooltipText(const std::u16string& tooltip_text); raw_ptr<aura::Window> window_; std::unique_ptr<DelegatedFrameHostClient> delegated_frame_host_client_; // NOTE: this may be null during destruction. std::unique_ptr<DelegatedFrameHost> delegated_frame_host_; std::unique_ptr<WindowObserver> window_observer_; // Tracks the ancestors of the RWHVA window for window location changes. std::unique_ptr<WindowAncestorObserver> ancestor_window_observer_; // Are we in the process of closing? Tracked so we don't try to shutdown // again while inside shutdown, causing a double-free. bool in_shutdown_; // True if in the process of handling a window bounds changed notification. bool in_bounds_changed_; // Our parent host view, if this is a popup. NULL otherwise. raw_ptr<RenderWidgetHostViewAura> popup_parent_host_view_; // Our child popup host. NULL if we do not have a child popup. raw_ptr<RenderWidgetHostViewAura> popup_child_host_view_; class EventObserverForPopupExit; std::unique_ptr<EventObserverForPopupExit> event_observer_for_popup_exit_; // True when content is being loaded. Used to show an hourglass cursor. bool is_loading_; // The cursor for the page. This is passed up from the renderer. WebCursor current_cursor_; // Indicates if there is onging composition text. bool has_composition_text_; // Current tooltip text. std::u16string tooltip_; // Whether or not a frame observer has been added. bool added_frame_observer_; // Used to track the last cursor visibility update that was sent to the // renderer via NotifyRendererOfCursorVisibilityState(). enum CursorVisibilityState { UNKNOWN, VISIBLE, NOT_VISIBLE, }; CursorVisibilityState cursor_visibility_state_in_renderer_; #if defined(OS_WIN) // The LegacyRenderWidgetHostHWND class provides a dummy HWND which is used // for accessibility, as the container for windowless plugins like // Flash/Silverlight, etc and for legacy drivers for trackpoints/trackpads, // etc. // The LegacyRenderWidgetHostHWND instance is created during the first call // to RenderWidgetHostViewAura::InternalSetBounds. The instance is destroyed // when the LegacyRenderWidgetHostHWND hwnd is destroyed. raw_ptr<content::LegacyRenderWidgetHostHWND> legacy_render_widget_host_HWND_; // Set to true if the legacy_render_widget_host_HWND_ instance was destroyed // by Windows. This could happen if the browser window was destroyed by // DestroyWindow for e.g. This flag helps ensure that we don't try to create // the LegacyRenderWidgetHostHWND instance again as that would be a futile // exercise. bool legacy_window_destroyed_; // Contains a copy of the last context menu request parameters. Only set when // we receive a request to show the context menu on a long press. std::unique_ptr<ContextMenuParams> last_context_menu_params_; // Handles the showing/hiding of the VK on Windows. friend class VirtualKeyboardControllerWin; std::unique_ptr<VirtualKeyboardControllerWin> virtual_keyboard_controller_win_; gfx::Point last_mouse_move_location_; #endif // The last selection bounds reported to the view. gfx::SelectionBound selection_start_; gfx::SelectionBound selection_end_; // The insets for the window bounds (not for screen) when the window is // partially occluded. gfx::Insets insets_; // Cache the occluded bounds in screen coordinate of the virtual keyboard. gfx::Rect keyboard_occluded_bounds_; std::unique_ptr<wm::ScopedTooltipDisabler> tooltip_disabler_; float device_scale_factor_; // While this is a ui::EventHandler for targetting, |event_handler_| actually // provides an implementation, and directs events to |host_|. std::unique_ptr<RenderWidgetHostViewEventHandler> event_handler_; // If this object is the main view of a RenderWidgetHostImpl, this value // equals to the FrameSinkId of that widget. const viz::FrameSinkId frame_sink_id_; std::unique_ptr<CursorManager> cursor_manager_; // Latest capture sequence number which is incremented when the caller // requests surfaces be synchronized via // EnsureSurfaceSynchronizedForWebTest(). uint32_t latest_capture_sequence_number_ = 0u; // The pointer type of the most recent gesture/mouse/touch event. ui::EventPointerType last_pointer_type_ = ui::EventPointerType::kUnknown; // The pointer type that caused the most recent focus. This value will be // incorrect if the focus was not triggered by a user gesture. ui::EventPointerType last_pointer_type_before_focus_ = ui::EventPointerType::kUnknown; bool is_first_navigation_ = true; viz::LocalSurfaceId inset_surface_id_; // See OnDisplayMetricsChanged() for details. bool needs_to_update_display_metrics_ = false; // Saved value of WebPreferences' |double_tap_to_zoom_enabled|. bool double_tap_to_zoom_enabled_ = false; // Current visibility state. Initialized based on // RenderWidgetHostImpl::is_hidden(). Visibility visibility_; // Represents a feature of the physical display whose offset and mask_length // are expressed in DIPs relative to the view. See display_feature.h for more // details. absl::optional<DisplayFeature> display_feature_; absl::optional<display::ScopedDisplayObserver> display_observer_; base::WeakPtrFactory<RenderWidgetHostViewAura> weak_ptr_factory_{this}; }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_AURA_H_
11,377
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Plenipotentiary", "definitions": [ "A person, especially a diplomat, invested with the full power of independent action on behalf of their government, typically in a foreign country." ], "parts-of-speech": "Noun" }
99
887
/* * Copyright (C) 2012 Open Source Robotics Foundation * * 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. * */ /* Desc: Position Interface for Player * Author: <NAME> * Date: 2 March 2006 */ /** @addtogroup player @par Power Interface */ #include <math.h> #include "GazeboDriver.hh" #include "PowerInterface.hh" ///////////////////////////////////////////////// PowerInterface::PowerInterface(player_devaddr_t addr, GazeboDriver *driver, ConfigFile *cf, int section) : GazeboInterface(addr, driver, cf, section) { this->iface = NULL; this->gz_id = NULL; this->datatime = 0; /* // Get the ID of the interface this->gz_id = (char*) calloc(1024, sizeof(char)); strcat(this->gz_id, GazeboClient::prefixId); strcat(this->gz_id, cf->ReadString(section, "gz_id", "")); // Allocate a Position Interface this->iface = gz_power_alloc(); this->datatime = -1; */ } ///////////////////////////////////////////////// PowerInterface::~PowerInterface() { /* // Release this interface gz_power_free(this->iface); */ } ///////////////////////////////////////////////// int PowerInterface::ProcessMessage(QueuePointer &respQueue, player_msghdr_t *hdr, void *data) { return 0; } ///////////////////////////////////////////////// void PowerInterface::Update() { /* player_power_data_t data; struct timeval ts; gz_power_lock(this->iface, 1); // Only Update when new data is present if (this->iface->data->head.time > this->datatime) { this->datatime = this->iface->data->head.time; ts.tv_sec = (int) (this->iface->data->head.time); ts.tv_usec = (int) (fmod(this->iface->data->head.time, 1) * 1e6); data.percent = this->iface->data->levels[0]; this->driver->Publish(this->device_addr, NULL, PLAYER_MSGTYPE_DATA, PLAYER_POWER_DATA_STATE, (void*)&data, sizeof(data), &this->datatime); } gz_power_unlock(this->iface); */ } ///////////////////////////////////////////////// void PowerInterface::Subscribe() { /* // Open the interface if (gz_power_open(this->iface, GazeboClient::client, this->gz_id) != 0) { printf("Error Subscribing to Gazebo Power Interface\n"); } */ } ///////////////////////////////////////////////// void PowerInterface::Unsubscribe() { /* gz_power_close(this->iface); */ }
935
6,811
<reponame>leo60228/VVVVVV #ifndef INPUT_H #define INPUT_H void titleinput(void); void gameinput(void); void mapinput(void); void teleporterinput(void); void gamecompleteinput(void); void gamecompleteinput2(void); #endif /* INPUT_H */
95
348
<filename>docs/data/leg-t2/085/08505078.json<gh_stars>100-1000 {"nom":"Damvix","circ":"5ème circonscription","dpt":"Vendée","inscrits":660,"abs":355,"votants":305,"blancs":30,"nuls":11,"exp":264,"res":[{"nuance":"REM","nom":"<NAME>","voix":169},{"nuance":"SOC","nom":"<NAME>","voix":95}]}
120
836
<reponame>dayanruben/android-test /* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.test.core.content.pm; import static androidx.test.internal.util.Checks.checkNotNull; import static androidx.test.internal.util.Checks.checkState; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import androidx.annotation.Nullable; /** Builder for {@link PackageInfo}. */ public final class PackageInfoBuilder { @Nullable private String packageName; @Nullable private ApplicationInfo applicationInfo; private PackageInfoBuilder() {} /** * Start building a new {@link PackageInfo}. * * @return a new instance of {@link PackageInfoBuilder}. */ public static PackageInfoBuilder newBuilder() { return new PackageInfoBuilder(); } /** * Sets the package name. * * <p>Default is {@code null}. * * @see PackageInfo#packageName */ public PackageInfoBuilder setPackageName(String packageName) { this.packageName = packageName; return this; } /** * Sets the application info. * * <p>Default is {@code null} * * @see PackageInfo#applicationInfo */ public PackageInfoBuilder setApplicationInfo(ApplicationInfo applicationInfo) { this.applicationInfo = applicationInfo; return this; } /** Returns a {@link PackageInfo} with the provided data. */ public PackageInfo build() { // Check mandatory fields and correctness. checkNotNull(packageName, "Mandatory field 'packageName' missing."); PackageInfo packageInfo = new PackageInfo(); packageInfo.packageName = packageName; if (applicationInfo == null) { applicationInfo = ApplicationInfoBuilder.newBuilder().setPackageName(packageName).build(); } packageInfo.applicationInfo = applicationInfo; checkState( packageInfo.packageName.equals(packageInfo.applicationInfo.packageName), "Field 'packageName' must match field 'applicationInfo.packageName'"); return packageInfo; } }
756
426
package com.richardradics.cleanaa.app; import android.content.res.TypedArray; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import android.widget.TextView; import com.richardradics.cleanaa.R; import com.richardradics.core.app.BaseActivity; import com.richardradics.core.navigation.Navigator; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.ViewById; /** * Created by radicsrichard on 15. 05. 13.. */ @EActivity public class CleanActivity extends BaseActivity { @ViewById(R.id.toolbar) protected Toolbar toolbar; @ViewById(R.id.toolbar_title) protected TextView titleTextView; @Bean protected CleanErrorHandler cleanErrorHandler; public TextView getTitleTextView() { return titleTextView; } public void setTitleTextView(TextView titleTextView) { this.titleTextView = titleTextView; } public Toolbar getToolbar() { return toolbar; } public void setToolbar(Toolbar toolbar) { this.toolbar = toolbar; } @AfterViews protected void onBaseViewFinish() { initToolBar(); } protected void initToolBar() { if (toolbar != null) { toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); titleTextView = (TextView) findViewById(R.id.toolbar_title); setSupportActionBar(toolbar); titleTextView.setText(getTitle()); toolbar.setNavigationIcon(R.drawable.ic_backarrow); } } @OptionsItem(android.R.id.home) protected void homeSelected() { Navigator.navigateUp(this); } protected int getActionBarSize() { TypedValue typedValue = new TypedValue(); int[] textSizeAttr = new int[]{R.attr.actionBarSize}; int indexOfAttrTextSize = 0; TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr); int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1); a.recycle(); return actionBarSize; } protected int getScreenHeight() { return findViewById(android.R.id.content).getHeight(); } }
905
697
import nz.sodium.*; import java.util.Collection; import java.util.HashMap; import java.util.Map; public abstract class Junction<ContainerA, A> { private int nextID; private StreamSink<Lambda1<Map<Integer, ContainerA>, Map<Integer, ContainerA>>> sUpdate = new StreamSink<>((f1, f2) -> a -> f1.apply(f2.apply(a))); protected Cell<Collection<ContainerA>> clients; public Junction() { clients = sUpdate .<Map<Integer, ContainerA>>accum( new HashMap<Integer, ContainerA>(), (f, m) -> f.apply(m)) .map(m -> m.values()); } public Listener add(ContainerA c) { int id; synchronized (this) { id = nextID++; } sUpdate.send(m0 -> { java.util.HashMap<Integer, ContainerA> m = new HashMap(m0); m.put(id, c); return m; }); return new Listener() { public void unlisten() { sUpdate.send(m0 -> { java.util.HashMap<Integer, ContainerA> m = new HashMap(m0); m.remove(id); return m; }); } }; } }
698
826
"""Cement core mail module.""" from abc import abstractmethod from ..core.interface import Interface from ..core.handler import Handler from ..utils.misc import minimal_logger LOG = minimal_logger(__name__) class MailInterface(Interface): """ This class defines the Mail Interface. Handlers that implement this interface must provide the methods and attributes defined below. In general, most implementations should sub-class from the provided :class:`MailHandler` base class as a starting point. """ class Meta: """Handler meta-data.""" interface = 'mail' """The label identifier of the interface.""" @abstractmethod def send(self, body, **kwargs): """ Send a mail message. Keyword arguments override configuration defaults (cc, bcc, etc). Args: body (str): The message body to send Keyword Args: to (list): List of recipients (generally email addresses) from_addr (str): Address (generally email) of the sender cc (list): List of CC Recipients bcc (list): List of BCC Recipients subject (str): Message subject line Returns: bool: ``True`` if message was sent successfully, ``False`` otherwise Example: .. code-block:: python # Using all configuration defaults app.mail.send('This is my message body') # Overriding configuration defaults app.mail.send('My message body' to=['<EMAIL>'], from_addr='<EMAIL>', cc=['<EMAIL>', '<EMAIL>'], subject='This is my subject', ) """ pass # pragma: nocover class MailHandler(MailInterface, Handler): """ Mail handler implementation. **Configuration** This handler supports the following configuration settings: * **to** - Default ``to`` addresses (list, or comma separated depending on the ConfigHandler in use) * **from_addr** - Default ``from_addr`` address * **cc** - Default ``cc`` addresses (list, or comma separated depending on the ConfigHandler in use) * **bcc** - Default ``bcc`` addresses (list, or comma separated depending on the ConfigHandler in use) * **subject** - Default ``subject`` * **subject_prefix** - Additional string to prepend to the ``subject`` """ class Meta: """ Handler meta-data (can be passed as keyword arguments to the parent class). """ #: Configuration default values config_defaults = { 'to': [], 'from_addr': '<EMAIL>', 'cc': [], 'bcc': [], 'subject': 'Default Subject Line', 'subject_prefix': '', } def _setup(self, app_obj): super()._setup(app_obj) self._validate_config() def _validate_config(self): # convert comma separated strings to lists (ConfigParser) for item in ['to', 'cc', 'bcc']: if item in self.app.config.keys(self._meta.config_section): value = self.app.config.get(self._meta.config_section, item) # convert a comma-separated string to a list if type(value) is str: value_list = value.split(',') # clean up extra space if they had it inbetween commas value_list = [x.strip() for x in value_list] # set the new extensions value in the config self.app.config.set(self._meta.config_section, item, value_list)
1,610
301
//****************************************************************** // // Copyright 2017 Intel Mobile Communications GmbH All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // /* This file contains plugin specific code that adapts the native resource model * of native devices into the resource model of OIC. The file is divided into two * sections; first plugin specific entry points are implemented followed by the * implementation of the resource entity handler required by the IoTivity implementation * for each resource. * * NOTE: This file is plumbed ready for dynamic resource additions. There is a * thread provided to manage the devices. When a resource is found it is added * to a work queue which is serviced by the plugin process function. The plugin * process function is a thread safe place for the plugin specific code to call * OIC APIs. */ #include <algorithm> #include <stdlib.h> #include <stdio.h> #define __STDC_FORMAT_MACROS #include <string.h> #include <string> #include <math.h> #include <signal.h> #include <pthread.h> #include <iostream> #include <map> #include <mutex> #include "experimental/logger.h" #include "mpmErrorCode.h" #include "pluginServer.h" #include "hue_light.h" #include "hue_auth_spec.h" #include "hue_light.h" #include "hue_file.h" #include "hue_bridge.h" #include "curlClient.h" #include "oic_string.h" #include "oic_malloc.h" #include "hue_resource.h" #include "iotivity_config.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <sys/types.h> #include "messageHandler.h" #include "ConcurrentIotivityUtils.h" #include "IotivityWorkItem.h" #include "cbor.h" /******************************************************************************* * Pound defines and structure declarations go here ******************************************************************************/ #define MAX_QUERY_STRING 200 #define TAG "HUE_RESOURCE" using namespace OC::Bridging; /******************************************************************************* * global data goes here ******************************************************************************/ MPMPluginCtx *g_pluginCtx = NULL; std::mutex addedLightsLock; std::mutex authorizedBridgesLock; std::map<std::string, HueBridge> authorizedBridges; typedef std::map<std::string, HueBridge>::iterator bridgeItr; std::map<std::string, HueLightSharedPtr> g_discoveredLightsMap; std::map<std::string, HueLightSharedPtr> addedLights; static void *hueDiscoveryThread(void *pointer); const std::string HUE_SWITCH_RESOURCE_TYPE = "oic.r.switch.binary"; const std::string HUE_BRIGHTNESS_RESOURCE_TYPE = "oic.r.light.brightness"; const std::string HUE_CHROMA_RESOURCE_TYPE = "oic.r.colour.chroma"; const std::string SWITCH_RELATIVE_URI = "/switch"; const std::string BRIGHTNESS_RELATIVE_URI = "/brightness"; const std::string CHROMA_RELATIVE_URI = "/chroma"; const uint BINARY_SWITCH_CALLBACK = 0; const uint BRIGHTNESS_CALLBACK = 1; const uint CHROMA_CALLBACK = 2; FILE *hue_fopen(const char *path, const char *mode) { std::string filename = std::string("hue_") + path; return fopen(filename.c_str(), mode); } MPMResult pluginCreate(MPMPluginCtx **pluginSpecificCtx) { MPMResult result = MPM_RESULT_INTERNAL_ERROR; if (g_pluginCtx == NULL) { *pluginSpecificCtx = NULL; /* allocate a context structure for the plugin */ MPMPluginCtx *ctx = (MPMPluginCtx *) OICMalloc(sizeof(MPMPluginCtx)); /* initialize the plugin context */ if (ctx != NULL) { memset(ctx, 0, sizeof(MPMPluginCtx)); *pluginSpecificCtx = ctx; g_pluginCtx = ctx; } else { OIC_LOG(ERROR, TAG, "Unable to allocate plugin specific context"); goto exit; } ctx->device_name = DEVICE_NAME; ctx->resource_type = DEVICE_TYPE; ctx->open = hue_fopen; result = MPM_RESULT_OK; } else { result = MPM_RESULT_ALREADY_CREATED; } exit: OIC_LOG_V(INFO, TAG, "Plugin create return value:%d.", result); /* * NOTE: What do we do if the create for some reason failed. To we assume that the destroy * will be called if the create fails?? Let let the plugin loader pick up the pieces by * calling destroy on an imperfectly created plugin. Calling entry point APIs from within * the implementation can cause some real problems (e.g. deadlock situations). */ return result; } MPMResult pluginStart(MPMPluginCtx *ctx) { MPMResult result = MPM_RESULT_STARTED_FAILED; int error = 0; if (ctx == NULL || g_pluginCtx == NULL) { goto exit; } if (ctx->started) { result = MPM_RESULT_ALREADY_STARTED; goto exit; } result = hueInit(ctx, addAuthorizedBridgeCB, RemoveAuthorizedBridgeCB); if (MPM_RESULT_OK == result) { /*start bridge discovery*/ if (DiscoverHueBridges() != MPM_RESULT_OK) { // DiscoverBridges if fails we try again in discovery thread, so don't return failure OIC_LOG(ERROR, TAG, "DiscoverBridges failed"); } else { OIC_LOG(INFO, TAG, " DiscoverBridges succeeded"); } /* create house keeping thread */ ctx->stay_in_process_loop = true; error = pthread_create(&(ctx->thread_handle), NULL, hueDiscoveryThread, ctx); if (error == 0) { ctx->started = true; result = MPM_RESULT_OK; } else { OIC_LOG_V(ERROR, TAG, "Can't create plugin specific thread :[%s]", strerror(errno)); pluginStop(ctx); result = MPM_RESULT_STARTED_FAILED; } } else { OIC_LOG(ERROR, TAG, "hueAuthCreate Failed. Cannot create plugin"); } exit: OIC_LOG_V(INFO, TAG, "Plugin start return value:%d.", result); return result; } // Checks if brightness has changed in the 0 - 100 range for OCF light. bool hasBrightnessChangedInOCFScale(const HueLight::light_state_t &stateprev, const HueLight::light_state_t &statenew) { uint16_t ocfBrightnessPrev = stateprev.bri / 2.54; uint16_t ocfBrightnessNew = statenew.bri / 2.54; return ocfBrightnessNew != ocfBrightnessPrev; } bool isSecureEnvSet() { char *non_secure_env = getenv("NONSECURE"); if (non_secure_env != NULL && (strcmp(non_secure_env, "true")) == 0) { OIC_LOG(INFO, TAG, "Creating NON SECURE resources"); return false; } OIC_LOG(INFO, TAG, "Creating SECURE resources"); return true; } MPMResult createPayloadForMetaData(MPMResourceList **list, const std::string &configURI, const std::string rt, const std::string res_if) { MPMResourceList *temp = (MPMResourceList *)OICCalloc(1, sizeof(MPMResourceList)); if (temp == NULL) { OIC_LOG_V(ERROR, TAG, "Calloc failed for createPayloadForMetaData %s", strerror(errno)); return MPM_RESULT_OUT_OF_MEMORY; } OICStrcpy(temp->rt, MPM_MAX_LENGTH_64, rt.c_str()); OICStrcpy(temp->href, MPM_MAX_URI_LEN, configURI.c_str()); OICStrcpy(temp->interfaces, MPM_MAX_LENGTH_64, res_if.c_str()); temp->bitmap = BM; temp->next = *list; *list = temp; return MPM_RESULT_OK; } void addAuthorizedBridgeCB(const char *macAddress, const char *ClientId) { HueBridge bridge; HueBridge::hue_bridge_data_tag bridgeData; MPMResult result = MPM_RESULT_INTERNAL_ERROR; if (authorizedBridges.find(macAddress) == authorizedBridges.end()) { uint32_t prefix_size = MAX_QUERY_STRING; char *prefix = (char *) OICMalloc(prefix_size); if (NULL == prefix) { OIC_LOG_V(INFO, TAG, " Failed to malloc prefix"); return; } /*get prefix for discovering lights*/ result = hueAuthGetHttpPrefix(prefix, &prefix_size, macAddress, ClientId); if (result == MPM_RESULT_INSUFFICIENT_BUFFER) { char *tmp = (char *) OICRealloc(prefix, prefix_size); if (NULL == tmp) { OIC_LOG_V(INFO, TAG, " Failed to realloc prefix"); OICFree(prefix); return; } prefix = tmp; result = hueAuthGetHttpPrefix(prefix, &prefix_size, macAddress, ClientId); } if (result == MPM_RESULT_OK) { bridge.setBridgeCurlQuery(prefix); bridge.getBridgeConfigFromCloud(); bridge.getBridgeConfig(bridgeData); OIC_LOG_V(DEBUG, TAG, " \t\n\nBRIDGE AUTHORIZED\nclientID: %s\nip : %s\nmac: %s\nname : %s\nsw : %s\n", ClientId, bridgeData.ip.c_str(), bridgeData.mac.c_str(), bridgeData.name.c_str(), bridgeData.swVersion.c_str() ); OIC_LOG_V(INFO, TAG, " \n Curl prefix for bridge is %s \n", prefix); } else { OIC_LOG_V(INFO, TAG, " Failed To Authorize the bridge bridge - %s", macAddress); OICFree(prefix); return; } authorizedBridges[macAddress] = bridge; OICFree(prefix); } else { OIC_LOG_V(INFO, TAG, "Bridge is already authorized \n"); } } MPMResult pluginScan(MPMPluginCtx *, MPMPipeMessage *) { OIC_LOG(DEBUG, TAG, "Inside Plugin scan"); std::string uri, uniqueId ; HueLight::light_config_t config; HueLight::light_state_t state; std::lock_guard<std::mutex> lock(authorizedBridgesLock); /*iterate for every bridge in the authorized bridge map*/ for (bridgeItr it = authorizedBridges.begin(); it != authorizedBridges.end(); it++) { HueBridge *bridge = &(it->second); if (bridge == NULL) { continue; } // now start a new discovery and get new lights HueLight::lights lightsScanned; bridge->discoverHueLights(); bridge->getScannedLights(lightsScanned); for (uint32_t i = 0; i < lightsScanned.size(); ++i) { HueLightSharedPtr light = lightsScanned[i]; light->getConfig(config); light->getState(state); if (!state.reachable) { OIC_LOG(INFO, TAG, "Ignoring OFFLINE light"); continue; } uniqueId = createuniqueID(config.uniqueId); uri = (HUE_LIGHT_URI + uniqueId) ; OIC_LOG_V(INFO, TAG, "Found Reachable Light - light name=%s, id=%s, reachable=%d", config.name.c_str(), config.uniqueId.c_str(), state.reachable); if (addedLights.find(uri) != addedLights.end()) { OIC_LOG_V(INFO, TAG, "Already Added %s. Ignoring", uri.c_str()); continue; } g_discoveredLightsMap[uri] = light; MPMSendResponse(uri.c_str(), uri.size(), MPM_SCAN); } } return MPM_RESULT_OK; } /** * CreateuniqueID - Creates the unique id by removing Delimiters.. * @param[in] deviceId - Unique Id of the Device * @return unique id without any delimiters */ std::string createuniqueID(std::string deviceId) { std::string uniqueId(deviceId); std::string token = ""; std::string delimiter1 = ":"; std::string delimiter2 = "-"; size_t pos = 0; while ( (pos = uniqueId.find(delimiter1)) != std::string::npos) { uniqueId.replace(pos, 1, token); } while ( (pos = uniqueId.find(delimiter2)) != std::string::npos) { uniqueId.replace(pos, 3, token); } return uniqueId; } void createOCFResources(std::string uri) { uint8_t resourceProperties = (OC_OBSERVABLE | OC_DISCOVERABLE); if (isSecureEnvSet()) { resourceProperties |= OC_SECURE; } ConcurrentIotivityUtils::queueCreateResource(uri + SWITCH_RELATIVE_URI, HUE_SWITCH_RESOURCE_TYPE.c_str(), OC_RSRVD_INTERFACE_ACTUATOR, entityHandler, (void *) BINARY_SWITCH_CALLBACK, resourceProperties); ConcurrentIotivityUtils::queueCreateResource(uri + BRIGHTNESS_RELATIVE_URI, HUE_BRIGHTNESS_RESOURCE_TYPE.c_str(), OC_RSRVD_INTERFACE_ACTUATOR, entityHandler, (void *) BRIGHTNESS_CALLBACK, resourceProperties); ConcurrentIotivityUtils::queueCreateResource(uri + CHROMA_RELATIVE_URI, HUE_CHROMA_RESOURCE_TYPE.c_str(), OC_RSRVD_INTERFACE_ACTUATOR, entityHandler, (void *) CHROMA_CALLBACK, resourceProperties); } MPMResult pluginAdd(MPMPluginCtx *, MPMPipeMessage *message) { if (message->payloadSize <= 0 && message->payload == NULL) { OIC_LOG(ERROR, TAG, "No payload received, failed to add device"); return MPM_RESULT_INTERNAL_ERROR; } MPMResourceList *list = NULL; MPMResult result = MPM_RESULT_INTERNAL_ERROR; std::string uri = reinterpret_cast<const char *>(message->payload); if (addedLights.find(uri) != addedLights.end()) { OIC_LOG_V(ERROR, TAG, "%s already added", uri.c_str()); return MPM_RESULT_ALREADY_CREATED; } if (g_discoveredLightsMap.find(uri) == g_discoveredLightsMap.end()) { OIC_LOG_V(ERROR, TAG, "%s was NOT discovered in a scan", uri.c_str()); return result; } std::lock_guard<std::mutex> lock(addedLightsLock); addedLights[uri] = g_discoveredLightsMap[uri]; uint8_t *buff = (uint8_t *)OICCalloc(1, MPM_MAX_METADATA_LEN); if (buff == NULL) { OIC_LOG_V(ERROR, TAG, "Calloc failed %s", strerror(errno)); return MPM_RESULT_OUT_OF_MEMORY; } size_t size = MPM_MAX_METADATA_LEN; HueLightSharedPtr light; hueFile bridgeCtx; hueLightDetails deviceDetails; HueLight::light_config_t config; MPMDeviceSpecificData deviceConfiguration; memset(&deviceDetails, 0, sizeof(hueLightDetails)); memset(&deviceConfiguration, 0, sizeof(MPMDeviceSpecificData)); // Create Resources and form metadata for RECONNECT createOCFResources(uri); result = createPayloadForMetaData(&list, uri+SWITCH_RELATIVE_URI, HUE_SWITCH_RESOURCE_TYPE.c_str(), OC_RSRVD_INTERFACE_ACTUATOR); result= createPayloadForMetaData(&list, uri + BRIGHTNESS_RELATIVE_URI, HUE_BRIGHTNESS_RESOURCE_TYPE.c_str(),OC_RSRVD_INTERFACE_ACTUATOR); result = createPayloadForMetaData(&list, uri + CHROMA_RELATIVE_URI, HUE_CHROMA_RESOURCE_TYPE.c_str(), OC_RSRVD_INTERFACE_ACTUATOR); if(result != MPM_RESULT_OK) { OIC_LOG_V(ERROR, TAG, " Failed creating payload for metadata"); return result; } light = g_discoveredLightsMap[uri]; light->getConfig(config); std::string data; data = light->getBridgeMac(); std::transform(data.begin(), data.end(), data.begin(), ::tolower); OICStrcpy(deviceDetails.bridgeMac, MPM_MAX_UNIQUE_ID_LEN, data.c_str()); deviceDetails.bridgeMac[MPM_MAX_UNIQUE_ID_LEN - 1] = '\0'; OICStrcpy(deviceDetails.lightMac, MPM_MAX_LENGTH_32, config.uniqueId.c_str()); OICStrcpy(deviceDetails.lightUri, MPM_MAX_URI_LEN, config.uri.c_str()); OICStrcpy(deviceDetails.prefix, MPM_MAX_LENGTH_256, light->getUri().c_str()); OICStrcpy(deviceDetails.lightNo, MPM_MAX_LENGTH_32, light->getShortId().c_str()); findAuthorizedBridge(deviceDetails.bridgeMac, NULL, bridgeCtx); OICStrcpy(deviceDetails.clientId, MPM_MAX_LENGTH_64, bridgeCtx.clientID); OICStrcpy(deviceConfiguration.devName, MPM_MAX_LENGTH_64, DEVICE_NAME); OICStrcpy(deviceConfiguration.devType, MPM_MAX_LENGTH_64, DEVICE_TYPE); OICStrcpy(deviceConfiguration.manufacturerName, MPM_MAX_LENGTH_256, MANUFACTURER_NAME); MPMFormMetaData(list, &deviceConfiguration, buff, size, &deviceDetails, sizeof(deviceDetails)); MPMAddResponse response; memset(&response, 0, sizeof(MPMAddResponse)); OICStrcpy(response.uri, MPM_MAX_URI_LEN, uri.c_str()); memcpy(response.metadata, buff, MPM_MAX_METADATA_LEN); size_t response_size = sizeof(MPMAddResponse); MPMSendResponse(&response, response_size, MPM_ADD); OICFree(buff); return MPM_RESULT_OK; } MPMResult pluginRemove(MPMPluginCtx *, MPMPipeMessage *message) { if (message->payloadSize <= 0 && message->payload == NULL) { OIC_LOG(ERROR, TAG, "No paylaod received, failed to remove device"); return MPM_RESULT_INTERNAL_ERROR; } std::string uri = reinterpret_cast<const char*>(message->payload); OIC_LOG_V(DEBUG, TAG, "device uri to be removed - %s ", uri.c_str()); std::lock_guard<std::mutex> lock(addedLightsLock); if (addedLights.find(uri) == addedLights.end()) { OIC_LOG(ERROR, TAG, "Device to be removed is not added yet"); return MPM_RESULT_NOT_PRESENT; } ConcurrentIotivityUtils::queueDeleteResource(uri + SWITCH_RELATIVE_URI); ConcurrentIotivityUtils::queueDeleteResource(uri + BRIGHTNESS_RELATIVE_URI); ConcurrentIotivityUtils::queueDeleteResource(uri + CHROMA_RELATIVE_URI); addedLights.erase(uri); MPMSendResponse(uri.c_str(), uri.size(), MPM_REMOVE); return MPM_RESULT_OK; } MPMResult pluginReconnect(MPMPluginCtx *, MPMPipeMessage *message) { if (message->payloadSize <= 0 && message->payload == NULL) { OIC_LOG(ERROR, TAG, "No paylaod received, failed to reconnect"); return MPM_RESULT_INTERNAL_ERROR; } MPMResult result = MPM_RESULT_INTERNAL_ERROR; hueLightDetails *plugindetails = NULL; void *details = NULL; HueDiscoveredCtx discoveredCtx; std::size_t pos = 0; std::string light_Prefix, ip, light_mac, light_no, uri; HueBridge bridge; MPMResourceList *list = NULL, *temp = NULL; MPMParseMetaData(message->payload, MPM_MAX_METADATA_LEN, &list, &details); plugindetails = (hueLightDetails *) details; // Find Bridge ip and light id; light_no = plugindetails->lightNo; light_Prefix = plugindetails->prefix; pos = light_Prefix.find("/"); ip = light_Prefix.substr(0, (pos)); OIC_LOG_V(DEBUG, TAG, " \n\n Reconnect meta data \n\n Bridge Mac - %s\n Light Mac - %s\nip - %s\n Client ID -%s\n Light no - %s\n" "\n prefix - %s \n ", plugindetails->bridgeMac, plugindetails->lightMac, ip.c_str(), plugindetails->clientId, plugindetails->lightNo, plugindetails->prefix); if (('\0' != plugindetails->bridgeMac[0]) && ('\0' != plugindetails->clientId[0])) { if (authorizedBridges.find(plugindetails->bridgeMac) == authorizedBridges.end()) { memset(&discoveredCtx, 0, sizeof(HueDiscoveredCtx)); if (false == findDiscoveredBridge(plugindetails->bridgeMac, &discoveredCtx)) { OICStrcpy(discoveredCtx.macAddrString, MAX_STRING - 1, plugindetails->bridgeMac); OICStrcpy(discoveredCtx.ipAddrString, MAX_STRING - 1, ip.c_str()); OICStrcpy(discoveredCtx.clientIDs, MAX_STRING * MAX_CLIENTS, plugindetails->clientId); discoveredCtx.numClients = 1; addAuthorizedBridge(plugindetails->bridgeMac, plugindetails->clientId); result = addDiscoveredBridge(discoveredCtx); } else { updateDiscoverBridgeDetails(plugindetails->bridgeMac, plugindetails->clientId); } uint32_t prefix_size = MAX_QUERY_STRING; char *prefix = (char *) OICMalloc(prefix_size); if (NULL == prefix) { OIC_LOG_V(INFO, TAG, " Failed to malloc prefix"); return MPM_RESULT_INTERNAL_ERROR; } result = hueAuthGetHttpPrefix(prefix, &prefix_size, plugindetails->bridgeMac, plugindetails->clientId); if (result == MPM_RESULT_INSUFFICIENT_BUFFER) { char *tmp = (char *) OICRealloc(prefix, prefix_size); if (NULL == tmp) { OIC_LOG(DEBUG, TAG, "Failed to realloc prefix"); OICFree(prefix); return MPM_RESULT_INTERNAL_ERROR; } prefix = tmp; result = hueAuthGetHttpPrefix(prefix, &prefix_size, plugindetails->bridgeMac, plugindetails->clientId); } if (result != MPM_RESULT_OK) { OIC_LOG(DEBUG, TAG, "hueAuthGetHttpPrefix failed"); OICFree(prefix); return result; } bridge.setBridgeMAC(plugindetails->bridgeMac); bridge.setBridgeCurlQuery(prefix); authorizedBridges[plugindetails->bridgeMac] = bridge; OICFree(prefix); } } for (bridgeItr it = authorizedBridges.begin(); it != authorizedBridges.end(); it++) { HueBridge *authorizedbridge = &(it->second); std::string data; data = authorizedbridge->getBridgeMAC(); std::transform(data.begin(), data.end(), data.begin(), ::tolower); if (plugindetails->bridgeMac == data) { OIC_LOG(DEBUG, TAG, "Bridge Found and is authorized"); addReconnectLightsToBridge(plugindetails, authorizedbridge, ip); result = MPM_RESULT_OK; } } while (list) { temp = list; list = list->next; OICFree(temp); } free(plugindetails); return MPM_RESULT_OK; } void addReconnectLightsToBridge(hueLightDetails *plugindetails, HueBridge *bridge, std::string bridgeIp) { HueLight::light_config_t config; std::string uuid, uri; OIC_LOG(INFO, TAG, " RECONNECTING ALL THE LIGHTS......."); std::shared_ptr<HueLight> light = std::make_shared<HueLight>(plugindetails->prefix, bridgeIp, plugindetails->bridgeMac, plugindetails->lightNo, "NULL"); if (!light) { OIC_LOG(ERROR, TAG, " Pointer returned NULL to the light object"); return; } config.uri = plugindetails->lightUri; config.uniqueId = plugindetails->lightMac; light->setConfig(config); bridge->fillLightDetails(light); uuid = createuniqueID(config.uniqueId); uri = (HUE_LIGHT_URI + uuid ); createOCFResources(uri); g_discoveredLightsMap[uri] = light; addedLights[uri] = light; } /* * Removes bridge from the authorized bridge map. */ void RemoveAuthorizedBridgeCB(const char *macAddrString) { OIC_LOG_V(INFO, TAG, "Remove Bridge called for bridge = %s", macAddrString); std::lock_guard<std::mutex> lock(authorizedBridgesLock); bridgeItr it = authorizedBridges.find(macAddrString); if (it != authorizedBridges.end()) { /*remove the bridge*/ authorizedBridges.erase(it); } return; } /* Plugin specific entry-point function to stop the plugin's threads * * returns: * MPM_RESULT_OK - no errors * MPM_RESULT_INTERNAL_ERROR - stack process error */ MPMResult pluginStop(MPMPluginCtx *ctx) { MPMResult result = MPM_RESULT_INTERNAL_ERROR; if (NULL != ctx && g_pluginCtx != NULL) { result = MPM_RESULT_OK; //stop the presence before stopping the plugin OCStopPresence(); if (ctx->started == true) { ctx->stay_in_process_loop = false; pthread_join(ctx->thread_handle, NULL); ctx->started = false; } //destroy the resources hueAuthDestroy(); clearBridgeDetails(); } OIC_LOG_V(INFO, TAG, "Plugin stop: OUT - return value:%d", result); return (result); } MPMResult pluginDestroy(MPMPluginCtx *ctx) { MPMResult result = MPM_RESULT_INTERNAL_ERROR; if (ctx != NULL && g_pluginCtx != NULL) { result = MPM_RESULT_OK; if (ctx->started == true) { result = pluginStop(ctx); } /* freeing the resource allocated in create */ OICFree(ctx); g_pluginCtx = NULL; } OIC_LOG_V(INFO, TAG, "Plugin destroy's return value:%d", result); return (result); } OCEntityHandlerResult handleEntityHandlerRequests( OCEntityHandlerFlag , OCEntityHandlerRequest *entityHandlerRequest, std::string resourceType) { OCEntityHandlerResult ehResult = OC_EH_ERROR; OCRepPayload *responsePayload = NULL; OCRepPayload *payload = OCRepPayloadCreate(); try { if (entityHandlerRequest == NULL) { throw "Entity handler received a null entity request context" ; } std::string uri = OCGetResourceUri(entityHandlerRequest->resource); HueLightSharedPtr hueLight = getHueLightFromOCFResourceUri(uri); char *interfaceQuery = NULL; char *resourceTypeQuery = NULL; char *dupQuery = OICStrdup(entityHandlerRequest->query); if (dupQuery) { MPMExtractFiltersFromQuery(dupQuery, &interfaceQuery, &resourceTypeQuery); } switch (entityHandlerRequest->method) { case OC_REST_GET: OIC_LOG_V(INFO, TAG, " GET Request for: %s", uri.c_str()); ehResult = processGetRequest(payload, hueLight, resourceType); break; case OC_REST_PUT: case OC_REST_POST: OIC_LOG_V(INFO, TAG, "PUT / POST Request on %s", uri.c_str()); ehResult = processPutRequest(entityHandlerRequest, hueLight, resourceType, payload); // To include "if" in all payloads. interfaceQuery = (char *) OC_RSRVD_INTERFACE_DEFAULT; break; default: OIC_LOG_V(ERROR, TAG, "UnSupported Method [%d] Received ", entityHandlerRequest->method); ConcurrentIotivityUtils::respondToRequestWithError(entityHandlerRequest, " Unsupported Method", OC_EH_METHOD_NOT_ALLOWED); return OC_EH_OK; } responsePayload = getCommonPayload(uri.c_str(),interfaceQuery, resourceType, payload); ConcurrentIotivityUtils::respondToRequest(entityHandlerRequest, responsePayload, ehResult); OICFree(dupQuery); } catch (const char *errorMessage) { OIC_LOG_V(ERROR, TAG, "Error - %s ", errorMessage); ConcurrentIotivityUtils::respondToRequestWithError(entityHandlerRequest, errorMessage, OC_EH_ERROR); ehResult = OC_EH_OK; } OCRepPayloadDestroy(responsePayload); return ehResult; } // Entity handler for binary switch OCEntityHandlerResult entityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest *entityHandlerRequest, void *callback) { uintptr_t callbackParamResourceType = (uintptr_t)callback; std::string resourceType; if (callbackParamResourceType == BINARY_SWITCH_CALLBACK) { resourceType = HUE_SWITCH_RESOURCE_TYPE; } else if (callbackParamResourceType == BRIGHTNESS_CALLBACK) { resourceType = HUE_BRIGHTNESS_RESOURCE_TYPE; } else { resourceType = HUE_CHROMA_RESOURCE_TYPE; } return handleEntityHandlerRequests(flag, entityHandlerRequest, resourceType); } OCEntityHandlerResult processGetRequest(OCRepPayload *payload, HueLightSharedPtr hueLight, std::string resType) { HueLight::light_state_t light_state; hueLight->getState(light_state); if (payload == NULL) { throw "payload is null"; } if (HUE_SWITCH_RESOURCE_TYPE == resType) { if (!OCRepPayloadSetPropBool(payload, "value", light_state.power)) { throw "Failed to set 'value' (power) in payload"; } OIC_LOG_V(INFO, TAG, "Light State: %s", light_state.power ? "true" : "false"); } else if (HUE_BRIGHTNESS_RESOURCE_TYPE == resType) { uint8_t ocfBrightness = light_state.bri / 2.54; if (!OCRepPayloadSetPropInt(payload, "brightness", ocfBrightness)) { throw "Failed to set 'brightness' in payload"; } OIC_LOG_V(INFO, TAG, " Brightness State (Hue Bulb): %" PRIu64 " Brightness(OCF) : %d", light_state.bri, ocfBrightness); } else if (HUE_CHROMA_RESOURCE_TYPE == resType) { if (!OCRepPayloadSetPropInt(payload, "hue", light_state.hue) || !OCRepPayloadSetPropInt(payload, "saturation", light_state.sat)) { throw "Failed to set 'hue' or 'saturation' in payload" ; } size_t csc_dimensions[MAX_REP_ARRAY_DEPTH] = {2, 0, 0}; if (!OCRepPayloadSetDoubleArray(payload, "csc", light_state.csc, csc_dimensions)) { throw "Failed to set csc in payload" ; } OIC_LOG_V(INFO, TAG, "hue: %" PRIu64 ", sat: %" PRIu64 ", csc: [%f, %f] in payload.", light_state.hue, light_state.sat, light_state.csc[0], light_state.csc[1]); } else { throw "Failed due to unkwown resource type"; } return OC_EH_OK; } OCEntityHandlerResult processPutRequest(OCEntityHandlerRequest *ehRequest, HueLightSharedPtr hueLight, std::string resourceType, OCRepPayload *payload) { if (!ehRequest || !ehRequest->payload || ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION) { throw "Incoming payload is NULL or not a representation"; } OCRepPayload *input = reinterpret_cast<OCRepPayload *>(ehRequest->payload); if (!input) { throw "PUT payload is null"; } HueLight::light_state_t state; light_resource_t light_resource; if (hueLight->getState(state, true) != MPM_RESULT_OK) { throw "Error Getting light. Aborting PUT" ; } if (HUE_SWITCH_RESOURCE_TYPE == resourceType) { if (!OCRepPayloadGetPropBool(input, "value", &light_resource.power)) { throw "No value (power) in representation" ; } OIC_LOG_V(INFO, TAG, "PUT/POST value (power):%s", light_resource.power ? "true" : "false"); state.power = light_resource.power; if (!OCRepPayloadSetPropBool(payload, "value", state.power)) { throw "Failed to set 'value' (power) in payload"; } } else if (HUE_BRIGHTNESS_RESOURCE_TYPE == resourceType) { if (!OCRepPayloadGetPropInt(input, "brightness", &light_resource.bri)) { throw "No brightness in representation" ; } OIC_LOG_V(INFO, TAG, "PUT/POST brightness:%" PRIu64 "", light_resource.bri); // Sclae up from 1-100 for OCF Light to 1-254 for Hue device light_resource.bri *= 2.54; // Add 1 to make sure when we scale down later by dividing by 2.54, we try and // arryto the same number. if (light_resource.bri != 254) { light_resource.bri += 1; } // Get the current powered state of light and then set the value accordingly. // If the light is turned off, then PUT to bri will yield in a blink // and quickly to off state. In short, it is invalid. state.bri = light_resource.bri; state.power = true; if (!OCRepPayloadSetPropInt(payload, "brightness", state.bri)) { throw "Failed to set 'brightness' in payload"; } } else if (HUE_CHROMA_RESOURCE_TYPE == resourceType) { bool isChromaPropertyInPayload = false; if (!OCRepPayloadGetPropInt(input, "hue", &light_resource.hue)) { OIC_LOG(INFO, TAG, "No hue in PUT payload"); } else { state.hue = light_resource.hue; isChromaPropertyInPayload = true; OIC_LOG_V(INFO, TAG, "PUT/POST hue :%" PRIu64 "", state.hue); } if (!OCRepPayloadGetPropInt(input, "saturation", &light_resource.sat)) { OIC_LOG(INFO, TAG, "No saturation in PUT payload"); } else { state.sat = light_resource.sat; isChromaPropertyInPayload = true; OIC_LOG_V(INFO, TAG, "PUT/POST sat :%" PRIu64 "", state.sat); } if (!OCRepPayloadSetPropInt(payload, "hue", state.hue) || !OCRepPayloadSetPropInt(payload, "saturation", state.sat)) { throw "Failed to set 'hue' or 'saturation' in payload" ; } size_t csc_dimensions[MAX_REP_ARRAY_DEPTH] = {2, 0, 0}; double *cscInPayload = NULL; if (!OCRepPayloadGetDoubleArray(input, "csc", &cscInPayload, csc_dimensions)) { OIC_LOG(INFO, TAG, "No csc in PUT payload"); } else { if (cscInPayload != NULL) { isChromaPropertyInPayload = true; state.csc[0] = cscInPayload[0]; state.csc[1] = cscInPayload[1]; OIC_LOG_V(INFO, TAG, "PUT/POST csc (sat) :[%f, %f]", state.csc[0], state.csc[1]); } } if (isChromaPropertyInPayload) { state.power = true; light_resource.power = true; } OICFree(cscInPayload); } else { throw "Failed due to unkwown resource type" ; } if (hueLight->setState(state) != MPM_RESULT_OK) { throw "Error setting light state" ; } return OC_EH_OK; } OCRepPayload *getCommonPayload(const char *uri, char *interfaceQuery, std::string resType, OCRepPayload *payload) { if (!OCRepPayloadSetUri(payload, uri)) { throw "Unable to set URI in the payload"; } if (!OCRepPayloadAddResourceType(payload, resType.c_str())) { throw "Failed to set light resource type" ; } OIC_LOG_V(INFO, TAG, "Checking against if: %s", interfaceQuery); // If the interface filter is explicitly oic.if.baseline, include all properties. if (interfaceQuery && std::string(interfaceQuery) == std::string(OC_RSRVD_INTERFACE_DEFAULT)) { if (!OCRepPayloadAddInterface(payload, OC_RSRVD_INTERFACE_ACTUATOR)) { throw "Failed to set light interface"; } if (!OCRepPayloadAddInterface(payload, std::string(OC_RSRVD_INTERFACE_DEFAULT).c_str())) { throw "Failed to set baseline interface" ; } } return payload; } /** * Monitors the light state changes and sends notification if * any change. Also discovers new Bridges...! * * @param[in] pointer pluginctx */ static void *hueDiscoveryThread(void *pointer) { MPMPluginCtx *ctx = (MPMPluginCtx *) pointer; if (ctx == NULL) { return NULL; } OIC_LOG(INFO, TAG, "Plugin specific thread handler entered"); HueLight::light_config_t config; std::string uniqueId, uri; while (true == ctx->stay_in_process_loop) { addedLightsLock.lock(); for (auto itr : addedLights) { HueLightSharedPtr light = itr.second; if (!light) { continue; } light->getConfig(config); std::string uniqueId = createuniqueID(config.uniqueId); uri = (HUE_LIGHT_URI + uniqueId ) ; HueLight::light_state_t oldState, newState ; light->getState(oldState); light->getState(newState, true); if (oldState.power != newState.power) { ConcurrentIotivityUtils::queueNotifyObservers(itr.first + SWITCH_RELATIVE_URI); } else if (hasBrightnessChangedInOCFScale(oldState, newState)) { ConcurrentIotivityUtils::queueNotifyObservers(itr.first + BRIGHTNESS_RELATIVE_URI); } else if ((oldState.hue != newState.hue) || (oldState.sat != newState.sat)) { ConcurrentIotivityUtils::queueNotifyObservers(itr.first + CHROMA_RELATIVE_URI); } else { ; //Do nothing here.. } } addedLightsLock.unlock(); /*start the periodic bridge discovery*/ DiscoverHueBridges(); sleep(MPM_THREAD_PROCESS_SLEEPTIME); } OIC_LOG(INFO, TAG, "Leaving plugin specific thread handler"); pthread_exit(NULL); } HueLightSharedPtr getHueLightFromOCFResourceUri(std::string resourceUri) { OIC_LOG_V(INFO, TAG, "Request for %s ", resourceUri.c_str()); for (auto uriToHuePair : addedLights) { if (resourceUri.find(uriToHuePair.first) != std::string::npos) { return uriToHuePair.second; } } throw "Resource" + resourceUri + "not found"; }
16,846
5,169
{ "name": "TestinDemo", "version": "1.0.0", "summary": "This is a testing demo for log message servies", "description": "This is testing Library Data and working Data", "homepage": "https://github.com/izooto-mobile-sdk/TestinDemo", "license": "MIT", "authors": { "amitgupta": "<EMAIL>" }, "platforms": { "ios": "11.0" }, "source": { "git": "https://github.com/izooto-mobile-sdk/TestinDemo.git", "tag": "1.0.0" }, "source_files": "TestinDemo/**/*", "exclude_files": "TestinDemo/**/*.plist", "requires_arc": true }
234
348
{"nom":"Changey","circ":"1ère circonscription","dpt":"Haute-Marne","inscrits":224,"abs":104,"votants":120,"blancs":10,"nuls":10,"exp":100,"res":[{"nuance":"REM","nom":"<NAME>","voix":59},{"nuance":"LR","nom":"<NAME>","voix":41}]}
89
605
<filename>compiler-rt/lib/hwasan/hwasan_allocation_functions.cpp //===-- hwasan_allocation_functions.cpp -----------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file is a part of HWAddressSanitizer. // // Definitions for __sanitizer allocation functions. // //===----------------------------------------------------------------------===// #include "hwasan.h" #include "interception/interception.h" #include "sanitizer_common/sanitizer_allocator_dlsym.h" #include "sanitizer_common/sanitizer_allocator_interface.h" #include "sanitizer_common/sanitizer_tls_get_addr.h" #if !SANITIZER_FUCHSIA using namespace __hwasan; struct DlsymAlloc : public DlSymAllocator<DlsymAlloc> { static bool UseImpl() { return !hwasan_inited; } }; extern "C" { SANITIZER_INTERFACE_ATTRIBUTE int __sanitizer_posix_memalign(void **memptr, uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; CHECK_NE(memptr, 0); int res = hwasan_posix_memalign(memptr, alignment, size, &stack); return res; } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer_memalign(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_memalign(alignment, size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer_aligned_alloc(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_aligned_alloc(alignment, size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer___libc_memalign(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; void *ptr = hwasan_memalign(alignment, size, &stack); if (ptr) DTLS_on_libc_memalign(ptr, size); return ptr; } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer_valloc(uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_valloc(size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer_pvalloc(uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_pvalloc(size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_free(void *ptr) { if (!ptr) return; if (DlsymAlloc::PointerIsMine(ptr)) return DlsymAlloc::Free(ptr); GET_MALLOC_STACK_TRACE; hwasan_free(ptr, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_cfree(void *ptr) { if (!ptr) return; if (DlsymAlloc::PointerIsMine(ptr)) return DlsymAlloc::Free(ptr); GET_MALLOC_STACK_TRACE; hwasan_free(ptr, &stack); } SANITIZER_INTERFACE_ATTRIBUTE uptr __sanitizer_malloc_usable_size(const void *ptr) { return __sanitizer_get_allocated_size(ptr); } SANITIZER_INTERFACE_ATTRIBUTE struct __sanitizer_struct_mallinfo __sanitizer_mallinfo() { __sanitizer_struct_mallinfo sret; internal_memset(&sret, 0, sizeof(sret)); return sret; } SANITIZER_INTERFACE_ATTRIBUTE int __sanitizer_mallopt(int cmd, int value) { return 0; } SANITIZER_INTERFACE_ATTRIBUTE void __sanitizer_malloc_stats(void) { // FIXME: implement, but don't call REAL(malloc_stats)! } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer_calloc(uptr nmemb, uptr size) { if (DlsymAlloc::Use()) return DlsymAlloc::Callocate(nmemb, size); GET_MALLOC_STACK_TRACE; return hwasan_calloc(nmemb, size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer_realloc(void *ptr, uptr size) { if (DlsymAlloc::Use() || DlsymAlloc::PointerIsMine(ptr)) return DlsymAlloc::Realloc(ptr, size); GET_MALLOC_STACK_TRACE; return hwasan_realloc(ptr, size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer_reallocarray(void *ptr, uptr nmemb, uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_reallocarray(ptr, nmemb, size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void *__sanitizer_malloc(uptr size) { if (UNLIKELY(!hwasan_init_is_running)) ENSURE_HWASAN_INITED(); if (DlsymAlloc::Use()) return DlsymAlloc::Allocate(size); GET_MALLOC_STACK_TRACE; return hwasan_malloc(size, &stack); } } // extern "C" #if HWASAN_WITH_INTERCEPTORS # define INTERCEPTOR_ALIAS(RET, FN, ARGS...) \ extern "C" SANITIZER_INTERFACE_ATTRIBUTE RET WRAP(FN)(ARGS) \ ALIAS("__sanitizer_" #FN); \ extern "C" SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE RET FN( \ ARGS) ALIAS("__sanitizer_" #FN) INTERCEPTOR_ALIAS(int, posix_memalign, void **memptr, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, aligned_alloc, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, __libc_memalign, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, valloc, SIZE_T size); INTERCEPTOR_ALIAS(void, free, void *ptr); INTERCEPTOR_ALIAS(uptr, malloc_usable_size, const void *ptr); INTERCEPTOR_ALIAS(void *, calloc, SIZE_T nmemb, SIZE_T size); INTERCEPTOR_ALIAS(void *, realloc, void *ptr, SIZE_T size); INTERCEPTOR_ALIAS(void *, reallocarray, void *ptr, SIZE_T nmemb, SIZE_T size); INTERCEPTOR_ALIAS(void *, malloc, SIZE_T size); # if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR_ALIAS(void *, memalign, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, pvalloc, SIZE_T size); INTERCEPTOR_ALIAS(void, cfree, void *ptr); INTERCEPTOR_ALIAS(__sanitizer_struct_mallinfo, mallinfo); INTERCEPTOR_ALIAS(int, mallopt, int cmd, int value); INTERCEPTOR_ALIAS(void, malloc_stats, void); # endif #endif // #if HWASAN_WITH_INTERCEPTORS #endif // SANITIZER_FUCHSIA
2,324
5,169
<filename>Specs/b/6/3/WeSdkMediation_Facebook/5.4.0.4/WeSdkMediation_Facebook.podspec.json<gh_stars>1000+ { "name": "WeSdkMediation_Facebook", "version": "5.4.0.4", "summary": "Facebook Adapters for mediating through WeSdk.", "homepage": "https://github.com/webeyemob/WeSdkiOSPub", "license": { "type": "MIT" }, "authors": "WeSdk", "platforms": { "ios": "9.0" }, "source": { "git": "https://github.com/webeyemob/WeSdkiOSPub.git", "tag": "facebook-5.4.0.4" }, "vendored_frameworks": "WeSdkMediation_Facebook/5.4.0.4/WeMobMediation_Facebook.framework", "dependencies": { "FBAudienceNetwork": [ "~> 5.4.0" ], "WeSdk": [ "~> 1.2.8" ] } }
336
607
class A; template <typename T> ::A* B::fn();
21
2,151
/* * Copyright 2008 <NAME> * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdint.h> #include "pipe/p_defines.h" #include "util/u_inlines.h" #include "util/u_pack_color.h" #include "util/u_format.h" #include "util/u_surface.h" #include "nv50_context.h" #include "nv50_resource.h" #include "nv50_defs.xml.h" #include "nv50_texture.xml.h" #define NV50_ENG2D_SUPPORTED_FORMATS 0xff0843e080608409ULL /* return TRUE for formats that can be converted among each other by NV50_2D */ static INLINE boolean nv50_2d_format_faithful(enum pipe_format format) { uint8_t id = nv50_format_table[format].rt; return (id >= 0xc0) && (NV50_ENG2D_SUPPORTED_FORMATS & (1ULL << (id - 0xc0))); } static INLINE uint8_t nv50_2d_format(enum pipe_format format) { uint8_t id = nv50_format_table[format].rt; /* Hardware values for color formats range from 0xc0 to 0xff, * but the 2D engine doesn't support all of them. */ if ((id >= 0xc0) && (NV50_ENG2D_SUPPORTED_FORMATS & (1ULL << (id - 0xc0)))) return id; switch (util_format_get_blocksize(format)) { case 1: return NV50_SURFACE_FORMAT_R8_UNORM; case 2: return NV50_SURFACE_FORMAT_R16_UNORM; case 4: return NV50_SURFACE_FORMAT_BGRA8_UNORM; default: return 0; } } static int nv50_2d_texture_set(struct nouveau_pushbuf *push, int dst, struct nv50_miptree *mt, unsigned level, unsigned layer) { struct nouveau_bo *bo = mt->base.bo; uint32_t width, height, depth; uint32_t format; uint32_t mthd = dst ? NV50_2D_DST_FORMAT : NV50_2D_SRC_FORMAT; uint32_t offset = mt->level[level].offset; format = nv50_2d_format(mt->base.base.format); if (!format) { NOUVEAU_ERR("invalid/unsupported surface format: %s\n", util_format_name(mt->base.base.format)); return 1; } width = u_minify(mt->base.base.width0, level) << mt->ms_x; height = u_minify(mt->base.base.height0, level) << mt->ms_y; offset = mt->level[level].offset; if (!mt->layout_3d) { offset += mt->layer_stride * layer; depth = 1; layer = 0; } else { depth = u_minify(mt->base.base.depth0, level); } if (!nouveau_bo_memtype(bo)) { BEGIN_NV04(push, SUBC_2D(mthd), 2); PUSH_DATA (push, format); PUSH_DATA (push, 1); BEGIN_NV04(push, SUBC_2D(mthd + 0x14), 5); PUSH_DATA (push, mt->level[level].pitch); PUSH_DATA (push, width); PUSH_DATA (push, height); PUSH_DATAh(push, bo->offset + offset); PUSH_DATA (push, bo->offset + offset); } else { BEGIN_NV04(push, SUBC_2D(mthd), 5); PUSH_DATA (push, format); PUSH_DATA (push, 0); PUSH_DATA (push, mt->level[level].tile_mode); PUSH_DATA (push, depth); PUSH_DATA (push, layer); BEGIN_NV04(push, SUBC_2D(mthd + 0x18), 4); PUSH_DATA (push, width); PUSH_DATA (push, height); PUSH_DATAh(push, bo->offset + offset); PUSH_DATA (push, bo->offset + offset); } #if 0 if (dst) { BEGIN_NV04(push, SUBC_2D(NV50_2D_CLIP_X), 4); PUSH_DATA (push, 0); PUSH_DATA (push, 0); PUSH_DATA (push, width); PUSH_DATA (push, height); } #endif return 0; } static int nv50_2d_texture_do_copy(struct nouveau_pushbuf *push, struct nv50_miptree *dst, unsigned dst_level, unsigned dx, unsigned dy, unsigned dz, struct nv50_miptree *src, unsigned src_level, unsigned sx, unsigned sy, unsigned sz, unsigned w, unsigned h) { static const uint32_t duvdxy[5] = { 0x40000000, 0x80000000, 0x00000001, 0x00000002, 0x00000004 }; int ret; uint32_t ctrl; #if 0 ret = MARK_RING(chan, 2 * 16 + 32, 4); if (ret) return ret; #endif ret = nv50_2d_texture_set(push, 1, dst, dst_level, dz); if (ret) return ret; ret = nv50_2d_texture_set(push, 0, src, src_level, sz); if (ret) return ret; /* NOTE: 2D engine doesn't work for MS8 */ if (src->ms_x) ctrl = 0x11; /* 0/1 = CENTER/CORNER, 00/10 = POINT/BILINEAR */ BEGIN_NV04(push, NV50_2D(BLIT_CONTROL), 1); PUSH_DATA (push, ctrl); BEGIN_NV04(push, NV50_2D(BLIT_DST_X), 4); PUSH_DATA (push, dx << dst->ms_x); PUSH_DATA (push, dy << dst->ms_y); PUSH_DATA (push, w << dst->ms_x); PUSH_DATA (push, h << dst->ms_y); BEGIN_NV04(push, NV50_2D(BLIT_DU_DX_FRACT), 4); PUSH_DATA (push, duvdxy[2 + ((int)src->ms_x - (int)dst->ms_x)] & 0xf0000000); PUSH_DATA (push, duvdxy[2 + ((int)src->ms_x - (int)dst->ms_x)] & 0x0000000f); PUSH_DATA (push, duvdxy[2 + ((int)src->ms_y - (int)dst->ms_y)] & 0xf0000000); PUSH_DATA (push, duvdxy[2 + ((int)src->ms_y - (int)dst->ms_y)] & 0x0000000f); BEGIN_NV04(push, NV50_2D(BLIT_SRC_X_FRACT), 4); PUSH_DATA (push, 0); PUSH_DATA (push, sx << src->ms_x); PUSH_DATA (push, 0); PUSH_DATA (push, sy << src->ms_y); return 0; } static void nv50_resource_copy_region(struct pipe_context *pipe, struct pipe_resource *dst, unsigned dst_level, unsigned dstx, unsigned dsty, unsigned dstz, struct pipe_resource *src, unsigned src_level, const struct pipe_box *src_box) { struct nv50_context *nv50 = nv50_context(pipe); int ret; boolean m2mf; unsigned dst_layer = dstz, src_layer = src_box->z; /* Fallback for buffers. */ if (dst->target == PIPE_BUFFER && src->target == PIPE_BUFFER) { util_resource_copy_region(pipe, dst, dst_level, dstx, dsty, dstz, src, src_level, src_box); return; } /* 0 and 1 are equal, only supporting 0/1, 2, 4 and 8 */ assert((src->nr_samples | 1) == (dst->nr_samples | 1)); m2mf = (src->format == dst->format) || (util_format_get_blocksizebits(src->format) == util_format_get_blocksizebits(dst->format)); nv04_resource(dst)->status |= NOUVEAU_BUFFER_STATUS_GPU_WRITING; if (m2mf) { struct nv50_m2mf_rect drect, srect; unsigned i; unsigned nx = util_format_get_nblocksx(src->format, src_box->width); unsigned ny = util_format_get_nblocksy(src->format, src_box->height); nv50_m2mf_rect_setup(&drect, dst, dst_level, dstx, dsty, dstz); nv50_m2mf_rect_setup(&srect, src, src_level, src_box->x, src_box->y, src_box->z); for (i = 0; i < src_box->depth; ++i) { nv50_m2mf_transfer_rect(nv50, &drect, &srect, nx, ny); if (nv50_miptree(dst)->layout_3d) drect.z++; else drect.base += nv50_miptree(dst)->layer_stride; if (nv50_miptree(src)->layout_3d) srect.z++; else srect.base += nv50_miptree(src)->layer_stride; } return; } assert((src->format == dst->format) || (nv50_2d_format_faithful(src->format) && nv50_2d_format_faithful(dst->format))); BCTX_REFN(nv50->bufctx, 2D, nv04_resource(src), RD); BCTX_REFN(nv50->bufctx, 2D, nv04_resource(dst), WR); nouveau_pushbuf_bufctx(nv50->base.pushbuf, nv50->bufctx); nouveau_pushbuf_validate(nv50->base.pushbuf); for (; dst_layer < dstz + src_box->depth; ++dst_layer, ++src_layer) { ret = nv50_2d_texture_do_copy(nv50->base.pushbuf, nv50_miptree(dst), dst_level, dstx, dsty, dst_layer, nv50_miptree(src), src_level, src_box->x, src_box->y, src_layer, src_box->width, src_box->height); if (ret) break; } nouveau_bufctx_reset(nv50->bufctx, NV50_BIND_2D); } static void nv50_clear_render_target(struct pipe_context *pipe, struct pipe_surface *dst, const union pipe_color_union *color, unsigned dstx, unsigned dsty, unsigned width, unsigned height) { struct nv50_context *nv50 = nv50_context(pipe); struct nouveau_pushbuf *push = nv50->base.pushbuf; struct nv50_miptree *mt = nv50_miptree(dst->texture); struct nv50_surface *sf = nv50_surface(dst); struct nouveau_bo *bo = mt->base.bo; BEGIN_NV04(push, NV50_3D(CLEAR_COLOR(0)), 4); PUSH_DATAf(push, color->f[0]); PUSH_DATAf(push, color->f[1]); PUSH_DATAf(push, color->f[2]); PUSH_DATAf(push, color->f[3]); #if 0 if (MARK_RING(chan, 18, 2)) return; #endif BEGIN_NV04(push, NV50_3D(RT_CONTROL), 1); PUSH_DATA (push, 1); BEGIN_NV04(push, NV50_3D(RT_ADDRESS_HIGH(0)), 5); PUSH_DATAh(push, bo->offset + sf->offset); PUSH_DATA (push, bo->offset + sf->offset); PUSH_DATA (push, nv50_format_table[dst->format].rt); PUSH_DATA (push, mt->level[sf->base.u.tex.level].tile_mode); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(RT_HORIZ(0)), 2); if (nouveau_bo_memtype(bo)) PUSH_DATA(push, sf->width); else PUSH_DATA(push, NV50_3D_RT_HORIZ_LINEAR | mt->level[0].pitch); PUSH_DATA (push, sf->height); BEGIN_NV04(push, NV50_3D(RT_ARRAY_MODE), 1); PUSH_DATA (push, 1); if (!nouveau_bo_memtype(bo)) { BEGIN_NV04(push, NV50_3D(ZETA_ENABLE), 1); PUSH_DATA (push, 0); } /* NOTE: only works with D3D clear flag (5097/0x143c bit 4) */ BEGIN_NV04(push, NV50_3D(VIEWPORT_HORIZ(0)), 2); PUSH_DATA (push, (width << 16) | dstx); PUSH_DATA (push, (height << 16) | dsty); BEGIN_NV04(push, NV50_3D(CLEAR_BUFFERS), 1); PUSH_DATA (push, 0x3c); nv50->dirty |= NV50_NEW_FRAMEBUFFER; } static void nv50_clear_depth_stencil(struct pipe_context *pipe, struct pipe_surface *dst, unsigned clear_flags, double depth, unsigned stencil, unsigned dstx, unsigned dsty, unsigned width, unsigned height) { struct nv50_context *nv50 = nv50_context(pipe); struct nouveau_pushbuf *push = nv50->base.pushbuf; struct nv50_miptree *mt = nv50_miptree(dst->texture); struct nv50_surface *sf = nv50_surface(dst); struct nouveau_bo *bo = mt->base.bo; uint32_t mode = 0; assert(nouveau_bo_memtype(bo)); /* ZETA cannot be linear */ if (clear_flags & PIPE_CLEAR_DEPTH) { BEGIN_NV04(push, NV50_3D(CLEAR_DEPTH), 1); PUSH_DATAf(push, depth); mode |= NV50_3D_CLEAR_BUFFERS_Z; } if (clear_flags & PIPE_CLEAR_STENCIL) { BEGIN_NV04(push, NV50_3D(CLEAR_STENCIL), 1); PUSH_DATA (push, stencil & 0xff); mode |= NV50_3D_CLEAR_BUFFERS_S; } #if 0 if (MARK_RING(chan, 17, 2)) return; #endif BEGIN_NV04(push, NV50_3D(ZETA_ADDRESS_HIGH), 5); PUSH_DATAh(push, bo->offset + sf->offset); PUSH_DATA (push, bo->offset + sf->offset); PUSH_DATA (push, nv50_format_table[dst->format].rt); PUSH_DATA (push, mt->level[sf->base.u.tex.level].tile_mode); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(ZETA_ENABLE), 1); PUSH_DATA (push, 1); BEGIN_NV04(push, NV50_3D(ZETA_HORIZ), 3); PUSH_DATA (push, sf->width); PUSH_DATA (push, sf->height); PUSH_DATA (push, (1 << 16) | 1); BEGIN_NV04(push, NV50_3D(VIEWPORT_HORIZ(0)), 2); PUSH_DATA (push, (width << 16) | dstx); PUSH_DATA (push, (height << 16) | dsty); BEGIN_NV04(push, NV50_3D(CLEAR_BUFFERS), 1); PUSH_DATA (push, mode); nv50->dirty |= NV50_NEW_FRAMEBUFFER; } void nv50_clear(struct pipe_context *pipe, unsigned buffers, const union pipe_color_union *color, double depth, unsigned stencil) { struct nv50_context *nv50 = nv50_context(pipe); struct nouveau_pushbuf *push = nv50->base.pushbuf; struct pipe_framebuffer_state *fb = &nv50->framebuffer; unsigned i; uint32_t mode = 0; /* don't need NEW_BLEND, COLOR_MASK doesn't affect CLEAR_BUFFERS */ if (!nv50_state_validate(nv50, NV50_NEW_FRAMEBUFFER, 9 + (fb->nr_cbufs * 2))) return; if (buffers & PIPE_CLEAR_COLOR && fb->nr_cbufs) { BEGIN_NV04(push, NV50_3D(CLEAR_COLOR(0)), 4); PUSH_DATAf(push, color->f[0]); PUSH_DATAf(push, color->f[1]); PUSH_DATAf(push, color->f[2]); PUSH_DATAf(push, color->f[3]); mode = NV50_3D_CLEAR_BUFFERS_R | NV50_3D_CLEAR_BUFFERS_G | NV50_3D_CLEAR_BUFFERS_B | NV50_3D_CLEAR_BUFFERS_A; } if (buffers & PIPE_CLEAR_DEPTH) { BEGIN_NV04(push, NV50_3D(CLEAR_DEPTH), 1); PUSH_DATA (push, fui(depth)); mode |= NV50_3D_CLEAR_BUFFERS_Z; } if (buffers & PIPE_CLEAR_STENCIL) { BEGIN_NV04(push, NV50_3D(CLEAR_STENCIL), 1); PUSH_DATA (push, stencil & 0xff); mode |= NV50_3D_CLEAR_BUFFERS_S; } BEGIN_NV04(push, NV50_3D(CLEAR_BUFFERS), 1); PUSH_DATA (push, mode); for (i = 1; i < fb->nr_cbufs; i++) { BEGIN_NV04(push, NV50_3D(CLEAR_BUFFERS), 1); PUSH_DATA (push, (i << 6) | 0x3c); } } struct nv50_blitctx { struct nv50_screen *screen; struct { struct pipe_framebuffer_state fb; struct nv50_program *vp; struct nv50_program *gp; struct nv50_program *fp; unsigned num_textures[3]; unsigned num_samplers[3]; struct pipe_sampler_view *texture[2]; struct nv50_tsc_entry *sampler[2]; unsigned dirty; } saved; struct nv50_program vp; struct nv50_program fp; struct nv50_tsc_entry sampler[2]; /* nearest, bilinear */ uint32_t fp_offset; uint16_t color_mask; uint8_t filter; }; static void nv50_blitctx_make_vp(struct nv50_blitctx *blit) { static const uint32_t code[] = { 0x10000001, /* mov b32 o[0x00] s[0x00] */ /* HPOS.x */ 0x0423c788, 0x10000205, /* mov b32 o[0x04] s[0x04] */ /* HPOS.y */ 0x0423c788, 0x10000409, /* mov b32 o[0x08] s[0x08] */ /* TEXC.x */ 0x0423c788, 0x1000060d, /* mov b32 o[0x0c] s[0x0c] */ /* TEXC.y */ 0x0423c788, 0x10000811, /* exit mov b32 o[0x10] s[0x10] */ /* TEXC.z */ 0x0423c789, }; blit->vp.type = PIPE_SHADER_VERTEX; blit->vp.translated = TRUE; blit->vp.code = (uint32_t *)code; /* const_cast */ blit->vp.code_size = sizeof(code); blit->vp.max_gpr = 4; blit->vp.max_out = 5; blit->vp.out_nr = 2; blit->vp.out[0].mask = 0x3; blit->vp.out[0].sn = TGSI_SEMANTIC_POSITION; blit->vp.out[1].hw = 2; blit->vp.out[1].mask = 0x7; blit->vp.out[1].sn = TGSI_SEMANTIC_GENERIC; blit->vp.vp.attrs[0] = 0x73; blit->vp.vp.psiz = 0x40; blit->vp.vp.edgeflag = 0x40; } static void nv50_blitctx_make_fp(struct nv50_blitctx *blit) { static const uint32_t code[] = { /* 3 coords RGBA in, RGBA out, also for Z32_FLOAT(_S8X24_UINT) */ 0x80000000, /* interp $r0 v[0x0] */ 0x80010004, /* interp $r1 v[0x4] */ 0x80020009, /* interp $r2 flat v[0x8] */ 0x00040780, 0xf6800001, /* texauto live { $r0,1,2,3 } $t0 $s0 { $r0,1,2 } */ 0x0000c785, /* exit */ /* 3 coords ZS in, S encoded in R, Z encoded in GBA (8_UNORM) */ 0x80000000, /* interp $r0 v[0x00] */ 0x80010004, /* interp $r1 v[0x04] */ 0x80020108, /* interp $r2 flat v[0x8] */ 0x10008010, /* mov b32 $r4 $r0 */ 0xf2820201, /* texauto live { $r0,#,#,# } $t1 $s1 { $r0,1,2 } */ 0x00000784, 0xa000000d, /* cvt f32 $r3 s32 $r0 */ 0x44014780, 0x10000801, /* mov b32 $r0 $r4 */ 0x0403c780, 0xf2800001, /* texauto live { $r0,#,#,# } $t0 $s0 { $r0,1,2 } */ 0x00000784, 0xc03f0009, /* mul f32 $r2 $r0 (2^24 - 1) */ 0x04b7ffff, 0xa0000409, /* cvt rni s32 $r2 f32 $r2 */ 0x8c004780, 0xc0010601, /* mul f32 $r0 $r3 1/0xff */ 0x03b8080b, 0xd03f0405, /* and b32 $r1 $r2 0x0000ff */ 0x0000000f, 0xd000040d, /* and b32 $r3 $r2 0xff0000 */ 0x000ff003, 0xd0000409, /* and b32 $r2 $r2 0x00ff00 */ 0x00000ff3, 0xa0000205, /* cvt f32 $r1 s32 $r1 */ 0x44014780, 0xa000060d, /* cvt f32 $r3 s32 $r3 */ 0x44014780, 0xa0000409, /* cvt f32 $r2 s32 $r2 */ 0x44014780, 0xc0010205, /* mul f32 $r1 $r1 1/0x0000ff */ 0x03b8080b, 0xc001060d, /* mul f32 $r3 $r3 1/0x00ff00 */ 0x0338080b, 0xc0010409, /* mul f32 $r2 $r2 1/0xff0000 */ 0x0378080b, 0xf0000001, /* exit never nop */ 0xe0000001, /* 3 coords ZS in, Z encoded in RGB, S encoded in A (U8_UNORM) */ 0x80000000, /* interp $r0 v[0x00] */ 0x80010004, /* interp $r1 v[0x04] */ 0x80020108, /* interp $r2 flat v[0x8] */ 0x10008010, /* mov b32 $r4 $r0 */ 0xf2820201, /* texauto live { $r0,#,#,# } $t1 $s1 { $r0,1,2 } */ 0x00000784, 0xa000000d, /* cvt f32 $r3 s32 $r0 */ 0x44014780, 0x10000801, /* mov b32 $r0 $r4 */ 0x0403c780, 0xf2800001, /* texauto live { $r0,#,#,# } $t0 $s0 { $r0,1,2 } */ 0x00000784, 0xc03f0009, /* mul f32 $r2 $r0 (2^24 - 1) */ 0x04b7ffff, 0xa0000409, /* cvt rni s32 $r2 f32 $r2 */ 0x8c004780, 0xc001060d, /* mul f32 $r3 $r3 1/0xff */ 0x03b8080b, 0xd03f0401, /* and b32 $r0 $r2 0x0000ff */ 0x0000000f, 0xd0000405, /* and b32 $r1 $r2 0x00ff00 */ 0x00000ff3, 0xd0000409, /* and b32 $r2 $r2 0xff0000 */ 0x000ff003, 0xa0000001, /* cvt f32 $r0 s32 $r0 */ 0x44014780, 0xa0000205, /* cvt f32 $r1 s32 $r1 */ 0x44014780, 0xa0000409, /* cvt f32 $r2 s32 $r2 */ 0x44014780, 0xc0010001, /* mul f32 $r0 $r0 1/0x0000ff */ 0x03b8080b, 0xc0010205, /* mul f32 $r1 $r1 1/0x00ff00 */ 0x0378080b, 0xc0010409, /* mul f32 $r2 $r2 1/0xff0000 */ 0x0338080b, 0xf0000001, /* exit never nop */ 0xe0000001 }; blit->fp.type = PIPE_SHADER_FRAGMENT; blit->fp.translated = TRUE; blit->fp.code = (uint32_t *)code; /* const_cast */ blit->fp.code_size = sizeof(code); blit->fp.max_gpr = 5; blit->fp.max_out = 4; blit->fp.in_nr = 1; blit->fp.in[0].mask = 0x7; /* last component flat */ blit->fp.in[0].linear = 1; blit->fp.in[0].sn = TGSI_SEMANTIC_GENERIC; blit->fp.out_nr = 1; blit->fp.out[0].mask = 0xf; blit->fp.out[0].sn = TGSI_SEMANTIC_COLOR; blit->fp.fp.interp = 0x00020403; blit->fp.gp.primid = 0x80; } static void nv50_blitctx_make_sampler(struct nv50_blitctx *blit) { /* clamp to edge, min/max lod = 0, nearest filtering */ blit->sampler[0].id = -1; blit->sampler[0].tsc[0] = NV50_TSC_0_SRGB_CONVERSION_ALLOWED | (NV50_TSC_WRAP_CLAMP_TO_EDGE << NV50_TSC_0_WRAPS__SHIFT) | (NV50_TSC_WRAP_CLAMP_TO_EDGE << NV50_TSC_0_WRAPT__SHIFT) | (NV50_TSC_WRAP_CLAMP_TO_EDGE << NV50_TSC_0_WRAPR__SHIFT); blit->sampler[0].tsc[1] = NV50_TSC_1_MAGF_NEAREST | NV50_TSC_1_MINF_NEAREST | NV50_TSC_1_MIPF_NONE; /* clamp to edge, min/max lod = 0, bilinear filtering */ blit->sampler[1].id = -1; blit->sampler[1].tsc[0] = blit->sampler[0].tsc[0]; blit->sampler[1].tsc[1] = NV50_TSC_1_MAGF_LINEAR | NV50_TSC_1_MINF_LINEAR | NV50_TSC_1_MIPF_NONE; } /* Since shaders cannot export stencil, we cannot copy stencil values when * rendering to ZETA, so we attach the ZS surface to a colour render target. */ static INLINE enum pipe_format nv50_blit_zeta_to_colour_format(enum pipe_format format) { switch (format) { case PIPE_FORMAT_Z16_UNORM: return PIPE_FORMAT_R16_UNORM; case PIPE_FORMAT_Z24_UNORM_S8_UINT: case PIPE_FORMAT_S8_UINT_Z24_UNORM: case PIPE_FORMAT_Z24X8_UNORM: return PIPE_FORMAT_R8G8B8A8_UNORM; case PIPE_FORMAT_Z32_FLOAT: return PIPE_FORMAT_R32_FLOAT; case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT: return PIPE_FORMAT_R32G32_FLOAT; default: assert(0); return PIPE_FORMAT_NONE; } } static void nv50_blitctx_get_color_mask_and_fp(struct nv50_blitctx *blit, enum pipe_format format, uint8_t mask) { blit->color_mask = 0; switch (format) { case PIPE_FORMAT_Z24X8_UNORM: case PIPE_FORMAT_Z24_UNORM_S8_UINT: blit->fp_offset = 0xb0; if (mask & PIPE_MASK_Z) blit->color_mask |= 0x0111; if (mask & PIPE_MASK_S) blit->color_mask |= 0x1000; break; case PIPE_FORMAT_S8_UINT_Z24_UNORM: blit->fp_offset = 0x18; if (mask & PIPE_MASK_Z) blit->color_mask |= 0x1110; if (mask & PIPE_MASK_S) blit->color_mask |= 0x0001; break; default: blit->fp_offset = 0; if (mask & (PIPE_MASK_R | PIPE_MASK_Z)) blit->color_mask |= 0x0001; if (mask & (PIPE_MASK_G | PIPE_MASK_S)) blit->color_mask |= 0x0010; if (mask & PIPE_MASK_B) blit->color_mask |= 0x0100; if (mask & PIPE_MASK_A) blit->color_mask |= 0x1000; break; } } static void nv50_blit_set_dst(struct nv50_context *nv50, struct pipe_resource *res, unsigned level, unsigned layer) { struct pipe_context *pipe = &nv50->base.pipe; struct pipe_surface templ; if (util_format_is_depth_or_stencil(res->format)) templ.format = nv50_blit_zeta_to_colour_format(res->format); else templ.format = res->format; templ.usage = PIPE_USAGE_STREAM; templ.u.tex.level = level; templ.u.tex.first_layer = templ.u.tex.last_layer = layer; nv50->framebuffer.cbufs[0] = nv50_miptree_surface_new(pipe, res, &templ); nv50->framebuffer.nr_cbufs = 1; nv50->framebuffer.zsbuf = NULL; nv50->framebuffer.width = nv50->framebuffer.cbufs[0]->width; nv50->framebuffer.height = nv50->framebuffer.cbufs[0]->height; } static INLINE void nv50_blit_fixup_tic_entry(struct pipe_sampler_view *view) { struct nv50_tic_entry *ent = nv50_tic_entry(view); ent->tic[2] &= ~(1 << 31); /* scaled coordinates, ok with 3d textures ? */ /* magic: */ ent->tic[3] = 0x20000000; /* affects quality of near vertical edges in MS8 */ } static void nv50_blit_set_src(struct nv50_context *nv50, struct pipe_resource *res, unsigned level, unsigned layer) { struct pipe_context *pipe = &nv50->base.pipe; struct pipe_sampler_view templ; templ.format = res->format; templ.u.tex.first_layer = templ.u.tex.last_layer = layer; templ.u.tex.first_level = templ.u.tex.last_level = level; templ.swizzle_r = PIPE_SWIZZLE_RED; templ.swizzle_g = PIPE_SWIZZLE_GREEN; templ.swizzle_b = PIPE_SWIZZLE_BLUE; templ.swizzle_a = PIPE_SWIZZLE_ALPHA; nv50->textures[2][0] = nv50_create_sampler_view(pipe, res, &templ); nv50->textures[2][1] = NULL; nv50_blit_fixup_tic_entry(nv50->textures[2][0]); nv50->num_textures[0] = nv50->num_textures[1] = 0; nv50->num_textures[2] = 1; templ.format = nv50_zs_to_s_format(res->format); if (templ.format != res->format) { nv50->textures[2][1] = nv50_create_sampler_view(pipe, res, &templ); nv50_blit_fixup_tic_entry(nv50->textures[2][1]); nv50->num_textures[2] = 2; } } static void nv50_blitctx_prepare_state(struct nv50_blitctx *blit) { struct nouveau_pushbuf *push = blit->screen->base.pushbuf; /* blend state */ BEGIN_NV04(push, NV50_3D(COLOR_MASK(0)), 1); PUSH_DATA (push, blit->color_mask); BEGIN_NV04(push, NV50_3D(BLEND_ENABLE(0)), 1); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(LOGIC_OP_ENABLE), 1); PUSH_DATA (push, 0); /* rasterizer state */ #ifndef NV50_SCISSORS_CLIPPING BEGIN_NV04(push, NV50_3D(SCISSOR_ENABLE(0)), 1); PUSH_DATA (push, 1); #endif BEGIN_NV04(push, NV50_3D(VERTEX_TWO_SIDE_ENABLE), 1); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(FRAG_COLOR_CLAMP_EN), 1); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(MULTISAMPLE_ENABLE), 1); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(MSAA_MASK(0)), 4); PUSH_DATA (push, 0xffff); PUSH_DATA (push, 0xffff); PUSH_DATA (push, 0xffff); PUSH_DATA (push, 0xffff); BEGIN_NV04(push, NV50_3D(POLYGON_MODE_FRONT), 3); PUSH_DATA (push, NV50_3D_POLYGON_MODE_FRONT_FILL); PUSH_DATA (push, NV50_3D_POLYGON_MODE_BACK_FILL); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(CULL_FACE_ENABLE), 1); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(POLYGON_STIPPLE_ENABLE), 1); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(POLYGON_OFFSET_FILL_ENABLE), 1); PUSH_DATA (push, 0); /* zsa state */ BEGIN_NV04(push, NV50_3D(DEPTH_TEST_ENABLE), 1); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(STENCIL_ENABLE), 1); PUSH_DATA (push, 0); BEGIN_NV04(push, NV50_3D(ALPHA_TEST_ENABLE), 1); PUSH_DATA (push, 0); } static void nv50_blitctx_pre_blit(struct nv50_blitctx *blit, struct nv50_context *nv50) { int s; blit->saved.fb.width = nv50->framebuffer.width; blit->saved.fb.height = nv50->framebuffer.height; blit->saved.fb.nr_cbufs = nv50->framebuffer.nr_cbufs; blit->saved.fb.cbufs[0] = nv50->framebuffer.cbufs[0]; blit->saved.fb.zsbuf = nv50->framebuffer.zsbuf; blit->saved.vp = nv50->vertprog; blit->saved.gp = nv50->gmtyprog; blit->saved.fp = nv50->fragprog; nv50->vertprog = &blit->vp; nv50->gmtyprog = NULL; nv50->fragprog = &blit->fp; for (s = 0; s < 3; ++s) { blit->saved.num_textures[s] = nv50->num_textures[s]; blit->saved.num_samplers[s] = nv50->num_samplers[s]; } blit->saved.texture[0] = nv50->textures[2][0]; blit->saved.texture[1] = nv50->textures[2][1]; blit->saved.sampler[0] = nv50->samplers[2][0]; blit->saved.sampler[1] = nv50->samplers[2][1]; nv50->samplers[2][0] = &blit->sampler[blit->filter]; nv50->samplers[2][1] = &blit->sampler[blit->filter]; nv50->num_samplers[0] = nv50->num_samplers[1] = 0; nv50->num_samplers[2] = 2; blit->saved.dirty = nv50->dirty; nv50->dirty = NV50_NEW_FRAMEBUFFER | NV50_NEW_VERTPROG | NV50_NEW_FRAGPROG | NV50_NEW_GMTYPROG | NV50_NEW_TEXTURES | NV50_NEW_SAMPLERS; } static void nv50_blitctx_post_blit(struct nv50_context *nv50, struct nv50_blitctx *blit) { int s; pipe_surface_reference(&nv50->framebuffer.cbufs[0], NULL); nv50->framebuffer.width = blit->saved.fb.width; nv50->framebuffer.height = blit->saved.fb.height; nv50->framebuffer.nr_cbufs = blit->saved.fb.nr_cbufs; nv50->framebuffer.cbufs[0] = blit->saved.fb.cbufs[0]; nv50->framebuffer.zsbuf = blit->saved.fb.zsbuf; nv50->vertprog = blit->saved.vp; nv50->gmtyprog = blit->saved.gp; nv50->fragprog = blit->saved.fp; pipe_sampler_view_reference(&nv50->textures[2][0], NULL); pipe_sampler_view_reference(&nv50->textures[2][1], NULL); for (s = 0; s < 3; ++s) { nv50->num_textures[s] = blit->saved.num_textures[s]; nv50->num_samplers[s] = blit->saved.num_samplers[s]; } nv50->textures[2][0] = blit->saved.texture[0]; nv50->textures[2][1] = blit->saved.texture[1]; nv50->samplers[2][0] = blit->saved.sampler[0]; nv50->samplers[2][1] = blit->saved.sampler[1]; nv50->dirty = blit->saved.dirty | (NV50_NEW_FRAMEBUFFER | NV50_NEW_SCISSOR | NV50_NEW_SAMPLE_MASK | NV50_NEW_RASTERIZER | NV50_NEW_ZSA | NV50_NEW_BLEND | NV50_NEW_TEXTURES | NV50_NEW_SAMPLERS | NV50_NEW_VERTPROG | NV50_NEW_GMTYPROG | NV50_NEW_FRAGPROG); } static void nv50_resource_resolve(struct pipe_context *pipe, const struct pipe_resolve_info *info) { struct nv50_context *nv50 = nv50_context(pipe); struct nv50_screen *screen = nv50->screen; struct nv50_blitctx *blit = screen->blitctx; struct nouveau_pushbuf *push = nv50->base.pushbuf; struct pipe_resource *src = info->src.res; struct pipe_resource *dst = info->dst.res; float x0, x1, y0, y1, z; float x_range, y_range; nv50_blitctx_get_color_mask_and_fp(blit, dst->format, info->mask); blit->filter = util_format_is_depth_or_stencil(dst->format) ? 0 : 1; nv50_blitctx_pre_blit(blit, nv50); nv50_blit_set_dst(nv50, dst, info->dst.level, info->dst.layer); nv50_blit_set_src(nv50, src, 0, info->src.layer); nv50_blitctx_prepare_state(blit); nv50_state_validate(nv50, ~0, 36); x_range = (float)(info->src.x1 - info->src.x0) / (float)(info->dst.x1 - info->dst.x0); y_range = (float)(info->src.y1 - info->src.y0) / (float)(info->dst.y1 - info->dst.y0); x0 = (float)info->src.x0 - x_range * (float)info->dst.x0; y0 = (float)info->src.y0 - y_range * (float)info->dst.y0; x1 = x0 + 16384.0f * x_range; y1 = y0 + 16384.0f * y_range; x0 *= (float)(1 << nv50_miptree(src)->ms_x); x1 *= (float)(1 << nv50_miptree(src)->ms_x); y0 *= (float)(1 << nv50_miptree(src)->ms_y); y1 *= (float)(1 << nv50_miptree(src)->ms_y); z = (float)info->src.layer; BEGIN_NV04(push, NV50_3D(FP_START_ID), 1); PUSH_DATA (push, blit->fp.code_base + blit->fp_offset); BEGIN_NV04(push, NV50_3D(VIEWPORT_TRANSFORM_EN), 1); PUSH_DATA (push, 0); /* Draw a large triangle in screen coordinates covering the whole * render target, with scissors defining the destination region. * The vertex is supplied with non-normalized texture coordinates * arranged in a way to yield the desired offset and scale. */ BEGIN_NV04(push, NV50_3D(SCISSOR_HORIZ(0)), 2); PUSH_DATA (push, (info->dst.x1 << 16) | info->dst.x0); PUSH_DATA (push, (info->dst.y1 << 16) | info->dst.y0); BEGIN_NV04(push, NV50_3D(VERTEX_BEGIN_GL), 1); PUSH_DATA (push, NV50_3D_VERTEX_BEGIN_GL_PRIMITIVE_TRIANGLES); BEGIN_NV04(push, NV50_3D(VTX_ATTR_3F_X(1)), 3); PUSH_DATAf(push, x0); PUSH_DATAf(push, y0); PUSH_DATAf(push, z); BEGIN_NV04(push, NV50_3D(VTX_ATTR_2F_X(0)), 2); PUSH_DATAf(push, 0.0f); PUSH_DATAf(push, 0.0f); BEGIN_NV04(push, NV50_3D(VTX_ATTR_3F_X(1)), 3); PUSH_DATAf(push, x1); PUSH_DATAf(push, y0); PUSH_DATAf(push, z); BEGIN_NV04(push, NV50_3D(VTX_ATTR_2F_X(0)), 2); PUSH_DATAf(push, 16384 << nv50_miptree(dst)->ms_x); PUSH_DATAf(push, 0.0f); BEGIN_NV04(push, NV50_3D(VTX_ATTR_3F_X(1)), 3); PUSH_DATAf(push, x0); PUSH_DATAf(push, y1); PUSH_DATAf(push, z); BEGIN_NV04(push, NV50_3D(VTX_ATTR_2F_X(0)), 2); PUSH_DATAf(push, 0.0f); PUSH_DATAf(push, 16384 << nv50_miptree(dst)->ms_y); BEGIN_NV04(push, NV50_3D(VERTEX_END_GL), 1); PUSH_DATA (push, 0); /* re-enable normally constant state */ BEGIN_NV04(push, NV50_3D(VIEWPORT_TRANSFORM_EN), 1); PUSH_DATA (push, 1); nv50_blitctx_post_blit(nv50, blit); } boolean nv50_blitctx_create(struct nv50_screen *screen) { screen->blitctx = CALLOC_STRUCT(nv50_blitctx); if (!screen->blitctx) { NOUVEAU_ERR("failed to allocate blit context\n"); return FALSE; } screen->blitctx->screen = screen; nv50_blitctx_make_vp(screen->blitctx); nv50_blitctx_make_fp(screen->blitctx); nv50_blitctx_make_sampler(screen->blitctx); screen->blitctx->color_mask = 0x1111; return TRUE; } void nv50_init_surface_functions(struct nv50_context *nv50) { struct pipe_context *pipe = &nv50->base.pipe; pipe->resource_copy_region = nv50_resource_copy_region; pipe->resource_resolve = nv50_resource_resolve; pipe->clear_render_target = nv50_clear_render_target; pipe->clear_depth_stencil = nv50_clear_depth_stencil; }
16,150
7,353
/* Wrapper for wepoll.c */ #ifdef _WIN32 #include "wepoll.c" #endif
31
1,127
<reponame>kurylo/openvino // Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <openvino/cc/ngraph/itt.hpp> #include "transformations/substitute_softsign.hpp" #include "transformations/utils/transformation_helper.hpp" #include "transformations/utils/utils.hpp" #include <ngraph/opsets/opset8.hpp> #include <ngraph/pattern/op/wrap_type.hpp> #include <ngraph/pattern/op/or.hpp> #include <ngraph/rt_info.hpp> #include <ops/softsign.hpp> using namespace GNAPluginNS; using Node = std::shared_ptr<ngraph::Node>; namespace { void DoTransformation(Node start_node, Node last_node) { auto activation = std::make_shared<ov::intel_gna::op::SoftSign>(start_node); activation->set_friendly_name(last_node->get_friendly_name()); ngraph::copy_runtime_info(last_node, activation); ngraph::replace_node(last_node, activation); } class IsConstValueAcceptable { public: IsConstValueAcceptable(double expected_value) : m_expected_value(expected_value) {} bool operator()(const ngraph::Output<ngraph::Node>& output) const { auto node = std::dynamic_pointer_cast<ngraph::opset8::Constant>(output.get_node_shared_ptr()); if (!node) return false; float value; if (!ngraph::op::util::get_single_value(node, value)) { return false; } return (value == m_expected_value); } private: const double m_expected_value; }; } // namespace SubstituteSoftsign::SubstituteSoftsign() { MATCHER_SCOPE(SubstituteSoftsign); auto root = ngraph::pattern::any_input(); auto abs = ngraph::pattern::wrap_type<ngraph::opset8::Abs>({root}); auto add_const = ngraph::pattern::wrap_type<ngraph::opset8::Constant>(IsConstValueAcceptable(1.0)); auto add = ngraph::pattern::wrap_type<ngraph::opset8::Add>({abs, add_const}); auto power_const = ngraph::pattern::wrap_type<ngraph::opset8::Constant>(IsConstValueAcceptable(-1.0)); auto power = ngraph::pattern::wrap_type<ngraph::opset8::Power>({add, power_const}); auto multiply = ngraph::pattern::wrap_type<ngraph::opset8::Multiply>({root, power}); auto divide = ngraph::pattern::wrap_type<ngraph::opset8::Divide>({root, add}); auto last = std::make_shared<ngraph::pattern::op::Or>(ngraph::OutputVector{multiply, divide}); ngraph::matcher_pass_callback callback = [=](ngraph::pattern::Matcher& m) { const auto& pattern_map = m.get_pattern_value_map(); auto root_node = pattern_map.at(root).get_node_shared_ptr(); auto last_node_it = pattern_map.find(multiply); if (last_node_it == pattern_map.end()) last_node_it = pattern_map.find(divide); if (last_node_it == pattern_map.end()) return false; auto last_node = last_node_it->second.get_node_shared_ptr(); DoTransformation(root_node, last_node); return true; }; auto m = std::make_shared<ngraph::pattern::Matcher>(last, matcher_name); this->register_matcher(m, callback); }
1,195
348
{"nom":"Baneuil","circ":"2ème circonscription","dpt":"Dordogne","inscrits":305,"abs":142,"votants":163,"blancs":22,"nuls":6,"exp":135,"res":[{"nuance":"REM","nom":"<NAME>","voix":86},{"nuance":"FN","nom":"<NAME>","voix":49}]}
91
347
<filename>mapproxy/test/test_http_helper.py # This file is part of the MapProxy project. # Copyright (C) 2013 Omniscale <http://omniscale.de> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import requests from mapproxy.test.http import ( MockServ, RequestsMismatchError, mock_httpd, basic_auth_value, query_eq, ) class TestMockServ(object): def test_no_requests(self): serv = MockServ() with serv: pass def test_expects_get_no_body(self): serv = MockServ() serv.expects('/test') with serv: resp = requests.get('http://localhost:%d/test' % serv.port) assert resp.status_code == 200 assert resp.content == b'' def test_expects_w_header(self): serv = MockServ() serv.expects('/test', headers={'Accept': 'Coffee'}) with serv: resp = requests.get('http://localhost:%d/test' % serv.port, headers={'Accept': 'Coffee'}) assert resp.ok def test_expects_w_header_but_missing(self): serv = MockServ() serv.expects('/test', headers={'Accept': 'Coffee'}) try: with serv: requests.get('http://localhost:%d/test' % serv.port) except RequestsMismatchError as ex: assert ex.assertions[0].expected == 'Accept: Coffee' def test_expects_post(self): # TODO POST handling in MockServ is hacky. # data just gets appended to URL serv = MockServ() serv.expects('/test?foo', method='POST') with serv: requests.post('http://localhost:%d/test' % serv.port, data=b'foo') def test_expects_post_but_get(self): serv = MockServ() serv.expects('/test', method='POST') try: with serv: requests.get('http://localhost:%d/test' % serv.port) except RequestsMismatchError as ex: assert ex.assertions[0].expected == 'POST' assert ex.assertions[0].actual == 'GET' else: raise AssertionError('AssertionError expected') def test_returns(self): serv = MockServ() serv.expects('/test') serv.returns(body=b'hello') with serv: resp = requests.get('http://localhost:%d/test' % serv.port) assert 'Content-type' not in resp.headers assert resp.content == b'hello' def test_returns_headers(self): serv = MockServ() serv.expects('/test') serv.returns(body=b'hello', headers={'content-type': 'text/plain'}) with serv: resp = requests.get('http://localhost:%d/test' % serv.port) assert resp.headers['Content-type'] == 'text/plain' assert resp.content == b'hello' def test_returns_status(self): serv = MockServ() serv.expects('/test') serv.returns(body=b'hello', status_code=418) with serv: resp = requests.get('http://localhost:%d/test' % serv.port) assert resp.status_code == 418 assert resp.content == b'hello' def test_multiple_requests(self): serv = MockServ() serv.expects('/test1').returns(body=b'hello1') serv.expects('/test2').returns(body=b'hello2') with serv: resp = requests.get('http://localhost:%d/test1' % serv.port) assert resp.content == b'hello1' resp = requests.get('http://localhost:%d/test2' % serv.port) assert resp.content == b'hello2' def test_too_many_requests(self): serv = MockServ() serv.expects('/test1').returns(body=b'hello1') with serv: resp = requests.get('http://localhost:%d/test1' % serv.port) assert resp.content == b'hello1' try: requests.get('http://localhost:%d/test2' % serv.port) except requests.exceptions.RequestException: pass else: raise AssertionError('RequestException expected') def test_missing_requests(self): serv = MockServ() serv.expects('/test1').returns(body=b'hello1') serv.expects('/test2').returns(body=b'hello2') try: with serv: resp = requests.get('http://localhost:%d/test1' % serv.port) assert resp.content == b'hello1' except RequestsMismatchError as ex: assert 'requests mismatch:\n - missing requests' in str(ex) else: raise AssertionError('AssertionError expected') def test_reset_unordered(self): serv = MockServ(unordered=True) serv.expects('/test1').returns(body=b'hello1') serv.expects('/test2').returns(body=b'hello2') with serv: resp = requests.get('http://localhost:%d/test1' % serv.port) assert resp.content == b'hello1' resp = requests.get('http://localhost:%d/test2' % serv.port) assert resp.content == b'hello2' serv.reset() with serv: resp = requests.get('http://localhost:%d/test2' % serv.port) assert resp.content == b'hello2' resp = requests.get('http://localhost:%d/test1' % serv.port) assert resp.content == b'hello1' def test_unexpected(self): serv = MockServ(unordered=True) serv.expects('/test1').returns(body=b'hello1') serv.expects('/test2').returns(body=b'hello2') try: with serv: resp = requests.get('http://localhost:%d/test1' % serv.port) assert resp.content == b'hello1' try: requests.get('http://localhost:%d/test3' % serv.port) except requests.exceptions.RequestException: pass else: raise AssertionError('RequestException expected') resp = requests.get('http://localhost:%d/test2' % serv.port) assert resp.content == b'hello2' except RequestsMismatchError as ex: assert 'unexpected request' in ex.assertions[0] else: raise AssertionError('AssertionError expected') class TestMockHttpd(object): def test_no_requests(self): with mock_httpd(('localhost', 42423), []): pass def test_headers_status_body(self): with mock_httpd(('localhost', 42423), [ ({'path':'/test', 'headers': {'Accept': 'Coffee'}}, {'body': b'ok', 'status': 418})]): resp = requests.get('http://localhost:42423/test', headers={'Accept': 'Coffee'}) assert resp.status_code == 418 def test_auth(self): with mock_httpd(('localhost', 42423), [ ({'path':'/test', 'headers': {'Accept': 'Coffee'}, 'require_basic_auth': True}, {'body': b'ok', 'status': 418})]): resp = requests.get('http://localhost:42423/test') assert resp.status_code == 401 assert resp.content == b'no access' resp = requests.get('http://localhost:42423/test', headers={ 'Authorization': basic_auth_value('foo', 'bar'), 'Accept': 'Coffee'} ) assert resp.content == b'ok' def test_query_eq(): assert query_eq('?baz=42&foo=bar', '?foo=bar&baz=42') assert query_eq('?baz=42.00&foo=bar', '?foo=bar&baz=42.0') assert query_eq('?baz=42.000000001&foo=bar', '?foo=bar&baz=42.0') assert not query_eq('?baz=42.00000001&foo=bar', '?foo=bar&baz=42.0') assert query_eq('?baz=42.000000001,23.99999999999&foo=bar', '?foo=bar&baz=42.0,24.0') assert not query_eq('?baz=42.00000001&foo=bar', '?foo=bar&baz=42.0')
3,780
589
<reponame>ClaudioWaldvogel/inspectIT package rocks.inspectit.ui.rcp.editor.graph.plot; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import org.apache.commons.collections.CollectionUtils; import org.eclipse.swt.widgets.Display; import rocks.inspectit.shared.all.communication.IAggregatedData; import rocks.inspectit.shared.all.communication.data.AggregatedHttpTimerData; import rocks.inspectit.shared.all.communication.data.HttpTimerData; import rocks.inspectit.shared.cs.cmr.service.IHttpTimerDataAccessService; import rocks.inspectit.shared.cs.indexing.aggregation.IAggregator; import rocks.inspectit.ui.rcp.editor.inputdefinition.InputDefinition; import rocks.inspectit.ui.rcp.editor.inputdefinition.extra.HttpChartingInputDefinitionExtra; import rocks.inspectit.ui.rcp.editor.inputdefinition.extra.InputDefinitionExtrasMarkerFactory; import rocks.inspectit.ui.rcp.util.data.RegExAggregatedHttpTimerData; /** * {@link PlotController} for displaying many Http requests in the graph. * * @author <NAME> * */ public class HttpTimerPlotController extends AbstractTimerDataPlotController<HttpTimerData> { /** * {@link IAggregator}. */ private static final IAggregator<HttpTimerData> AGGREGATOR = new SimpleHttpAggregator(); /** * Templates that will be used for data display. Every template is one line in line chart. */ private List<HttpTimerData> templates; /** * List of {@link RegExAggregatedHttpTimerData} if regular expression is defined. */ private List<RegExAggregatedHttpTimerData> regExTemplates; /** * If true tag values from templates will be used in plotting. Otherwise URI is used. */ private boolean plotByTagValue = false; /** * If true than regular expression transformation will be performed on the template URIs. */ private boolean regExTransformation = false; /** * {@link IHttpTimerDataAccessService}. */ private IHttpTimerDataAccessService dataAccessService; /** * List of displayed data. */ List<HttpTimerData> displayedData = Collections.emptyList(); /** * Date to display data to. */ Date toDate = new Date(0); /** * Date to display data from. */ Date fromDate = new Date(Long.MAX_VALUE); /** * Date that mark the last displayed data on the graph. */ Date latestDataDate = new Date(0); /** * {@inheritDoc} */ @Override public void setInputDefinition(InputDefinition inputDefinition) { super.setInputDefinition(inputDefinition); if (inputDefinition.hasInputDefinitionExtra(InputDefinitionExtrasMarkerFactory.HTTP_CHARTING_EXTRAS_MARKER)) { HttpChartingInputDefinitionExtra inputDefinitionExtra = inputDefinition.getInputDefinitionExtra(InputDefinitionExtrasMarkerFactory.HTTP_CHARTING_EXTRAS_MARKER); templates = inputDefinitionExtra.getTemplates(); plotByTagValue = inputDefinitionExtra.isPlotByTagValue(); regExTransformation = inputDefinitionExtra.isRegExTransformation(); if (regExTransformation) { regExTemplates = inputDefinitionExtra.getRegExTemplates(); } } dataAccessService = inputDefinition.getRepositoryDefinition().getHttpTimerDataAccessService(); } /** * {@inheritDoc} */ @Override public boolean showLegend() { return templates.size() > 1; } /** * {@inheritDoc} */ @Override public void update(Date from, Date to) { // complete load if we have no data, or wanted time range is completely outside the current boolean completeLoad = CollectionUtils.isEmpty(displayedData) || fromDate.after(to) || toDate.before(from); // left append if currently displayed from date is after the new from date boolean leftAppend = fromDate.after(from); // right append if the currently displayed to date is before new to date or the date of the // last data is before new date boolean rightAppend = toDate.before(to) || latestDataDate.before(to); if (completeLoad) { List<HttpTimerData> httpTimerDatas = dataAccessService.getChartingHttpTimerDataFromDateToDate(templates, from, to, plotByTagValue); if (CollectionUtils.isNotEmpty(httpTimerDatas)) { fromDate = (Date) from.clone(); toDate = (Date) to.clone(); } displayedData = httpTimerDatas; } else { if (rightAppend) { Date startingFrom = new Date(latestDataDate.getTime() + 1); List<HttpTimerData> httpTimerDatas = dataAccessService.getChartingHttpTimerDataFromDateToDate(templates, startingFrom, to, plotByTagValue); if (CollectionUtils.isNotEmpty(httpTimerDatas)) { displayedData.addAll(httpTimerDatas); toDate = (Date) to.clone(); } } if (leftAppend) { Date endingTo = new Date(fromDate.getTime() - 1); List<HttpTimerData> httpTimerDatas = dataAccessService.getChartingHttpTimerDataFromDateToDate(templates, from, endingTo, plotByTagValue); if (CollectionUtils.isNotEmpty(httpTimerDatas)) { displayedData.addAll(0, httpTimerDatas); fromDate = (Date) from.clone(); } } } // update the last displayed data if (CollectionUtils.isNotEmpty(displayedData)) { latestDataDate = new Date(displayedData.get(displayedData.size() - 1).getTimeStamp().getTime()); } Map<Object, List<HttpTimerData>> map = new HashMap<>(); for (HttpTimerData data : displayedData) { HttpTimerData template = findTemplateForData(data); if (null == template) { continue; } Object seriesKey = getSeriesKey(template); List<HttpTimerData> list = map.get(seriesKey); if (null == list) { list = new ArrayList<>(); map.put(seriesKey, list); } list.add(data); } for (Entry<Object, List<HttpTimerData>> entry : map.entrySet()) { entry.setValue(adjustSamplingRate(entry.getValue(), from, to, AGGREGATOR)); } final Map<Object, List<HttpTimerData>> finalMap = map; // update plots in UI thread Display.getDefault().asyncExec(new Runnable() { @Override public void run() { setDurationPlotData(finalMap); setCountPlotData(finalMap); } }); } /** * Finds matching template for the given {@link HttpTimerData} based on if regular expression * transformation is active or not. * * @param httpTimerData * Data to find matching template. * @return Matching template of <code>null</code> if one can not be found. */ private HttpTimerData findTemplateForData(HttpTimerData httpTimerData) { if (regExTransformation) { for (RegExAggregatedHttpTimerData regExTemplate : regExTemplates) { if (HttpTimerData.REQUEST_METHOD_MULTIPLE.equals(regExTemplate.getHttpInfo().getRequestMethod()) || Objects.equals(regExTemplate.getHttpInfo().getRequestMethod(), httpTimerData.getHttpInfo().getRequestMethod())) { if (null != findTemplateForUriData(httpTimerData, regExTemplate.getAggregatedDataList(), true)) { return regExTemplate; } } } } else if (plotByTagValue) { return findTemplateForTagData(httpTimerData, templates); } else { return findTemplateForUriData(httpTimerData, templates, false); } return null; } /** * Finds matching template for the given {@link HttpTimerData} by uri. * * @param httpTimerData * Data to find matching template. * @param templates * List of templates to search. * @param checkOnlyUri * If matching should be done only by uri. * @return Matching template of <code>null</code> if one can not be found. */ private HttpTimerData findTemplateForUriData(HttpTimerData httpTimerData, List<HttpTimerData> templates, boolean checkOnlyUri) { for (HttpTimerData template : templates) { if (Objects.equals(template.getHttpInfo().getUri(), httpTimerData.getHttpInfo().getUri())) { if (!checkOnlyUri && HttpTimerData.REQUEST_METHOD_MULTIPLE.equals(template.getHttpInfo().getRequestMethod())) { return template; } else if (Objects.equals(template.getHttpInfo().getRequestMethod(), httpTimerData.getHttpInfo().getRequestMethod())) { return template; } } } return null; } /** * Finds matching template for the given {@link HttpTimerData} by tag value. * * @param httpTimerData * Data to find matching template. * @param templates * List of templates to search. * @return Matching template of <code>null</code> if one can not be found. */ private HttpTimerData findTemplateForTagData(HttpTimerData httpTimerData, List<HttpTimerData> templates) { for (HttpTimerData template : templates) { if (Objects.equals(template.getHttpInfo().getInspectItTaggingHeaderValue(), httpTimerData.getHttpInfo().getInspectItTaggingHeaderValue())) { if (HttpTimerData.REQUEST_METHOD_MULTIPLE.equals(template.getHttpInfo().getRequestMethod()) || Objects.equals(template.getHttpInfo().getRequestMethod(), httpTimerData.getHttpInfo().getRequestMethod())) { return template; } } } return null; } /** * Returns the series key for the {@link HttpTimerData} object. * * @param httpTimerData * {@link HttpTimerData}. * @return Key used to initialize the series and later on compare which series data should be * added to. */ @Override protected Comparable<?> getSeriesKey(HttpTimerData httpTimerData) { if (regExTransformation && (httpTimerData instanceof RegExAggregatedHttpTimerData)) { return "Transformed URI: " + ((RegExAggregatedHttpTimerData) httpTimerData).getTransformedUri() + " [" + httpTimerData.getHttpInfo().getRequestMethod() + "]"; } else { if (plotByTagValue) { return "Tag: " + httpTimerData.getHttpInfo().getInspectItTaggingHeaderValue() + " [" + httpTimerData.getHttpInfo().getRequestMethod() + "]"; } else { return "URI: " + httpTimerData.getHttpInfo().getUri() + " [" + httpTimerData.getHttpInfo().getRequestMethod() + "]"; } } } /** * {@inheritDoc} */ @Override protected List<HttpTimerData> getTemplates() { if (regExTransformation) { return new ArrayList<HttpTimerData>(regExTemplates); } else { return templates; } } /** * Simple {@link IAggregator} to use for {@link HttpTimerData} aggregation, since we separate * the data correctly before aggregation. * * @author <NAME> * */ private static class SimpleHttpAggregator implements IAggregator<HttpTimerData> { /** * {@inheritDoc} */ @Override public void aggregate(IAggregatedData<HttpTimerData> aggregatedObject, HttpTimerData objectToAdd) { aggregatedObject.aggregate(objectToAdd); } /** * {@inheritDoc} */ @Override public IAggregatedData<HttpTimerData> getClone(HttpTimerData object) { return new AggregatedHttpTimerData(); } /** * {@inheritDoc} */ @Override public Object getAggregationKey(HttpTimerData object) { return 1; } } }
3,705
2,436
package com.ss.android.ugc.bytex.common.utils; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FrameNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LineNumberNode; import org.objectweb.asm.tree.LookupSwitchInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MultiANewArrayInsnNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class OpcodesUtils { private static Map<Integer, String> OPCODE_MAP; static { Map<Integer, String> map = new HashMap<>(); map.put(0, "NOP"); map.put(1, "ACONST_NULL"); map.put(2, "ICONST_M1"); map.put(3, "ICONST_0"); map.put(4, "ICONST_1"); map.put(5, "ICONST_2"); map.put(6, "ICONST_3"); map.put(7, "ICONST_4"); map.put(8, "ICONST_5"); map.put(9, "LCONST_0"); map.put(10, "LCONST_1"); map.put(11, "FCONST_0"); map.put(12, "FCONST_1"); map.put(13, "FCONST_2"); map.put(14, "DCONST_0"); map.put(15, "DCONST_1"); map.put(16, "BIPUSH"); map.put(17, "SIPUSH"); map.put(18, "LDC"); map.put(19, "LDC_W"); map.put(20, "LDC2_W"); map.put(21, "ILOAD"); map.put(22, "LLOAD"); map.put(23, "FLOAD"); map.put(24, "DLOAD"); map.put(25, "ALOAD"); map.put(26, "ILOAD_0"); map.put(27, "ILOAD_1"); map.put(28, "ILOAD_2"); map.put(29, "ILOAD_3"); map.put(30, "LLOAD_0"); map.put(31, "LLOAD_1"); map.put(32, "LLOAD_2"); map.put(33, "LLOAD_3"); map.put(34, "FLOAD_0"); map.put(35, "FLOAD_1"); map.put(36, "FLOAD_2"); map.put(37, "FLOAD_3"); map.put(38, "DLOAD_0"); map.put(39, "DLOAD_1"); map.put(40, "DLOAD_2"); map.put(41, "DLOAD_3"); map.put(42, "ALOAD_0"); map.put(43, "ALOAD_1"); map.put(44, "ALOAD_2"); map.put(45, "ALOAD_3"); map.put(46, "IALOAD"); map.put(47, "LALOAD"); map.put(48, "FALOAD"); map.put(49, "DALOAD"); map.put(50, "AALOAD"); map.put(51, "BALOAD"); map.put(52, "CALOAD"); map.put(53, "SALOAD"); map.put(54, "ISTORE"); map.put(55, "LSTORE"); map.put(56, "FSTORE"); map.put(57, "DSTORE"); map.put(58, "ASTORE"); map.put(59, "ISTORE_0"); map.put(60, "ISTORE_1"); map.put(61, "ISTORE_2"); map.put(62, "ISTORE_3"); map.put(63, "LSTORE_0"); map.put(64, "LSTORE_1"); map.put(65, "LSTORE_2"); map.put(66, "LSTORE_3"); map.put(67, "FSTORE_0"); map.put(68, "FSTORE_1"); map.put(69, "FSTORE_2"); map.put(70, "FSTORE_3"); map.put(71, "DSTORE_0"); map.put(72, "DSTORE_1"); map.put(73, "DSTORE_2"); map.put(74, "DSTORE_3"); map.put(75, "ASTORE_0"); map.put(76, "ASTORE_1"); map.put(77, "ASTORE_2"); map.put(78, "ASTORE_3"); map.put(79, "IASTORE"); map.put(80, "LASTORE"); map.put(81, "FASTORE"); map.put(82, "DASTORE"); map.put(83, "AASTORE"); map.put(84, "BASTORE"); map.put(85, "CASTORE"); map.put(86, "SASTORE"); map.put(87, "POP"); map.put(88, "POP2"); map.put(89, "DUP"); map.put(90, "DUP_X1"); map.put(91, "DUP_X2"); map.put(92, "DUP2"); map.put(93, "DUP2_X1"); map.put(94, "DUP2_X2"); map.put(95, "SWAP"); map.put(96, "IADD"); map.put(97, "LADD"); map.put(98, "FADD"); map.put(99, "DADD"); map.put(100, "ISUB"); map.put(101, "LSUB"); map.put(102, "FSUB"); map.put(103, "DSUB"); map.put(104, "IMUL"); map.put(105, "LMUL"); map.put(106, "FMUL"); map.put(107, "DMUL"); map.put(108, "IDIV"); map.put(109, "LDIV"); map.put(110, "FDIV"); map.put(111, "DDIV"); map.put(112, "IREM"); map.put(113, "LREM"); map.put(114, "FREM"); map.put(115, "DREM"); map.put(116, "INEG"); map.put(117, "LNEG"); map.put(118, "FNEG"); map.put(119, "DNEG"); map.put(120, "ISHL"); map.put(121, "LSHL"); map.put(122, "ISHR"); map.put(123, "LSHR"); map.put(124, "IUSHR"); map.put(125, "LUSHR"); map.put(126, "IAND"); map.put(127, "LAND"); map.put(128, "IOR"); map.put(129, "LOR"); map.put(130, "IXOR"); map.put(131, "LXOR"); map.put(132, "IINC"); map.put(133, "I2L"); map.put(134, "I2F"); map.put(135, "I2D"); map.put(136, "L2I"); map.put(137, "L2F"); map.put(138, "L2D"); map.put(139, "F2I"); map.put(140, "F2L"); map.put(141, "F2D"); map.put(142, "D2I"); map.put(143, "D2L"); map.put(144, "D2F"); map.put(145, "I2B"); map.put(146, "I2C"); map.put(147, "I2S"); map.put(148, "LCMP"); map.put(149, "FCMPL"); map.put(150, "FCMPG"); map.put(151, "DCMPL"); map.put(152, "DCMPG"); map.put(153, "IFEQ"); map.put(154, "IFNE"); map.put(155, "IFLT"); map.put(156, "IFGE"); map.put(157, "IFGT"); map.put(158, "IFLE"); map.put(159, "IF_ICMPEQ"); map.put(160, "IF_ICMPNE"); map.put(161, "IF_ICMPLT"); map.put(162, "IF_ICMPGE"); map.put(163, "IF_ICMPGT"); map.put(164, "IF_ICMPLE"); map.put(165, "IF_ACMPEQ"); map.put(166, "IF_ACMPNE"); map.put(167, "GOTO"); map.put(168, "JSR"); map.put(169, "RET"); map.put(170, "TABLESWITCH"); map.put(171, "LOOKUPSWITCH"); map.put(172, "IRETURN"); map.put(173, "LRETURN"); map.put(174, "FRETURN"); map.put(175, "DRETURN"); map.put(176, "ARETURN"); map.put(177, "RETURN"); map.put(178, "GETSTATIC"); map.put(179, "PUTSTATIC"); map.put(180, "GETFIELD"); map.put(181, "PUTFIELD"); map.put(182, "INVOKEVIRTUAL"); map.put(183, "INVOKESPECIAL"); map.put(184, "INVOKESTATIC"); map.put(185, "INVOKEINTERFACE"); map.put(186, "INVOKEDYNAMIC"); map.put(187, "NEW"); map.put(188, "NEWARRAY"); map.put(189, "ANEWARRAY"); map.put(190, "ARRAYLENGTH"); map.put(191, "ATHROW"); map.put(192, "CHECKCAST"); map.put(193, "INSTANCEOF"); map.put(194, "MONITORENTER"); map.put(195, "MONITOREXIT"); map.put(196, "WIDE"); map.put(197, "MULTIANEWARRAY"); map.put(198, "IFNULL"); map.put(199, "IFNONNULL"); map.put(200, "GOTO_W"); map.put(201, "JSR_W"); OPCODE_MAP = Collections.unmodifiableMap(map); } public static String getOpcodeString(int code) { String opcodeString = OPCODE_MAP.get(code); if (opcodeString == null || "".equals(opcodeString.trim())) { return String.valueOf(code); } return opcodeString; } public static String covertToString(AbstractInsnNode node) { if (node == null) { return null; } final String DIVIDER = " "; StringBuilder stringBuilder = new StringBuilder(); if (node instanceof MethodInsnNode) { MethodInsnNode realInsnNode = (MethodInsnNode) node; stringBuilder. append(getOpcodeString(node.getOpcode())). append(DIVIDER).append(realInsnNode.owner). append(DIVIDER).append(realInsnNode.name). append(DIVIDER).append(realInsnNode.desc). append(DIVIDER).append(realInsnNode.itf); } else if (node instanceof FieldInsnNode) { FieldInsnNode realInsnNode = (FieldInsnNode) node; stringBuilder. append(getOpcodeString(node.getOpcode())). append(DIVIDER).append(realInsnNode.owner). append(DIVIDER).append(realInsnNode.name). append(DIVIDER).append(realInsnNode.desc); } else if (node instanceof TableSwitchInsnNode) { TableSwitchInsnNode realInsnNode = (TableSwitchInsnNode) node; stringBuilder. append(getOpcodeString(node.getOpcode())). append(DIVIDER).append(realInsnNode.min). append(DIVIDER).append(realInsnNode.max). append(DIVIDER).append(covertToString(realInsnNode.dflt)). append(DIVIDER).append("{"); for (Object label : realInsnNode.labels) { stringBuilder.append(covertToString((AbstractInsnNode) label)).append(";"); } stringBuilder.append("}"); } else if (node instanceof LineNumberNode) { LineNumberNode realInsnNode = (LineNumberNode) node; stringBuilder. append("LINENUMBER"). append(DIVIDER).append(realInsnNode.line). append(DIVIDER).append(covertToString(realInsnNode.start)); } else if (node instanceof IincInsnNode) { IincInsnNode realInsnNode = (IincInsnNode) node; stringBuilder. append(getOpcodeString(node.getOpcode())). append(DIVIDER).append(realInsnNode.var). append(DIVIDER).append(realInsnNode.incr); } else if (node instanceof IntInsnNode) { IntInsnNode realInsnNode = (IntInsnNode) node; stringBuilder. append(getOpcodeString(realInsnNode.getOpcode())). append(DIVIDER).append(realInsnNode.operand); } else if (node instanceof LabelNode) { LabelNode realInsnNode = (LabelNode) node; String position; try { position = String.valueOf(realInsnNode.getLabel().getOffset()); } catch (Exception ignore) { position = Integer.toHexString(realInsnNode.hashCode()); } stringBuilder. append("L").append(position); } else if (node instanceof MultiANewArrayInsnNode) { MultiANewArrayInsnNode realInsnNode = (MultiANewArrayInsnNode) node; stringBuilder. append(getOpcodeString(node.getOpcode())). append(DIVIDER).append(realInsnNode.desc). append(DIVIDER).append(realInsnNode.dims); } else if (node instanceof LdcInsnNode) { LdcInsnNode realInsnNode = (LdcInsnNode) node; stringBuilder. append(getOpcodeString(node.getOpcode())). append(DIVIDER).append(realInsnNode.cst); } else if (node instanceof TypeInsnNode) { TypeInsnNode realInsnNode = (TypeInsnNode) node; stringBuilder. append(getOpcodeString(realInsnNode.getOpcode())). append(DIVIDER).append(realInsnNode.desc); } else if (node instanceof VarInsnNode) { VarInsnNode realInsnNode = (VarInsnNode) node; stringBuilder. append(getOpcodeString(realInsnNode.getOpcode())). append(DIVIDER).append(realInsnNode.var); } else if (node instanceof InvokeDynamicInsnNode) { InvokeDynamicInsnNode realInsnNode = (InvokeDynamicInsnNode) node; stringBuilder. append(getOpcodeString(node.getOpcode())). append(DIVIDER).append(realInsnNode.name). append(DIVIDER).append(realInsnNode.desc). append(DIVIDER).append(realInsnNode.bsm.getOwner()).append(".").append(realInsnNode.bsm.getName()) .append("("); for (Object bsmArg : realInsnNode.bsmArgs) { stringBuilder.append(bsmArg).append(","); } stringBuilder.append(")"); } else if (node instanceof FrameNode) { FrameNode realInsnNode = (FrameNode) node; switch (realInsnNode.type) { case Opcodes.F_NEW: case Opcodes.F_FULL: stringBuilder.append(realInsnNode.type == Opcodes.F_NEW ? "F_NEW" : "F_FULL") .append(DIVIDER).append(realInsnNode.local) .append(DIVIDER).append(realInsnNode.stack); break; case Opcodes.F_APPEND: stringBuilder.append("F_APPEND") .append(DIVIDER).append(realInsnNode.local); break; case Opcodes.F_CHOP: stringBuilder.append("F_CHOP") .append(DIVIDER).append(realInsnNode.local); break; case Opcodes.F_SAME: stringBuilder.append("F_SAME"); break; case Opcodes.F_SAME1: stringBuilder.append("F_SAME1") .append(DIVIDER).append(realInsnNode.stack); break; } } else if (node instanceof JumpInsnNode) { JumpInsnNode realInsnNode = (JumpInsnNode) node; stringBuilder. append(getOpcodeString(realInsnNode.getOpcode())). append(DIVIDER).append(covertToString(realInsnNode.label)); } else if (node instanceof InsnNode) { InsnNode realInsnNode = (InsnNode) node; stringBuilder. append(getOpcodeString(realInsnNode.getOpcode())); } else if (node instanceof LookupSwitchInsnNode) { LookupSwitchInsnNode realInsnNode = (LookupSwitchInsnNode) node; stringBuilder. append(getOpcodeString(realInsnNode.getOpcode())). append(DIVIDER).append(covertToString(realInsnNode.dflt)). append(DIVIDER).append(realInsnNode.keys). append(DIVIDER).append("["); for (Object label : realInsnNode.labels) { stringBuilder.append(covertToString((AbstractInsnNode) label)).append(";"); } stringBuilder.append("]"); } else { stringBuilder.append("unknow insnNode ").append(getOpcodeString(node.getOpcode())); } return stringBuilder.toString(); } }
8,282
5,169
{ "name": "LLLocation", "module_name": "LLLocation", "version": "0.0.1", "summary": "Simple get location on iOS device. Write in swift4.", "homepage": "https://github.com/Kila2/LLLocation", "license": "MIT", "authors": { "Kila2": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "source": { "git": "https://github.com/Kila2/LLLocation.git", "tag": "0.0.1" }, "source_files": "LLLocation/**/*.{h,swift}", "pushed_with_swift_version": "4.0" }
219
1,694
<reponame>CrackerCat/iWeChat<filename>header6.6.1/WXMediaMessage.h // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> @class NSData, NSString; @interface WXMediaMessage : NSObject { NSString *title; NSString *description; NSData *thumbData; NSString *mediaTagName; id mediaObject; NSString *messageExt; NSString *messageAction; } + (id)message; @property(retain, nonatomic) NSString *messageAction; // @synthesize messageAction; @property(retain, nonatomic) NSString *messageExt; // @synthesize messageExt; @property(retain, nonatomic) id mediaObject; // @synthesize mediaObject; @property(retain, nonatomic) NSString *mediaTagName; // @synthesize mediaTagName; @property(retain, nonatomic) NSData *thumbData; // @synthesize thumbData; @property(retain, nonatomic) NSString *description; // @synthesize description; @property(retain, nonatomic) NSString *title; // @synthesize title; - (void).cxx_destruct; - (void)setThumbImage:(id)arg1; - (id)init; @end
418
1,998
<filename>samples/csharp_dotnetcore/63.twilio-adapter/appsettings.json { "TwilioNumber": "", "TwilioAccountSid": "", "TwilioAuthToken": "", "TwilioValidationUrl": "" }
75
2,151
<filename>tests/unittests/shared/imc/double_nacl_close_test.c /* * Copyright 2010 The Native Client 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 <stdio.h> #include "native_client/src/shared/imc/nacl_imc_c.h" #include "native_client/src/shared/platform/nacl_error.h" /* Writes the last error message to the standard error. */ static void failWithErrno(const char* message) { char buffer[256]; if (0 == NaClGetLastErrorString(buffer, sizeof(buffer))) { fprintf(stderr, "%s: %s", message, buffer); } exit(EXIT_FAILURE); } int main(int argc, char* argv[]) { int result; NaClHandle pair[2]; UNREFERENCED_PARAMETER(argc); UNREFERENCED_PARAMETER(argv); if (0 != NaClSocketPair(pair)) { failWithErrno("SocketPair"); } if (0 != NaClClose(pair[0])) { failWithErrno("NaClClose"); } if (0 != NaClClose(pair[1])) { failWithErrno("NaClClose"); } /* Checking the double close. It should return -1. */ result = NaClClose(pair[0]); if (-1 != result) { fprintf(stderr, "Double NaClClose returned %d, but -1 expected\n", result); exit(EXIT_FAILURE); } return 0; }
469
474
<gh_stars>100-1000 // // QNTranscodeViewController.h // ShortVideo // // Created by hxiongan on 2019/4/15. // Copyright © 2019年 ahx. All rights reserved. // #import "QNBaseViewController.h" #import <Photos/Photos.h> @interface QNTranscodeViewController : QNBaseViewController @property (nonatomic, strong) PHAsset *phAsset; @property (nonatomic, strong) NSURL *sourceURL; @end
139
5,079
<filename>tests/test_django_settings_module.py """Tests which check the various ways you can set DJANGO_SETTINGS_MODULE If these tests fail you probably forgot to run "python setup.py develop". """ import django import pytest BARE_SETTINGS = """ # At least one database must be configured DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' }, } SECRET_KEY = 'foobar' """ def test_ds_ini(testdir, monkeypatch): monkeypatch.delenv("DJANGO_SETTINGS_MODULE") testdir.makeini( """ [pytest] DJANGO_SETTINGS_MODULE = tpkg.settings_ini """ ) pkg = testdir.mkpydir("tpkg") pkg.join("settings_ini.py").write(BARE_SETTINGS) testdir.makepyfile( """ import os def test_ds(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_ini' """ ) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines([ "django: settings: tpkg.settings_ini (from ini)", "*= 1 passed in *", ]) assert result.ret == 0 def test_ds_env(testdir, monkeypatch): monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "tpkg.settings_env") pkg = testdir.mkpydir("tpkg") settings = pkg.join("settings_env.py") settings.write(BARE_SETTINGS) testdir.makepyfile( """ import os def test_settings(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_env' """ ) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines([ "django: settings: tpkg.settings_env (from env)", "*= 1 passed in *", ]) def test_ds_option(testdir, monkeypatch): monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "DO_NOT_USE_env") testdir.makeini( """ [pytest] DJANGO_SETTINGS_MODULE = DO_NOT_USE_ini """ ) pkg = testdir.mkpydir("tpkg") settings = pkg.join("settings_opt.py") settings.write(BARE_SETTINGS) testdir.makepyfile( """ import os def test_ds(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_opt' """ ) result = testdir.runpytest_subprocess("--ds=tpkg.settings_opt") result.stdout.fnmatch_lines([ "django: settings: tpkg.settings_opt (from option)", "*= 1 passed in *", ]) def test_ds_env_override_ini(testdir, monkeypatch): "DSM env should override ini." monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "tpkg.settings_env") testdir.makeini( """\ [pytest] DJANGO_SETTINGS_MODULE = DO_NOT_USE_ini """ ) pkg = testdir.mkpydir("tpkg") settings = pkg.join("settings_env.py") settings.write(BARE_SETTINGS) testdir.makepyfile( """ import os def test_ds(): assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_env' """ ) result = testdir.runpytest_subprocess() assert result.parseoutcomes()["passed"] == 1 assert result.ret == 0 def test_ds_non_existent(testdir, monkeypatch): """ Make sure we do not fail with INTERNALERROR if an incorrect DJANGO_SETTINGS_MODULE is given. """ monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "DOES_NOT_EXIST") testdir.makepyfile("def test_ds(): pass") result = testdir.runpytest_subprocess() result.stderr.fnmatch_lines(["*ImportError:*DOES_NOT_EXIST*"]) assert result.ret != 0 def test_ds_after_user_conftest(testdir, monkeypatch): """ Test that the settings module can be imported, after pytest has adjusted the sys.path. """ monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "settings_after_conftest") testdir.makepyfile("def test_ds(): pass") testdir.makepyfile(settings_after_conftest="SECRET_KEY='secret'") # testdir.makeconftest("import sys; print(sys.path)") result = testdir.runpytest_subprocess("-v") result.stdout.fnmatch_lines(["* 1 passed in*"]) assert result.ret == 0 def test_ds_in_pytest_configure(testdir, monkeypatch): monkeypatch.delenv("DJANGO_SETTINGS_MODULE") pkg = testdir.mkpydir("tpkg") settings = pkg.join("settings_ds.py") settings.write(BARE_SETTINGS) testdir.makeconftest( """ import os from django.conf import settings def pytest_configure(): if not settings.configured: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tpkg.settings_ds') """ ) testdir.makepyfile( """ def test_anything(): pass """ ) r = testdir.runpytest_subprocess() assert r.parseoutcomes()["passed"] == 1 assert r.ret == 0 def test_django_settings_configure(testdir, monkeypatch): """ Make sure Django can be configured without setting DJANGO_SETTINGS_MODULE altogether, relying on calling django.conf.settings.configure() and then invoking pytest. """ monkeypatch.delenv("DJANGO_SETTINGS_MODULE") p = testdir.makepyfile( run=""" from django.conf import settings settings.configure(SECRET_KEY='set from settings.configure()', DATABASES={'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' }}, INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes',]) import pytest pytest.main() """ ) testdir.makepyfile( """ import pytest from django.conf import settings from django.test.client import RequestFactory from django.test import TestCase from django.contrib.auth.models import User def test_access_to_setting(): assert settings.SECRET_KEY == 'set from settings.configure()' # This test requires Django to be properly configured to be run def test_rf(rf): assert isinstance(rf, RequestFactory) # This tests that pytest-django actually configures the database # according to the settings above class ATestCase(TestCase): def test_user_count(self): assert User.objects.count() == 0 @pytest.mark.django_db def test_user_count(): assert User.objects.count() == 0 """ ) result = testdir.runpython(p) result.stdout.fnmatch_lines(["* 4 passed in*"]) def test_settings_in_hook(testdir, monkeypatch): monkeypatch.delenv("DJANGO_SETTINGS_MODULE") testdir.makeconftest( """ from django.conf import settings def pytest_configure(): settings.configure(SECRET_KEY='set from pytest_configure', DATABASES={'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes',]) """ ) testdir.makepyfile( """ import pytest from django.conf import settings from django.contrib.auth.models import User def test_access_to_setting(): assert settings.SECRET_KEY == 'set from pytest_configure' @pytest.mark.django_db def test_user_count(): assert User.objects.count() == 0 """ ) r = testdir.runpytest_subprocess() assert r.ret == 0 def test_django_not_loaded_without_settings(testdir, monkeypatch): """ Make sure Django is not imported at all if no Django settings is specified. """ monkeypatch.delenv("DJANGO_SETTINGS_MODULE") testdir.makepyfile( """ import sys def test_settings(): assert 'django' not in sys.modules """ ) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines(["* 1 passed in*"]) assert result.ret == 0 def test_debug_false(testdir, monkeypatch): monkeypatch.delenv("DJANGO_SETTINGS_MODULE") testdir.makeconftest( """ from django.conf import settings def pytest_configure(): settings.configure(SECRET_KEY='set from pytest_configure', DEBUG=True, DATABASES={'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes',]) """ ) testdir.makepyfile( """ from django.conf import settings def test_debug_is_false(): assert settings.DEBUG is False """ ) r = testdir.runpytest_subprocess() assert r.ret == 0 @pytest.mark.skipif( not hasattr(django, "setup"), reason="This Django version does not support app loading", ) @pytest.mark.django_project( extra_settings=""" INSTALLED_APPS = [ 'tpkg.app.apps.TestApp', ] """ ) def test_django_setup_sequence(django_testdir): django_testdir.create_app_file( """ from django.apps import apps, AppConfig class TestApp(AppConfig): name = 'tpkg.app' def ready(self): try: populating = apps.loading except AttributeError: # Django < 2.0 populating = apps._lock.locked() print('READY(): populating=%r' % populating) """, "apps.py", ) django_testdir.create_app_file( """ from django.apps import apps try: populating = apps.loading except AttributeError: # Django < 2.0 populating = apps._lock.locked() print('IMPORT: populating=%r,ready=%r' % (populating, apps.ready)) SOME_THING = 1234 """, "models.py", ) django_testdir.create_app_file("", "__init__.py") django_testdir.makepyfile( """ from django.apps import apps from tpkg.app.models import SOME_THING def test_anything(): try: populating = apps.loading except AttributeError: # Django < 2.0 populating = apps._lock.locked() print('TEST: populating=%r,ready=%r' % (populating, apps.ready)) """ ) result = django_testdir.runpytest_subprocess("-s", "--tb=line") result.stdout.fnmatch_lines(["*IMPORT: populating=True,ready=False*"]) result.stdout.fnmatch_lines(["*READY(): populating=True*"]) if django.VERSION < (2, 0): result.stdout.fnmatch_lines(["*TEST: populating=False,ready=True*"]) else: result.stdout.fnmatch_lines(["*TEST: populating=True,ready=True*"]) assert result.ret == 0 def test_no_ds_but_django_imported(testdir, monkeypatch): """pytest-django should not bail out, if "django" has been imported somewhere, e.g. via pytest-splinter.""" monkeypatch.delenv("DJANGO_SETTINGS_MODULE") testdir.makepyfile( """ import os import django from pytest_django.lazy_django import django_settings_is_configured def test_django_settings_is_configured(): assert django_settings_is_configured() is False def test_env(): assert 'DJANGO_SETTINGS_MODULE' not in os.environ def test_cfg(pytestconfig): assert pytestconfig.option.ds is None """ ) r = testdir.runpytest_subprocess("-s") assert r.ret == 0 def test_no_ds_but_django_conf_imported(testdir, monkeypatch): """pytest-django should not bail out, if "django.conf" has been imported somewhere, e.g. via hypothesis (#599).""" monkeypatch.delenv("DJANGO_SETTINGS_MODULE") testdir.makepyfile( """ import os import sys # line copied from hypothesis/extras/django.py from django.conf import settings as django_settings # Don't let pytest poke into this object, generating a # django.core.exceptions.ImproperlyConfigured del django_settings from pytest_django.lazy_django import django_settings_is_configured def test_django_settings_is_configured(): assert django_settings_is_configured() is False def test_django_conf_is_imported(): assert 'django.conf' in sys.modules def test_env(): assert 'DJANGO_SETTINGS_MODULE' not in os.environ def test_cfg(pytestconfig): assert pytestconfig.option.ds is None """ ) r = testdir.runpytest_subprocess("-s") assert r.ret == 0 def test_no_django_settings_but_django_imported(testdir, monkeypatch): """Make sure we do not crash when Django happens to be imported, but settings is not properly configured""" monkeypatch.delenv("DJANGO_SETTINGS_MODULE") testdir.makeconftest("import django") r = testdir.runpytest_subprocess("--help") assert r.ret == 0
6,176
455
#!/foo/python import os import fileinput import json for line in fileinput.input(): input_data = json.loads(line) if input_data['message']: print(json.dumps({'env': os.environ['PT_message'], 'stdin': input_data['message']}))
91
3,428
<reponame>ghalimi/stdlib<gh_stars>1000+ {"id":"01510","group":"easy-ham-1","checksum":{"type":"MD5","value":"08454da046a34bf7a209a3f3957066fa"},"text":"From <EMAIL> Fri Sep 20 11:28:07 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: <EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [1172.16.17.32])\n\tby jmason.org (Postfix) with ESMTP id 2948016F16\n\tfor <jm@localhost>; Fri, 20 Sep 2002 11:28:06 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Fri, 20 Sep 2002 11:28:06 +0100 (IST)\nReceived: from proton.pathname.com\n (adsl-216-103-211-240.dsl.snfc21.pacbell.net [216.103.211.240]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g8JLUVC04528 for\n <<EMAIL>>; Thu, 19 Sep 2002 22:30:31 +0100\nReceived: from quinlan by proton.pathname.com with local (Exim 3.35 #1\n (Debian)) id 17s8t2-0003Io-00; Thu, 19 Sep 2002 14:31:00 -0700\nTo: <EMAIL>in.taint.org (<NAME>)\nCc: <NAME> <<EMAIL>>,\n\[email protected]\nSubject: Re: [SAdev] phew!\nReferences: <2<EMAIL>19113604.<EMAIL>>\nFrom: <NAME> <<EMAIL>>\nDate: 19 Sep 2002 14:31:00 -0700\nIn-Reply-To: <EMAIL>'s message of \"Thu, 19 Sep 2002 12:35:59 +0100\"\nMessage-Id: <<EMAIL>>\nX-Mailer: Gnus v5.7/Emacs 20.7\n\<EMAIL> (<NAME>) writes:\n\n> Yes -- 50% of the entire set for training and 50% for evaluation.\n\nOnce you've settled on the final method for any one release, why not\nuse 100% of the data for a final run?\n \nDan\n\n\n"}
658
2,151
<reponame>zipated/src // 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 REMOTING_IOS_FACADE_HOST_INFO_H_ #define REMOTING_IOS_FACADE_HOST_INFO_H_ #include <string> #include <vector> #include "base/time/time.h" #include "base/values.h" namespace remoting { enum HostStatus { kHostStatusOnline, kHostStatusOffline }; // |remoting::HostInfo| is an object containing the data from host list fetch // for transport in native code. struct HostInfo { HostInfo(); HostInfo(const HostInfo& other); ~HostInfo(); // Returns true if |host_info| is valid and initializes HostInfo. bool ParseHostInfo(const base::DictionaryValue& host_info); // Returns true if the chromoting host is ready to accept connections. bool IsReadyForConnection() const; std::string host_id; std::string host_jid; std::string host_name; std::string host_os; std::string host_os_version; std::string host_version; HostStatus status = kHostStatusOffline; std::string offline_reason; std::string public_key; base::Time updated_time; std::vector<std::string> token_url_patterns; }; } // namespace remoting #endif // REMOTING_IOS_FACADE_HOST_INFO_H_
420
353
<reponame>johannespitz/functionsimsearch #include <map> #include <fstream> #include <string> #include <vector> #include "disassembly/flowgraph.hpp" #include "disassembly/flowgraphwithinstructions.hpp" #include "third_party/json/src/json.hpp" // Copy constructor. Somewhat hideously expensive. FlowgraphWithInstructions::FlowgraphWithInstructions( const FlowgraphWithInstructions& original) : Flowgraph(original) { instructions_ = original.instructions_; } FlowgraphWithInstructions::FlowgraphWithInstructions() { } bool FlowgraphWithInstructions::AddInstructions(address node_address, const std::vector<Instruction>& instructions) { instructions_[node_address] = instructions; return true; } bool FlowgraphWithInstructions::ParseNodeJSON(const nlohmann::json& node) { if ((node.find("address") == node.end()) || (node.find("instructions") == node.end())) { return false; } uint64_t address = node["address"].get<uint64_t>(); std::vector<Instruction> instructions; for (const auto& instruction : node["instructions"]) { if (instruction.find("mnemonic") == instruction.end() || instruction.find("operands") == instruction.end()) { return false; } std::string mnemonic = instruction["mnemonic"].get<std::string>(); std::vector<std::string> operands; for (const auto& operand : instruction["operands"]) { operands.push_back(operand.get<std::string>()); } instructions.emplace_back(mnemonic, operands); } AddNode(address); AddInstructions(address, instructions); return true; } bool FlowgraphWithInstructions::ParseEdgeJSON(const nlohmann::json& edge) { if ((edge.find("source") == edge.end()) || (edge.find("destination") == edge.end())) { return false; } uint64_t source = edge["source"].get<uint64_t>(); uint64_t destination = edge["destination"].get<uint64_t>(); AddEdge(source, destination); return true; } bool FlowgraphWithInstructions::ParseJSON(const nlohmann::json& json_graph) { if ((json_graph.find("nodes") == json_graph.end()) || (json_graph.find("edges") == json_graph.end())) { return false; } for (const auto& node : json_graph["nodes"]) { if (ParseNodeJSON(node) == false) { return false; } } for (const auto& edge : json_graph["edges"]) { if (ParseEdgeJSON(edge) == false) { return false; } } return true; } bool FlowgraphWithInstructionsFromJSON(const char* json, FlowgraphWithInstructions* graph) { auto json_graph = nlohmann::json::parse(json); if ((json_graph.find("nodes") == json_graph.end()) || (json_graph.find("edges") == json_graph.end())) { return false; } return graph->ParseJSON(json_graph); } bool FlowgraphWithInstructionsFromJSONFile(const std::string& filename, FlowgraphWithInstructions* graph) { std::ifstream t(filename); std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); return FlowgraphWithInstructionsFromJSON(str.c_str(), graph); } std::string FlowgraphWithInstructions::GetDisassembly() const { std::stringstream output; // TODO(thomasdullien): The code takes the lowest address in a function as the // beginning address here. There has to be a better way? output << "\n[!] Function at " << std::hex << instructions_.begin()->first; for (const auto& block : instructions_) { output << "\t\tBlock at " << std::hex << block.first; output << " (" << std::dec << static_cast<size_t>(block.second.size()) << ")\n"; for (const auto& instruction : block.second) { output << "\t\t\t " << instruction.AsString() << "\n"; } } return output.str(); }
1,267
334
<gh_stars>100-1000 import pytest from starlite import ImproperlyConfiguredException, Starlite, get, post from starlite.exceptions import MethodNotAllowedException from starlite.routes import HTTPRoute @get(path="/") def my_get_handler() -> None: pass @post(path="/") def my_post_handler() -> None: pass @pytest.mark.asyncio # type: ignore[misc] async def test_http_route_raises_for_unsupported_method() -> None: route = HTTPRoute(path="/", route_handlers=[my_get_handler, my_post_handler]) with pytest.raises(MethodNotAllowedException): await route.handle(scope={"method": "DELETE"}, receive=lambda x: x, send=lambda x: x) # type: ignore def test_register_validation_duplicate_handlers_for_same_route_and_method() -> None: @get(path="/first") def first_route_handler() -> None: pass @get(path="/first") def second_route_handler() -> None: pass with pytest.raises(ImproperlyConfiguredException): Starlite(route_handlers=[first_route_handler, second_route_handler])
382
687
# Lint as: python3 # # Copyright 2020 The XLS 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. import os from typing import Tuple, Text from xls.common import check_simulator from xls.common import test_base from xls.dslx.python.interp_value import interp_value_from_ir_string from xls.fuzzer import sample_runner from xls.fuzzer.python import cpp_sample as sample # An IR function with a loop which runs for many iterations. LONG_LOOP_IR = """package long_loop fn body(i: bits[64], accum: bits[64]) -> bits[64] { ret one: bits[64] = literal(value=1) } fn main(x: bits[64]) -> bits[64] { zero: bits[64] = literal(value=0, id=1) ret result: bits[64] = counted_for(zero, trip_count=0xffff_ffff_ffff, stride=1, body=body, id=5) } """ def _read_file(dirname: Text, filename: Text) -> Text: """Returns the contents of the file in the given directory as a string.""" with open(os.path.join(dirname, filename), 'r') as f: return f.read() def _split_nonempty_lines(dirname: Text, filename: Text) -> Tuple[Text]: """Returns a tuple of the stripped non-empty lines in the file.""" return tuple( l.strip() for l in _read_file(dirname, filename).splitlines() if l) class SampleRunnerTest(test_base.TestCase): def _make_sample_dir(self): # Keep the directory around (no cleanup) if the test fails for easier # debugging. success = test_base.TempFileCleanup.SUCCESS # type: test_base.TempFileCleanup return self.create_tempdir(cleanup=success).full_path def test_interpret_dslx_single_value(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' runner.run( sample.Sample(dslx_text, sample.SampleOptions(convert_to_ir=False), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ]])) self.assertEqual( _read_file(sample_dir, 'sample.x.results').strip(), 'bits[8]:0x8e') def test_interpret_dslx_multiple_values(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' runner.run( sample.Sample(dslx_text, sample.SampleOptions(convert_to_ir=False), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ], [ interp_value_from_ir_string('bits[8]:222'), interp_value_from_ir_string('bits[8]:240') ]])) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.x.results'), ['bits[8]:0x8e', 'bits[8]:0xce']) def test_interpret_invalid_dslx(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'syntaxerror!!! fn main(x: u8, y: u8) -> u8 { x + y }' with self.assertRaises(sample_runner.SampleError): runner.run( sample.Sample(dslx_text, sample.SampleOptions(convert_to_ir=False), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ]])) # Verify the exception text is written out to file. self.assertIn('Expected start of top-level construct', _read_file(sample_dir, 'exception.txt')) def test_dslx_to_ir(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' runner.run( sample.Sample(dslx_text, sample.SampleOptions(optimize_ir=False))) self.assertIn('package sample', _read_file(sample_dir, 'sample.ir')) def test_evaluate_ir(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' runner.run( sample.Sample(dslx_text, sample.SampleOptions(optimize_ir=False), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ], [ interp_value_from_ir_string('bits[8]:222'), interp_value_from_ir_string('bits[8]:240') ]])) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.x.results'), ['bits[8]:0x8e', 'bits[8]:0xce']) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.ir.results'), ['bits[8]:0x8e', 'bits[8]:0xce']) def test_evaluate_ir_wide(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: bits[100], y: bits[100]) -> bits[100] { x + y }' runner.run( sample.Sample( dslx_text, sample.SampleOptions(optimize_ir=False), [[ interp_value_from_ir_string('bits[100]:{0:#x}'.format(10**30)), interp_value_from_ir_string('bits[100]:{0:#x}'.format(10**30)), ], [ interp_value_from_ir_string('bits[100]:{0:#x}'.format(2**80)), interp_value_from_ir_string('bits[100]:{0:#x}'.format(2**81)), ]])) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.x.results'), [ 'bits[100]:0x9_3e59_39a0_8ce9_dbd4_8000_0000', 'bits[100]:0x3_0000_0000_0000_0000_0000' ]) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.ir.results'), [ 'bits[100]:0x9_3e59_39a0_8ce9_dbd4_8000_0000', 'bits[100]:0x3_0000_0000_0000_0000_0000' ]) def test_interpret_mixed_signedness(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: s8) -> s8 { (x as s8) + y }' runner.run( sample.Sample(dslx_text, sample.SampleOptions(optimize_ir=False), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100').to_signed() ]])) self.assertEqual( _read_file(sample_dir, 'sample.x.results').strip(), 'bits[8]:0x8e') def test_interpret_mixed_signedness_unsigned_inputs(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: s8) -> s8 { (x as s8) + y }' runner.run( sample.Sample(dslx_text, sample.SampleOptions(optimize_ir=False), sample.parse_args_batch('bits[8]:0xb0; bits[8]:0x0a'))) self.assertEqual( _read_file(sample_dir, 'sample.x.results').strip(), 'bits[8]:0xba') def test_evaluate_ir_miscompare_single_result(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' runner._evaluate_ir = lambda *args: (interp_value_from_ir_string('bits[8]:1' ),) with self.assertRaises(sample_runner.SampleError) as e: runner.run( sample.Sample(dslx_text, sample.SampleOptions(optimize_ir=False), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ]])) self.assertIn( 'Result miscompare for sample 0:\n' 'args: bits[8]:0x2a; bits[8]:0x64\n' 'evaluated unopt IR (JIT), evaluated unopt IR (interpreter) =\n' ' bits[8]:0x1\n' 'interpreted DSLX =\n' ' bits[8]:0x8e', str(e.exception)) self.assertIn('Result miscompare for sample 0', _read_file(sample_dir, 'exception.txt')) def test_evaluate_ir_miscompare_multiple_results(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' results = (interp_value_from_ir_string('bits[8]:100'), interp_value_from_ir_string('bits[8]:1')) runner._evaluate_ir = lambda *args: results with self.assertRaises(sample_runner.SampleError) as e: runner.run( sample.Sample(dslx_text, sample.SampleOptions(optimize_ir=False), [[ interp_value_from_ir_string('bits[8]:40'), interp_value_from_ir_string('bits[8]:60') ], [ interp_value_from_ir_string('bits[8]:2'), interp_value_from_ir_string('bits[8]:1') ]])) self.assertIn('Result miscompare for sample 1', str(e.exception)) self.assertIn('Result miscompare for sample 1', _read_file(sample_dir, 'exception.txt')) def test_evaluate_ir_miscompare_number_of_results(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' # Give back two results instead of one. def fake_evaluate_ir(*_): return (interp_value_from_ir_string('bits[8]:100'), interp_value_from_ir_string('bits[8]:100')) runner._evaluate_ir = fake_evaluate_ir args_batch = [(interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:64'))] with self.assertRaises(sample_runner.SampleError) as e: runner.run( sample.Sample(dslx_text, sample.SampleOptions(optimize_ir=False), args_batch)) self.assertIn( 'Results for evaluated unopt IR (JIT) has 2 values, interpreted DSLX has 1', str(e.exception)) self.assertIn( 'Results for evaluated unopt IR (JIT) has 2 values, interpreted DSLX has 1', _read_file(sample_dir, 'exception.txt')) def test_interpret_opt_ir(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' runner.run( sample.Sample(dslx_text, sample.SampleOptions(), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ]])) self.assertIn('package sample', _read_file(sample_dir, 'sample.opt.ir')) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.opt.ir.results'), ['bits[8]:0x8e']) def test_interpret_opt_ir_miscompare(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' results = [ (interp_value_from_ir_string('bits[8]:100'),), # correct result (interp_value_from_ir_string('bits[8]:100'),), # correct result (interp_value_from_ir_string('bits[8]:0'),), # incorrect result (interp_value_from_ir_string('bits[8]:100'),), # correct result ] def result_gen(*_): return results.pop(0) runner._evaluate_ir = result_gen with self.assertRaises(sample_runner.SampleError) as e: runner.run( sample.Sample(dslx_text, sample.SampleOptions(), [[ interp_value_from_ir_string('bits[8]:40'), interp_value_from_ir_string('bits[8]:60') ]])) self.assertIn('Result miscompare for sample 0', str(e.exception)) self.assertIn('evaluated opt IR (JIT)', str(e.exception)) def test_codegen_combinational(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' runner.run( sample.Sample( dslx_text, sample.SampleOptions( codegen=True, codegen_args=['--generator=combinational'], simulate=True), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ]])) self.assertIn('endmodule', _read_file(sample_dir, 'sample.v')) # A combinational block should not have a blocking assignment. self.assertNotIn('<=', _read_file(sample_dir, 'sample.v')) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.v.results'), ['bits[8]:0x8e']) def test_codegen_combinational_wrong_results(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) runner._simulate = lambda *args: (interp_value_from_ir_string('bits[8]:1'),) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' with self.assertRaises(sample_runner.SampleError) as e: runner.run( sample.Sample( dslx_text, sample.SampleOptions( codegen=True, codegen_args=['--generator=combinational'], simulate=True, simulator='iverilog'), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ]])) self.assertIn('Result miscompare for sample 0', str(e.exception)) @test_base.skipIf(not check_simulator.runs_system_verilog(), 'uses SystemVerilog') def test_codegen_pipeline(self): sample_dir = self._make_sample_dir() print('sample_dir = ' + sample_dir) runner = sample_runner.SampleRunner(sample_dir) dslx_text = 'fn main(x: u8, y: u8) -> u8 { x + y }' runner.run( sample.Sample( dslx_text, sample.SampleOptions( codegen=True, codegen_args=('--generator=pipeline', '--pipeline_stages=2'), simulate=True), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ]])) # A pipelined block should have a blocking assignment. self.assertIn('<=', _read_file(sample_dir, 'sample.v')) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.v.results'), ['bits[8]:0x8e']) def test_ir_input(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) ir_text = """package foo fn foo(x: bits[8], y: bits[8]) -> bits[8] { ret add.1: bits[8] = add(x, y) } """ runner.run( sample.Sample(ir_text, sample.SampleOptions(input_is_dslx=False), [[ interp_value_from_ir_string('bits[8]:42'), interp_value_from_ir_string('bits[8]:100') ]])) self.assertIn('package foo', _read_file(sample_dir, 'sample.ir')) self.assertIn('package foo', _read_file(sample_dir, 'sample.opt.ir')) self.assertSequenceEqual( _split_nonempty_lines(sample_dir, 'sample.opt.ir.results'), ['bits[8]:0x8e']) def test_bad_ir_input(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) ir_text = """bogus ir string""" with self.assertRaises(sample_runner.SampleError): runner.run( sample.Sample(ir_text, sample.SampleOptions(input_is_dslx=False))) self.assertIn('Expected \'package\' keyword', _read_file(sample_dir, 'opt_main.stderr')) self.assertRegex( _read_file(sample_dir, 'exception.txt'), '.*opt_main.*returned non-zero exit status') def test_timeout(self): sample_dir = self._make_sample_dir() runner = sample_runner.SampleRunner(sample_dir) with self.assertRaises(sample_runner.SampleError) as e: runner.run( sample.Sample( LONG_LOOP_IR, sample.SampleOptions( input_is_dslx=False, optimize_ir=False, use_jit=False, codegen=False, timeout_seconds=3), [[ interp_value_from_ir_string('bits[64]:42'), ]])) self.assertIn('timed out after 3 seconds', str(e.exception)) if __name__ == '__main__': test_base.main()
7,888
1,609
<gh_stars>1000+ // // // Copyright (C) 2020 Schrödinger, LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #pragma once #include "Configuration.h" namespace RDKit { namespace CIPLabeler { class Tetrahedral : public Configuration { public: Tetrahedral() = delete; Tetrahedral(const CIPMol &mol, Atom *focus); void setPrimaryLabel(Descriptor desc) override; Descriptor label(const Rules &comp) override; Descriptor label(Node *node, Digraph &digraph, const Rules &comp) override; private: Descriptor label(Node *node, const Rules &comp) const; }; } // namespace CIPLabeler } // namespace RDKit
255
2,151
<reponame>zipated/src // Copyright (c) 2012 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 "net/third_party/quic/platform/api/quic_clock.h" namespace net { QuicClock::QuicClock() {} QuicClock::~QuicClock() {} QuicTime QuicClock::ConvertWallTimeToQuicTime( const QuicWallTime& walltime) const { // .......................... // | | | // unix epoch |walltime| WallNow() // .......................... // | | | // clock epoch | Now() // result // // result = Now() - (WallNow() - walltime) return Now() - QuicTime::Delta::FromMicroseconds( WallNow() .Subtract(QuicTime::Delta::FromMicroseconds( walltime.ToUNIXMicroseconds())) .ToUNIXMicroseconds()); } } // namespace net
458
545
<gh_stars>100-1000 // // SmileClimacons.h // SmileWeather-Example // // Created by <NAME> on 7/26/15. // Copyright (c) 2015 rain. All rights reserved. // #ifndef SmileWeather_Example_SmileClimacons_h #define SmileWeather_Example_SmileClimacons_h typedef enum { ClimaconCloud = '!', ClimaconCloudSun = '"', ClimaconCloudMoon = '#', ClimaconRain = '$', ClimaconRainSun = '%', ClimaconRainMoon = '&', ClimaconRainAlt = '\'', ClimaconRainSunAlt = '(', ClimaconRainMoonAlt = ')', ClimaconDownpour = '*', ClimaconDownpourSun = '+', ClimaconDownpourMoon = ',', ClimaconDrizzle = '-', ClimaconDrizzleSun = '.', ClimaconDrizzleMoon = '/', ClimaconSleet = '0', ClimaconSleetSun = '1', ClimaconSleetMoon = '2', ClimaconHail = '3', ClimaconHailSun = '4', ClimaconHailMoon = '5', ClimaconFlurries = '6', ClimaconFlurriesSun = '7', ClimaconFlurriesMoon = '8', ClimaconSnow = '9', ClimaconSnowSun = ':', ClimaconSnowMoon = ';', ClimaconFog = '<', ClimaconFogSun = '=', ClimaconFogMoon = '>', ClimaconHaze = '?', ClimaconHazeSun = '@', ClimaconHazeMoon = 'A', ClimaconWind = 'B', ClimaconWindCloud = 'C', ClimaconWindCloudSun = 'D', ClimaconWindCloudMoon = 'E', ClimaconLightning = 'F', ClimaconLightningSun = 'G', ClimaconLightningMoon = 'H', ClimaconSun = 'I', ClimaconSunset = 'J', ClimaconSunrise = 'K', ClimaconSunLow = 'L', ClimaconSunLower = 'M', ClimaconMoon = 'N', ClimaconMoonNew = 'O', ClimaconMoonWaxingCrescent = 'P', ClimaconMoonWaxingQuarter = 'Q', ClimaconMoonWaxingGibbous = 'R', ClimaconMoonFull = 'S', ClimaconMoonWaningGibbous = 'T', ClimaconMoonWaningQuarter = 'U', ClimaconMoonWaningCrescent = 'V', ClimaconSnowflake = 'W', ClimaconTornado = 'X', ClimaconThermometer = 'Y', ClimaconThermometerLow = 'Z', ClimaconThermometerMediumLoew = '[', ClimaconThermometerMediumHigh = '\\', ClimaconThermometerHigh = ']', ClimaconThermometerFull = '^', ClimaconCelsius = '_', ClimaconFahrenheit = '\'', ClimaconCompass = 'a', ClimaconCompassNorth = 'b', ClimaconCompassEast = 'c', ClimaconCompassSouth = 'd', ClimaconCompassWest = 'e', ClimaconUmbrella = 'f', ClimaconSunglasses = 'g', ClimaconCloudRefresh = 'h', ClimaconCloudUp = 'i', ClimaconCloudDown = 'j' } Climacons; #endif
2,145
841
<filename>resteasy-core/src/main/java/org/jboss/resteasy/core/providerfactory/ResteasyProviderFactoryDelegate.java /* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.resteasy.core.providerfactory; import org.jboss.resteasy.spi.AsyncClientResponseProvider; import org.jboss.resteasy.spi.AsyncResponseProvider; import org.jboss.resteasy.spi.AsyncStreamProvider; import org.jboss.resteasy.spi.ContextInjector; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpResponse; import org.jboss.resteasy.spi.InjectorFactory; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.spi.StringParameterUnmarshaller; import org.jboss.resteasy.spi.interception.JaxrsInterceptorRegistry; import org.jboss.resteasy.spi.metadata.ResourceBuilder; import org.jboss.resteasy.spi.statistics.StatisticsController; import jakarta.ws.rs.RuntimeType; import jakarta.ws.rs.client.ClientRequestFilter; import jakarta.ws.rs.client.ClientResponseFilter; import jakarta.ws.rs.client.RxInvoker; import jakarta.ws.rs.client.RxInvokerProvider; import jakarta.ws.rs.container.ContainerRequestFilter; import jakarta.ws.rs.container.ContainerResponseFilter; import jakarta.ws.rs.container.DynamicFeature; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.Configuration; import jakarta.ws.rs.core.Feature; import jakarta.ws.rs.core.Link.Builder; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response.ResponseBuilder; import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.Variant.VariantListBuilder; import jakarta.ws.rs.ext.ContextResolver; import jakarta.ws.rs.ext.ExceptionMapper; import jakarta.ws.rs.ext.MessageBodyReader; import jakarta.ws.rs.ext.MessageBodyWriter; import jakarta.ws.rs.ext.ParamConverter; import jakarta.ws.rs.ext.ReaderInterceptor; import jakarta.ws.rs.ext.WriterInterceptor; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * * A ResteasyProviderFactoryDelegate. * * @author <NAME> */ public class ResteasyProviderFactoryDelegate extends ResteasyProviderFactory { private final ResteasyProviderFactoryImpl resteasyProviderFactoryDelegator; public ResteasyProviderFactoryDelegate(final ResteasyProviderFactory resteasyProviderFactoryDelegator) { this.resteasyProviderFactoryDelegator = Objects.requireNonNull((ResteasyProviderFactoryImpl) resteasyProviderFactoryDelegator); } @Override public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return resteasyProviderFactoryDelegator.getMessageBodyReader(type, genericType, annotations, mediaType); } @Override public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return resteasyProviderFactoryDelegator.getMessageBodyWriter(type, genericType, annotations, mediaType); } @Override public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type) { return resteasyProviderFactoryDelegator.getExceptionMapper(type); } @Override public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType) { return resteasyProviderFactoryDelegator.getContextResolver(contextType, mediaType); } @Override public String toHeaderString(Object object) { return resteasyProviderFactoryDelegator.toHeaderString(object); } @Override public Configuration getConfiguration() { return resteasyProviderFactoryDelegator.getConfiguration(); } @Override public ResteasyProviderFactory property(String name, Object value) { return resteasyProviderFactoryDelegator.property(name, value); } @Override public ResteasyProviderFactory register(Class<?> componentClass) { return resteasyProviderFactoryDelegator.register(componentClass); } @Override public ResteasyProviderFactory register(Class<?> componentClass, int priority) { return resteasyProviderFactoryDelegator.register(componentClass, priority); } @Override public ResteasyProviderFactory register(Class<?> componentClass, Class<?>... contracts) { return resteasyProviderFactoryDelegator.register(componentClass, contracts); } @Override public ResteasyProviderFactory register(Class<?> componentClass, Map<Class<?>, Integer> contracts) { return resteasyProviderFactoryDelegator.register(componentClass, contracts); } @Override public ResteasyProviderFactory register(Object component) { return resteasyProviderFactoryDelegator.register(component); } @Override public ResteasyProviderFactory register(Object component, int priority) { return resteasyProviderFactoryDelegator.register(component, priority); } @Override public ResteasyProviderFactory register(Object component, Class<?>... contracts) { return resteasyProviderFactoryDelegator.register(component, contracts); } @Override public ResteasyProviderFactory register(Object component, Map<Class<?>, Integer> contracts) { return resteasyProviderFactoryDelegator.register(component, contracts); } @Override public RuntimeType getRuntimeType() { return resteasyProviderFactoryDelegator.getRuntimeType(); } @Override public Map<String, Object> getProperties() { return resteasyProviderFactoryDelegator.getProperties(); } @Override public Object getProperty(String name) { return resteasyProviderFactoryDelegator.getProperty(name); } @Override public Collection<String> getPropertyNames() { return resteasyProviderFactoryDelegator.getPropertyNames(); } @Override public boolean isEnabled(Feature feature) { return resteasyProviderFactoryDelegator.isEnabled(feature); } @Override public boolean isEnabled(Class<? extends Feature> featureClass) { return resteasyProviderFactoryDelegator.isEnabled(featureClass); } @Override public boolean isRegistered(Object component) { return resteasyProviderFactoryDelegator.isRegistered(component); } @Override public boolean isRegistered(Class<?> componentClass) { return resteasyProviderFactoryDelegator.isRegistered(componentClass); } @Override public Map<Class<?>, Integer> getContracts(Class<?> componentClass) { return null; } @Override public Set<Class<?>> getClasses() { return resteasyProviderFactoryDelegator.getClasses(); } @Override public Set<Object> getInstances() { return resteasyProviderFactoryDelegator.getInstances(); } @Override public Set<DynamicFeature> getServerDynamicFeatures() { return resteasyProviderFactoryDelegator.getServerDynamicFeatures(); } @Override public Set<DynamicFeature> getClientDynamicFeatures() { return resteasyProviderFactoryDelegator.getClientDynamicFeatures(); } @Override public Map<Class<?>, AsyncResponseProvider> getAsyncResponseProviders() { return resteasyProviderFactoryDelegator.getAsyncResponseProviders(); } @Override public Map<Class<?>, AsyncClientResponseProvider> getAsyncClientResponseProviders() { return resteasyProviderFactoryDelegator.getAsyncClientResponseProviders(); } @Override public Map<Class<?>, AsyncStreamProvider> getAsyncStreamProviders() { return resteasyProviderFactoryDelegator.getAsyncStreamProviders(); } @Override public Map<Type, ContextInjector> getContextInjectors() { return resteasyProviderFactoryDelegator.getContextInjectors(); } @Override public Map<Type, ContextInjector> getAsyncContextInjectors() { return resteasyProviderFactoryDelegator.getAsyncContextInjectors(); } @Override public Set<Class<?>> getProviderClasses() { return resteasyProviderFactoryDelegator.getProviderClasses(); } @Override public Set<Object> getProviderInstances() { return resteasyProviderFactoryDelegator.getProviderInstances(); } @Override public <T> T getContextData(Class<T> type) { return resteasyProviderFactoryDelegator.getContextData(type); } @Override public <T> T getContextData(Class<T> rawType, Type genericType, Annotation[] annotations, boolean unwrapAsync) { return resteasyProviderFactoryDelegator.getContextData(rawType, genericType, annotations, unwrapAsync); } @Override protected void registerBuiltin() { throw new UnsupportedOperationException(); } @Override public boolean isRegisterBuiltins() { return resteasyProviderFactoryDelegator.isRegisterBuiltins(); } @Override public void setRegisterBuiltins(boolean registerBuiltins) { resteasyProviderFactoryDelegator.setRegisterBuiltins(registerBuiltins); } @Override public InjectorFactory getInjectorFactory() { return resteasyProviderFactoryDelegator.getInjectorFactory(); } @Override public void setInjectorFactory(InjectorFactory injectorFactory) { resteasyProviderFactoryDelegator.setInjectorFactory(injectorFactory); } @Override public JaxrsInterceptorRegistry<ReaderInterceptor> getServerReaderInterceptorRegistry() { return resteasyProviderFactoryDelegator.getServerReaderInterceptorRegistry(); } @Override public JaxrsInterceptorRegistry<WriterInterceptor> getServerWriterInterceptorRegistry() { return resteasyProviderFactoryDelegator.getServerWriterInterceptorRegistry(); } @Override public JaxrsInterceptorRegistry<ContainerRequestFilter> getContainerRequestFilterRegistry() { return resteasyProviderFactoryDelegator.getContainerRequestFilterRegistry(); } @Override public JaxrsInterceptorRegistry<ContainerResponseFilter> getContainerResponseFilterRegistry() { return resteasyProviderFactoryDelegator.getContainerResponseFilterRegistry(); } @Override public JaxrsInterceptorRegistry<ReaderInterceptor> getClientReaderInterceptorRegistry() { return resteasyProviderFactoryDelegator.getClientReaderInterceptorRegistry(); } @Override public JaxrsInterceptorRegistry<WriterInterceptor> getClientWriterInterceptorRegistry() { return resteasyProviderFactoryDelegator.getClientWriterInterceptorRegistry(); } @Override public JaxrsInterceptorRegistry<ClientRequestFilter> getClientRequestFilterRegistry() { return resteasyProviderFactoryDelegator.getClientRequestFilterRegistry(); } @Override public JaxrsInterceptorRegistry<ClientResponseFilter> getClientResponseFilters() { return resteasyProviderFactoryDelegator.getClientResponseFilters(); } @Override public boolean isBuiltinsRegistered() { return resteasyProviderFactoryDelegator.isBuiltinsRegistered(); } @Override public void setBuiltinsRegistered(boolean builtinsRegistered) { resteasyProviderFactoryDelegator.setBuiltinsRegistered(builtinsRegistered); } @Override public void addHeaderDelegate(Class clazz, HeaderDelegate header) { resteasyProviderFactoryDelegator.addHeaderDelegate(clazz, header); } @SuppressWarnings("deprecation") @Override public <T> MessageBodyReader<T> getServerMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return resteasyProviderFactoryDelegator.getServerMessageBodyReader(type, genericType, annotations, mediaType); } @Override public <T> MessageBodyReader<T> getClientMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return resteasyProviderFactoryDelegator.getClientMessageBodyReader(type, genericType, annotations, mediaType); } @Override public List<ContextResolver> getContextResolvers(Class<?> clazz, MediaType type) { return resteasyProviderFactoryDelegator.getContextResolvers(clazz, type); } @Override public ParamConverter getParamConverter(Class clazz, Type genericType, Annotation[] annotations) { return resteasyProviderFactoryDelegator.getParamConverter(clazz, genericType, annotations); } @Override public <T> StringParameterUnmarshaller<T> createStringParameterUnmarshaller(Class<T> clazz) { return resteasyProviderFactoryDelegator.createStringParameterUnmarshaller(clazz); } @Override public void registerProvider(Class provider) { resteasyProviderFactoryDelegator.registerProvider(provider); } @Override public String toString(Object object, Class clazz, Type genericType, Annotation[] annotations) { return resteasyProviderFactoryDelegator.toString(object, clazz, genericType, annotations); } @Override public HeaderDelegate getHeaderDelegate(Class<?> aClass) { return resteasyProviderFactoryDelegator.getHeaderDelegate(aClass); } @Override public void registerProvider(Class provider, boolean isBuiltin) { resteasyProviderFactoryDelegator.registerProvider(provider, isBuiltin); } @Override public void registerProvider(Class provider, Integer priorityOverride, boolean isBuiltin, Map<Class<?>, Integer> contracts) { resteasyProviderFactoryDelegator.registerProvider(provider, priorityOverride, isBuiltin, contracts); } @Override public void registerProviderInstance(Object provider) { resteasyProviderFactoryDelegator.registerProviderInstance(provider); } @Override public void registerProviderInstance(Object provider, Map<Class<?>, Integer> contracts, Integer priorityOverride, boolean builtIn) { resteasyProviderFactoryDelegator.registerProviderInstance(provider, contracts, priorityOverride, builtIn); } @Override public <T> AsyncResponseProvider<T> getAsyncResponseProvider(Class<T> type) { return resteasyProviderFactoryDelegator.getAsyncResponseProvider(type); } @Override public <T> AsyncClientResponseProvider<T> getAsyncClientResponseProvider(Class<T> type) { return resteasyProviderFactoryDelegator.getAsyncClientResponseProvider(type); } @Override public <T> AsyncStreamProvider<T> getAsyncStreamProvider(Class<T> type) { return resteasyProviderFactoryDelegator.getAsyncStreamProvider(type); } @Override public MediaType getConcreteMediaTypeFromMessageBodyWriters(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return resteasyProviderFactoryDelegator.getConcreteMediaTypeFromMessageBodyWriters(type, genericType, annotations, mediaType); } @Override public Map<MessageBodyWriter<?>, Class<?>> getPossibleMessageBodyWritersMap(Class type, Type genericType, Annotation[] annotations, MediaType accept) { return resteasyProviderFactoryDelegator.getPossibleMessageBodyWritersMap(type, genericType, annotations, accept); } @SuppressWarnings("deprecation") @Override public <T> MessageBodyWriter<T> getServerMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return resteasyProviderFactoryDelegator.getServerMessageBodyWriter(type, genericType, annotations, mediaType); } @Override public <T> MessageBodyWriter<T> getClientMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return resteasyProviderFactoryDelegator.getClientMessageBodyWriter(type, genericType, annotations, mediaType); } @Override public <T> T createProviderInstance(Class<? extends T> clazz) { return resteasyProviderFactoryDelegator.createProviderInstance(clazz); } @Override public <T> T injectedInstance(Class<? extends T> clazz) { return resteasyProviderFactoryDelegator.injectedInstance(clazz); } @Override public <T> T injectedInstance(Class<? extends T> clazz, HttpRequest request, HttpResponse response) { return resteasyProviderFactoryDelegator.injectedInstance(clazz, request, response); } @Override public void injectProperties(Object obj) { resteasyProviderFactoryDelegator.injectProperties(obj); } @Override public void injectProperties(Object obj, HttpRequest request, HttpResponse response) { resteasyProviderFactoryDelegator.injectProperties(obj, request, response); } @Override public Map<String, Object> getMutableProperties() { return resteasyProviderFactoryDelegator.getMutableProperties(); } @Override public ResteasyProviderFactory setProperties(Map<String, Object> properties) { return resteasyProviderFactoryDelegator.setProperties(properties); } @Override public Collection<Feature> getEnabledFeatures() { return resteasyProviderFactoryDelegator.getEnabledFeatures(); } @Override public <I extends RxInvoker> RxInvokerProvider<I> getRxInvokerProvider(Class<I> clazz) { return resteasyProviderFactoryDelegator.getRxInvokerProvider(clazz); } @Override public RxInvokerProvider<?> getRxInvokerProviderFromReactiveClass(Class<?> clazz) { return resteasyProviderFactoryDelegator.getRxInvokerProviderFromReactiveClass(clazz); } @Override public boolean isReactive(Class<?> clazz) { return resteasyProviderFactoryDelegator.isReactive(clazz); } @Override public ResourceBuilder getResourceBuilder() { return resteasyProviderFactoryDelegator.getResourceBuilder(); } @Override public void initializeClientProviders(ResteasyProviderFactory factory) { resteasyProviderFactoryDelegator.initializeClientProviders(factory); } @Override public UriBuilder createUriBuilder() { return resteasyProviderFactoryDelegator.createUriBuilder(); } @Override public ResponseBuilder createResponseBuilder() { return resteasyProviderFactoryDelegator.createResponseBuilder(); } @Override public VariantListBuilder createVariantListBuilder() { return resteasyProviderFactoryDelegator.createVariantListBuilder(); } @Override public <T> T createEndpoint(Application application, Class<T> endpointType) throws IllegalArgumentException, UnsupportedOperationException { return resteasyProviderFactoryDelegator.createEndpoint(application, endpointType); } @Override public <T> HeaderDelegate<T> createHeaderDelegate(Class<T> type) throws IllegalArgumentException { return resteasyProviderFactoryDelegator.createHeaderDelegate(type); } @Override public Builder createLinkBuilder() { return resteasyProviderFactoryDelegator.createLinkBuilder(); } @Override public StatisticsController getStatisticsController() { return resteasyProviderFactoryDelegator.getStatisticsController(); } @Override protected boolean isOnServer() { return resteasyProviderFactoryDelegator.isOnServer(); } }
6,188
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.web.beans.analysis.analyzer.type; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import org.netbeans.modules.web.beans.analysis.analyzer.AbstractScopedAnalyzer; import org.netbeans.modules.web.beans.analysis.analyzer.AnnotationUtil; import org.netbeans.modules.web.beans.analysis.analyzer.ClassModelAnalyzer.ClassAnalyzer; import org.netbeans.modules.web.beans.analysis.analyzer.ModelAnalyzer.Result; import org.netbeans.modules.web.beans.api.model.WebBeansModel; import org.netbeans.spi.editor.hints.Severity; import org.openide.util.NbBundle; /** * @author ads * */ public class ScopedBeanAnalyzer extends AbstractScopedAnalyzer implements ClassAnalyzer { /* (non-Javadoc) * @see org.netbeans.modules.web.beans.analysis.analyzer.ClassModelAnalyzer.ClassAnalyzer#analyze(javax.lang.model.element.TypeElement, javax.lang.model.element.TypeElement, org.netbeans.modules.web.beans.api.model.WebBeansModel, java.util.List, org.netbeans.api.java.source.CompilationInfo, java.util.concurrent.atomic.AtomicBoolean) */ @Override public void analyze( TypeElement element, TypeElement parent, WebBeansModel model, AtomicBoolean cancel, Result result ) { analyzeScope(element, model, cancel , result ); } /* (non-Javadoc) * @see org.netbeans.modules.web.beans.analysis.analyzer.AbstractScopedAnalyzer#checkScope(javax.lang.model.element.TypeElement, javax.lang.model.element.Element, org.netbeans.modules.web.beans.api.model.WebBeansModel, java.util.List, org.netbeans.api.java.source.CompilationInfo, java.util.concurrent.atomic.AtomicBoolean) */ @Override protected void checkScope( TypeElement scopeElement, Element element, WebBeansModel model, AtomicBoolean cancel , Result result ) { if ( cancel.get() ){ return; } checkProxiability(scopeElement, element, model, result ); if ( cancel.get() ){ return; } checkPublicField(scopeElement , element , model , result ); if ( cancel.get() ){ return; } checkParameterizedBean(scopeElement , element , model , result ); if ( cancel.get() ){ return; } checkInterceptorDecorator( scopeElement , element , model , result); if ( cancel.get() ){ return; } checkPassivationCapable( scopeElement , element , model , result ); } private void checkPassivationCapable( TypeElement scopeElement, Element element, WebBeansModel model, Result result ) { if ( !isPassivatingScope(scopeElement, model) ){ return; } if ( AnnotationUtil.isSessionBean(element, model.getCompilationController())){ if ( AnnotationUtil.hasAnnotation(element, AnnotationUtil.STATEFUL, model.getCompilationController())) { return; } else { result.addError(element, model , NbBundle.getMessage(ScopedBeanAnalyzer.class, "ERR_NotPassivationSessionBean", // NOI18N scopeElement.getQualifiedName().toString())); return; } } if ( !isSerializable(element, model) ){ result.addError(element, model , NbBundle.getMessage(ScopedBeanAnalyzer.class, "ERR_NotPassivationManagedBean", // NOI18N scopeElement.getQualifiedName().toString())); } // TODO : all interceptors ans decorators of bean should be also passivation capable } private void checkInterceptorDecorator( TypeElement scopeElement, Element element, WebBeansModel model, Result result ) { if ( scopeElement.getQualifiedName().contentEquals(AnnotationUtil.DEPENDENT)){ return; } AnnotationMirror annotationMirror = AnnotationUtil.getAnnotationMirror( element, model.getCompilationController(), AnnotationUtil.INTERCEPTOR, AnnotationUtil.DECORATOR); if ( annotationMirror!= null ){ result.addNotification( Severity.WARNING, element, model, NbBundle.getMessage(ScopedBeanAnalyzer.class, "WARN_ScopedDecoratorInterceptor" )); // NOI18N } } private void checkParameterizedBean( TypeElement scopeElement, Element element, WebBeansModel model, Result result ) { if ( AnnotationUtil.DEPENDENT.contentEquals( scopeElement.getQualifiedName())) { return; } result.requireCdiEnabled(element, model); TypeMirror type = element.asType(); if ( type instanceof DeclaredType ){ List<? extends TypeMirror> typeArguments = ((DeclaredType)type).getTypeArguments(); if ( typeArguments.size() != 0 ){ result.addError(element, model, NbBundle.getMessage(ScopedBeanAnalyzer.class, "ERR_IncorrectScopeForParameterizedBean" )); // NOI18N } } } private void checkPublicField( TypeElement scopeElement, Element element, WebBeansModel model, Result result ) { if ( AnnotationUtil.DEPENDENT.contentEquals( scopeElement.getQualifiedName())) { return; } result.requireCdiEnabled(element, model); List<VariableElement> fields = ElementFilter.fieldsIn( element.getEnclosedElements()); for (VariableElement field : fields) { Set<Modifier> modifiers = field.getModifiers(); if ( modifiers.contains(Modifier.PUBLIC ) && (!modifiers.contains(Modifier.STATIC) || !model.isCdi11OrLater())){ result.addError(element, model , NbBundle.getMessage(ScopedBeanAnalyzer.class, "ERR_IcorrectScopeWithPublicField", field.getSimpleName().toString())); return; } } } private void checkProxiability( TypeElement scopeElement, Element element, WebBeansModel model, Result result ) { boolean isNormal = AnnotationUtil.hasAnnotation(scopeElement, AnnotationUtil.NORMAL_SCOPE_FQN, model.getCompilationController()); if ( isNormal ){ result.requireCdiEnabled(element, model); checkFinal( element , model, result ); } } private void checkFinal( Element element, WebBeansModel model, Result result ) { if ( !( element instanceof TypeElement )){ return; } Set<Modifier> modifiers = element.getModifiers(); if ( modifiers.contains( Modifier.FINAL) ){ result.addError( element, model, NbBundle.getMessage(ScopedBeanAnalyzer.class, "ERR_FinalScopedClass")); return; } List<ExecutableElement> methods = ElementFilter.methodsIn( element.getEnclosedElements()); for (ExecutableElement method : methods) { modifiers = method.getModifiers(); if (modifiers.contains(Modifier.FINAL)) { result.addNotification( Severity.WARNING, method, model, NbBundle.getMessage( ScopedBeanAnalyzer.class, "WARN_FinalScopedClassMethod")); } } } }
3,965
11,877
<gh_stars>1000+ /* * Copyright 2021 <NAME>. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.benmanes.caffeine.cache; import java.util.ArrayList; import java.util.Map; import java.util.Queue; import org.jetbrains.kotlinx.lincheck.LinChecker; import org.jetbrains.kotlinx.lincheck.annotations.OpGroupConfig; import org.jetbrains.kotlinx.lincheck.annotations.Operation; import org.jetbrains.kotlinx.lincheck.annotations.Param; import org.jetbrains.kotlinx.lincheck.paramgen.IntGen; import org.jetbrains.kotlinx.lincheck.strategy.managed.modelchecking.ModelCheckingOptions; import org.jetbrains.kotlinx.lincheck.strategy.stress.StressOptions; import org.jetbrains.kotlinx.lincheck.verifier.VerifierState; import org.testng.annotations.Test; /** * Linearizability checks for {@link MpscGrowableArrayQueue}. This tests the JCTools' version until * our copy is resync'd due to requiring an iterator for reporting the state. * * @author <EMAIL> (<NAME>) */ @OpGroupConfig(name = "consumer", nonParallel = true) @Param(name = "element", gen = IntGen.class, conf = "1:5") public final class MpscGrowableArrayQueueLincheckTest extends VerifierState { private final Queue<Integer> queue; public MpscGrowableArrayQueueLincheckTest() { queue = new org.jctools.queues.MpscGrowableArrayQueue<>(4, 65_536); } @Operation public boolean offer(@Param(name = "element") int e) { return queue.offer(e); } @Operation(group = "consumer") public Integer poll() { return queue.poll(); } /** * This test checks that the concurrent map is linearizable with bounded model checking. Unlike * stress testing, this approach can also provide a trace of an incorrect execution. However, it * uses sequential consistency model, so it can not find any low-level bugs (e.g., missing * 'volatile'), and thus, it it recommended to have both test modes. * <p> * This test requires the following JVM arguments, * <ul> * <li>--add-opens java.base/jdk.internal.misc=ALL-UNNAMED * <li>--add-exports java.base/jdk.internal.util=ALL-UNNAMED * </ul> */ @Test(groups = "lincheck") public void modelCheckingTest() { var options = new ModelCheckingOptions() .iterations(100) // the number of different scenarios .invocationsPerIteration(10_000); // how deeply each scenario is tested new LinChecker(getClass(), options).check(); } /** This test checks that the concurrent map is linearizable with stress testing. */ @Test(groups = "lincheck") public void stressTest() { var options = new StressOptions() .iterations(100) // the number of different scenarios .invocationsPerIteration(10_000); // how deeply each scenario is tested new LinChecker(getClass(), options).check(); } /** * Provides something with correct <tt>equals</tt> and <tt>hashCode</tt> methods that can be * interpreted as an internal data structure state for faster verification. The only limitation is * that it should be different for different data structure states. For {@link Map} it itself is * used. * * @return object representing internal state */ @Override protected Object extractState() { return new ArrayList<Integer>(queue); } }
1,239
1,127
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import unittest import numpy as np from generator import generator, generate from openvino.tools.mo.front.common.partial_infer.utils import int64_array, mo_array, is_fully_defined, \ dynamic_dimension_value, dynamic_dimension, shape_array, compatible_shapes, shape_delete, shape_insert, \ strict_compare_tensors, clarify_partial_shape from openvino.tools.mo.utils.error import Error def gen_masked_array(array, masked_indices): """ Creates a masked array from the input array by masking specific elements. :param array: the input array :param masked_indices: element indices to be masked :return: the result masked array """ res = np.ma.masked_array(array) for index in masked_indices: res[index] = np.ma.masked return res @generator class IsFullyDefinedTest(unittest.TestCase): @generate(*[(None, False), (int64_array([2, 3, 5, 7]), True), # int64 array with valid values (np.array([2, 3, 5, 7]), True), # any numpy array with valid values (np.array([2, dynamic_dimension_value]), True), # array with dynamic dimension value is fully defined! (shape_array([2, dynamic_dimension_value, 5]), False), # masked array with at least one masked element (shape_array([2, 4, 5]), True), # masked array with no masked elements is fully defined (dynamic_dimension, False), # dynamic dimension is not fully defined (dynamic_dimension_value, True), # dynamic dimension value is fully defined ((dynamic_dimension_value, dynamic_dimension_value), True), # list with dynamic dimension values is # fully defined ((dynamic_dimension, 1), False), # tuple with dynamic dimension is not fully defined ([dynamic_dimension, 1], False), # list with dynamic dimension is not fully defined ]) def test_is_fully_defined(self, data, result): self.assertEqual(is_fully_defined(data), result) @generator class ShapeArrayTest(unittest.TestCase): @generate(*[([1], shape_array([1]), True), # if we provide a list with dynamic_dimension_value then it is converted to dynamic dimension ([dynamic_dimension_value, 5], gen_masked_array([1, 5], [0]), True), # if we provide a list with dynamic_dimension then the generated shape array still have it ([7, dynamic_dimension], gen_masked_array([7, 1], [1]), True), # negative test to make sure that np.ma.allequal works properly ([2], gen_masked_array([1], []), False), ]) def test_shape_array(self, data, ref, result): self.assertEqual(strict_compare_tensors(shape_array(data), ref), result) @generator class CompareShapesTest(unittest.TestCase): @generate(*[(gen_masked_array([1, 2, 3], []), gen_masked_array([1, 2, 3], []), True), (gen_masked_array([4, 2, 3], []), gen_masked_array([1, 2, 3], []), False), (gen_masked_array([1, 2], []), gen_masked_array([1, 2, 3], []), False), (gen_masked_array([1, 2, 3], []), gen_masked_array([1, 2], []), False), (gen_masked_array([1, 2, 3], [1]), gen_masked_array([1, 5, 3], [1]), True), # [1, d, 3] vs [1, d, 3] (gen_masked_array([1, 2, 3], [2]), gen_masked_array([1, 5, 3], [1]), True), # [1, 2, d] vs [1, d, 3] (gen_masked_array([1, 2, 3], []), gen_masked_array([1, 5, 3], [1]), True), # [1, 2, 3] vs [1, d, 3] (gen_masked_array([1, 2, 3], [0]), gen_masked_array([1, 5, 3], []), False), # [d, 2, 3] vs [1, 5, 3] (np.array([1, 2, 3]), gen_masked_array([1, 5, 3], [1]), True), # [1, 2, 3] vs [1, d, 3] (np.array([1, 2]), gen_masked_array([1, 5, 3], [1]), False), (np.array([1, 2]), np.array([1, 2]), True), (np.array([1, 2]), np.array([3, 2]), False), ]) def test_compare_shapes(self, input1, input2, result): self.assertEqual(compatible_shapes(input1, input2), result) @generator class ShapeDeleteTest(unittest.TestCase): @generate(*[(gen_masked_array([1, 2, 3], []), [], gen_masked_array([1, 2, 3], [])), # [1, d, 3] -> [d, 3]. Indices input is a list (gen_masked_array([1, 2, 3], [1]), [0], gen_masked_array([2, 3], [0])), # [1, d, 3] -> [d, 3]. Indices input is a numpy array (gen_masked_array([1, 2, 3], [1]), np.array([0]), gen_masked_array([2, 3], [0])), # [1, d, 3] -> [d, 3]. Indices input is a masked array (gen_masked_array([1, 2, 3], [1]), gen_masked_array([0], []), gen_masked_array([2, 3], [0])), # [1, d, 3] -> [d, 3]. Indices input is a numpy array with scalar (gen_masked_array([1, 2, 3], [1]), np.array(0), gen_masked_array([2, 3], [0])), # [1, d, 3] -> [d, 3]. Indices input is an integer (gen_masked_array([1, 2, 3], [1]), 0, gen_masked_array([2, 3], [0])), # [1, d, 3] -> [d, 3] (gen_masked_array([1, 2, 3, 4], [1]), [0, 2], gen_masked_array([2, 4], [0])), # [1, d, 3, 4] -> [d, 4] (gen_masked_array([1, 2, 3], [1]), [0, 2, 1], gen_masked_array([], [])), # [1, d, 3] -> [] (gen_masked_array([1, 2, 3], [1]), [0, 2], gen_masked_array([2], [0])), # [1, d, 3] -> [d] # [1, d, d, 4] -> [d, d] (gen_masked_array([1, 2, 3, 4], [1, 2]), [3, 0], gen_masked_array([2, 3], [0, 1])), (gen_masked_array([1, 2, 3, 4], [2]), 3, gen_masked_array([1, 2, 3], [2])), # [1, 2, d, 4] -> [1, 2, d] ([1, 2, 3, 4], [1], [1, 3, 4]), # [1, 2, 3, 4] -> [1, 3, 4]. Input is a regular lists (np.array([1, 2, 3, 4]), [1], [1, 3, 4]), # [1, 2, 3, 4] -> [1, 3, 4]. Input is a regular arrays (np.array([1, 2, 3, 4]), [-1, -3], [1, 3]), # [1, 2, 3, 4] -> [1, 3]. Negative indices (np.array([1, 2, 3, 4]), -2, [1, 2, 4]), # [1, 2, 3, 4] -> [1, 2, 4]. Negative index ]) def test_shape_delete(self, shape, indices, result): self.assertTrue(strict_compare_tensors(shape_delete(shape, indices), result)) def test_shape_delete_raise_exception(self): with self.assertRaisesRegex(Error, '.*Incorrect parameter type.*'): shape_delete(gen_masked_array([1, 2, 3], []), {}) @generator class ShapeInsertTest(unittest.TestCase): @generate(*[(gen_masked_array([1, 2, 3], []), 1, [5], gen_masked_array([1, 5, 2, 3], [])), (gen_masked_array([1, 2, 3], [1]), 1, [5], gen_masked_array([1, 5, 2, 3], [2])), (gen_masked_array([1, 2, 3], [1]), 1, [dynamic_dimension], gen_masked_array([1, 5, 2, 3], [1, 2])), (gen_masked_array([1, 2, 3], [1]), 0, [dynamic_dimension], gen_masked_array([5, 1, 2, 3], [0, 2])), (gen_masked_array([1, 2, 3], [1]), np.int64(0), [dynamic_dimension], gen_masked_array([5, 1, 2, 3], [0, 2])), (gen_masked_array([1, 2, 3], [1]), 3, [dynamic_dimension], gen_masked_array([1, 2, 3, 5], [1, 3])), (gen_masked_array([1, 2, 3], [1]), 3, [dynamic_dimension, dynamic_dimension], gen_masked_array([1, 2, 3, 5, 6], [1, 3, 4])), (gen_masked_array([1], [0]), 0, [7, dynamic_dimension], gen_masked_array([7, 5, 2], [1, 2])), ]) def test_shape_insert(self, shape, pos, values, result): self.assertTrue(strict_compare_tensors(shape_insert(shape, pos, values), result)) def test_shape_insert_raise_exception(self): with self.assertRaisesRegex(Error, '.*Incorrect parameter type.*'): shape_insert(gen_masked_array([1, 2, 3], []), 2, {}) @generator class mo_array_test(unittest.TestCase): @generate(*[(mo_array([2, 3, 5, 7]), np.array([2, 3, 5, 7])), (mo_array([2., 3., 5., 7.], dtype=np.float64), np.array([2., 3., 5., 7.])), (mo_array([2., 3., 5., 7.]), np.array([2., 3., 5., 7.], dtype=np.float32)), ]) def test_mo_array_positive(self, data, result): self.assertEqual(data.dtype, result.dtype) @generate(*[(mo_array([2., 3., 5., 7.]), np.array([2., 3., 5., 7.])), ]) def test_mo_array_negative(self, data, result): self.assertNotEqual(data.dtype, result.dtype) class clarify_partial_shape_test(unittest.TestCase): def test_clarify_1(self): actual_result = clarify_partial_shape([shape_array([dynamic_dimension, 10, dynamic_dimension]), shape_array([4, dynamic_dimension, dynamic_dimension])]) ref_result = shape_array([4, 10, dynamic_dimension]) assert strict_compare_tensors(actual_result, ref_result)
4,287
1,428
#include <iostream> #include <cstring> #include <cstdlib> using namespace std; int main(int argc,char *argv[]) { string str; int k=0; str=argv[1]; int n=(str.length()); int arr[n]; int newarr[n]; for(int i=0;i<n;i++) { if(str[i]==' ') arr[i]=-1; else arr[i]=str[i]-'0'; } int i=0, j=0; for(int i=0;i<n;i++){ newarr[i]=0; } while(i<n) { if(arr[i]!=-1) { if(newarr[j]==0){ newarr[j]=arr[i]; k++;} else if(newarr[j]/10==0) newarr[j]=(newarr[j]*10)+arr[i]; else if((newarr[j]/10)<10 || (newarr[j]/10)>=0 ) newarr[j]=(newarr[j]*10)+arr[i]; } else { j++; } i++; } int max=0; int min=0; max=newarr[0]; min=newarr[0]; //for(int i=0;n<'\0';i++); //int len=i; for (int i=0;i<k;i++) { if(newarr[i]>max) max=newarr[i]; if(newarr[i]<min) min=newarr[i]; } int a=atoi(argv[2]); if(a==1) cout<<max; else if(a==2) cout<<min; else return 0; }
564
575
// Copyright 2014 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 MEDIA_FORMATS_MP2T_ES_PARSER_H_ #define MEDIA_FORMATS_MP2T_ES_PARSER_H_ #include <stdint.h> #include <list> #include <memory> #include <utility> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "media/base/media_export.h" #include "media/base/stream_parser_buffer.h" namespace media { class DecryptConfig; class OffsetByteQueue; class StreamParserBuffer; namespace mp2t { class MEDIA_EXPORT EsParser { public: using EmitBufferCB = base::RepeatingCallback<void(scoped_refptr<StreamParserBuffer>)>; using GetDecryptConfigCB = base::RepeatingCallback<const DecryptConfig*()>; EsParser(); virtual ~EsParser(); // ES parsing. // Should use kNoTimestamp when a timestamp is not valid. bool Parse(const uint8_t* buf, int size, base::TimeDelta pts, DecodeTimestamp dts); // Flush any pending buffer. virtual void Flush() = 0; // Reset the state of the ES parser. void Reset(); protected: struct TimingDesc { TimingDesc(); TimingDesc(DecodeTimestamp dts, base::TimeDelta pts); DecodeTimestamp dts; base::TimeDelta pts; }; // Parse ES data from |es_queue_|. // Return true when successful. virtual bool ParseFromEsQueue() = 0; // Reset the internal state of the ES parser. virtual void ResetInternal() = 0; // Get the timing descriptor with the largest byte count that is less or // equal to |es_byte_count|. // This timing descriptor and all the ones that come before (in stream order) // are removed from list |timing_desc_list_|. // If no timing descriptor is found, then the default TimingDesc is returned. TimingDesc GetTimingDescriptor(int64_t es_byte_count); // Bytes of the ES stream that have not been emitted yet. std::unique_ptr<media::OffsetByteQueue> es_queue_; private: // Anchor some timing information into the ES queue. // Here are two examples how this timing info is applied according to // the MPEG-2 TS spec - ISO/IEC 13818: // - "In the case of audio, if a PTS is present in PES packet header it shall // refer to the first access unit commencing in the PES packet. An audio // access unit commences in a PES packet if the first byte of the audio // access unit is present in the PES packet." // - "For AVC video streams conforming to one or more profiles defined // in Annex A of Rec. ITU-T H.264 | ISO/IEC 14496-10 video, if a PTS is // present in the PES packet header, it shall refer to the first AVC access // unit that commences in this PES packet. std::list<std::pair<int64_t, TimingDesc>> timing_desc_list_; DISALLOW_COPY_AND_ASSIGN(EsParser); }; } // namespace mp2t } // namespace media #endif // MEDIA_FORMATS_MP2T_ES_PARSER_H_
985
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. #include "net/third_party/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.h" #include <stddef.h> #include "base/logging.h" #include "base/macros.h" #include "net/third_party/quic/http/decoder/quic_http_decode_buffer.h" #include "net/third_party/quic/http/decoder/quic_http_frame_decoder_listener.h" #include "net/third_party/quic/http/quic_http_constants.h" #include "net/third_party/quic/http/quic_http_structures.h" #include "net/third_party/quic/platform/api/quic_bug_tracker.h" #include "net/third_party/quic/platform/api/quic_fallthrough.h" namespace net { std::ostream& operator<<(std::ostream& out, QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState v) { switch (v) { case QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState:: kStartDecodingFixedFields: return out << "kStartDecodingFixedFields"; case QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState:: kHandleFixedFieldsStatus: return out << "kHandleFixedFieldsStatus"; case QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState::kReadOpaqueData: return out << "kReadOpaqueData"; case QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState:: kResumeDecodingFixedFields: return out << "kResumeDecodingFixedFields"; } // Since the value doesn't come over the wire, only a programming bug should // result in reaching this point. int unknown = static_cast<int>(v); QUIC_BUG << "Invalid QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState: " << unknown; return out << "QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState(" << unknown << ")"; } QuicHttpDecodeStatus QuicHttpGoAwayQuicHttpPayloadDecoder::StartDecodingPayload( QuicHttpFrameDecoderState* state, QuicHttpDecodeBuffer* db) { DVLOG(2) << "QuicHttpGoAwayQuicHttpPayloadDecoder::StartDecodingPayload: " << state->frame_header(); DCHECK_EQ(QuicHttpFrameType::GOAWAY, state->frame_header().type); DCHECK_LE(db->Remaining(), state->frame_header().payload_length); DCHECK_EQ(0, state->frame_header().flags); state->InitializeRemainders(); payload_state_ = PayloadState::kStartDecodingFixedFields; return ResumeDecodingPayload(state, db); } QuicHttpDecodeStatus QuicHttpGoAwayQuicHttpPayloadDecoder::ResumeDecodingPayload( QuicHttpFrameDecoderState* state, QuicHttpDecodeBuffer* db) { DVLOG(2) << "QuicHttpGoAwayQuicHttpPayloadDecoder::ResumeDecodingPayload: " "remaining_payload=" << state->remaining_payload() << ", db->Remaining=" << db->Remaining(); const QuicHttpFrameHeader& frame_header = state->frame_header(); DCHECK_EQ(QuicHttpFrameType::GOAWAY, frame_header.type); DCHECK_LE(db->Remaining(), frame_header.payload_length); DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_); QuicHttpDecodeStatus status = QuicHttpDecodeStatus::kDecodeError; size_t avail; while (true) { DVLOG(2) << "QuicHttpGoAwayQuicHttpPayloadDecoder::ResumeDecodingPayload " "payload_state_=" << payload_state_; switch (payload_state_) { case PayloadState::kStartDecodingFixedFields: status = state->StartDecodingStructureInPayload(&goaway_fields_, db); QUIC_FALLTHROUGH_INTENDED; case PayloadState::kHandleFixedFieldsStatus: if (status == QuicHttpDecodeStatus::kDecodeDone) { state->listener()->OnGoAwayStart(frame_header, goaway_fields_); } else { // Not done decoding the structure. Either we've got more payload // to decode, or we've run out because the payload is too short, // in which case OnFrameSizeError will have already been called. DCHECK((status == QuicHttpDecodeStatus::kDecodeInProgress && state->remaining_payload() > 0) || (status == QuicHttpDecodeStatus::kDecodeError && state->remaining_payload() == 0)) << "\n status=" << status << "; remaining_payload=" << state->remaining_payload(); payload_state_ = PayloadState::kResumeDecodingFixedFields; return status; } QUIC_FALLTHROUGH_INTENDED; case PayloadState::kReadOpaqueData: // The opaque data is all the remains to be decoded, so anything left // in the decode buffer is opaque data. avail = db->Remaining(); if (avail > 0) { state->listener()->OnGoAwayOpaqueData(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() > 0) { payload_state_ = PayloadState::kReadOpaqueData; return QuicHttpDecodeStatus::kDecodeInProgress; } state->listener()->OnGoAwayEnd(); return QuicHttpDecodeStatus::kDecodeDone; case PayloadState::kResumeDecodingFixedFields: status = state->ResumeDecodingStructureInPayload(&goaway_fields_, db); payload_state_ = PayloadState::kHandleFixedFieldsStatus; continue; } QUIC_BUG << "PayloadState: " << payload_state_; } } } // namespace net
2,169
19,824
<gh_stars>1000+ { "main": "dist/keystone-ui-icons-icons-RefreshCcwIcon.cjs.js", "module": "dist/keystone-ui-icons-icons-RefreshCcwIcon.esm.js" }
69
940
/* * util_windows.h - Miscellaneous utilities for Win32 * * Basilisk II (C) 1997-2008 <NAME> * * Windows platform specific code copyright (C) <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _UTIL_WINDOWS_H #define _UTIL_WINDOWS_H #include <memory> #include <string> BOOL exists( const TCHAR *path ); int32 get_file_size( const TCHAR *path ); BOOL create_file( const TCHAR *path, DWORD size ); bool check_drivers(void); // Thread wrappers extern HANDLE create_thread(LPTHREAD_START_ROUTINE start_routine, void *arg = NULL); extern void wait_thread(HANDLE thread); extern void kill_thread(HANDLE thread); // Mutex wrappers class mutex_t { CRITICAL_SECTION cs; public: mutex_t() { InitializeCriticalSection(&cs); } ~mutex_t() { DeleteCriticalSection(&cs); } void lock() { EnterCriticalSection(&cs); } void unlock() { LeaveCriticalSection(&cs); } }; // Network control panel helpers extern const TCHAR *ether_name_to_guid(const TCHAR *name); extern const TCHAR *ether_guid_to_name(const TCHAR *guid); // Get TAP-Win32 devices (caller free()s returned buffer) extern const TCHAR *ether_tap_devices(void); // Wide string versions of commonly used functions extern void ErrorAlert(const wchar_t *text); extern void WarningAlert(const wchar_t *text); // ----------------- String conversion functions ----------------- // Null deleter -- does nothing. Allows returning a non-owning // unique_ptr. This should go away if observer_ptr makes it into // the standard. template <class T> struct null_delete { constexpr null_delete() noexcept = default; template <class U> null_delete(const null_delete<U>&) noexcept { } void operator ()(T*) const noexcept { } }; template <class T> struct null_delete<T[]> { constexpr null_delete() noexcept = default; void operator ()(T*) const noexcept { } template <class U> void operator ()(U*) const = delete; }; // Functions returning null-terminated C strings std::unique_ptr<char[]> str(const wchar_t* s); std::unique_ptr<wchar_t[]> wstr(const char* s); inline std::unique_ptr<const char[], null_delete<const char[]>> str(const char* s) { return std::unique_ptr<const char[], null_delete<const char[]>>(s); } inline std::unique_ptr<const wchar_t[], null_delete<const wchar_t[]>> wstr(const wchar_t* s) { return std::unique_ptr<const wchar_t[], null_delete<const wchar_t[]>>(s); } #ifdef _UNICODE #define tstr wstr #else #define tstr str #endif // Functions returning std::strings std::string to_string(const wchar_t* s); std::wstring to_wstring(const char* s); inline std::string to_string(const char* s) { return std::string(s); } inline std::wstring to_wstring(const wchar_t* s) { return std::wstring(s); } #ifdef _UNICODE #define to_tstring to_wstring #else #define to_tstring to_string #endif // BSD strlcpy/strlcat with overloads for converting between wide and narrow strings size_t strlcpy(char* dst, const char* src, size_t size); size_t strlcpy(char* dst, const wchar_t* src, size_t size); size_t strlcat(char* dst, const char* src, size_t size); size_t strlcat(char* dst, const wchar_t* src, size_t size); size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t size); size_t wcslcpy(wchar_t* dst, const char* src, size_t size); size_t wcslcat(wchar_t* dst, const wchar_t* src, size_t size); size_t wcslcat(wchar_t* dst, const char* src, size_t size); #ifdef _UNICODE #define tcslcpy wcslcpy #define tcslcat wcslcat #else #define tcslcpy strlcpy #define tcslcat strlcat #endif #endif // _UTIL_WINDOWS_H
1,567
432
/** * @file screen.h * @author <NAME> * @date 2005-2006 * * @brief Header for screen functions. * * Note that screen here refers to physical monitors. Screens are * determined using the xinerama extension (if available). There will * always be at least one screen. * */ #ifndef SCREEN_H #define SCREEN_H /** Structure to contain information about a screen. */ typedef struct ScreenType { int index; /**< The index of this screen. */ int x, y; /**< The location of this screen. */ int width, height; /**< The size of this screen. */ } ScreenType; /*@{*/ #define InitializeScreens() (void)(0) void StartupScreens(void); void ShutdownScreens(void); #define DestroyScreens() (void)(0) /*@}*/ /** Get the screen of the specified coordinates. * @param x The x-coordinate. * @param y The y-coordinate. * @return The screen. */ const ScreenType *GetCurrentScreen(int x, int y); /** Get the screen containing the mouse. * @return The screen containing the mouse. */ const ScreenType *GetMouseScreen(void); /** Get the screen of the specified index. * @param index The screen index (0 based). * @return The screen. */ const ScreenType *GetScreen(int index); /** Get the number of screens. * @return The number of screens. */ int GetScreenCount(void); #endif /* SCREEN_H */
426
415
<reponame>Quipyowert2/zzuf<filename>src/common/fd.h /* * zzuf - general purpose fuzzer * * Copyright © 2002—2015 <NAME> <<EMAIL>> * 2012 <NAME> <<EMAIL>> * * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What the Fuck You Want * to Public License, Version 2, as published by the WTFPL Task Force. * See http://www.wtfpl.net/ for more details. */ #pragma once /* * fd.h: file descriptor functions */ #include "common/common.h" #include <stdint.h> #include <wchar.h> extern void zzuf_include_pattern(char const *); extern void zzuf_exclude_pattern(char const *); extern void zzuf_set_seed(int32_t); extern void zzuf_set_ratio(double, double); extern double zzuf_get_ratio(void); extern void zzuf_set_auto_increment(void); extern void _zz_fd_init(void); extern void _zz_fd_fini(void); extern int _zz_mustwatch(char const *); extern int _zz_mustwatchw(wchar_t const *); extern int _zz_iswatched(int); extern void _zz_register(int); extern void _zz_unregister(int); extern void _zz_lockfd(int); extern void _zz_unlock(int); extern int _zz_islocked(int); extern int _zz_isactive(int); extern int64_t _zz_getpos(int); extern void _zz_setpos(int, int64_t); extern void _zz_addpos(int, int64_t); extern void _zz_setfuzzed(int, int); extern int _zz_getfuzzed(int); extern fuzz_context_t *_zz_getfuzz(int);
565
346
package com.kizitonwose.colorpreference; /** * Created by <NAME> on 10/2/2016. */ public enum PreviewSize { NORMAL, LARGE; public static PreviewSize getSize(int num) { switch (num) { case 1: return NORMAL; case 2: return LARGE; default: return NORMAL; } } }
197
833
# 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. # ResNet 34 (2015) # Paper: https://arxiv.org/pdf/1512.03385.pdf import tensorflow from tensorflow.keras import Model, Input from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, ReLU, BatchNormalization from tensorflow.keras.layers import Add, GlobalAveragePooling2D def stem(inputs): """ Construct the Stem Convolution Group inputs : input vector """ # First Convolutional layer, where pooled feature maps will be reduced by 75% x = Conv2D(64, (7, 7), strides=(2, 2), padding='same', activation='relu', kernel_initializer="he_normal")(inputs) x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x) return x def learner(x): """ Construct the Learner x : input to the learner """ # First Residual Block Group of 64 filters x = residual_group(x, 64, 3) # Second Residual Block Group of 128 filters x = residual_group(x, 128, 3) # Third Residual Block Group of 256 filters x = residual_group(x, 256, 5) # Fourth Residual Block Group of 512 filters x = residual_group(x, 512, 2, False) return x def residual_group(x, n_filters, n_blocks, conv=True): """ Construct a Residual Group x : input to the group n_filters: number of filters n_blocks : number of blocks in the group conv : flag to include the convolution block connector """ for _ in range(n_blocks): x = residual_block(x, n_filters) # Double the size of filters and reduce feature maps by 75% (strides=2, 2) to fit the next Residual Group if conv: x = conv_block(x, n_filters * 2) return x def residual_block(x, n_filters): """ Construct a Residual Block of Convolutions x : input into the block n_filters: number of filters """ shortcut = x x = Conv2D(n_filters, (3, 3), strides=(1, 1), padding="same", activation="relu", kernel_initializer="he_normal")(x) x = Conv2D(n_filters, (3, 3), strides=(1, 1), padding="same", activation="relu", kernel_initializer="he_normal")(x) x = Add()([shortcut, x]) return x def conv_block(x, n_filters): """ Construct Block of Convolutions without Pooling x : input into the block n_filters: number of filters """ x = Conv2D(n_filters, (3, 3), strides=(2, 2), padding="same", activation="relu", kernel_initializer="he_normal")(x) x = Conv2D(n_filters, (3, 3), strides=(2, 2), padding="same", activation="relu", kernel_initializer="he_normal")(x) return x def classifier(x, n_classes): """ Construct the Classifier Group x : input vector n_classes : number of output classes """ # Pool at the end of all the convolutional residual blocks x = GlobalAveragePooling2D()(x) # Final Dense Outputting Layer for the outputs outputs = Dense(n_classes, activation='softmax', kernel_initializer='he_normal')(x) return outputs # The input tensor inputs = Input(shape=(224, 224, 3)) # The Stem Convolution Group x = stem(inputs) # The learner x = learner(x) # The Classifier for 1000 classes outputs = classifier(x, 1000) # Instantiate the Model model = Model(inputs, outputs)
1,463
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Rite", "definitions": [ "A religious or other solemn ceremony or act.", "A body of customary observances characteristic of a Church or a part of it.", "A social custom, practice, or conventional act." ], "parts-of-speech": "Noun" }
122
471
<reponame>madanagopaltcomcast/pxCore ///////////////////////////////////////////////////////////////////////////// // Name: referencenotes.h // Purpose: topic overview // Author: wxWidgets team // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// /** @page overview_referencenotes Notes on Using this Reference Manual @tableofcontents In the descriptions of the wxWidgets classes and their member functions, note that descriptions of inherited member functions are not duplicated in derived classes unless their behaviour is different. So in using a class such as wxScrolledWindow, be aware that wxWindow functions may be relevant. Where not explicitly stated, size and position arguments may usually be given a value of ::wxDefaultSize and ::wxDefaultPosition, in which case wxWidgets will choose suitable values. */
221
3,662
<gh_stars>1000+ # yellowbrick.style.rcmod # Modifies the matplotlib rcParams in order to make yellowbrick appealing. # # Author: <NAME> # Created: Thu Oct 06 08:45:38 2016 -0400 # # Copyright (C) 2016 The scikit-yb developers # For license information, see LICENSE.txt # # ID: rcmod.py [c6aff34] <EMAIL> $ """ Modifies the matplotlib rcParams in order to make yellowbrick more appealing. This has been modified from Seaborn's rcmod.py: github.com/mwaskom/seaborn in order to alter the matplotlib rc dictionary on the fly. NOTE: matplotlib 2.0 styles mean we can simply convert this to a stylesheet! """ ########################################################################## ## Imports ########################################################################## import functools import numpy as np import matplotlib as mpl # Check to see if we have a slightly modern version of mpl from distutils.version import LooseVersion mpl_ge_150 = LooseVersion(mpl.__version__) >= "1.5.0" from .. import _orig_rc_params from .palettes import color_palette, set_color_codes ########################################################################## ## Exports ########################################################################## __all__ = ["set_aesthetic", "set_style", "set_palette", "reset_defaults", "reset_orig"] ########################################################################## ## rcParams Keys ########################################################################## _style_keys = ( "axes.facecolor", "axes.edgecolor", "axes.grid", "axes.axisbelow", "axes.linewidth", "axes.labelcolor", "figure.facecolor", "grid.color", "grid.linestyle", "text.color", "xtick.color", "ytick.color", "xtick.direction", "ytick.direction", "xtick.major.size", "ytick.major.size", "xtick.minor.size", "ytick.minor.size", "legend.frameon", "legend.numpoints", "legend.scatterpoints", "lines.solid_capstyle", "image.cmap", "font.family", "font.sans-serif", ) _context_keys = ( "figure.figsize", "font.size", "axes.labelsize", "axes.titlesize", "xtick.labelsize", "ytick.labelsize", "legend.fontsize", "grid.linewidth", "lines.linewidth", "patch.linewidth", "lines.markersize", "lines.markeredgewidth", "xtick.major.width", "ytick.major.width", "xtick.minor.width", "ytick.minor.width", "xtick.major.pad", "ytick.major.pad", ) ########################################################################## ## rcParams Keys ########################################################################## def set_aesthetic( palette="yellowbrick", font="sans-serif", font_scale=1, color_codes=True, rc=None ): """ Set aesthetic parameters in one step. Each set of parameters can be set directly or temporarily, see the referenced functions below for more information. Parameters ---------- palette : string or sequence Color palette, see :func:`color_palette` font : string Font family, see matplotlib font manager. font_scale : float, optional Separate scaling factor to independently scale the size of the font elements. color_codes : bool If ``True`` and ``palette`` is a yellowbrick palette, remap the shorthand color codes (e.g. "b", "g", "r", etc.) to the colors from this palette. rc : dict or None Dictionary of rc parameter mappings to override the above. """ _set_context(font_scale) set_style(rc={"font.family": font}) set_palette(palette, color_codes=color_codes) if rc is not None: mpl.rcParams.update(rc) def reset_defaults(): """ Restore all RC params to default settings. """ mpl.rcParams.update(mpl.rcParamsDefault) def reset_orig(): """ Restore all RC params to original settings (respects custom rc). """ mpl.rcParams.update(_orig_rc_params) ########################################################################## ## Axes Styles ########################################################################## def _axes_style(style=None, rc=None): """ Return a parameter dict for the aesthetic style of the plots. NOTE: This is an internal method from Seaborn that is simply used to create a default aesthetic in yellowbrick. If you'd like to use these styles then import Seaborn! This affects things like the color of the axes, whether a grid is enabled by default, and other aesthetic elements. This function returns an object that can be used in a ``with`` statement to temporarily change the style parameters. Parameters ---------- style : dict, reset, or None A dictionary of parameters or the name of a preconfigured set. rc : dict, optional Parameter mappings to override the values in the preset seaborn style dictionaries. This only updates parameters that are considered part of the style definition. """ if isinstance(style, dict): style_dict = style else: # Define colors here dark_gray = ".15" light_gray = ".8" # Common parameters style_dict = { "figure.facecolor": "white", "text.color": dark_gray, "axes.labelcolor": dark_gray, "legend.frameon": False, "legend.numpoints": 1, "legend.scatterpoints": 1, "xtick.direction": "out", "ytick.direction": "out", "xtick.color": dark_gray, "ytick.color": dark_gray, "axes.axisbelow": True, "image.cmap": "Greys", "font.family": ["sans-serif"], "font.sans-serif": [ "Arial", "Liberation Sans", "Bitstream Vera Sans", "sans-serif", ], "grid.linestyle": "-", "axes.grid": True, "lines.solid_capstyle": "round", "axes.facecolor": "white", "axes.edgecolor": light_gray, "axes.linewidth": 1.25, "grid.color": light_gray, "xtick.major.size": 0, "ytick.major.size": 0, "xtick.minor.size": 0, "ytick.minor.size": 0, } # Override these settings with the provided rc dictionary if rc is not None: rc = {k: v for k, v in rc.items() if k in _style_keys} style_dict.update(rc) # Wrap in an _AxesStyle object so this can be used in a with statement style_object = _AxesStyle(style_dict) return style_object def set_style(style=None, rc=None): """ Set the aesthetic style of the plots. This affects things like the color of the axes, whether a grid is enabled by default, and other aesthetic elements. Parameters ---------- style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks} A dictionary of parameters or the name of a preconfigured set. rc : dict, optional Parameter mappings to override the values in the preset seaborn style dictionaries. This only updates parameters that are considered part of the style definition. """ style_object = _axes_style(style, rc) mpl.rcParams.update(style_object) ########################################################################## ## Context ########################################################################## def _plotting_context(context=None, font_scale=1, rc=None): """ Return a parameter dict to scale elements of the figure. NOTE: This is an internal method from Seaborn that is simply used to create a default aesthetic in yellowbrick. If you'd like to use these styles then import Seaborn! This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. The base context is "notebook", and the other contexts are "paper", "talk", and "poster", which are version of the notebook parameters scaled by .8, 1.3, and 1.6, respectively. This function returns an object that can be used in a ``with`` statement to temporarily change the context parameters. Parameters ---------- context : dict, None, or one of {paper, notebook, talk, poster} A dictionary of parameters or the name of a preconfigured set. font_scale : float, optional Separate scaling factor to independently scale the size of the font elements. rc : dict, optional Parameter mappings to override the values in the preset seaborn context dictionaries. This only updates parameters that are considered part of the context definition. """ if isinstance(context, dict): context_dict = context else: # Set up dictionary of default parameters base_context = { "figure.figsize": np.array([8, 5.5]), "font.size": 12, "axes.labelsize": 11, "axes.titlesize": 12, "xtick.labelsize": 10, "ytick.labelsize": 10, "legend.fontsize": 10, "grid.linewidth": 1, "lines.linewidth": 1.75, "patch.linewidth": 0.3, "lines.markersize": 7, "lines.markeredgewidth": 0, "xtick.major.width": 1, "ytick.major.width": 1, "xtick.minor.width": 0.5, "ytick.minor.width": 0.5, "xtick.major.pad": 7, "ytick.major.pad": 7, } # Scale all the parameters by the same factor depending on the context scaling = dict(paper=0.8, notebook=1, talk=1.3, poster=1.6)["notebook"] context_dict = {k: v * scaling for k, v in base_context.items()} # Now independently scale the fonts font_keys = [ "axes.labelsize", "axes.titlesize", "legend.fontsize", "xtick.labelsize", "ytick.labelsize", "font.size", ] font_dict = {k: context_dict[k] * font_scale for k in font_keys} context_dict.update(font_dict) # Implement hack workaround for matplotlib bug # See https://github.com/mwaskom/seaborn/issues/344 # There is a bug in matplotlib 1.4.2 that makes points invisible when # they don't have an edgewidth. It will supposedly be fixed in 1.4.3. if mpl.__version__ == "1.4.2": context_dict["lines.markeredgewidth"] = 0.01 # Override these settings with the provided rc dictionary if rc is not None: rc = {k: v for k, v in rc.items() if k in _context_keys} context_dict.update(rc) # Wrap in a _PlottingContext object so this can be used in a with statement context_object = _PlottingContext(context_dict) return context_object def _set_context(context=None, font_scale=1, rc=None): """ Set the plotting context parameters. NOTE: This is an internal method from Seaborn that is simply used to create a default aesthetic in yellowbrick. If you'd like to use these styles then import Seaborn! This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. The base context is "notebook", and the other contexts are "paper", "talk", and "poster", which are version of the notebook parameters scaled by .8, 1.3, and 1.6, respectively. Parameters ---------- context : dict, None, or one of {paper, notebook, talk, poster} A dictionary of parameters or the name of a preconfigured set. font_scale : float, optional Separate scaling factor to independently scale the size of the font elements. rc : dict, optional Parameter mappings to override the values in the preset seaborn context dictionaries. This only updates parameters that are considered part of the context definition. """ context_object = _plotting_context(context, font_scale, rc) mpl.rcParams.update(context_object) class _RCAesthetics(dict): def __enter__(self): rc = mpl.rcParams self._orig = {k: rc[k] for k in self._keys} self._set(self) def __exit__(self, exc_type, exc_value, exc_tb): self._set(self._orig) def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): with self: return func(*args, **kwargs) return wrapper class _AxesStyle(_RCAesthetics): """Light wrapper on a dict to set style temporarily.""" _keys = _style_keys _set = staticmethod(set_style) class _PlottingContext(_RCAesthetics): """Light wrapper on a dict to set context temporarily.""" _keys = _context_keys _set = staticmethod(_set_context) ########################################################################## ## Colors/Palettes ########################################################################## def set_palette(palette, n_colors=None, color_codes=False): """ Set the matplotlib color cycle using a seaborn palette. Parameters ---------- palette : yellowbrick color palette | seaborn color palette (with ``sns_`` prepended) Palette definition. Should be something that :func:`color_palette` can process. n_colors : int Number of colors in the cycle. The default number of colors will depend on the format of ``palette``, see the :func:`color_palette` documentation for more information. color_codes : bool If ``True`` and ``palette`` is a seaborn palette, remap the shorthand color codes (e.g. "b", "g", "r", etc.) to the colors from this palette. """ colors = color_palette(palette, n_colors) if mpl_ge_150: from cycler import cycler cyl = cycler("color", colors) mpl.rcParams["axes.prop_cycle"] = cyl else: mpl.rcParams["axes.color_cycle"] = list(colors) mpl.rcParams["patch.facecolor"] = colors[0] if color_codes: set_color_codes(palette)
5,329
8,747
<reponame>lovyan03/esp-idf #!/usr/bin/env python import os import re import subprocess import sys import tempfile import textwrap import unittest from future.utils import iteritems class ConfgenBaseTestCase(unittest.TestCase): @classmethod def setUpClass(self): self.args = dict() self.functions = {'in': self.assertIn, 'not in': self.assertNotIn, 'equal': self.assertEqual, 'not equal': self.assertNotEqual} try: regex_func = self.assertRegex except AttributeError: # Python 2 fallback regex_func = self.assertRegexpMatches finally: self.functions['regex'] = lambda instance, s, expr: regex_func(instance, expr, s) # reverse args order def setUp(self): with tempfile.NamedTemporaryFile(prefix='test_confgen_', delete=False) as f: self.output_file = f.name self.addCleanup(os.remove, self.output_file) def invoke_confgen(self, args): call_args = [sys.executable, '../../confgen.py'] for (k, v) in iteritems(args): if k != 'output': if isinstance(v, type('')): # easy Python 2/3 compatible str/unicode call_args += ['--{}'.format(k), v] else: for i in v: call_args += ['--{}'.format(k), i] call_args += ['--output', args['output'], self.output_file] # these arguments belong together subprocess.check_call(call_args) def invoke_and_test(self, in_text, out_text, test='in'): """ Main utility function for testing confgen: - Runs confgen via invoke_confgen(), using output method pre-set in test class setup - in_text is the Kconfig file input content - out_text is some expected output from confgen - 'test' can be any function key from self.functions dict (see above). Default is 'in' to test if out_text is a substring of the full confgen output. """ with tempfile.NamedTemporaryFile(mode='w+', prefix='test_confgen_', delete=False) as f: self.addCleanup(os.remove, f.name) f.write(textwrap.dedent(in_text)) self.args['kconfig'] = f.name self.invoke_confgen(self.args) with open(self.output_file) as f_result: result = f_result.read() try: out_text = textwrap.dedent(out_text) except TypeError: pass # probably a regex self.functions[test](self, out_text, result) class CmakeTestCase(ConfgenBaseTestCase): @classmethod def setUpClass(self): super(CmakeTestCase, self).setUpClass() self.args.update({'output': 'cmake'}) def testStringEscape(self): self.invoke_and_test(""" config PASSWORD string "password" default "\\\\~!@#$%^&*()\\\"" """, 'set(CONFIG_PASSWORD "\\\\~!@#$%^&*()\\\"")') def testHexPrefix(self): self.invoke_and_test(HEXPREFIX_KCONFIG, 'set(CONFIG_HEX_NOPREFIX "0x33")') self.invoke_and_test(HEXPREFIX_KCONFIG, 'set(CONFIG_HEX_PREFIX "0x77")') class JsonTestCase(ConfgenBaseTestCase): @classmethod def setUpClass(self): super(JsonTestCase, self).setUpClass() self.args.update({'output': 'json'}) def testStringEscape(self): self.invoke_and_test(""" config PASSWORD string "password" default "\\\\~!@#$%^&*()\\\"" """, '"PASSWORD": "\\\\~!@#$%^&*()\\\""') def testHexPrefix(self): # hex values come out as integers in JSON, due to no hex type self.invoke_and_test(HEXPREFIX_KCONFIG, '"HEX_NOPREFIX": %d' % 0x33) self.invoke_and_test(HEXPREFIX_KCONFIG, '"HEX_PREFIX": %d' % 0x77) class JsonMenuTestCase(ConfgenBaseTestCase): @classmethod def setUpClass(self): super(JsonMenuTestCase, self).setUpClass() self.args.update({'output': 'json_menus'}) def testMultipleRanges(self): self.invoke_and_test(""" config IDF_TARGET string "IDF target" default "esp32" config SOME_SETTING int "setting for the chip" range 0 100 if IDF_TARGET="esp32s0" range 0 10 if IDF_TARGET="esp32" range -10 1 if IDF_TARGET="esp32s2" """, re.compile(r'"range":\s+\[\s+0,\s+10\s+\]'), 'regex') def testHexRanges(self): self.invoke_and_test(""" config SOME_SETTING hex "setting for the chip" range 0x0 0xaf if UNDEFINED range 0x10 0xaf """, r'"range":\s+\[\s+16,\s+175\s+\]', 'regex') class ConfigTestCase(ConfgenBaseTestCase): @classmethod def setUpClass(self): super(ConfigTestCase, self).setUpClass() self.args.update({'output': 'config'}) self.input = """ config TEST bool "test" default "n" """ def setUp(self): super(ConfigTestCase, self).setUp() with tempfile.NamedTemporaryFile(mode='w+', prefix='test_confgen_', delete=False) as f: self.addCleanup(os.remove, f.name) self.args.update({'config': f.name}) # this is input in contrast with {'output': 'config'} f.write(textwrap.dedent(""" CONFIG_TEST=y CONFIG_UNKNOWN=y """)) def testKeepSavedOption(self): self.invoke_and_test(self.input, 'CONFIG_TEST=y') def testDiscardUnknownOption(self): self.invoke_and_test(self.input, 'CONFIG_UNKNOWN', 'not in') class MakefileTestCase(ConfgenBaseTestCase): @classmethod def setUpClass(self): super(MakefileTestCase, self).setUpClass() self.args.update({'output': 'makefile'}) def setUp(self): super(MakefileTestCase, self).setUp() with tempfile.NamedTemporaryFile(mode='w+', prefix='test_confgen_', delete=False) as f1: self.addCleanup(os.remove, f1.name) with tempfile.NamedTemporaryFile(mode='w+', prefix='test_confgen_', delete=False) as f2: self.addCleanup(os.remove, f2.name) self.args.update({'env': ['COMPONENT_KCONFIGS_PROJBUILD_SOURCE_FILE={}'.format(f1.name), 'COMPONENT_KCONFIGS_SOURCE_FILE={}'.format(f2.name), 'IDF_TARGET=esp32']}) def testTarget(self): with open(os.path.join(os.environ['IDF_PATH'], 'Kconfig')) as f: self.invoke_and_test(f.read(), 'CONFIG_IDF_TARGET="esp32"') def testHexPrefix(self): self.invoke_and_test(HEXPREFIX_KCONFIG, 'CONFIG_HEX_NOPREFIX=0x33') self.invoke_and_test(HEXPREFIX_KCONFIG, 'CONFIG_HEX_PREFIX=0x77') class HeaderTestCase(ConfgenBaseTestCase): @classmethod def setUpClass(self): super(HeaderTestCase, self).setUpClass() self.args.update({'output': 'header'}) def testStringEscape(self): self.invoke_and_test(""" config PASSWORD string "password" default "\\\\~!@#$%^&*()\\\"" """, '#define CONFIG_PASSWORD "\\\\~!@#$%^&*()\\\""') def testHexPrefix(self): self.invoke_and_test(HEXPREFIX_KCONFIG, '#define CONFIG_HEX_NOPREFIX 0x33') self.invoke_and_test(HEXPREFIX_KCONFIG, '#define CONFIG_HEX_PREFIX 0x77') class DocsTestCase(ConfgenBaseTestCase): @classmethod def setUpClass(self): super(DocsTestCase, self).setUpClass() self.args.update({'output': 'docs', 'env': 'IDF_TARGET=esp32'}) def testChoice(self): self.invoke_and_test(""" menu "TEST" choice TYPES prompt "types" default TYPES_OP2 help Description of TYPES config TYPES_OP1 bool "option 1" config TYPES_OP2 bool "option 2" endchoice endmenu """, """ TEST ---- Contains: - :ref:`CONFIG_TYPES` .. _CONFIG_TYPES: CONFIG_TYPES ^^^^^^^^^^^^ types :emphasis:`Found in:` :ref:`test` Description of TYPES Available options: - option 1 (TYPES_OP1) - option 2 (TYPES_OP2) """) # this is more readable than regex # Used by multiple testHexPrefix() test cases to verify correct hex output for each format HEXPREFIX_KCONFIG = """ config HEX_NOPREFIX hex "Hex Item default no prefix" default 33 config HEX_PREFIX hex "Hex Item default prefix" default 0x77 """ if __name__ == '__main__': unittest.main()
4,272
3,372
<filename>aws-java-sdk-codeguruprofiler/src/main/java/com/amazonaws/services/codeguruprofiler/model/FindingsReportSummary.java /* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codeguruprofiler.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Information about potential recommendations that might be created from the analysis of profiling data. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/FindingsReportSummary" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class FindingsReportSummary implements Serializable, Cloneable, StructuredPojo { /** * <p> * The universally unique identifier (UUID) of the recommendation report. * </p> */ private String id; /** * <p> * The end time of the period during which the metric is flagged as anomalous. This is specified using the ISO 8601 * format. For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * </p> */ private java.util.Date profileEndTime; /** * <p> * The start time of the profile the analysis data is about. This is specified using the ISO 8601 format. For * example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * </p> */ private java.util.Date profileStartTime; /** * <p> * The name of the profiling group that is associated with the analysis data. * </p> */ private String profilingGroupName; /** * <p> * The total number of different recommendations that were found by the analysis. * </p> */ private Integer totalNumberOfFindings; /** * <p> * The universally unique identifier (UUID) of the recommendation report. * </p> * * @param id * The universally unique identifier (UUID) of the recommendation report. */ public void setId(String id) { this.id = id; } /** * <p> * The universally unique identifier (UUID) of the recommendation report. * </p> * * @return The universally unique identifier (UUID) of the recommendation report. */ public String getId() { return this.id; } /** * <p> * The universally unique identifier (UUID) of the recommendation report. * </p> * * @param id * The universally unique identifier (UUID) of the recommendation report. * @return Returns a reference to this object so that method calls can be chained together. */ public FindingsReportSummary withId(String id) { setId(id); return this; } /** * <p> * The end time of the period during which the metric is flagged as anomalous. This is specified using the ISO 8601 * format. For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * </p> * * @param profileEndTime * The end time of the period during which the metric is flagged as anomalous. This is specified using the * ISO 8601 format. For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 * PM UTC. */ public void setProfileEndTime(java.util.Date profileEndTime) { this.profileEndTime = profileEndTime; } /** * <p> * The end time of the period during which the metric is flagged as anomalous. This is specified using the ISO 8601 * format. For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * </p> * * @return The end time of the period during which the metric is flagged as anomalous. This is specified using the * ISO 8601 format. For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 * PM UTC. */ public java.util.Date getProfileEndTime() { return this.profileEndTime; } /** * <p> * The end time of the period during which the metric is flagged as anomalous. This is specified using the ISO 8601 * format. For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * </p> * * @param profileEndTime * The end time of the period during which the metric is flagged as anomalous. This is specified using the * ISO 8601 format. For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 * PM UTC. * @return Returns a reference to this object so that method calls can be chained together. */ public FindingsReportSummary withProfileEndTime(java.util.Date profileEndTime) { setProfileEndTime(profileEndTime); return this; } /** * <p> * The start time of the profile the analysis data is about. This is specified using the ISO 8601 format. For * example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * </p> * * @param profileStartTime * The start time of the profile the analysis data is about. This is specified using the ISO 8601 format. For * example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. */ public void setProfileStartTime(java.util.Date profileStartTime) { this.profileStartTime = profileStartTime; } /** * <p> * The start time of the profile the analysis data is about. This is specified using the ISO 8601 format. For * example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * </p> * * @return The start time of the profile the analysis data is about. This is specified using the ISO 8601 format. * For example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. */ public java.util.Date getProfileStartTime() { return this.profileStartTime; } /** * <p> * The start time of the profile the analysis data is about. This is specified using the ISO 8601 format. For * example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * </p> * * @param profileStartTime * The start time of the profile the analysis data is about. This is specified using the ISO 8601 format. For * example, 2020-06-01T13:15:02.001Z represents 1 millisecond past June 1, 2020 1:15:02 PM UTC. * @return Returns a reference to this object so that method calls can be chained together. */ public FindingsReportSummary withProfileStartTime(java.util.Date profileStartTime) { setProfileStartTime(profileStartTime); return this; } /** * <p> * The name of the profiling group that is associated with the analysis data. * </p> * * @param profilingGroupName * The name of the profiling group that is associated with the analysis data. */ public void setProfilingGroupName(String profilingGroupName) { this.profilingGroupName = profilingGroupName; } /** * <p> * The name of the profiling group that is associated with the analysis data. * </p> * * @return The name of the profiling group that is associated with the analysis data. */ public String getProfilingGroupName() { return this.profilingGroupName; } /** * <p> * The name of the profiling group that is associated with the analysis data. * </p> * * @param profilingGroupName * The name of the profiling group that is associated with the analysis data. * @return Returns a reference to this object so that method calls can be chained together. */ public FindingsReportSummary withProfilingGroupName(String profilingGroupName) { setProfilingGroupName(profilingGroupName); return this; } /** * <p> * The total number of different recommendations that were found by the analysis. * </p> * * @param totalNumberOfFindings * The total number of different recommendations that were found by the analysis. */ public void setTotalNumberOfFindings(Integer totalNumberOfFindings) { this.totalNumberOfFindings = totalNumberOfFindings; } /** * <p> * The total number of different recommendations that were found by the analysis. * </p> * * @return The total number of different recommendations that were found by the analysis. */ public Integer getTotalNumberOfFindings() { return this.totalNumberOfFindings; } /** * <p> * The total number of different recommendations that were found by the analysis. * </p> * * @param totalNumberOfFindings * The total number of different recommendations that were found by the analysis. * @return Returns a reference to this object so that method calls can be chained together. */ public FindingsReportSummary withTotalNumberOfFindings(Integer totalNumberOfFindings) { setTotalNumberOfFindings(totalNumberOfFindings); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getId() != null) sb.append("Id: ").append(getId()).append(","); if (getProfileEndTime() != null) sb.append("ProfileEndTime: ").append(getProfileEndTime()).append(","); if (getProfileStartTime() != null) sb.append("ProfileStartTime: ").append(getProfileStartTime()).append(","); if (getProfilingGroupName() != null) sb.append("ProfilingGroupName: ").append(getProfilingGroupName()).append(","); if (getTotalNumberOfFindings() != null) sb.append("TotalNumberOfFindings: ").append(getTotalNumberOfFindings()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof FindingsReportSummary == false) return false; FindingsReportSummary other = (FindingsReportSummary) obj; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; if (other.getProfileEndTime() == null ^ this.getProfileEndTime() == null) return false; if (other.getProfileEndTime() != null && other.getProfileEndTime().equals(this.getProfileEndTime()) == false) return false; if (other.getProfileStartTime() == null ^ this.getProfileStartTime() == null) return false; if (other.getProfileStartTime() != null && other.getProfileStartTime().equals(this.getProfileStartTime()) == false) return false; if (other.getProfilingGroupName() == null ^ this.getProfilingGroupName() == null) return false; if (other.getProfilingGroupName() != null && other.getProfilingGroupName().equals(this.getProfilingGroupName()) == false) return false; if (other.getTotalNumberOfFindings() == null ^ this.getTotalNumberOfFindings() == null) return false; if (other.getTotalNumberOfFindings() != null && other.getTotalNumberOfFindings().equals(this.getTotalNumberOfFindings()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); hashCode = prime * hashCode + ((getProfileEndTime() == null) ? 0 : getProfileEndTime().hashCode()); hashCode = prime * hashCode + ((getProfileStartTime() == null) ? 0 : getProfileStartTime().hashCode()); hashCode = prime * hashCode + ((getProfilingGroupName() == null) ? 0 : getProfilingGroupName().hashCode()); hashCode = prime * hashCode + ((getTotalNumberOfFindings() == null) ? 0 : getTotalNumberOfFindings().hashCode()); return hashCode; } @Override public FindingsReportSummary clone() { try { return (FindingsReportSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.codeguruprofiler.model.transform.FindingsReportSummaryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
5,142
409
{ "id": "centrifugal", "name": "<NAME>", "description": "insert cool description here", "author": "<NAME>", "menuPriority": 71, "selectable": true, "styleId": "centrifugal", "musicId": "tengil", "luaFile": "Scripts/Levels/centrifugal.lua", "difficultyMults": [1.2, 1.4, 1.6, 0.6, 0.3] }
152
583
#pragma once #include <type_traits> #include "storage/segment_iterables.hpp" #include "storage/lz4_segment.hpp" #include "storage/vector_compression/resolve_compressed_vector_type.hpp" namespace opossum { template <typename T> class LZ4SegmentIterable : public PointAccessibleSegmentIterable<LZ4SegmentIterable<T>> { public: using ValueType = T; explicit LZ4SegmentIterable(const LZ4Segment<T>& segment) : _segment{segment} {} template <typename Functor> void _on_with_iterators(const Functor& functor) const { using ValueIterator = typename std::vector<T>::const_iterator; auto decompressed_segment = _segment.decompress(); _segment.access_counter[SegmentAccessCounter::AccessType::Sequential] += decompressed_segment.size(); if (_segment.null_values()) { auto begin = Iterator<ValueIterator>{decompressed_segment.cbegin(), _segment.null_values()->cbegin(), ChunkOffset{0u}}; auto end = Iterator<ValueIterator>{decompressed_segment.cend(), _segment.null_values()->cend(), static_cast<ChunkOffset>(decompressed_segment.size())}; functor(begin, end); } else { auto begin = Iterator<ValueIterator>{decompressed_segment.cbegin(), std::nullopt, ChunkOffset{0u}}; auto end = Iterator<ValueIterator>{decompressed_segment.cend(), std::nullopt, static_cast<ChunkOffset>(decompressed_segment.size())}; functor(begin, end); } } /** * For the point access, we first retrieve the values for all chunk offsets in the position list and then save * the decompressed values in a vector. The first value in that vector (index 0) is the value for the chunk offset * at index 0 in the position list. */ template <typename Functor, typename PosListType> void _on_with_iterators(const std::shared_ptr<PosListType>& position_filter, const Functor& functor) const { const auto position_filter_size = position_filter->size(); _segment.access_counter[SegmentAccessCounter::access_type(*position_filter)] += position_filter_size; // vector storing the uncompressed values auto decompressed_filtered_segment = std::vector<ValueType>(position_filter_size); // _segment.decompress() takes the currently cached block (reference) and its id in addition to the requested // element. If the requested element is not within that block, the next block will be decompressed and written to // `cached_block` while the value and the new block id are returned. In case the requested element is within the // cached block, the value and the input block id are returned. for (auto index = size_t{0u}; index < position_filter_size; ++index) { const auto& position = (*position_filter)[index]; // NOLINTNEXTLINE auto [value, block_index] = _segment.decompress(position.chunk_offset, cached_block_index, cached_block); decompressed_filtered_segment[index] = std::move(value); cached_block_index = block_index; } using PosListIteratorType = decltype(position_filter->cbegin()); if (_segment.null_values()) { auto begin = PointAccessIterator<PosListIteratorType>{decompressed_filtered_segment.begin(), _segment.null_values()->cbegin(), position_filter->cbegin(), position_filter->cbegin()}; auto end = PointAccessIterator<PosListIteratorType>{decompressed_filtered_segment.begin(), _segment.null_values()->cend(), position_filter->cbegin(), position_filter->cend()}; functor(begin, end); } else { auto begin = PointAccessIterator<PosListIteratorType>{decompressed_filtered_segment.begin(), std::nullopt, position_filter->cbegin(), position_filter->cbegin()}; auto end = PointAccessIterator<PosListIteratorType>{decompressed_filtered_segment.begin(), std::nullopt, position_filter->cbegin(), position_filter->cend()}; functor(begin, end); } } size_t _on_size() const { return _segment.size(); } private: const LZ4Segment<T>& _segment; mutable std::vector<char> cached_block; mutable std::optional<size_t> cached_block_index = std::nullopt; private: template <typename ValueIterator> class Iterator : public AbstractSegmentIterator<Iterator<ValueIterator>, SegmentPosition<T>> { public: using ValueType = T; using IterableType = LZ4SegmentIterable<T>; using NullValueIterator = typename pmr_vector<bool>::const_iterator; public: // Begin and End Iterator explicit Iterator(ValueIterator data_it, std::optional<NullValueIterator> null_value_it, ChunkOffset chunk_offset) : _chunk_offset{chunk_offset}, _data_it{std::move(data_it)}, _null_value_it{std::move(null_value_it)} {} private: friend class boost::iterator_core_access; // grants the boost::iterator_facade access to the private interface void increment() { ++_chunk_offset; ++_data_it; if (_null_value_it) ++(*_null_value_it); } void decrement() { --_chunk_offset; --_data_it; if (_null_value_it) --(*_null_value_it); } void advance(std::ptrdiff_t n) { _chunk_offset += n; _data_it += n; if (_null_value_it) *_null_value_it += n; } bool equal(const Iterator& other) const { return _data_it == other._data_it; } std::ptrdiff_t distance_to(const Iterator& other) const { return std::ptrdiff_t{other._chunk_offset} - std::ptrdiff_t{_chunk_offset}; } SegmentPosition<T> dereference() const { return SegmentPosition<T>{*_data_it, _null_value_it ? **_null_value_it : false, _chunk_offset}; } private: ChunkOffset _chunk_offset; ValueIterator _data_it; std::optional<NullValueIterator> _null_value_it; }; template <typename PosListIteratorType> class PointAccessIterator : public AbstractPointAccessSegmentIterator<PointAccessIterator<PosListIteratorType>, SegmentPosition<T>, PosListIteratorType> { public: using ValueType = T; using IterableType = LZ4SegmentIterable<T>; using DataIteratorType = typename std::vector<T>::const_iterator; using NullValueIterator = typename pmr_vector<bool>::const_iterator; // Begin Iterator PointAccessIterator(DataIteratorType data_it, std::optional<NullValueIterator> null_value_it, PosListIteratorType position_filter_begin, PosListIteratorType position_filter_it) : AbstractPointAccessSegmentIterator<PointAccessIterator<PosListIteratorType>, SegmentPosition<T>, PosListIteratorType>{std::move(position_filter_begin), std::move(position_filter_it)}, _data_it{std::move(data_it)}, _null_value_it{std::move(null_value_it)} {} private: friend class boost::iterator_core_access; // grants the boost::iterator_facade access to the private interface SegmentPosition<T> dereference() const { const auto& chunk_offsets = this->chunk_offsets(); const auto& value = *(_data_it + chunk_offsets.offset_in_poslist); const auto is_null = _null_value_it && *(*_null_value_it + chunk_offsets.offset_in_referenced_chunk); return SegmentPosition<T>{value, is_null, chunk_offsets.offset_in_poslist}; } private: DataIteratorType _data_it; std::optional<NullValueIterator> _null_value_it; }; }; } // namespace opossum
3,147
318
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is 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. // __END_LICENSE__ #ifndef VW_GEOMETRY_CUTPOLYUTILS_H #define VW_GEOMETRY_CUTPOLYUTILS_H #include <vector> #include <iostream> #include <cmath> #include <cstdlib> #include <sstream> #include <string> #include <vw/Geometry/geomUtils.h> namespace vw { namespace geometry { struct valIndex{ double val; int index; bool isOutward; int nextIndexInward; // Useful only when isOutward is true }; void cutPolyLine(// inputs -- the polygonal line int numVerts, const double * xv, const double * yv, // inputs -- the cutting window double xll, double yll, double xur, double yur, // outputs -- the cut polygons std::vector< double> & cutX, std::vector< double> & cutY, std::vector< int> & cutNumPolys); void cutPoly(// inputs -- the polygons int numPolys, const int * numVerts, const double * xv, const double * yv, // inputs -- the cutting window double xll, double yll, double xur, double yur, // outputs -- the cut polygons std::vector< double> & cutX, std::vector< double> & cutY, std::vector< int> & cutNumPolys); inline bool lessThan (valIndex A, valIndex B){ return A.val < B.val; } void processPointsOnCutline(std::vector<valIndex> & ptsOnCutline); void cutToHalfSpace(// inputs double nx, double ny, double dotH, int numV, const double * xv, const double * yv, // outputs -- the cut polygons std::vector<double> & cutX, std::vector<double> & cutY, std::vector<int> & cutNumPolys); }} #endif // VW_GEOMETRY_CUTPOLYUTILS_H
1,161
495
/* * Copyright 2014-2016 Media for Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.m4m; /** * This class is used to store and pass Uri references that conform to RFC 2396 in String form. */ public class Uri { private String uri; /** * Instantiates an object using a specified URI. * * @param uri URI. */ public Uri(String uri) { this.uri = uri; } /** * Returns an URI. * * @return URI. */ public String getString() { return uri; } }
346
1,006
/**************************************************************************** * libs/libc/net/lib_freeifaddrs.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <ifaddrs.h> #include "libc.h" /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: freeifaddrs * * Description: * The freeifaddrs() function frees the data structure returned by * getifaddrs(). * * Input Parameters: * addrs - The data structure to free * * Returned Value: * None * ****************************************************************************/ void freeifaddrs(FAR struct ifaddrs *addrs) { while (addrs != NULL) { FAR struct ifaddrs *tmp = addrs; addrs = addrs->ifa_next; lib_free(tmp); } }
443
1,561
// Copyright 1996-2021 Cyberbotics Ltd. // // 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. /* * Description: Abstract tab used to build specifi tabs */ #ifndef ABSTRACT_WIDGET_HPP #define ABSTRACT_WIDGET_HPP #include <QtWidgets/QWidget> #include <graph2d/Graph2D.hpp> class QGridLayout; class QCheckBox; class QLabel; using namespace webotsQtUtils; class AbstractWidget : public QWidget { Q_OBJECT public: AbstractWidget(QWidget *parent = 0); virtual ~AbstractWidget(); virtual void update() = 0; public slots: void updateEnableCheckBoxText(); protected: webotsQtUtils::Graph2D *mGraph; // Disable cppcheck errors reproducible only on Windows on David's computer // cppcheck-suppress unsafeClassCanLeak QGridLayout *mLayout; // cppcheck-suppress unsafeClassCanLeak QCheckBox *mEnableCheckBox; // cppcheck-suppress unsafeClassCanLeak QLabel *mValueLabel; // colors static QColor black() { return QColor(0, 0, 0); } static QColor red() { return QColor(200, 50, 50); } static QColor green() { return QColor(50, 200, 50); } static QColor blue() { return QColor(50, 50, 200); } static int pointsKeptNumber() { return 200; } }; #endif // ABSTRACT_WIDGET_HPP
542
841
<reponame>brunolmfg/resteasy package org.jboss.resteasy.test.providers.custom.resource; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.ExceptionMapper; import jakarta.ws.rs.ext.Provider; import java.io.IOException; @Provider public class ProviderContextInjectionIOExceptionExceptionMapper implements ExceptionMapper<IOException> { @Override public Response toResponse(IOException exception) { return Response.status(Response.Status.ACCEPTED).build(); } }
158
1,510
/* * 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. */ import org.apache.drill.exec.vector.complex.writer.FieldWriter; <@pp.dropOutputFile /> <@pp.changeOutputFile name="/org/apache/drill/exec/vector/complex/impl/RepeatedDictWriter.java" /> <#include "/@includes/license.ftl" /> package org.apache.drill.exec.vector.complex.impl; <#include "/@includes/vv_imports.ftl" /> /* * This class is generated using freemarker and the ${.template_name} template. */ public class RepeatedDictWriter extends AbstractFieldWriter implements BaseWriter.DictWriter { final RepeatedDictVector container; private final SingleDictWriter dictWriter; private int currentChildIndex; public RepeatedDictWriter(RepeatedDictVector container, FieldWriter parent) { super(parent); this.container = Preconditions.checkNotNull(container, "Container cannot be null!"); this.dictWriter = new SingleDictWriter((DictVector) container.getDataVector(), this); } @Override public void allocate() { container.allocateNew(); } @Override public void clear() { container.clear(); } @Override public void close() { clear(); container.close(); } @Override public int getValueCapacity() { return container.getValueCapacity(); } public void setValueCount(int count){ container.getMutator().setValueCount(count); } @Override public void startList() { // make sure that the current vector can support the end position of this list. if (container.getValueCapacity() <= idx()) { container.getMutator().setValueCount(idx() + 1); } // update the repeated vector to state that there is current+1 objects. final RepeatedDictHolder h = new RepeatedDictHolder(); container.getAccessor().get(idx(), h); if (h.start >= h.end) { container.getMutator().startNewValue(idx()); } currentChildIndex = container.getOffsetVector().getAccessor().get(idx()); } @Override public void endList() { // noop, we initialize state at start rather than end. } @Override public MaterializedField getField() { return container.getField(); } @Override public void start() { currentChildIndex = container.getMutator().add(idx()); dictWriter.setPosition(currentChildIndex); dictWriter.start(); } @Override public void end() { dictWriter.end(); } @Override public void startKeyValuePair() { dictWriter.startKeyValuePair(); } @Override public void endKeyValuePair() { dictWriter.endKeyValuePair(); } @Override public ListWriter list(String name) { return dictWriter.list(name); } @Override public MapWriter map(String name) { return dictWriter.map(name); } @Override public DictWriter dict(String name) { return dictWriter.dict(name); } <#list vv.types as type> <#list type.minor as minor> <#assign lowerName = minor.class?uncap_first /> <#if lowerName == "int" ><#assign lowerName = "integer" /></#if> @Override public ${minor.class}Writer ${lowerName}(String name) { return (FieldWriter) dictWriter.${lowerName}(name); } <#if minor.class?contains("Decimal") > @Override public ${minor.class}Writer ${lowerName}(String name, int scale, int precision) { return (FieldWriter) dictWriter.${lowerName}(name, scale, precision); } </#if> </#list> </#list> }
1,311
1,438
package com.dexvis.dex.task.vis.prefuse; import java.util.HashMap; import java.util.Map; import javax.swing.JFrame; import org.simpleframework.xml.Root; import prefuse.data.Graph; import prefuse.data.Schema; import ca.utoronto.cs.prefuseextensions.demo.StarburstDemo; import com.dexvis.dex.exception.DexException; import com.dexvis.dex.wf.DexTask; import com.dexvis.dex.wf.DexTaskState; @Root public class PrefuseStarburst extends DexTask { public PrefuseStarburst() { super(); setCategory("Visualization: Prefuse"); setName("Prefuse Starburst"); setHelpFile("visualization/prefuse/PrefuseStarburst.html"); } public void connect(Graph g, prefuse.data.Node parent, Map<String, Map> connectionMap) { for (String key : connectionMap.keySet()) { prefuse.data.Node node = g.addNode(); node.setString(0, key); g.addEdge(parent, node); connect(g, node, connectionMap.get(key)); } } @Override public DexTaskState execute(DexTaskState state) throws DexException { JFrame frame = new JFrame("Starburst"); Graph g = new Graph(); Schema graphSchema = new Schema(); graphSchema.addColumn("label", String.class, ""); g.addColumns(graphSchema); Map<String, Map> rootMap = new HashMap<String, Map>(); rootMap = new HashMap<String, Map>(); Map<String, Map> curMap; for (int row = 0; row < state.getDexData().getData().size(); row++) { curMap = rootMap; for (int col = 0; col < state.getDexData().getHeader().size(); col++) { if (!curMap.containsKey(state.getDexData().getData().get(row).get(col))) { Map<String, Map> newMap = new HashMap<String, Map>(); curMap.put(state.getDexData().getData().get(row).get(col), newMap); } curMap = curMap.get(state.getDexData().getData().get(row).get(col)); } } System.out.println("MAP: " + rootMap); // Create the nodes: prefuse.data.Node rootNode = g.addNode(); rootNode.setString(0, state.getDexData().getHeader().get(0)); connect(g, rootNode, rootMap); StarburstDemo starburst = new StarburstDemo(g, "label"); frame.add(starburst); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setSize(800, 800); frame.setVisible(true); return state; } }
1,030
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.glassfish.common.nodes; import org.netbeans.modules.glassfish.spi.GlassfishModule; import org.netbeans.modules.glassfish.spi.ResourceDecorator; import org.netbeans.modules.glassfish.spi.ResourceDesc; import org.netbeans.modules.glassfish.spi.ServerUtilities; import org.openide.nodes.Children; import org.openide.util.Lookup; /** * * @author <NAME> */ public class Hk2ResourceNode extends Hk2ItemNode { public Hk2ResourceNode(final Lookup lookup, final ResourceDesc resource, final ResourceDecorator decorator, final Class customizer) { super(Children.LEAF, lookup, resource.getName(), decorator); setDisplayName(resource.getName()); setShortDescription("<html>name: " + resource.getName() + "</html>"); if(decorator.canUnregister()) { getCookieSet().add(new Hk2Cookie.Unregister(lookup, resource.getName(), resource.getCommandType(), decorator.getCmdPropertyName(), decorator.isCascadeDelete())); } if (decorator.canEditDetails()) { GlassfishModule m = lookup.lookup(GlassfishModule.class); if (null != m) { String rootDir = m.getInstanceProperties().get(GlassfishModule.GLASSFISH_FOLDER_ATTR); if (ServerUtilities.isTP2(rootDir)) { // don't add the edit details cookie } else { // add the editor cookie getCookieSet().add(new Hk2Cookie.EditDetails( lookup, getDisplayName(), resource.getCommandType(), customizer)); } } } } }
979
1,738
<gh_stars>1000+ /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include <AzTest/AzTest.h> #include <AzCore/Memory/AllocatorScope.h> #include "ArchiveHost.h" #include <Serialization/STL.h> #include <Serialization/IArchive.h> #include <Serialization/StringList.h> #include <Serialization/SmartPtr.h> #include <memory> namespace Serialization { struct SMember { string name; float weight; SMember() : weight(0.0f) {} void CheckEquality(const SMember& copy) const { EXPECT_TRUE(name == copy.name); EXPECT_TRUE(weight == copy.weight); } void Change(int index) { name = "Changed name "; name += (index % 10) + '0'; weight = float(index); } void Serialize(IArchive& ar) { ar(name, "name"); ar(weight, "weight"); } }; class CPolyBase : public _i_reference_target_t { public: CPolyBase() { baseMember = "Regular base member"; } virtual void Change() { baseMember = "Changed base member"; } virtual void Serialize(IArchive& ar) { ar(baseMember, "baseMember"); } virtual void CheckEquality(const CPolyBase* copy) const { EXPECT_TRUE(baseMember == copy->baseMember); } virtual bool IsDerivedA() const { return false; } virtual bool IsDerivedB() const { return false; } protected: string baseMember; }; class CPolyDerivedA : public CPolyBase { public: void Serialize(IArchive& ar) { CPolyBase::Serialize(ar); ar(derivedMember, "derivedMember"); } bool IsDerivedA() const override { return true; } void CheckEquality(const CPolyBase* copyBase) const { EXPECT_TRUE(copyBase->IsDerivedA()); const CPolyDerivedA* copy = (CPolyDerivedA*)copyBase; EXPECT_TRUE(derivedMember == copy->derivedMember); CPolyBase::CheckEquality(copyBase); } protected: string derivedMember; }; class CPolyDerivedB : public CPolyBase { public: CPolyDerivedB() : derivedMember("B Derived") {} bool IsDerivedB() const override { return true; } void Serialize(IArchive& ar) { CPolyBase::Serialize(ar); ar(derivedMember, "derivedMember"); } void CheckEquality(const CPolyBase* copyBase) const { EXPECT_TRUE(copyBase->IsDerivedB()); const CPolyDerivedB* copy = (const CPolyDerivedB*)copyBase; EXPECT_TRUE(derivedMember == copy->derivedMember); CPolyBase::CheckEquality(copyBase); } protected: string derivedMember; }; struct SNumericTypes { SNumericTypes() : m_bool(false) , m_char(0) , m_int8(0) , m_uint8(0) , m_int16(0) , m_uint16(0) , m_int32(0) , m_uint32(0) , m_int64(0) , m_uint64(0) , m_float(0.0f) , m_double(0.0) {} void Change() { m_bool = true; m_char = -1; m_int8 = -2; m_uint8 = 0xff - 3; m_int16 = -6; m_uint16 = 0xff - 7; m_int32 = -4; m_uint32 = -5; m_int64 = -8ll; m_uint64 = 9ull; m_float = -10.0f; m_double = -11.0; } void Serialize(IArchive& ar) { ar(m_bool, "bool"); ar(m_char, "char"); ar(m_int8, "int8"); ar(m_uint8, "uint8"); ar(m_int16, "int16"); ar(m_uint16, "uint16"); ar(m_int32, "int32"); ar(m_uint32, "uint32"); ar(m_int64, "int64"); ar(m_uint64, "uint64"); ar(m_float, "float"); ar(m_double, "double"); } void CheckEquality(const SNumericTypes& rhs) const { EXPECT_TRUE(m_bool == rhs.m_bool); EXPECT_TRUE(m_char == rhs.m_char); EXPECT_TRUE(m_int8 == rhs.m_int8); EXPECT_TRUE(m_uint8 == rhs.m_uint8); EXPECT_TRUE(m_int16 == rhs.m_int16); EXPECT_TRUE(m_uint16 == rhs.m_uint16); EXPECT_TRUE(m_int32 == rhs.m_int32); EXPECT_TRUE(m_uint32 == rhs.m_uint32); EXPECT_TRUE(m_int64 == rhs.m_int64); EXPECT_TRUE(m_uint64 == rhs.m_uint64); EXPECT_TRUE(m_float == rhs.m_float); EXPECT_TRUE(m_double == rhs.m_double); } bool m_bool; char m_char; int8 m_int8; uint8 m_uint8; int16 m_int16; uint16 m_uint16; int32 m_int32; uint32 m_uint32; int64 m_int64; uint64 m_uint64; float m_float; double m_double; }; class CComplexClass { public: CComplexClass() : index(0) { name = "Foo"; stringList.push_back("Choice 1"); stringList.push_back("Choice 2"); stringList.push_back("Choice 3"); polyPtr.reset(new CPolyDerivedA()); polyVector.push_back(new CPolyDerivedB); polyVector.push_back(new CPolyBase); SMember& a = stringToStructMap["a"]; a.name = "A"; SMember& b = stringToStructMap["b"]; b.name = "B"; members.resize(13); intToString.push_back(std::make_pair(1, "one")); intToString.push_back(std::make_pair(2, "two")); intToString.push_back(std::make_pair(3, "three")); stringToInt.push_back(std::make_pair("one", 1)); stringToInt.push_back(std::make_pair("two", 2)); stringToInt.push_back(std::make_pair("three", 3)); } void Change() { name = "Slightly changed name"; index = 2; polyPtr.reset(new CPolyDerivedB()); polyPtr->Change(); for (size_t i = 0; i < members.size(); ++i) { members[i].Change(int(i)); } members.erase(members.begin()); for (size_t i = 0; i < polyVector.size(); ++i) { polyVector[i]->Change(); } polyVector.resize(4); polyVector.push_back(new CPolyBase()); polyVector[4]->Change(); const size_t arrayLen = sizeof(array) / sizeof(array[0]); for (size_t i = 0; i < arrayLen; ++i) { array[i].Change(int(arrayLen - i)); } numericTypes.Change(); vectorOfStrings.push_back("str1"); vectorOfStrings.push_back("2str"); vectorOfStrings.push_back("thirdstr"); stringToStructMap.erase("a"); SMember& c = stringToStructMap["c"]; c.name = "C"; intToString.push_back(std::make_pair(4, "four")); stringToInt.push_back(std::make_pair("four", 4)); } void Serialize(IArchive& ar) { ar(name, "name"); ar(polyPtr, "polyPtr"); ar(polyVector, "polyVector"); ar(members, "members"); { StringListValue value(stringList, stringList[index]); ar(value, "stringList"); index = value.index(); if (index == -1) { index = 0; } } ar(array, "array"); ar(numericTypes, "numericTypes"); ar(vectorOfStrings, "vectorOfStrings"); ar(stringToInt, "stringToInt"); } void CheckEquality(const CComplexClass& copy) const { EXPECT_TRUE(name == copy.name); EXPECT_TRUE(index == copy.index); EXPECT_TRUE(polyPtr != 0); EXPECT_TRUE(copy.polyPtr != 0); polyPtr->CheckEquality(copy.polyPtr); EXPECT_TRUE(members.size() == copy.members.size()); for (size_t i = 0; i < members.size(); ++i) { members[i].CheckEquality(copy.members[i]); } EXPECT_TRUE(polyVector.size() == copy.polyVector.size()); for (size_t i = 0; i < polyVector.size(); ++i) { if (polyVector[i] == 0) { EXPECT_TRUE(copy.polyVector[i] == 0); continue; } EXPECT_TRUE(copy.polyVector[i] != 0); polyVector[i]->CheckEquality(copy.polyVector[i]); } const size_t arrayLen = sizeof(array) / sizeof(array[0]); for (size_t i = 0; i < arrayLen; ++i) { array[i].CheckEquality(copy.array[i]); } numericTypes.CheckEquality(copy.numericTypes); EXPECT_TRUE(stringToInt.size() == copy.stringToInt.size()); for (size_t i = 0; i < stringToInt.size(); ++i) { EXPECT_TRUE(stringToInt[i] == copy.stringToInt[i]); } } protected: string name; typedef std::vector<SMember> Members; std::vector<string> vectorOfStrings; std::vector<std::pair<int, string> > intToString; std::vector<std::pair<string, int> > stringToInt; Members members; int32 index; SNumericTypes numericTypes; StringListStatic stringList; std::vector< _smart_ptr<CPolyBase> > polyVector; _smart_ptr<CPolyBase> polyPtr; std::map<string, SMember> stringToStructMap; SMember array[5]; }; using ArchiveHostTestsAllocatorScope = AZ::AllocatorScope<AZ::LegacyAllocator, CryStringAllocator>; struct ArchiveHostTestsMemory : private ArchiveHostTestsAllocatorScope { ArchiveHostTestsMemory() { ArchiveHostTestsAllocatorScope::ActivateAllocators(); m_classFactoryRTTI = AZStd::make_unique<ClassFactoryRTTI>(); } ~ArchiveHostTestsMemory() { m_classFactoryRTTI.reset(); ArchiveHostTestsAllocatorScope::DeactivateAllocators(); } struct ClassFactoryRTTI { ClassFactoryRTTI() : CPolyBaseCPolyBase_DerivedDescription("base", "Base") , CPolyBaseCPolyBase_Creator(&CPolyBaseCPolyBase_DerivedDescription) , TypeCPolyBase_DerivedDescription("derived_a", "Derived A") , TypeCPolyBase_Creator(&TypeCPolyBase_DerivedDescription) , CPolyDerivedBCPolyBase_DerivedDescription("derived_b", "Derived B") , CPolyDerivedBCPolyBase_Creator(&CPolyDerivedBCPolyBase_DerivedDescription) {} ~ClassFactoryRTTI() { Serialization::ClassFactory<CPolyBase>::destroy(); } const Serialization::TypeDescription CPolyBaseCPolyBase_DerivedDescription; Serialization::ClassFactory<CPolyBase>::Creator<CPolyBase> CPolyBaseCPolyBase_Creator; const Serialization::TypeDescription TypeCPolyBase_DerivedDescription; Serialization::ClassFactory<CPolyBase>::Creator<CPolyDerivedA> TypeCPolyBase_Creator; const Serialization::TypeDescription CPolyDerivedBCPolyBase_DerivedDescription; Serialization::ClassFactory<CPolyBase>::Creator<CPolyDerivedB> CPolyDerivedBCPolyBase_Creator; }; AZStd::unique_ptr<ClassFactoryRTTI> m_classFactoryRTTI; }; TEST(ArchiveHostTests, JsonBasicTypes) { ArchiveHostTestsMemory memory; { std::unique_ptr<IArchiveHost> host(CreateArchiveHost()); DynArray<char> bufChanged; CComplexClass objChanged; objChanged.Change(); host->SaveJsonBuffer(bufChanged, SStruct(objChanged)); EXPECT_TRUE(!bufChanged.empty()); DynArray<char> bufResaved; { CComplexClass obj; EXPECT_TRUE(host->LoadJsonBuffer(SStruct(obj), bufChanged.data(), bufChanged.size())); EXPECT_TRUE(host->SaveJsonBuffer(bufResaved, SStruct(obj))); EXPECT_TRUE(!bufResaved.empty()); obj.CheckEquality(objChanged); } EXPECT_TRUE(bufChanged.size() == bufResaved.size()); for (size_t i = 0; i < bufChanged.size(); ++i) { EXPECT_TRUE(bufChanged[i] == bufResaved[i]); } } } TEST(ArchiveHostTests, BinBasicTypes) { ArchiveHostTestsMemory memory; { std::unique_ptr<IArchiveHost> host(CreateArchiveHost()); DynArray<char> bufChanged; CComplexClass objChanged; objChanged.Change(); host->SaveBinaryBuffer(bufChanged, SStruct(objChanged)); EXPECT_TRUE(!bufChanged.empty()); DynArray<char> bufResaved; { CComplexClass obj; EXPECT_TRUE(host->LoadBinaryBuffer(SStruct(obj), bufChanged.data(), bufChanged.size())); EXPECT_TRUE(host->SaveBinaryBuffer(bufResaved, SStruct(obj))); EXPECT_TRUE(!bufResaved.empty()); obj.CheckEquality(objChanged); } EXPECT_TRUE(bufChanged.size() == bufResaved.size()); for (size_t i = 0; i < bufChanged.size(); ++i) { EXPECT_TRUE(bufChanged[i] == bufResaved[i]); } } } }
7,677
1,125
<filename>modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/MultiSearchTemplateRequestBuilder.java /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.script.mustache; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.client.ElasticsearchClient; public class MultiSearchTemplateRequestBuilder extends ActionRequestBuilder<MultiSearchTemplateRequest, MultiSearchTemplateResponse, MultiSearchTemplateRequestBuilder> { protected MultiSearchTemplateRequestBuilder(ElasticsearchClient client, MultiSearchTemplateAction action) { super(client, action, new MultiSearchTemplateRequest()); } public MultiSearchTemplateRequestBuilder add(SearchTemplateRequest request) { if (request.getRequest().indicesOptions() == IndicesOptions.strictExpandOpenAndForbidClosed() && request().indicesOptions() != IndicesOptions.strictExpandOpenAndForbidClosed()) { request.getRequest().indicesOptions(request().indicesOptions()); } super.request.add(request); return this; } public MultiSearchTemplateRequestBuilder add(SearchTemplateRequestBuilder request) { if (request.request().getRequest().indicesOptions() == IndicesOptions.strictExpandOpenAndForbidClosed() && request().indicesOptions() != IndicesOptions.strictExpandOpenAndForbidClosed()) { request.request().getRequest().indicesOptions(request().indicesOptions()); } super.request.add(request); return this; } public MultiSearchTemplateRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) { request().indicesOptions(indicesOptions); return this; } /** * Sets how many search requests specified in this multi search requests are allowed to be ran concurrently. */ public MultiSearchTemplateRequestBuilder setMaxConcurrentSearchRequests(int maxConcurrentSearchRequests) { request().maxConcurrentSearchRequests(maxConcurrentSearchRequests); return this; } }
857
361
<reponame>romolodevito/commons-codec<filename>src/test/java/org/apache/commons/codec/binary/Codec105ErrorInputStream.java /* * 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.commons.codec.binary; import java.io.IOException; import java.io.InputStream; /** * Emits three line-feeds '\n' in a row, one at a time, and then EOF. * * Recreates the bug described in CODEC-105. * * @since 1.5 */ public class Codec105ErrorInputStream extends InputStream { private static final int EOF = -1; int countdown = 3; @Override public int read() throws IOException { if (this.countdown-- > 0) { return '\n'; } return EOF; } @Override public int read(final byte b[], final int pos, final int len) throws IOException { if (this.countdown-- > 0) { b[pos] = '\n'; return 1; } return EOF; } }
560
488
<reponame>ouankou/rose #ifndef AST_REWRITE_PREFIX_GENERATION_C #define AST_REWRITE_PREFIX_GENERATION_C // #include "rose.h" #include "rewrite.h" template <class ASTNodeCollection> MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: PrefixSuffixGenerationTraversal ( bool inputGenerateIncludeDirectives ) : generateIncludeDirectives(inputGenerateIncludeDirectives) { // Variable to help us recognise when we change scopes during the reverse traversal // previousStatement = NULL; previousScope = NULL; // Keep track of the number of #if and #endif so that they match up // (force them to match up by adding a trailing #endif if required). openingIfCounter = 0; closingEndifCounter = 0; } template <class ASTNodeCollection> typename MidLevelRewrite<ASTNodeCollection>::PrefixInheritedAttribute MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: evaluateInheritedAttribute ( SgNode* astNode, typename MidLevelRewrite<ASTNodeCollection>::PrefixInheritedAttribute inputInheritedAttribute ) { // This function is called for each node in the AST that would be generated by the reverse traversal // The work is divided into two parts: // 1) Adding the current statment to the current scope // a) only prefix relavant statements are added // * declarations // * comments and preprocessor directives are collected from all statements // b) only statements from the current file are collected unless (generateIncludeDirectives == true) // 2) The setup of the scope // a) leaving the current scope alone // b) pushing a new scope onto the stack of scopes static int counter = -1; counter++; #undef PRINT_DEBUGGING_INFO #ifdef _MSC_VER #define PRINT_DEBUGGING_INFO 0 #else #define PRINT_DEBUGGING_INFO false #endif #if 0 printf ("!!! In PrefixSuffixGenerationTraversal::evaluateInheritedAttribute: astNode = %p = %s stackOfScopes = %d \n", astNode,astNode->sage_class_name(),stackOfScopes.size()); #endif ROSE_ASSERT (previousScope != NULL); // Setup the current scope SgStatement* currentStatement = isSgStatement(astNode); if ( currentStatement != NULL ) { // The global scope is unconditionally pushed onto the stack of scopes so don't do it here. // A few other scope statements don't generate "{}" parings (generally because the basic // block contained within them generates the "{}" and only one pair is required. if ( isSgFunctionParameterList(currentStatement) == NULL && #if 0 // DQ (1/29/2004): Trying to debug replacement of basic block in function definition isSgFunctionDefinition(currentStatement) == NULL && #endif isSgCatchOptionStmt(currentStatement) == NULL && isSgGlobal(currentStatement) == NULL ) { // Skip the SgFunctionParameterList statement since unparsing // the function declaration will generate parameter list std::string targetFilename = Rose::getFileNameByTraversalBackToFileNode(currentStatement); // string declarationFilename = Rose::getFileName(currentStatement); // string declarationFilename = currentStatement->get_file_info()->get_filename(); // DQ (7/19/2005): // Within: "int y; switch(x){case 0:{y++;break;}default:{y++;break;}}" // Note that processing of "y++;" requires construction of declaration of "int y;" in the prefix, // but we must handle the case where the declaration of "int y;" is a part of a previous // transformation, so file equality is an insufficent test for inclusion of declarations // within the prefix. Since the previous transformation marked the startement as a transformation // the filename returned is incorrect. std::string declarationFilename; if (currentStatement->get_file_info()->isTransformation() == true) { declarationFilename = targetFilename; } else { declarationFilename = currentStatement->get_file_info()->get_filename(); } #if 0 printf ("targetFilename = %s declarationFilename = %s counter = %d (*i)->sage_class_name() = %s \n", targetFilename.c_str(),declarationFilename.c_str(),counter,astNode->sage_class_name()); printf ("Found a statement = %s \n",currentStatement->sage_class_name()); printf ("--- Current Scope = %s \n",currentStatement->get_scope()->sage_class_name()); printf ("In PrefixSuffixGenerationTraversal::evaluateInheritedAttribute(): Current statement = %s \n", currentStatement->unparseToString().c_str()); #endif // DQ (7/25/2005): Note that string equality operator could use get_file_id() // and be replaced by integer equality test. // Check if the current statment is located in the current file if ( generateIncludeDirectives == false || declarationFilename == targetFilename ) { #if PRINT_DEBUGGING_INFO printf ("Found a statement important to the prefix mechanism currentScope.size() = %" PRIuPTR " \n",currentScope.size()); #endif #if 0 // DQ (1/31/2004): Allow basic block to be replaced in SgFunctionDefinition bool qualifiedScopeStatement = isSgScopeStatement(currentStatement) != NULL; bool basicBlockPartOfFunctionDefinition = false; bool basicBlockPartOfSwitchStatement = isSgBasicBlock(currentStatement) != NULL && isSgSwitchStatement(currentStatement->get_scope()) != NULL; bool qualifiedOtherStatement = (isSgFunctionDeclaration(currentStatement) != NULL) || (isSgClassDeclaration(currentStatement) != NULL) || (isSgCaseOptionStmt(currentStatement) != NULL) || (isSgDefaultOptionStmt(currentStatement) != NULL); #else bool qualifiedScopeStatement = isSgScopeStatement(currentStatement) != NULL && isSgFunctionDefinition(currentStatement) == NULL; bool basicBlockPartOfFunctionDefinition = isSgBasicBlock(currentStatement) != NULL && isSgFunctionDefinition(currentStatement->get_scope()) != NULL; bool basicBlockPartOfSwitchStatement = isSgBasicBlock(currentStatement) != NULL && isSgSwitchStatement(currentStatement->get_scope()) != NULL; // DQ (8/8/2005): This is a structural question! bool basicBlockPartOfForStatement = isSgBasicBlock(currentStatement) != NULL && isSgForStatement(currentStatement->get_parent()) != NULL; bool qualifiedOtherStatement = (isSgFunctionDeclaration(currentStatement) != NULL) || (isSgClassDeclaration(currentStatement) != NULL) || (isSgCaseOptionStmt(currentStatement) != NULL) || (isSgDefaultOptionStmt(currentStatement) != NULL); #endif bool qualifiedStatement = !basicBlockPartOfFunctionDefinition && !basicBlockPartOfSwitchStatement && // DQ (8/8/2005): Added case to eliminate redundent scopes for for loops !basicBlockPartOfForStatement && (qualifiedScopeStatement || qualifiedOtherStatement); SgScopeStatement* currentStatementScope = isSgScopeStatement(currentStatement->get_scope()); ROSE_ASSERT (currentStatementScope != NULL); ROSE_ASSERT (previousScope != NULL); // bool isInSameScope = (previousScope == currentStatementScope); bool isInNestedScope = false; SgScopeStatement* tempScope = currentStatementScope; #if PRINT_DEBUGGING_INFO printf ("Initial tempScope = %s \n",tempScope->sage_class_name()); #endif while (tempScope != NULL && tempScope->variantT() != V_SgGlobal && tempScope != previousScope) { tempScope = tempScope->get_scope(); #if PRINT_DEBUGGING_INFO printf ("New tempScope = %s \n",tempScope->sage_class_name()); #endif } #if PRINT_DEBUGGING_INFO printf ("Final tempScope = %s previousScope = %s \n",tempScope->sage_class_name(),previousScope->sage_class_name()); #endif if (tempScope != previousScope) { #if PRINT_DEBUGGING_INFO printf ("Setting isInNestedScope = true \n"); #endif isInNestedScope = true; } #if PRINT_DEBUGGING_INFO printf ("previousScope = %p previousScope = %s previousScope = %s \n", previousScope,previousScope->sage_class_name(),previousScope->unparseToString().c_str()); printf ("currentStatementScope = %p currentStatementScope = %s currentStatementScope = %s \n", currentStatementScope,currentStatementScope->sage_class_name(),currentStatementScope->unparseToString().c_str()); printf ("isInNestedScope = %s \n",isInNestedScope ? "true" : "false"); printf ("qualifiedScopeStatement = %s \n",qualifiedScopeStatement ? "true" : "false"); printf ("basicBlockPartOfFunctionDefinition = %s \n",basicBlockPartOfFunctionDefinition ? "true" : "false"); printf ("basicBlockPartOfSwitchStatement = %s \n",basicBlockPartOfSwitchStatement ? "true" : "false"); printf ("qualifiedOtherStatement = %s \n",qualifiedOtherStatement ? "true" : "false"); printf ("qualifiedStatement = %s \n",qualifiedStatement ? "true" : "false"); #endif if ( /* (currentScope.size() >= 0) && */ (qualifiedStatement == true) && (isInNestedScope == true) ) { #if PRINT_DEBUGGING_INFO printf ("$$$$$ Push a new scope! currentStatement = %s currentStatement = %s stackOfScopes.size() = %" PRIuPTR " currentScope.size() = %" PRIuPTR " $$$$$ \n", currentStatementScope->sage_class_name(), currentStatement->unparseToString().c_str(), stackOfScopes.size(),currentScope.size()); display(currentScope,"Push Current scope: BEFORE"); #endif stackOfScopes.push(currentScope); #if PRINT_DEBUGGING_INFO printf ("View the stackOfScopes! stackOfScopes.size() = %" PRIuPTR " \n",stackOfScopes.size()); display(stackOfScopes,"Push Current scope: AFTER"); #endif // Empty the current scope stack so that it can be used // to accumulate new statements for the next scope. currentScope.erase(currentScope.begin(),currentScope.end()); ROSE_ASSERT (currentScope.size() == 0); // reset the previousStatement pointer used to recognize when the scopes are changed // previousStatement = currentStatement; previousScope = currentStatement->get_scope(); } #if PRINT_DEBUGGING_INFO else { printf ("$$$$$$$$$$$$$$$$ Skipped pushing current scope $$$$$$$$$$$$$$$$ \n"); } #endif bool isCaseOrDefaultOptionStatement = (isSgCaseOptionStmt(currentStatement) != NULL) || (isSgDefaultOptionStmt(currentStatement) != NULL); bool includeInPrefix = (isInNestedScope) || isCaseOrDefaultOptionStatement; DeclarationOrCommentListElement listElement (currentStatement,includeInPrefix); #if PRINT_DEBUGGING_INFO printf ("isCaseOrDefaultOptionStatement = %s \n",isCaseOrDefaultOptionStatement ? "true" : "false"); printf ("includeInPrefix = %s \n",includeInPrefix ? "true" : "false"); listElement.display("Element being pushed onto current scope"); #endif if (listElement.isValidDeclarationOrCommentListElement() == true) { currentScope.push_front(listElement); #if PRINT_DEBUGGING_INFO printf ("Pushed statement onto the currentScope: currentScope.size() = %d [%s] \n", currentScope.size(),currentStatement->unparseToString().c_str()); #endif } #if PRINT_DEBUGGING_INFO else { printf ("Skipped push of current statement onto current scope currentScope.size() = %d [%s] \n", currentScope.size(),currentStatement->unparseToString().c_str()); } #endif } #if PRINT_DEBUGGING_INFO else { printf ("Not an important statement to prefix: generateIncludeDirectives == true && declarationFilename != targetFilename \n"); } #endif } #if PRINT_DEBUGGING_INFO else { printf ("Skipping addition of this statement to the current scope (%s) \n",currentStatement->sage_class_name()); } #endif if ( isSgGlobal(currentStatement) != NULL ) { // push current scope onto stack of scopes (even if size == 0, // since top of stack is defined to be the global scope). // printf ("$$$$$ Pushing Global Scope $$$$$ \n"); stackOfScopes.push(currentScope); #if PRINT_DEBUGGING_INFO printf ("Pushed global scope onto the stack stackOfScopes.size() = %" PRIuPTR " \n",stackOfScopes.size()); #endif // Empty the current scope stack so that it can be used // to accumulate new statements for the next scope. currentScope.erase(currentScope.begin(),currentScope.end()); } #if PRINT_DEBUGGING_INFO char buffer[256]; sprintf (buffer,"At base of evaluateInheritedAttribute: stackOfScopes.size() = %" PRIuPTR "",stackOfScopes.size()); std::string displayString = buffer; display(displayString); printf ("################################ BASE ################################## \n"); #endif } #if PRINT_DEBUGGING_INFO printf ("Leaving evaluateInheritedAttribute(): stackOfScopes.size() = %" PRIuPTR " \n",stackOfScopes.size()); #endif return inputInheritedAttribute; } template <class ASTNodeCollection> typename MidLevelRewrite<ASTNodeCollection>::PrefixSynthesizedAttribute MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: evaluateSynthesizedAttribute ( SgNode* astNode, typename MidLevelRewrite<ASTNodeCollection>::PrefixInheritedAttribute inputInheritedAttribute, typename MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal::SynthesizedAttributesList inputSynthesizedAttributeList ) { #if 0 printf ("@@@ In evaluateSynthesizedAttribute: astNode = %p = %s \n",astNode,astNode->sage_class_name()); #endif #if 0 printf (" inputSynthesizedAttributeList.size() = %" PRIuPTR " \n",inputSynthesizedAttributeList.size()); #endif return PrefixSynthesizedAttribute(); } template <class ASTNodeCollection> MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal::DeclarationOrCommentListElement:: DeclarationOrCommentListElement ( SgStatement* astNode, bool includeInPrefix ) { // If the astNode is in the same scope as a previous statement then // don't save this node as a prefixStatement. prefixStatement = NULL; comments = astNode->getAttachedPreprocessingInfo(); originatingStatement = astNode; ROSE_ASSERT (originatingStatement != NULL); #if 0 printf ("In DeclarationOrCommentListElement constructor: astNode = %s includeInPrefix = %s \n",astNode->sage_class_name(),includeInPrefix ? "true" : "false"); #endif // Handle simple case of if the node is a declaration SgDeclarationStatement* declaration = isSgDeclarationStatement(astNode); if ( declaration != NULL ) { prefixStatement = declaration; } else { // Handle more complex case of it node is not a declaration if ( includeInPrefix == true ) { switch (astNode->variantT()) { // Scope statements case V_SgSwitchStatement: case V_SgForStatement: case V_SgWhileStmt: case V_SgDoWhileStmt: case V_SgIfStmt: case V_SgCatchOptionStmt: prefixStatement = astNode; break; // Other statements case V_SgCaseOptionStmt: case V_SgDefaultOptionStmt: prefixStatement = astNode; break; default: { #if 0 printf ("Not an acceptable prefix statement (copied any attached comments, but ignoring this statement in generating prefix) \n"); #endif } } } #if 0 else { printf ("Statement is in same scope as previous statement (so just extract comments only) \n"); } #endif } } template <class ASTNodeCollection> bool MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal::DeclarationOrCommentListElement:: isValidDeclarationOrCommentListElement() const { return ((prefixStatement != NULL) || (comments != NULL)) ? true : false; } // DQ (3/28/2006): declaration required by g++ 3.4.x and 4.x compilers) std::string unparseDeclarationToString ( SgDeclarationStatement* declaration, bool unparseAsDeclaration); std::string unparseStatementWithoutBasicBlockToString ( SgStatement* statement ); std::string unparseScopeStatementWithoutBasicBlockToString ( SgScopeStatement* scope ); template <class ASTNodeCollection> std::string MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal::DeclarationOrCommentListElement:: generateString( int & openingIfCounter, int & closingEndifCounter , bool generateIncludeDirectives, bool skipTrailingDirectives, bool unparseAsDeclaration ) { #if 1 printf ("In DeclarationOrCommentListElement::generateString(): \n"); printf (" openingIfCounter = %d \n",openingIfCounter); printf (" closingEndifCounter = %d \n",closingEndifCounter); printf (" generateIncludeDirectives = %s \n",generateIncludeDirectives ? "true" : "false"); printf (" skipTrailingDirectives = %s \n",skipTrailingDirectives ? "true" : "false"); printf (" unparseAsDeclaration = %s \n",unparseAsDeclaration ? "true" : "false"); #endif std::string returnString; // If we only have a comment, then the declaration pointer is NULL! if (prefixStatement != NULL) { // Handle the different sorts of statements that contribute to // the context info contained in the final prefix printf (" prefixStatement = %s \n",prefixStatement->sage_class_name()); SgDeclarationStatement* declaration = isSgDeclarationStatement(prefixStatement); if (declaration != NULL) { // printf (" generateString(): declaration->sage_class_name() = %s \n",declaration->sage_class_name()); // DQ (1/7/2004): New version of EDG (ver 3.3) normalizes member function definitions when // they appear in a class declaration where the class is declaration in global scope. // It builds only a member function declaration in place of the definition and builds // a member function definition in the global scope. This is equivalent semanticly, // but not structurally (syntacticly). This effects the prefix generation and the fix // is to non generate the declaration of member functions within global scope. // returnString = unparseDeclarationToString(declaration,unparseAsDeclaration); SgMemberFunctionDeclaration *memberFuctionDeclaration = isSgMemberFunctionDeclaration(prefixStatement); // printf ("In generateString(): memberFuctionDeclaration = %p \n",memberFuctionDeclaration); if (memberFuctionDeclaration != NULL) { ROSE_ASSERT(memberFuctionDeclaration->get_parent() != NULL); printf ("In generateString(): memberFuctionDeclaration->get_parent() = %s \n", memberFuctionDeclaration->get_parent()->sage_class_name()); } #if 1 // DQ (12/5/2004): Even in the case of a member function we might not want to unparse it except as a declaration! if ( (memberFuctionDeclaration != NULL) && (unparseAsDeclaration == true) ) #else // DQ (1/31/2004): member functions should have a prefix if ( (memberFuctionDeclaration != NULL) && (isSgGlobal(memberFuctionDeclaration->get_parent()) != NULL) && (unparseAsDeclaration == true) ) #endif { returnString = "/* skipped member function declaration in global scope */"; // returnString += unparseDeclarationToString(declaration,unparseAsDeclaration); } else { returnString = unparseDeclarationToString(declaration,unparseAsDeclaration); } } else { SgScopeStatement* scope = isSgScopeStatement(prefixStatement); if (scope != NULL) { // Unparse scope statements without their body (without SgBasicBlock) returnString = unparseScopeStatementWithoutBasicBlockToString(scope); } else { // Other statements (e.g. SgCaseOptionStmt and SgDefaultOptionStmt) // returnString = prefixStatement->unparseToString(); SgStatement* statement = isSgStatement(prefixStatement); ROSE_ASSERT (statement != NULL); returnString = unparseStatementWithoutBasicBlockToString(statement); } } } else { // printf (" generateString(): prefixStatement == NULL \n"); } printf (" After prefix statement processing: returnString = %s \n",returnString.c_str()); // printf (" generateIncludeDirectives = %s \n",generateIncludeDirectives ? "true" : "false"); // printf (" Comments: %s \n",comments ? "FOUND COMMENTS" : "NO COMMENTS FOUND"); ROSE_ASSERT (originatingStatement != NULL); #if 0 if (comments != NULL) { // Show where the comment came from! printf (" originatingStatement = %s \n",originatingStatement->sage_class_name()); printf (" originatingStatement = %s \n",originatingStatement->unparseToString().c_str()); } #endif // Don't prepend or append comments if (generateIncludeDirectives == true && comments != NULL) { // DQ (2/3/2004): prefixDesign.txt shows the counter example for why we can't ignore // more than comments if we are processing #include directives. The same applies for // #define directives as well. Thus is we are to support #include or #define directives // then we have to get all the other related (dependent) directive processing correct // as well. // printf (" Processing found comments! \n"); std::string commentPrefix; std::string commentSuffix; AttachedPreprocessingInfoType::iterator j; for (j = comments->begin(); j != comments->end(); j++) { ROSE_ASSERT ( (*j) != NULL ); #if 0 printf ("Attached Comment (relativePosition=%s): %s", ((*j)->relativePosition == PreprocessingInfo::before) ? "before" : "after",(*j)->getString()); #endif // We have to keep track of any open #if #endif pairings and make sure // that they match of the the remaining #if gts closed off with an #endif // But we only want ot count directives that are NOT skipped //#ifndef USE_ROSE_BOOST_WAVE_SUPPORT2 if ((*j)->getRelativePosition() == PreprocessingInfo::before || (skipTrailingDirectives == false)) { switch ( (*j)->getTypeOfDirective() ) { case PreprocessingInfo::CpreprocessorIfDeclaration: case PreprocessingInfo::CpreprocessorDeadIfDeclaration: case PreprocessingInfo::CpreprocessorIfdefDeclaration: case PreprocessingInfo::CpreprocessorIfndefDeclaration: openingIfCounter++; break; case PreprocessingInfo::CpreprocessorEndifDeclaration: closingEndifCounter++; break; // these don't count to force an increment of the openingIfCounter case PreprocessingInfo::CpreprocessorElseDeclaration: case PreprocessingInfo::CpreprocessorElifDeclaration: default: break; } } //#endif // AS Since Wave is a full preprocessor all the PreprocessorInfo with directive type // PreprocessingInfo::CpreprocessorIncludeDeclaration is actually the include files //included in this project. For non-wave ROSE all include directives in the code is //attached as such a PreprocessingInfo object, so therefore we have to support all //other PreprocessingInfo objects as well (see prefixDesign.txt). //PS! If we need to support all the other preprocessor directives it is just to remove //the #ifndef USE_ROSE_BOOST_WAVE_SUPPORT #endif pairs for the Wave work. // Only use the CPP directive in certain cases (ignore comments, etc.) if ( (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorIncludeDeclaration //#ifndef USE_ROSE_BOOST_WAVE_SUPPORT2 || (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorDefineDeclaration || (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorUndefDeclaration || (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorIfdefDeclaration || (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorIfndefDeclaration || (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorIfDeclaration || (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorElseDeclaration || (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorElifDeclaration || (*j)->getTypeOfDirective() == PreprocessingInfo::CpreprocessorEndifDeclaration || (*j)->getTypeOfDirective() == PreprocessingInfo::ClinkageSpecificationStart || (*j)->getTypeOfDirective() == PreprocessingInfo::ClinkageSpecificationEnd //#ifdef USE_ROSE_BOOST_WAVE_SUPPORT || (*j)->getTypeOfDirective() == PreprocessingInfo::CSkippedToken //#endif //#endif ) { if ((*j)->getRelativePosition() == PreprocessingInfo::before) { // The prefix does not need to be preceeded by a "\n" since they come first commentPrefix += (*j)->getString(); } else { if (skipTrailingDirectives == false) { commentSuffix += (*j)->getString(); } } } } // If we have a meaningful suffix to add (directives) then make sure it starts on a new line if (commentSuffix.length() > 0) commentSuffix = std::string("\n") + commentSuffix; returnString = commentPrefix + returnString + commentSuffix; // printf (" After comment/directive processing: returnString = %s \n",returnString.c_str()); } else { // printf (" Skipping comments processing \n"); } return returnString; } template <class ASTNodeCollection> std::string MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: generatePrefixString() { // This function generates a string by calling the functions to generate // the global declarations and the local declarations and concatinating // them together. std::string prefixString; // printf ("In generatePrefixString() stackOfScopes.size() = %" PRIuPTR " \n",stackOfScopes.size()); // printf ("Calling generatePrefixStringGlobalDeclarations() \n"); prefixString += generatePrefixStringGlobalDeclarations(); // printf ("Calling generatePrefixStringLocalDeclarations() \n"); prefixString += generatePrefixStringLocalDeclarations(); // printf ("DONE: calling generatePrefixStringLocalDeclarations() \n"); #if 0 printf ("############################### \n"); printf ("In generatePrefixString() prefixString = \n%s\n",prefixString.c_str()); printf ("############################### \n"); #endif return prefixString; } template <class ASTNodeCollection> std::string MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: generatePrefixStringFromStatementList( ListOfStatementsType & statementList, bool skipStatementListTrailingDirectives, // int & openingIfCounter, // int & closingEndifCounter, bool containsAdditionalScopes ) { std::string scopePrefixString; // Make a copy to avoid distroying the original list ListOfStatementsType tempList = statementList; const int lastDeclarationIndex = tempList.size()-1; int declarationCounter = 0; // printf ("In generatePrefixStringFromStatementList(): containsAdditionalScopes = %s \n",containsAdditionalScopes ? "true" : "false"); typename ListOfStatementsType::iterator lastDeclaration = tempList.end(); for (typename ListOfStatementsType::iterator j = tempList.begin(); j != tempList.end(); j++) { if ( containsAdditionalScopes && (*j).prefixStatement != NULL ) { lastDeclaration = j; // printf ("Setting the lastDeclaration to lastDeclaration.prefixStatement = %s \n",(*lastDeclaration).prefixStatement->unparseToString().c_str()); } } // ROSE_ASSERT (lastDeclaration != tempList.end()); // printf ("lastDeclaration.prefixStatement = %s \n",(*lastDeclaration).prefixStatement->unparseToString().c_str()); for (typename ListOfStatementsType::iterator i = tempList.begin(); i != tempList.end(); i++) { #if 0 if ( (*i).prefixStatement != NULL ) { // output the file, line, and column of the current declaration printf ("filename = %s line# = %d column# = %d \n",(*i).prefixStatement->get_file_info()->get_filename(),(*i).prefixStatement->get_file_info()->get_line(),(*i).prefixStatement->get_file_info()->get_col()); printf ("(*i).prefixStatement->unparseToString() = %s \n",(*i).prefixStatement->unparseToString().c_str()); } else { printf ("(*i).prefixStatement == NULL \n"); } #endif // Check for last declaration is the list and unparse without ";" if // it is a function, otherwise unparse as a regular declaration // bool unparseAsDeclaration = containsAdditionalScopes && ( i == lastDeclaration ) ? false : true; bool unparseAsDeclaration = ( i == lastDeclaration ) ? false : true; // ROSE_ASSERT (unparseAsDeclaration == true); // printf ("Before call to unparseToString(): unparseAsDeclaration = %s \n",(unparseAsDeclaration) ? "true" : "false"); #if 1 // Skip all trailing directives on the last element of each list (except maybe the last one) bool skipTrailingDirectives = ( skipStatementListTrailingDirectives && (declarationCounter == lastDeclarationIndex) ); #else bool skipTrailingDirectives = false; #endif // printf ("skipTrailingDirectives = %s \n",skipTrailingDirectives ? "true" : "false"); #if 0 // DQ (1/6/2004): Skip unparsing member function declarations (since they are defined in the class anyway) if ( (*i).prefixStatement != NULL) printf ("In generatePrefixStringFromStatementList(): (*i).prefixStatement->sage_class_name() = %s \n",(*i).prefixStatement->sage_class_name()); #endif std::string declarationString = (*i).generateString(openingIfCounter,closingEndifCounter, generateIncludeDirectives,skipTrailingDirectives, unparseAsDeclaration); printf ("declarationCounter = %d declarationString = %s \n",declarationCounter,declarationString.c_str()); scopePrefixString += declarationString + " \n"; declarationCounter++; } // printf ("openingIfCounter = %d closingEndifCounter = %d \n",openingIfCounter,closingEndifCounter); return scopePrefixString; } template <class ASTNodeCollection> std::string MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: generateEndifForPrefixString( // int openingIfCounter, int closingEndifCounter ) { // The name of this function should be changed from generateEndifForPrefixString // to generateDirectivesForPrefixString. std::string prefixString; #if PRINT_DEBUGGING_INFO printf ("In generateEndifForPrefixString(): openingIfCounter = %d closingEndifCounter = %d \n", openingIfCounter,closingEndifCounter); #endif // Add a trailing set of #endif directives if the #if and #endif directive counters don't match if (openingIfCounter != closingEndifCounter) { // printf ("---- Adding #endif to correct mismatched #if #endif pairings \n"); int numberOfOpeningIfDirectives = closingEndifCounter - openingIfCounter; // int numberOfClosingEndifDirectives = openingIfCounter - closingEndifCounter; int numberOfClosingEndifDirectives = -numberOfOpeningIfDirectives; // printf ("---- (before) numberOfOpeningIfDirectives = %d \n",numberOfOpeningIfDirectives); // printf ("---- (before) numberOfClosingEndifDirectives = %d \n",numberOfClosingEndifDirectives); #if 1 ROSE_ASSERT (numberOfOpeningIfDirectives < 0); ROSE_ASSERT (numberOfClosingEndifDirectives > 0); #else // Add any require #if directives for (int i = 0; i < numberOfOpeningIfDirectives; i++) { if (i==0) prefixString = std::string("\n// Prefix generated matching #if\n#if 1\n") + prefixString; else prefixString += std::string("// Prefix generated matching #if\n#if 1\n") + prefixString; // DQ (2/2/2004): Increment the closingEndifCounter to reflect the added endif openingIfCounter++; } #endif // Add any require #endif directives for (int i = 0; i < numberOfClosingEndifDirectives; i++) { if (i==0) prefixString += "\n// Prefix generated matching endif\n#endif\n"; else prefixString += "// Prefix generated matching endif\n#endif\n"; // DQ (2/2/2004): Increment the closingEndifCounter to reflect the added endif closingEndifCounter++; } } #if 0 printf ("---- prefixString = %s \n",prefixString.c_str()); printf ("---- (after) openingIfCounter = %d \n",openingIfCounter); printf ("---- (after) closingEndifCounter = %d \n",closingEndifCounter); #endif return prefixString; } template <class ASTNodeCollection> std::string MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: generatePrefixStringGlobalDeclarations() { std::string globalPrefixString; // printf ("In generatePrefixStringGlobalDeclarations() stackOfScopes.size() = %" PRIuPTR " \n",stackOfScopes.size()); // We need to handle the case of a prefix generated for SgGlobal // (in which case the stack of scopes is empty!). #if 0 // For now return early. printf ("NOTE: multiple returns in generatePrefixStringGlobalDeclarations() \n"); if (stackOfScopes.size() == 0) return globalPrefixString; #endif if (stackOfScopes.size() > 0) { ROSE_ASSERT (stackOfScopes.size() > 0); StackOfListsType tempStack = stackOfScopes; int stackCounter = 0; int stackSize = tempStack.size(); int lastScopeIndex = stackSize-1; bool skipStatementListTrailingDirectives = stackCounter < lastScopeIndex; #if 0 // Keep track of the number of #if and #endif so that they match up // (force them to match up by adding a trailing #endif if required). int openingIfCounter = 0; int closingEndifCounter = 0; #endif // If additional scopes are included then the last declaration will be treated // as a function declaration instead of a function prototype (with the next // scopes "{ }" defining the function). bool containsAdditionalScopes = (stackSize > 1) ? true : false; ListOfStatementsType globalScopeList = tempStack.top(); globalPrefixString = generatePrefixStringFromStatementList ( globalScopeList,skipStatementListTrailingDirectives, // openingIfCounter,closingEndifCounter, containsAdditionalScopes); // DQ (2/2/2004): Only call this once to avoid premature generation of #endif globalPrefixString += generateEndifForPrefixString ( /* openingIfCounter,closingEndifCounter */ ); } #if 0 printf ("############################### \n"); printf ("In generatePrefixString() globalPrefixString = \n%s\n",globalPrefixString.c_str()); printf ("############################### \n"); #endif #if 0 printf ("Exiting at base of generatePrefixStringGlobalDeclarations() \n"); ROSE_ABORT(); #endif return globalPrefixString; } template <class ASTNodeCollection> std::string MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: generatePrefixStringLocalDeclarations() { std::string localPrefixString; // We need to handle the case of a prefix generated for SgGlobal // (in which case the stack of scopes is empty!). #if 0 // For now return early. printf ("NOTE: multiple returns in generatePrefixStringLocalDeclarations() \n"); if (stackOfScopes.size() < 2) return localPrefixString; #endif // printf ("In generatePrefixStringLocalDeclarations() stackOfScopes.size() = %" PRIuPTR " \n",stackOfScopes.size()); if (stackOfScopes.size() > 1) { // Make a copy of the stack to avoid distroying it while traversing it StackOfListsType tempStack = stackOfScopes; int stackSize = tempStack.size(); int stackCounter = 0; #if 0 // Keep track of the number of #if and #endif so that they match up // (force them to match up by adding a trailing #endif if required). int openingIfCounter = 0; int closingEndifCounter = 0; #endif // bool firstOpenParen = true; // Pop off the global scope (which is on top of the stack) // printf ("In generatePrefixStringLocalDeclarations() pop off the global scope: tempStack.size() = %" PRIuPTR " \n",tempStack.size()); ROSE_ASSERT(tempStack.size() > 0); tempStack.pop(); stackSize--; // printf ("In generatePrefixStringLocalDeclarations(): stackSize = %d \n",stackSize); int lastScopeIndex = tempStack.size()-1; for (int j=0; j < stackSize; j++) { ListOfStatementsType tempList = tempStack.top(); #if 0 printf ("In generatePrefixStringLocalDeclarations(): stackCounter = %d lastScopeIndex = %d tempList.size() = %" PRIuPTR " \n",stackCounter,lastScopeIndex,tempList.size()); typename ListOfStatementsType::iterator i = tempList.begin(); while (i != tempList.end()) { printf ("---(*i).prefixStatement = %p (*i).comments = %p \n",(*i).prefixStatement,(*i).comments); if ((*i).prefixStatement != NULL) { printf (" IR Node (*i).prefixStatement = %s \n",(*i).prefixStatement->sage_class_name()); printf (" IR Node (*i).prefixStatement = %s \n",(*i).prefixStatement->unparseToString().c_str()); } i++; } #endif bool skipStatementListTrailingDirectives = stackCounter < lastScopeIndex; // bool containsAdditionalScopes = false; bool containsAdditionalScopes = stackCounter < lastScopeIndex; // DQ (8/8/2005): Skip output of initial "{" with the first local scope // (since it is part of the function template for the secondary file). // if (j > 0) // localPrefixString += "\n {"; char buffer[128] = ""; sprintf (buffer,"\n{ /* local stack #%d */ \n",j); // sprintf (buffer," /* local stack #%d */ \n",j); // localPrefixString += "\n{ /* local stack */ \n"; localPrefixString += std::string(buffer); localPrefixString += generatePrefixStringFromStatementList ( tempList,skipStatementListTrailingDirectives, // openingIfCounter,closingEndifCounter, containsAdditionalScopes); // printf ("In generatePrefixStringLocalDeclarations() incremental build: localPrefixString = %s \n",localPrefixString.c_str()); stackCounter++; tempStack.pop(); // localPrefixString += generateEndifForPrefixString(); } // printf ("After loop through non-global scopes: localPrefixString = %s \n",localPrefixString.c_str()); // localPrefixString += generateEndifForPrefixString ( /* openingIfCounter, closingEndifCounter */ ); } // printf ("After generateEndifForPrefixString(): localPrefixString = %s \n",localPrefixString.c_str()); #if 0 printf ("############################### \n"); printf ("In generatePrefixString() localPrefixString = \n%s\n",localPrefixString.c_str()); printf ("############################### \n"); #endif #if 0 printf ("Exiting at base of generatePrefixStringLocalDeclarations! \n"); ROSE_ABORT(); #endif return localPrefixString; } template <class ASTNodeCollection> std::string MidLevelRewrite<ASTNodeCollection>::PrefixSuffixGenerationTraversal:: generateSuffixString() { std::string suffixString; // DQ (8/8/2005): Fixed output to reflect more accurate reproduction of scopes (so that Milind's // AST Merge mechansim would be able to match names that included the scope depth). int lastScopeIndex = stackOfScopes.size()-0; // for (unsigned int i = 1; i < stackOfScopes.size(); i++) for (int i = 1; i < lastScopeIndex; i++) { // DQ (11/23/2003): Added ";" to close off class declararation statements // (for new code specificed as part of a class declaration). suffixString += " }; "; } // DQ (2/2/2004): Add this to prefix to close off any remaining directives // suffixString += generateEndifForPrefixString(); return suffixString; } // endif for AST_REWRITE_PREFIX_GENERATION_C #endif
19,597
2,606
package weixin.popular.bean.bizwifi.couponput.get; /** * @ProjectName weixin-popular * @Author: zeroJun * @Date: 2018/7/24 17:16 * @Description: */ public class CouponputGetResultData { private Integer shop_id; private Integer card_status; private String card_id; private String card_describe; private String start_date; private String end_date; public Integer getShop_id() { return shop_id; } public void setShop_id(Integer shop_id) { this.shop_id = shop_id; } public Integer getCard_status() { return card_status; } public void setCard_status(Integer card_status) { this.card_status = card_status; } public String getCard_id() { return card_id; } public void setCard_id(String card_id) { this.card_id = card_id; } public String getCard_describe() { return card_describe; } public void setCard_describe(String card_describe) { this.card_describe = card_describe; } public String getStart_date() { return start_date; } public void setStart_date(String start_date) { this.start_date = start_date; } public String getEnd_date() { return end_date; } public void setEnd_date(String end_date) { this.end_date = end_date; } }
560
1,526
<gh_stars>1000+ import time import threading import mock import unittest2 import testlib import mitogen.core class ShutdownTest(testlib.TestCase): klass = mitogen.core.Broker def test_poller_closed(self): broker = self.klass() actual_close = broker.poller.close broker.poller.close = mock.Mock() broker.shutdown() broker.join() self.assertEquals(1, len(broker.poller.close.mock_calls)) actual_close() class DeferTest(testlib.TestCase): klass = mitogen.core.Broker def test_defer(self): latch = mitogen.core.Latch() broker = self.klass() try: broker.defer(lambda: latch.put(123)) self.assertEquals(123, latch.get()) finally: broker.shutdown() broker.join() def test_defer_after_shutdown(self): latch = mitogen.core.Latch() broker = self.klass() broker.shutdown() broker.join() e = self.assertRaises(mitogen.core.Error, lambda: broker.defer(lambda: latch.put(123))) self.assertEquals(e.args[0], mitogen.core.Waker.broker_shutdown_msg) class DeferSyncTest(testlib.TestCase): klass = mitogen.core.Broker def test_okay(self): broker = self.klass() try: th = broker.defer_sync(lambda: threading.currentThread()) self.assertEquals(th, broker._thread) finally: broker.shutdown() broker.join() def test_exception(self): broker = self.klass() try: self.assertRaises(ValueError, broker.defer_sync, lambda: int('dave')) finally: broker.shutdown() broker.join() if __name__ == '__main__': unittest2.main()
851
5,169
{ "name": "FlowplayerCore", "version": "1.2.1", "summary": "The core library of Flowplayer's native iOS SDK.", "homepage": "https://flowplayer.com/", "license": { "type": "Flowplayer Commercial License v0.4", "file": "Release-FlowplayerCore/LICENSE.md" }, "authors": "Flowplayer AB", "platforms": { "ios": "10.0" }, "ios": { "vendored_frameworks": "Release-FlowplayerCore/Release-universal/FlowplayerCore.framework" }, "source": { "http": "https://github.com/flowplayer/flowplayer-ios-sdk-demo/releases/download/v1.2.1/Release-FlowplayerCore.zip" } }
231
335
{ "word": "Graminivorous", "definitions": [ "(of an animal) feeding on grass." ], "parts-of-speech": "Adjective" }
64
476
// Copyright (c) Facebook, Inc. and its affiliates. // // 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. #pragma once #include <atomic> #include <chrono> #include "rela/model_locker.h" #include "rela/prioritized_replay.h" #include "rela/types.h" namespace rela { class ThreadLoop { public: ThreadLoop() = default; ThreadLoop(const ThreadLoop&) = delete; ThreadLoop& operator=(const ThreadLoop&) = delete; virtual ~ThreadLoop() {} virtual void terminate() { terminated_ = true; } virtual void pause() { std::lock_guard<std::mutex> lk(mPaused_); paused_ = true; } virtual void resume() { { std::lock_guard<std::mutex> lk(mPaused_); paused_ = false; } cvPaused_.notify_one(); } virtual void waitUntilResume() { std::unique_lock<std::mutex> lk(mPaused_); cvPaused_.wait(lk, [this] { return !paused_; }); } virtual bool terminated() { return terminated_; } virtual bool paused() { return paused_; } virtual void mainLoop() = 0; private: std::atomic_bool terminated_{false}; std::mutex mPaused_; bool paused_ = false; std::condition_variable cvPaused_; }; } // namespace rela
555
396
package me.everything.providers.android.media; import android.net.Uri; import android.provider.BaseColumns; import android.provider.MediaStore; import me.everything.providers.core.Entity; import me.everything.providers.core.FieldMapping; import me.everything.providers.core.IgnoreMapping; /** * Created by sromku */ public class Playlist extends Entity { @IgnoreMapping public static Uri uriExternal = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI; @IgnoreMapping public static Uri uriInternal = MediaStore.Audio.Playlists.INTERNAL_CONTENT_URI; @FieldMapping(columnName = BaseColumns._ID, physicalType = FieldMapping.PhysicalType.Long) public long id; @FieldMapping(columnName = MediaStore.Audio.PlaylistsColumns.NAME, physicalType = FieldMapping.PhysicalType.String) public String name; @FieldMapping(columnName = MediaStore.Audio.PlaylistsColumns.DATA, physicalType = FieldMapping.PhysicalType.Blob) public byte[] data; @FieldMapping(columnName = MediaStore.Audio.PlaylistsColumns.DATE_ADDED, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Long) public long dateAdded; @FieldMapping(columnName = MediaStore.Audio.PlaylistsColumns.DATE_MODIFIED, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Long) public long dateModified; }
438
457
<reponame>jdamick/denominator package denominator; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import denominator.mock.MockProvider; import denominator.model.ResourceRecordSet; import denominator.model.Zone; import denominator.model.rdata.CERTData; import denominator.model.rdata.MXData; import denominator.model.rdata.NAPTRData; import denominator.model.rdata.SRVData; import denominator.model.rdata.SSHFPData; import static denominator.model.ResourceRecordSets.a; import static denominator.model.ResourceRecordSets.aaaa; import static denominator.model.ResourceRecordSets.cname; import static denominator.model.ResourceRecordSets.ns; import static denominator.model.ResourceRecordSets.ptr; import static denominator.model.ResourceRecordSets.spf; import static denominator.model.ResourceRecordSets.txt; import static java.lang.String.format; import static java.lang.System.getProperty; import static java.util.Arrays.asList; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; public class TestGraph { private final DNSApiManager manager; private final String zoneName; private final boolean addTrailingDotToZone; public TestGraph() { this(Denominator.create(new MockProvider()), "denominator.io."); } /** * To lazy initialize {@code manager}, pass null and override {@link #manager()}. */ protected TestGraph(DNSApiManager manager, String zoneName) { this.manager = manager; this.zoneName = zoneName; this.addTrailingDotToZone = manager == null || !manager.provider().name().equals("clouddns"); } /** * Returns null if the manager could not be initialized. * * <p/> Override to lazy initialize, for example if you are using TLS certificate auth. */ protected DNSApiManager manager() { return manager; } Zone createZoneIfAbsent() { assumeTrue("manager not initialized", manager() != null); assumeTrue("zone not specified", zoneName != null); Iterator<Zone> zonesWithName = manager().api().zones().iterateByName(zoneName); if (zonesWithName.hasNext()) { return zonesWithName.next(); } String id = manager().api().zones().put(Zone.create(null, zoneName, 86400, "test@" + zoneName)); return Zone.create(id, zoneName, 86400, "test@" + zoneName); } String deleteTestZone() { assumeTrue("manager not initialized", manager() != null); assumeTrue("zone not specified", zoneName != null); String zoneToCreate = "zonetest." + zoneName; Iterator<Zone> zonesWithName = manager().api().zones().iterateByName(zoneToCreate); while (zonesWithName.hasNext()) { manager().api().zones().delete(zonesWithName.next().id()); } return zoneToCreate; } List<ResourceRecordSet<?>> basicRecordSets(Class<?> testClass) { return filterRecordSets(testClass, manager().provider().basicRecordTypes()); } List<ResourceRecordSet<?>> recordSetsForProfile(Class<?> testClass, String profile) { return filterRecordSets(testClass, manager().provider().profileToRecordTypes().get(profile)); } private List<ResourceRecordSet<?>> filterRecordSets(Class<?> testClass, Collection<String> types) { List<ResourceRecordSet<?>> filtered = new ArrayList<ResourceRecordSet<?>>(); for (Map.Entry<String, ResourceRecordSet<?>> entry : stockRRSets(testClass).entrySet()) { if (types.contains(entry.getKey())) { filtered.add(entry.getValue()); } } return filtered; } /** * Creates sample record sets named base on the {@code testClass}. */ private Map<String, ResourceRecordSet<?>> stockRRSets(Class<?> testClass) { String rPrefix = testClass.getSimpleName().toLowerCase() + "." + getProperty("user.name").replace('.', '-'); String rSuffix = rPrefix + "." + zoneName; String dSuffix = rSuffix; if (addTrailingDotToZone && !rSuffix.endsWith(".")) { dSuffix = rSuffix + "."; } Map<String, ResourceRecordSet<?>> result = new LinkedHashMap<String, ResourceRecordSet<?>>(); result.put("A", a("ipv4-" + rSuffix, asList("192.0.2.1", "198.51.100.1", "203.0.113.1"))); result.put("AAAA", aaaa("ipv6-" + rSuffix, asList("fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "fdf8:f53e:61e4::18", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"))); result.put("CNAME", cname("www-" + rSuffix, asList("www-north-" + dSuffix, "www-east-" + dSuffix, "www-west-" + dSuffix))); result.put("CERT", ResourceRecordSet.<CERTData>builder().name("cert-" + rSuffix).type("CERT") .add(CERTData.builder().format(1).tag(2).algorithm(3).certificate("ABCD") .build()) .add(CERTData.builder().format(1).tag(2).algorithm(3).certificate("EFGH") .build()) .build()); result.put("MX", ResourceRecordSet.<MXData>builder().name("mail-" + rSuffix).type("MX") .add(MXData.create(10, "mail1-" + dSuffix)) .add(MXData.create(10, "mail2-" + dSuffix)) .add(MXData.create(10, "mail3-" + dSuffix)).build()); result.put("NS", ns("ns-" + rSuffix, asList("ns1-" + dSuffix, "ns2-" + dSuffix, "ns3-" + dSuffix))); result.put("NAPTR", ResourceRecordSet.<NAPTRData>builder().name("naptr-" + rSuffix).type("NAPTR") .add(NAPTRData.builder().order(1).preference(1).flags("U").services("E2U+sip") .regexp("!^.*$!sip:<EMAIL>!").replacement(".") .build()) .add(NAPTRData.builder().order(2).preference(1).flags("U").services("E2U+sip") .regexp("!^.*$!sip:<EMAIL>!").replacement(".") .build()) .build()); result.put("PTR", ptr("ptr-" + rSuffix, asList("ptr1-" + dSuffix, "ptr2-" + dSuffix, "ptr3-" + dSuffix))); result.put("SPF", spf("spf-" + rSuffix, asList("v=spf1 a -all", "v=spf1 mx -all", "v=spf1 ipv6 -all"))); result.put("SRV", // designate does not support priority zero! ResourceRecordSet.<SRVData>builder().name("_http._tcp" + rSuffix).type("SRV") .add(SRVData.builder().priority(1).weight(1).port(80) .target("ipv4-" + dSuffix) .build()) .add(SRVData.builder().priority(1).weight(1).port(8080) .target("ipv4-" + dSuffix) .build()) .add(SRVData.builder().priority(1).weight(1).port(443) .target("ipv4-" + dSuffix) .build()) .build()); result.put("SSHFP", ResourceRecordSet.<SSHFPData>builder().name("ipv4-" + rSuffix).type("SSHFP") .add(SSHFPData.createDSA("<KEY>")) .add(SSHFPData.createDSA("<KEY>")) .add(SSHFPData.createDSA("390E37C5B5DB9A1C455E648A41AF3CC83F99F102")).build()); result.put("TXT", txt("txt-" + rSuffix, asList("made in norway", "made in sweden", "made in finland"))); return result; } }
3,589
313
<reponame>saiive/ain<filename>test/functional/rpc_listaccounthistory.py #!/usr/bin/env python3 # Copyright (c) 2014-2019 The Bitcoin Core developers # Copyright (c) DeFi Blockchain Developers # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. """Test listaccounthistory RPC.""" from test_framework.test_framework import DefiTestFramework from test_framework.util import ( assert_equal, connect_nodes_bi ) class TokensRPCListAccountHistory(DefiTestFramework): def set_test_params(self): self.num_nodes = 3 self.setup_clean_chain = True self.extra_args = [ ['-acindex=1', '-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-bayfrontgardensheight=50'], ['-acindex=1', '-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-bayfrontgardensheight=50'], ['-acindex=1', '-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-bayfrontgardensheight=50'], ] def run_test(self): self.nodes[0].generate(101) num_tokens = len(self.nodes[0].listtokens()) # collateral address collateral_a = self.nodes[0].getnewaddress("", "legacy") # Create token self.nodes[0].createtoken({ "symbol": "GOLD", "name": "gold", "collateralAddress": collateral_a }) self.nodes[0].generate(1) # Make sure there's an extra token assert_equal(len(self.nodes[0].listtokens()), num_tokens + 1) # Stop node #2 for future revert self.stop_node(2) # Get token ID list_tokens = self.nodes[0].listtokens() for idx, token in list_tokens.items(): if (token["symbol"] == "GOLD"): token_a = idx # Mint some tokens self.nodes[0].minttokens(["300@" + token_a]) self.nodes[0].generate(1) # Get node 0 results results = self.nodes[0].listaccounthistory(collateral_a) # Expect two sends, two receives and one mint tokens assert_equal(len(results), 5) assert_equal(self.nodes[0].accounthistorycount(collateral_a), 5) # All TXs should be for collateral_a and contain a MintTokens TX found = False for txs in results: assert_equal(txs['owner'], collateral_a) if txs['type'] == 'MintToken': found = True assert_equal(found, True) # check amounts field is type of array for txs in results: assert(hasattr(txs['amounts'], '__len__') and (not isinstance(txs['amounts'], str))) # Get node 1 results results = self.nodes[1].listaccounthistory(collateral_a) # Expect one mint token TX assert_equal(len(results), 1) assert_equal(self.nodes[1].accounthistorycount(collateral_a), 1) # Check owner is collateral_a and type MintTokens assert_equal(results[0]['owner'], collateral_a) assert_equal(results[0]['type'], 'MintToken') # check amounts field is type of array assert(hasattr(results[0]['amounts'], '__len__') and (not isinstance(results[0]['amounts'], str))) result = self.nodes[0].listaccounthistory() assert 'blockReward' in [res['type'] for res in result] result = self.nodes[1].listaccounthistory() assert_equal(result, []) # REVERTING: #======================== self.start_node(2) self.nodes[2].generate(2) connect_nodes_bi(self.nodes, 1, 2) self.sync_blocks() # Get node 1 results results = self.nodes[1].listaccounthistory(collateral_a) # Expect mint token TX to be reverted assert_equal(len(results), 0) assert_equal(self.nodes[1].accounthistorycount(collateral_a), 0) if __name__ == '__main__': TokensRPCListAccountHistory().main ()
1,749
385
/* Compiled resource file. DO NOT EDIT! */ #include "Corrade/Corrade.h" #include "Corrade/Utility/Macros.h" #include "Corrade/Utility/Resource.h" namespace { Corrade::Utility::Implementation::ResourceGroup resource; } int resourceInitializer_ResourceTestNothingData(); int resourceInitializer_ResourceTestNothingData() { resource.name = "nothing"; resource.count = 0; resource.positions = nullptr; resource.filenames = nullptr; resource.data = nullptr; Corrade::Utility::Resource::registerData(resource); return 1; } CORRADE_AUTOMATIC_INITIALIZER(resourceInitializer_ResourceTestNothingData) int resourceFinalizer_ResourceTestNothingData(); int resourceFinalizer_ResourceTestNothingData() { Corrade::Utility::Resource::unregisterData(resource); return 1; } CORRADE_AUTOMATIC_FINALIZER(resourceFinalizer_ResourceTestNothingData)
282
1,159
<gh_stars>1000+ #include "trapezoid.h" #include "base/math/tolerance.h" #include "triangle.h" using namespace Geom; Trapezoid Trapezoid::Square(Point p0, Point p2) { auto center = (p0 + p2) / 2; auto halfDiagonal = (p2 - p0) / 2; auto p1 = center + halfDiagonal.normal(false); auto p3 = center + halfDiagonal.normal(true); return Trapezoid({ p0, p1, p2, p3 }); } bool Trapezoid::contains(const Point &p, double tolerance) const { auto boundaryArea = Triangle(std::array<Point, 3>{ points[0], points[1], p }).area() + Triangle(std::array<Point, 3>{ points[1], points[2], p }).area() + Triangle(std::array<Point, 3>{ points[2], points[3], p }).area() + Triangle(std::array<Point, 3>{ points[3], points[0], p }).area(); return Math::addTolerance(boundaryArea, tolerance) == area(); } double Trapezoid::area() const { return Triangle(std::array<Point, 3>{ points[0], points[1], points[2] }).area() + Triangle(std::array<Point, 3>{ points[2], points[3], points[0] }).area(); } bool VerticalTrapezoid::contains(const Point &p) const { if (p.x < points[0].x || p.x > points[1].x) return false; auto xf = Math::Range<double>(points[0].x, points[1].x).rescale(p.x); auto y0 = Math::interpolate(points[0].y, points[1].y, xf); auto y1 = Math::interpolate(points[3].y, points[2].y, xf); return Math::Range<double>(y0, y1).includes(p.y); }
550
1,540
<reponame>punamsapkale/testng<gh_stars>1000+ package test.failedreporter.issue2521; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; public class DataProviderWithFactoryMultiFailedReporterSample { private Integer data; @Factory(dataProvider = "dp") public DataProviderWithFactoryMultiFailedReporterSample(Integer data) { this.data = data; } @DataProvider public static Object[][] dp() { return new Object[][] { new Object[] {0}, new Object[] {1}, new Object[] {2}, }; } @Test public void f1() { if (data != 1) { throw new RuntimeException(); } } @Test public void f2() { if (data != 0) { throw new RuntimeException(); } } }
280
1,861
from pypykatz.commons.common import KatzSystemArchitecture, WindowsBuild, WindowsMinBuild from pypykatz.commons.win_datatypes import POINTER, ULONG, \ KIWI_GENERIC_PRIMARY_CREDENTIAL, PVOID, DWORD, LUID, \ LSA_UNICODE_STRING, WORD from pypykatz.commons.common import hexdump class RDPCredsTemplate: def __init__(self): self.signature = None self.cred_struct = None @staticmethod def get_template(sysinfo): template = RDPCredsTemplate() if sysinfo.buildnumber >= WindowsBuild.WIN_8.value: template.signatures = [b'\x00\x00\x00\x00\xbb\x47', b'\x00\x00\x00\x00\xf3\x47', b'\x00\x00\x00\x00\x3b\x01'] template.offset = 0 template.cred_struct = WTS_KIWI else: template.signatures = [b'\xc8\x00\x00\x00\xc8\x00\x00\x00'] template.offset = 16 template.cred_struct = WTS_KIWI_2008R2 return template class WTS_KIWI: def __init__(self, reader): self.unk0 = DWORD(reader) self.unk1 = DWORD(reader) self.cbDomain = WORD(reader).value self.cbUsername = WORD(reader).value self.cbPassword = WORD(reader).value self.unk2 = DWORD(reader) self.Domain = reader.read(512) self.UserName = reader.read(512) self.Password_addr = reader.tell() self.Password = reader.read(512) class WTS_KIWI_2008R2: def __init__(self, reader): self.unk0 = DWORD(reader) self.unk0 = DWORD(reader) self.cbDomain = WORD(reader).value + 511 #making it compatible with the pother version. this is probably a bool?) self.cbUsername = WORD(reader).value + 511 self.cbPassword = WORD(reader).value + 511 self.unk2 = DWORD(reader) self.Domain = reader.read(512) self.UserName = reader.read(512) self.Password_addr = reader.tell() self.Password = reader.read(512)
707
1,259
<reponame>mevinbabuc/flagsmith import pytest from features.feature_types import MULTIVARIATE from features.models import Feature from features.multivariate.models import MultivariateFeatureOption from features.value_types import STRING @pytest.fixture() def multivariate_feature(project): feature = Feature.objects.create( name="feature", project=project, type=MULTIVARIATE, initial_value="control" ) multivariate_options = [] for percentage_allocation in (30, 30, 40): string_value = f"multivariate option for {percentage_allocation}% of users." multivariate_options.append( MultivariateFeatureOption( feature=feature, default_percentage_allocation=percentage_allocation, type=STRING, string_value=string_value, ) ) MultivariateFeatureOption.objects.bulk_create(multivariate_options) return feature
359
1,946
#pragma once #include <memory> #include <string> #include <vector> #include "Poller.h" #include "Utils.h" class ControlSocket { public: ControlSocket(std::shared_ptr<Poller> poller); ~ControlSocket(); bool Startup(); bool Accept(); bool Recv(std::vector<std::string> &commands); void CloseClient(); void Shutdown(); void SendCommandResponse(const char *commandResponse); private: static const int CONTROL_PORT; static const char *CONTROL_HOST; std::shared_ptr<Poller> mPoller; SOCKET mSocket; SOCKET mClientSocket; std::string mBuf; };
194
432
/* @(#)main.c 8.2 (Berkeley) 4/2/94 */ /* $NetBSD: main.c,v 1.15 2009/04/14 08:50:06 lukem Exp $ */ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * <NAME> at The University of California, Berkeley. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <err.h> #include <paths.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "defs.h" #include "window_string.h" #include "char.h" #include "local.h" void usage(void) __dead2; int main(int argc, char **argv) { char *p; const char *kp; char fflag = 0; char dflag = 0; char xflag = 0; char *cmd = NULL; char tflag = 0; int ch; escapec = ESCAPEC; debug = strcmp(getprogname(), "a.out") == 0; while ((ch = getopt(argc, argv, "fc:e:tdDx")) != -1) { switch (ch) { case 'f': fflag++; break; case 'c': if (cmd != NULL) { warnx("Only one -c allowed"); usage(); } cmd = optarg; break; case 'e': setescape(optarg); break; case 't': tflag++; break; case 'd': dflag++; break; case 'D': debug = !debug; break; case 'x': xflag++; break; default: usage(); } } if ((kp = getenv("SHELL")) == NULL) kp = _PATH_BSHELL; if ((default_shellfile = str_cpy(kp)) == 0) errx(1, "Out of memory."); if ((p = strrchr(default_shellfile, '/'))) p++; else p = default_shellfile; default_shell[0] = p; default_shell[1] = 0; default_nline = NLINE; default_smooth = 1; (void) gettimeofday(&starttime, (struct timezone *)0); if (wwinit() < 0) errx(1, "%s", wwerror()); #ifdef OLD_TTY if (debug) wwnewtty.ww_tchars.t_quitc = wwoldtty.ww_tchars.t_quitc; if (xflag) { wwnewtty.ww_tchars.t_stopc = wwoldtty.ww_tchars.t_stopc; wwnewtty.ww_tchars.t_startc = wwoldtty.ww_tchars.t_startc; } #else if (debug) { wwnewtty.ww_termios.c_cc[VQUIT] = wwoldtty.ww_termios.c_cc[VQUIT]; wwnewtty.ww_termios.c_lflag |= ISIG; } if (xflag) { wwnewtty.ww_termios.c_cc[VSTOP] = wwoldtty.ww_termios.c_cc[VSTOP]; wwnewtty.ww_termios.c_cc[VSTART] = wwoldtty.ww_termios.c_cc[VSTART]; wwnewtty.ww_termios.c_iflag |= IXON; } #endif if (debug || xflag) (void) wwsettty(0, &wwnewtty); if ((cmdwin = wwopen(WWT_INTERNAL, wwbaud > 2400 ? WWO_REVERSE : 0, 1, wwncol, 0, 0, 0)) == 0) { wwflush(); warnx("%s.\r", wwerror()); goto bad; } SET(cmdwin->ww_wflags, WWW_MAPNL | WWW_NOINTR | WWW_NOUPDATE | WWW_UNCTRL); if ((framewin = wwopen(WWT_INTERNAL, WWO_GLASS|WWO_FRAME, wwnrow, wwncol, 0, 0, 0)) == 0) { wwflush(); warnx("%s.\r", wwerror()); goto bad; } wwadd(framewin, &wwhead); if ((boxwin = wwopen(WWT_INTERNAL, WWO_GLASS, wwnrow, wwncol, 0, 0, 0)) == 0) { wwflush(); warnx("%s.\r", wwerror()); goto bad; } fgwin = framewin; wwupdate(); wwflush(); setvars(); setterse(tflag); setcmd(1); if (cmd != NULL) (void) dolongcmd(cmd, (struct value *)0, 0); if (!fflag) if (dflag || doconfig() < 0) dodefault(); if (selwin != 0) setcmd(0); mloop(); bad: wwend(1); return 0; } void usage(void) { (void) fprintf(stderr, "usage: %s [-e escape-char] [-c command] [-t] [-f] [-d]\n", getprogname()); exit(1); }
2,036
484
<reponame>BurningEnlightenment/outcome /* Example of Outcome used with error code enums (C) 2017-2019 <NAME> <http://www.nedproductions.biz/> (3 commits) 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 in the accompanying file Licence.txt or 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. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../../include/outcome.hpp" #include <iostream> //! [declaration] struct udt { int a{0}; explicit udt(int _a) : a(_a) { } udt() = default; int operator*() const { return a; } }; enum class err { success, failure1, failure2 }; // Tell the standard library that enum err is an error code enum // by specialising the is_error_code_enum trait. See // http://en.cppreference.com/w/cpp/error/error_code/is_error_code_enum namespace std { template <> struct is_error_code_enum<err> : std::true_type { }; } // We also must declare a free function make_error_code. This is // discovered via ADL by the standard library. See // http://en.cppreference.com/w/cpp/error/errc/make_error_code inline std::error_code make_error_code(err c) { // We need to inherit from std::error_category to define // an error code domain with the standard library for // our strongly typed enum. See // http://en.cppreference.com/w/cpp/error/error_category static struct err_category : std::error_category { virtual const char *name() const noexcept override final { return "err_category"; }; virtual std::string message(int c) const override final { switch(static_cast<err>(c)) { case err::success: return "err::success"; case err::failure1: return "err::failure1"; case err::failure2: return "err::failure2"; } return "unknown"; } } category; return std::error_code(static_cast<int>(c), category); } //! [declaration] using namespace OUTCOME_V2_NAMESPACE; int main() { //! [usage] result<udt, err> res(err::failure1); // What happens here? What exception type is thrown? try { std::cout << *res.value() << std::endl; } catch(const std::exception &e) { std::cerr << "Exception thrown was " << e.what() << std::endl; } //! [usage] return 0; } void test() { //! [usage2] result<udt /*, std::error_code */> res(err::failure1); // What happens here? What exception type is thrown? try { std::cout << *res.value() << std::endl; } catch(const std::exception &e) { // Prints "Exception thrown was failure1", exactly the same as before std::cerr << "Exception thrown was " << e.what() << std::endl; } //! [usage2] } //! [usage3] result<udt> boo() { return err::failure1; } result<udt> foo() { OUTCOME_TRY(auto v, (boo())); return udt{5}; // emplace construct udt with 5 } //! [usage3]
1,195
3,651
<gh_stars>1000+ package com.orientechnologies.orient.core.metadata.security; public class OSecurityResourceDatabaseOp extends OSecurityResource { public static OSecurityResourceDatabaseOp DB = new OSecurityResourceDatabaseOp("database"); public static OSecurityResourceDatabaseOp CREATE = new OSecurityResourceDatabaseOp("database.create"); public static OSecurityResourceDatabaseOp COPY = new OSecurityResourceDatabaseOp("database.copy"); public static OSecurityResourceDatabaseOp DROP = new OSecurityResourceDatabaseOp("database.drop"); public static OSecurityResourceDatabaseOp EXISTS = new OSecurityResourceDatabaseOp("database.exists"); public static OSecurityResourceDatabaseOp COMMAND = new OSecurityResourceDatabaseOp("database.command"); public static OSecurityResourceDatabaseOp COMMAND_GREMLIN = new OSecurityResourceDatabaseOp("database.command.gremlin"); public static OSecurityResourceDatabaseOp FREEZE = new OSecurityResourceDatabaseOp("database.freeze"); public static OSecurityResourceDatabaseOp RELEASE = new OSecurityResourceDatabaseOp("database.release"); public static OSecurityResourceDatabaseOp PASS_THROUGH = new OSecurityResourceDatabaseOp("database.passthrough"); public static OSecurityResourceDatabaseOp BYPASS_RESTRICTED = new OSecurityResourceDatabaseOp("database.bypassRestricted"); public static OSecurityResourceDatabaseOp HOOK_RECORD = new OSecurityResourceDatabaseOp("database.hook.record"); private OSecurityResourceDatabaseOp(String resourceString) { super(resourceString); } }
421
640
# -*- coding: utf-8 -*- from app.const import * from app.base.controller import TPBaseHandler, TPBaseJsonHandler from app.model import stats class IndexHandler(TPBaseHandler): def get(self): ret = self.check_privilege(TP_PRIVILEGE_LOGIN_WEB) if ret != TPE_OK: return self.render('dashboard/index.mako')
160
580
/** * Copyright 2011, Big Switch Networks, Inc. * Originally created by <NAME>, Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ package net.floodlightcontroller.packet; import java.nio.ByteBuffer; /** * This class is a Rapid Spanning Tree Protocol * Bridge Protocol Data Unit * @author alexreimers */ public class BPDU extends BasePacket { public enum BPDUType { CONFIG, TOPOLOGY_CHANGE; } private final long destMac = 0x0180c2000000L; // 01-80-c2-00-00-00 // TODO - check this for RSTP private LLC llcHeader; private short protocolId = 0; private byte version = 0; private byte type; private byte flags; private byte[] rootBridgeId; private int rootPathCost; private byte[] senderBridgeId; // switch cluster MAC private short portId; // port it was transmitted from private short messageAge; // 256ths of a second private short maxAge; // 256ths of a second private short helloTime; // 256ths of a second private short forwardDelay; // 256ths of a second public BPDU(BPDUType type) { rootBridgeId = new byte[8]; senderBridgeId = new byte[8]; llcHeader = new LLC(); llcHeader.setDsap((byte) 0x42); llcHeader.setSsap((byte) 0x42); llcHeader.setCtrl((byte) 0x03); switch(type) { case CONFIG: this.type = 0x0; break; case TOPOLOGY_CHANGE: this.type = (byte) 0x80; // 1000 0000 break; default: this.type = 0; break; } } @Override public byte[] serialize() { byte[] data; // TODO check these if (type == 0x0) { // config data = new byte[38]; } else { // topology change data = new byte[7]; // LLC + TC notification } ByteBuffer bb = ByteBuffer.wrap(data); // Serialize the LLC header byte[] llc = llcHeader.serialize(); bb.put(llc, 0, llc.length); bb.putShort(protocolId); bb.put(version); bb.put(type); if (type == 0x0) { bb.put(flags); bb.put(rootBridgeId, 0, rootBridgeId.length); bb.putInt(rootPathCost); bb.put(senderBridgeId, 0, senderBridgeId.length); bb.putShort(portId); bb.putShort(messageAge); bb.putShort(maxAge); bb.putShort(helloTime); bb.putShort(forwardDelay); } return data; } @Override public IPacket deserialize(byte[] data, int offset, int length) { ByteBuffer bb = ByteBuffer.wrap(data, offset, length); // LLC header llcHeader.deserialize(data, offset, 3); this.protocolId = bb.getShort(); this.version = bb.get(); this.type = bb.get(); // These fields only exist if it's a configuration BPDU if (this.type == 0x0) { this.flags = bb.get(); bb.get(rootBridgeId, 0, 6); this.rootPathCost = bb.getInt(); bb.get(this.senderBridgeId, 0, 6); this.portId = bb.getShort(); this.messageAge = bb.getShort(); this.maxAge = bb.getShort(); this.helloTime = bb.getShort(); this.forwardDelay = bb.getShort(); } // TODO should we set other fields to 0? return this; } public long getDestMac() { return destMac; } }
1,945
424
import asyncio from collections import deque from datetime import datetime from pathlib import Path from re import Match, match from typing import Dict, Iterable, List, Tuple, Union from urllib import parse import requests from bs4 import BeautifulSoup, Tag from more_itertools import unique_everseen from pyppeteer import connect from .browser import get_browser_connection_url from .helpers import error_handler, pipe from .requests_cache import CachedResponse, CachedSession @error_handler def get_csrf_token(session: CachedSession) -> str: csrf_token_get_response: CachedResponse = session.get( "https://foxford.ru/api/csrf_token", headers={ "X-Requested-With": "XMLHttpRequest" } ) if csrf_token_get_response.status_code != 200: return {"fatal_error": "CSRF token fetch has failed"} if "token" not in csrf_token_get_response.json(): return {"fatal_error": "CSRF token structure is unknown"} return csrf_token_get_response.json()["token"] @error_handler def login(email: str, password: str, session: CachedSession) -> CachedSession: if not email or not password: return {"fatal_error": "No credentials provided"} credential_post_response: CachedResponse = session.post( "https://foxford.ru/user/login", headers={ "X-CSRF-Token": get_csrf_token(session), "X-Requested-With": "XMLHttpRequest" }, json={ "user": { "email": email, "password": password } } ) if credential_post_response.status_code != 200: return {"fatal_error": "Wrong credentials"} return session def get_user_courses(session: CachedSession) -> Tuple[Dict]: @error_handler def recursive_collection(page_num: int) -> Tuple[Dict]: course_list_response: CachedResponse = session.get( f"https://foxford.ru/api/user/bookmarks?page={page_num}&archived=false", headers={ "X-CSRF-Token": get_csrf_token(session), "X-Requested-With": "XMLHttpRequest" } ) if course_list_response.status_code != 200: return {"fatal_error": "Course list fetch has failed"} if "bookmarks" not in course_list_response.json(): return {"fatal_error": "Course list structure is unknown"} if all(False for _ in course_list_response.json()["bookmarks"]): return () if not {"name", "subtitle", "resource_id"}.issubset(set(course_list_response.json()["bookmarks"][0])): return {"fatal_error": "Course structure is unknown"} return ( *course_list_response.json()["bookmarks"], *recursive_collection(page_num + 1) ) return recursive_collection(1) class get_course_lessons(): @error_handler def __new__(self, course_id: int, session: CachedSession) -> Iterable[Dict]: lesson_list_at_somewhere_response: CachedResponse = session.get( f"https://foxford.ru/api/courses/{course_id}/lessons", headers={ "X-Requested-With": "XMLHttpRequest" } ) if lesson_list_at_somewhere_response.status_code != 200: return {"fatal_error": "Lesson list fetch has failed"} if not {"lessons", "cursors"}.issubset(set(lesson_list_at_somewhere_response.json())): return {"fatal_error": "Lesson list structure is unknown"} if "id" not in lesson_list_at_somewhere_response.json()["lessons"][0]: return {"fatal_error": "Lesson structure is unknown"} self.course_id = course_id self.session = session return pipe( lambda json: ( *self.recursive_collection( self, "before", json["cursors"]["before"] ), *json["lessons"], *self.recursive_collection( self, "after", json["cursors"]["after"] ) ), lambda lessons: map( lambda lesson: self.lesson_extension(self, lesson), lessons ) )(lesson_list_at_somewhere_response.json()) @error_handler def recursive_collection(self, direction: str, cursor: Union[int, None]) -> Tuple[Dict]: if not cursor: return () lesson_list_at_direction_response: CachedResponse = self.session.get( f"https://foxford.ru/api/courses/{self.course_id}/lessons?{direction}={cursor}", headers={ "X-Requested-With": "XMLHttpRequest" } ) if lesson_list_at_direction_response.status_code != 200: return {"fatal_error": "Lesson list fetch has failed"} if not {"lessons", "cursors"}.issubset(set(lesson_list_at_direction_response.json())): return {"fatal_error": "Lesson list structure is unknown"} if "id" not in lesson_list_at_direction_response.json()["lessons"][0]: return {"fatal_error": "Lesson structure is unknown"} if direction == "before": return ( *self.recursive_collection( self, direction, lesson_list_at_direction_response .json()["cursors"][direction] ), *lesson_list_at_direction_response.json()["lessons"] ) else: return ( *lesson_list_at_direction_response.json()["lessons"], *self.recursive_collection( self, direction, lesson_list_at_direction_response .json()["cursors"][direction] ) ) @error_handler def lesson_extension(self, lesson: Dict) -> Dict: lesson_extension_response: CachedResponse = self.session.get( f"https://foxford.ru/api/courses/{self.course_id}/lessons/{lesson['id']}", headers={ "X-Requested-With": "XMLHttpRequest" } ) if lesson_extension_response.status_code != 200: return {"fatal_error": "Lesson extension fetch has failed"} if not {"webinar_id", "access_state", "webinar_status", "is_locked"}.issubset(set(lesson_extension_response.json())): return {"fatal_error": "Lesson extension structure is unknown"} return lesson_extension_response.json() class get_resources_for_lessons(): def __new__(self, course_id: int, webinar_ids: Iterable[int], session: CachedSession) -> Tuple[Dict]: self.course_id = course_id self.webinar_ids = webinar_ids self.session = session return self.recursive_collection(self) @error_handler def recursive_collection(self) -> Tuple[Dict]: webinar_id: Union[int, None] = next(self.webinar_ids, None) if not webinar_id: return () video_source_response: CachedResponse = self.session.get( f"https://foxford.ru/groups/{webinar_id}" ) if video_source_response.status_code != 200: return {"fatal_error": "Video source fetch has failed"} return ( pipe( lambda res: self.retrieve_erly_iframe_src(self, res), lambda src: self.construct_resource_links(self, src) )(video_source_response), *self.recursive_collection(self) ) @error_handler def retrieve_erly_iframe_src(self, video_source_response: CachedResponse) -> str: erly_iframe: Union[Tag, None] = pipe( lambda r_content: BeautifulSoup( r_content, "html.parser" ), lambda soup: soup.select_one( "div.full_screen > iframe" ) )(video_source_response.content) if not erly_iframe: return {"fatal_error": ".full_screen > iframe wasn't found"} erly_iframe_src: Union[str, None] = erly_iframe.get("src") if not erly_iframe_src: return {"fatal_error": ".full_screen > iframe doesn't have src attribute"} return erly_iframe_src @error_handler def construct_resource_links(self, erly_iframe_src: str) -> Dict: search_params: Dict = dict( parse.parse_qsl( parse.urlparse(erly_iframe_src).query ) ) if not {"conf", "access_token"}.issubset(set(search_params)): return {"fatal_error": "Iframe src search params structure is unknown"} webinar_id_match: Union[Match, None] = match( r"^webinar-(\d+)$", search_params.get("conf") ) if not webinar_id_match: return {"fatal_error": "Unable to extract webinar id"} return { "video": f"https://storage.netology-group.services/api/v1/buckets/ms.webinar.foxford.ru/sets/{webinar_id_match[1]}/objects/mp4?access_token={search_params.get('access_token')}", "events": f"https://storage.netology-group.services/api/v1/buckets/meta.webinar.foxford.ru/sets/{webinar_id_match[1]}/objects/events.json?access_token={search_params.get('access_token')}" } def get_lesson_tasks(lesson_ids: Iterable[int], session: CachedSession) -> Iterable[List[Dict]]: @error_handler def fetch(lesson_id: int) -> List[Dict]: tasks_response: CachedResponse = session.get( f"https://foxford.ru/api/lessons/{lesson_id}/tasks", headers={ "X-Requested-With": "XMLHttpRequest" } ) if tasks_response.status_code != 200: return {"fatal_error": "Tasks fetch has failed"} if "id" not in tasks_response.json()[0]: return {"fatal_error": "Task structure is unknown"} return tasks_response.json() return map(fetch, lesson_ids) def construct_task_urls(lesson_ids: Iterable[int], lesson_tasks: Iterable[List[Dict]]) -> Iterable[Iterable[str]]: def combination(lesson_id: int, task_list: List[Dict]) -> Iterable[str]: return map( lambda task: f"https://foxford.ru/lessons/{lesson_id}/tasks/{task['id']}", task_list ) return map( combination, lesson_ids, lesson_tasks ) def construct_conspect_urls(lesson_ids: Iterable[int], conspect_amount: Iterable[int]) -> Iterable[Tuple[str]]: def recursive_collection(lesson_id: int, amount: int) -> Tuple[str]: if amount == 0: return () return ( *recursive_collection(lesson_id, amount - 1), f"https://foxford.ru/lessons/{lesson_id}/conspects/{amount}" ) return map( recursive_collection, lesson_ids, conspect_amount ) def build_dir_hierarchy(course_name: str, course_subtitle: str, grade: str, lessons: Iterable[Dict]) -> Iterable[Path]: def sanitize_string(string: str) -> str: return pipe( lambda char_list: filter( lambda char: char.isalpha() or char.isdigit() or char == " ", char_list ), lambda iterable: "".join(iterable), lambda filtered_char_list: filtered_char_list[:30].strip() )(string) def create_dir(lesson: Dict) -> Path: constructed_path: Path = Path( Path.cwd(), ( f"({grade}) " + sanitize_string(course_name) + " - " + sanitize_string(course_subtitle) ).strip(), ( f"({lesson['number']}) " + sanitize_string(lesson['title']) ).strip() ) if not constructed_path.exists(): constructed_path.mkdir(parents=True) return constructed_path return map( create_dir, lessons ) def download_resources(res_with_path: Dict, session: CachedSession) -> None: @error_handler def download_url(url: str, dest: Path) -> None: with requests.get(url, stream=True) as r: if r.status_code != 200: return {"fatal_error": "Video fetch has failed"} with dest.open("wb") as f: deque( map( lambda chunk: f.write(chunk), filter(None, r.iter_content(10 * 1024)) ), 0 ) def save_video() -> None: if res_with_path["destination"].joinpath("video.mp4").exists(): return download_url( res_with_path["video"], res_with_path["destination"].joinpath("video.mp4") ) @error_handler def parse_and_save_event_data() -> None: if res_with_path["destination"].joinpath("message_log.txt").exists(): return events_response: CachedResponse = session.get( res_with_path["events"] ) if events_response.status_code != 200: return {"fatal_error": "Events fetch has failed"} if "meta" not in events_response.json()[0]: return {"fatal_error": "Events structure is unknown"} with res_with_path["destination"].joinpath("message_log.txt").open("w", errors="replace") as f: pipe( lambda json: filter( lambda obj: obj["meta"]["action"] == "message", json ), lambda messages: map( lambda msg: f"[{datetime.fromtimestamp(msg['meta']['time'])}] {msg['meta']['user_name']}: {parse.unquote(msg['meta']['body'])}", messages ), lambda message_log: "\n".join(message_log), f.write )(events_response.json()) pipe( lambda json: filter( lambda obj: (obj["meta"]["action"] == "add_tab" or obj["meta"]["action"] == "change_tab") and obj["meta"]["content_type"] == "pdf", json ), lambda pdfs: map( lambda pdf: pdf["meta"]["url"], pdfs ), unique_everseen, lambda urls: enumerate(urls, 1), lambda enumed_urls: map( lambda item: download_url( item[1], res_with_path["destination"] .joinpath(f"{item[0]}.pdf") ), enumed_urls ), lambda task_map: deque(task_map, 0) )(events_response.json()) save_video() parse_and_save_event_data() print( f"-> {res_with_path['destination'].name}: \033[92m\u2713\033[0m" ) async def save_page(url: str, path: Path, folder: str, cookies: Iterable[Dict], semaphore: asyncio.Semaphore) -> None: async with semaphore: if not path.joinpath(folder).joinpath(url.split("/")[-1] + ".pdf").exists(): browser_endpoint = await get_browser_connection_url() browser = await connect(browserWSEndpoint=browser_endpoint) page = await browser.newPage() await page.emulateMedia("screen") await page.setViewport({"width": 411, "height": 823}) await page.setCookie(*cookies) await page.goto(url, {"waitUntil": "domcontentloaded"}) if await page.waitForFunction("() => window.MathJax", timeout=10000): await asyncio.sleep(3.5) await page.evaluate(""" async function() { await new Promise(function(resolve) { window.MathJax.Hub.Register.StartupHook( "End", resolve ) }) } """) await asyncio.sleep(0.1) await page.evaluate(""" document.querySelectorAll(".toggle_element > .toggle_content").forEach(el => el.style.display = "block") """, force_expr=True) await asyncio.sleep(0.1) await page.evaluate(""" document.querySelector("#cc_container").remove() """, force_expr=True) await asyncio.sleep(0.1) if not path.joinpath(folder).exists(): path.joinpath(folder).mkdir() path.joinpath(folder).joinpath(url.split("/")[-1] + ".pdf").touch() await page.pdf({ "path": str(path.joinpath(folder).joinpath(url.split("/")[-1] + ".pdf")), "printBackground": True }) await page.close() await browser.disconnect() print( f"-> {folder}/{url.split('/')[-3]}/{url.split('/')[-1]}: \033[92m\u2713\033[0m" )
8,383
933
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SRC_PROTOZERO_PROTO_RING_BUFFER_H_ #define SRC_PROTOZERO_PROTO_RING_BUFFER_H_ #include <stdint.h> #include "perfetto/ext/base/paged_memory.h" namespace protozero { // This class buffers and tokenizes proto messages. // // From a logical level, it works with a sequence of protos like this. // [ header 1 ] [ payload 1 ] // [ header 2 ] [ payload 2 ] // [ header 3 ] [ payload 3 ] // Where [ header ] is a variable-length sequence of: // [ Field ID = 1, type = length-delimited] [ length (varint) ]. // // The input to this class is byte-oriented, not message-oriented (like a TCP // stream or a pipe). The caller is not required to respect the boundaries of // each message; only guarantee that data is not lost or duplicated. The // following sequence of inbound events is possible: // 1. [ hdr 1 (incomplete) ... ] // 2. [ ... hdr 1 ] [ payload 1 ] [ hdr 2 ] [ payoad 2 ] [ hdr 3 ] [ pay... ] // 3. [ ...load 3 ] // // This class maintains inbound requests in a ring buffer. // The expected usage is: // ring_buf.Append(data, len); // for (;;) { // auto msg = ring_buf.ReadMessage(); // if (!msg.valid()) // break; // Decode(msg); // } // // After each call to Append, the caller is expected to call ReadMessage() until // it returns an invalid message (signalling no more messages could be decoded). // Note that a single Append can "unblock" > 1 messages, which is why the caller // needs to keep calling ReadMessage in a loop. // // Internal architecture // --------------------- // Internally this is similar to a ring-buffer, with the caveat that it never // wraps, it only expands. Expansions are rare. The deal is that in most cases // the read cursor follows very closely the write cursor. For instance, if the // underlying transport behaves as a dgram socket, after each Append, the read // cursor will chase completely the write cursor. Even if the underlying stream // is not always atomic, the expectation is that the read cursor will eventually // reach the write one within few messages. // A visual example, imagine we have four messages: 2it 4will 2be 4fine // Visually: // // Append("2it4wi"): A message and a bit: // [ 2it 4wi ] // ^R ^W // // After the ReadMessage(), the 1st message will be read, but not the 2nd. // [ 2it 4wi ] // ^R ^W // // Append("ll2be4f") // [ 2it 4will 2be 4f ] // ^R ^W // // After the ReadMessage() loop: // [ 2it 4will 2be 4f ] // ^R ^W // Append("ine") // [ 2it 4will 2be 4fine ] // ^R ^W // // In the next ReadMessage() the R cursor will chase the W cursor. When this // happens (very frequent) we can just reset both cursors to 0 and restart. // If we are unlucky and get to the end of the buffer, two things happen: // 1. We try first to recompact the buffer, moving everything left by R. // 2. If still there isn't enough space, we expand the buffer. // Given that each message is expected to be at most kMaxMsgSize (64 MB), the // expansion is bound at 2 * kMaxMsgSize. class ProtoRingBuffer { public: static constexpr size_t kMaxMsgSize = 64 * 1024 * 1024; struct Message { const uint8_t* start = nullptr; uint32_t len = 0; uint32_t field_id = 0; bool fatal_framing_error = false; const uint8_t* end() const { return start + len; } inline bool valid() const { return !!start; } }; ProtoRingBuffer(); ~ProtoRingBuffer(); ProtoRingBuffer(const ProtoRingBuffer&) = delete; ProtoRingBuffer& operator=(const ProtoRingBuffer&) = delete; // Appends data into the ring buffer, recompacting or resizing it if needed. // Will invaildate the pointers previously handed out. void Append(const void* data, size_t len); // If a protobuf message can be read, it returns the boundaries of the message // (without including the preamble) and advances the read cursor. // If no message is avaiable, returns a null range. // The returned pointer is only valid until the next call to Append(), as // that can recompact or resize the underlying buffer. Message ReadMessage(); // Exposed for testing. size_t capacity() const { return buf_.size(); } size_t avail() const { return buf_.size() - (wr_ - rd_); } private: perfetto::base::PagedMemory buf_; Message fastpath_{}; bool failed_ = false; // Set in case of an unrecoverable framing faiulre. size_t rd_ = 0; // Offset of the read cursor in |buf_|. size_t wr_ = 0; // Offset of the write cursor in |buf_|. }; } // namespace protozero #endif // SRC_PROTOZERO_PROTO_RING_BUFFER_H_
1,700