max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
510 | from textwrap import dedent
HEADER_ROW = -1
import_error_msg_template = dedent(
"""\
dependency packages for {0} not found.
you can install the dependencies with 'pip install pytablewriter[{0}]'
"""
)
| 78 |
458 | //@category CppClassAnalyzer
import cppclassanalyzer.data.ClassTypeInfoManager;
import cppclassanalyzer.data.ProgramClassTypeInfoManager;
import cppclassanalyzer.utils.CppClassAnalyzerUtils;
import ghidra.app.script.GhidraScript;
import ghidra.app.cmd.data.rtti.gcc.builder.AbstractTypeInfoProgramBuilder;
import ghidra.app.cmd.data.rtti.ClassTypeInfo;
import ghidra.app.cmd.data.rtti.GnuVtable;
import ghidra.app.cmd.data.rtti.gcc.ClassTypeInfoUtils;
import ghidra.app.cmd.data.rtti.gcc.CreateVtableBackgroundCmd;
import ghidra.app.cmd.data.rtti.gcc.GnuUtils;
import ghidra.app.cmd.data.rtti.gcc.UnresolvedClassTypeInfoException;
import ghidra.app.cmd.data.rtti.TypeInfo;
import ghidra.app.cmd.data.rtti.Vtable;
import ghidra.app.cmd.data.rtti.gcc.VtableModel;
import ghidra.app.cmd.data.rtti.gcc.VttModel;
import ghidra.app.cmd.data.rtti.gcc.typeinfo.TypeInfoModel;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.DataType;
import ghidra.program.model.data.DataUtilities;
import ghidra.program.model.listing.Data;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.mem.Memory;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.reloc.Relocation;
import ghidra.program.model.symbol.Symbol;
import ghidra.program.model.symbol.SymbolTable;
import ghidra.program.model.mem.MemoryBufferImpl;
import ghidra.program.model.data.InvalidDataTypeException;
import ghidra.program.model.data.Structure;
import javax.lang.model.element.Modifier;
import com.squareup.javapoet.ArrayTypeName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import static ghidra.app.util.datatype.microsoft.MSDataTypeUtils.getAbsoluteAddress;
import static ghidra.program.model.data.DataUtilities.ClearDataMode.CLEAR_ALL_CONFLICT_DATA;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TestBuilder extends GhidraScript {
private static final String MAP_OF_ENTRIES = "Map.ofEntries(\n";
private static final String TYPE_MAP_FIELD = "typeMap";
private static final String NAME_MAP_FIELD = "nameMap";
private static final String VTABLE_MAP_FIELD = "vtableMap";
private static final String VTT_MAP_FIELD = "vttMap";
private static final String RELOCATION_MAP_FIELD = "relocationMap";
private static final String FUNCTION_OFFSETS_FIELD = "functionOffsets";
private static final String RETURN_STRING_FIELD = "returnString";
private static final String FUNCTION_DESCRIPTORS_FIELD = "fDescriptors";
private Map<TypeInfo, byte[]> tiMap = new LinkedHashMap<>();
private Map<String, Address> nameMap = new LinkedHashMap<>();
private Map<Vtable, byte[]> vtableMap = new LinkedHashMap<>();
private Map<VttModel, byte[]> vttMap = new LinkedHashMap<>();
private Set<Function> functionSet = new LinkedHashSet<>();
private static final TypeName MAP_TYPE =
ParameterizedTypeName.get(Map.class, Long.class, String.class);
private static final TypeName ARRAY_TYPE = ArrayTypeName.of(Long.class);
private static final TypeName STRING_TYPE = TypeName.get(String.class);
private static final String VTABLE_PREFIX = "_ZTV";
private static final String CREATE_MEMORY = "createMemory($S, $S, $L)";
private static final String PURE_VIRTUAL = "__cxa_pure_virtual";
@Override
public void run() throws Exception {
populateMaps();
buildClass();
}
private void buildClass() throws Exception {
File file = askDirectory("Select Directory", "Ok");
String name = askString("Class Name", "Enter Class Name");
TypeSpec tester = TypeSpec.classBuilder(name)
.addModifiers(Modifier.PUBLIC)
.superclass(AbstractTypeInfoProgramBuilder.class)
.addField(getTypeMapField())
.addField(getNameMapField())
.addField(getVtableMapField())
.addField(getVttMapField())
.addField(getRelocationMapField())
.addField(getFunctionArrayField())
.addField(getReturnFunctionField())
.addField(getFunctionDescriptorField())
.addMethod(makeConstructor())
.addMethod(makeGetter("getTypeInfoMap", TYPE_MAP_FIELD, MAP_TYPE))
.addMethod(makeGetter("getTypeNameMap", NAME_MAP_FIELD, MAP_TYPE))
.addMethod(makeGetter("getVtableMap", VTABLE_MAP_FIELD, MAP_TYPE))
.addMethod(makeGetter("getVttMap", VTT_MAP_FIELD, MAP_TYPE))
.addMethod(makeGetter("getRelocationMap", RELOCATION_MAP_FIELD, MAP_TYPE))
.addMethod(makeGetter("getFunctionOffsets", FUNCTION_OFFSETS_FIELD, ARRAY_TYPE))
.addMethod(makeGetter("getReturnInstruction", RETURN_STRING_FIELD, STRING_TYPE))
.addMethod(
makeGetter("getFunctionDescriptors", FUNCTION_DESCRIPTORS_FIELD, STRING_TYPE))
.addMethod(makeSetupMemory())
.build();
JavaFile.builder("ghidra.app.cmd.data.rtti.gcc.builder", tester)
.skipJavaLangImports(true)
.indent(" ")
.build().writeTo(file);
}
private FieldSpec getTypeMapField() throws Exception {
return FieldSpec.builder(MAP_TYPE, TYPE_MAP_FIELD)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer(getTypeMapInitializer()).build();
}
private FieldSpec getNameMapField() throws Exception {
return FieldSpec.builder(MAP_TYPE, NAME_MAP_FIELD)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer(getNameMapInitializer()).build();
}
private FieldSpec getVtableMapField() throws Exception {
return FieldSpec.builder(MAP_TYPE, VTABLE_MAP_FIELD)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer(getVtableMapInitializer()).build();
}
private FieldSpec getVttMapField() throws Exception {
return FieldSpec.builder(MAP_TYPE, VTT_MAP_FIELD)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer(getVttMapInitializer()).build();
}
private FieldSpec getRelocationMapField() throws Exception {
return FieldSpec.builder(MAP_TYPE, RELOCATION_MAP_FIELD)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer(getRelocationMapInitializer()).build();
}
private FieldSpec getFunctionArrayField() throws Exception {
return FieldSpec.builder(ARRAY_TYPE, FUNCTION_OFFSETS_FIELD)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer(getFunctionArrayInitializer()).build();
}
private FieldSpec getReturnFunctionField() throws Exception {
for (Symbol symbol : currentProgram.getSymbolTable().getSymbols("g_foo")) {
Function function = getFunctionAt(symbol.getAddress());
return FieldSpec.builder(String.class, RETURN_STRING_FIELD)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer("$S", byteArrayToHex(getBytes(
function.getEntryPoint(), (int) function.getBody().getNumAddresses())))
.build();
}
return null;
}
private FieldSpec getFunctionDescriptorField() throws Exception {
FieldSpec.Builder builder = FieldSpec.builder(STRING_TYPE, FUNCTION_DESCRIPTORS_FIELD)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL);
if (GnuUtils.hasFunctionDescriptors(currentProgram)) {
MemoryBlock block = getFunctionDescriptorBlock();
byte[] bytes = new byte[(int) block.getSize()];
block.getBytes(block.getStart(), bytes);
return builder.initializer("$S", byteArrayToHex(bytes)).build();
} return builder.initializer("$S", "").build();
}
private MemoryBlock getFunctionDescriptorBlock() {
return currentProgram.getMemory().getBlock(".opd");
}
private CodeBlock getTypeMapInitializer() throws Exception {
List<CodeBlock> blocks = new LinkedList<>();
for (TypeInfo type : tiMap.keySet()) {
blocks.add(
CodeBlock.builder().add(
"getEntry(0x$LL, $S)",
type.getAddress().toString(), byteArrayToHex(tiMap.get(type))
).build());
}
return CodeBlock.builder()
.add(MAP_OF_ENTRIES)
.indent()
.add(CodeBlock.join(blocks, ",\n"))
.unindent()
.add("\n)")
.build();
}
private CodeBlock getNameMapInitializer() throws Exception {
List<CodeBlock> blocks = new LinkedList<>();
for (String name : nameMap.keySet()) {
blocks.add(
CodeBlock.builder().add(
"getEntry(0x$LL, $S)",
nameMap.get(name), name
).build());
}
return CodeBlock.builder()
.add(MAP_OF_ENTRIES)
.indent()
.add(CodeBlock.join(blocks, ",\n"))
.unindent()
.add("\n)")
.build();
}
private CodeBlock getVtableMapInitializer() throws Exception {
List<CodeBlock> blocks = new LinkedList<>();
for (Vtable vtable : vtableMap.keySet()) {
blocks.add(
CodeBlock.builder().add(
"getEntry(0x$LL, $S)",
vtable.getAddress().toString(), byteArrayToHex(vtableMap.get(vtable))
).build());
}
return CodeBlock.builder()
.add(MAP_OF_ENTRIES)
.indent()
.add(CodeBlock.join(blocks, ",\n"))
.unindent()
.add("\n)")
.build();
}
private CodeBlock getVttMapInitializer() throws Exception {
List<CodeBlock> blocks = new LinkedList<>();
for (VttModel vtt : vttMap.keySet()) {
blocks.add(
CodeBlock.builder().add(
"getEntry(0x$LL, $S)",
vtt.getAddress().toString(), byteArrayToHex(vttMap.get(vtt))
).build());
}
return CodeBlock.builder()
.add(MAP_OF_ENTRIES)
.indent()
.add(CodeBlock.join(blocks, ",\n"))
.unindent()
.add("\n)")
.build();
}
private static boolean validRelocationSymbol(String symbolName) {
if (symbolName == null) {
return false;
} if (symbolName.equals(PURE_VIRTUAL)) {
return true;
} if (symbolName.contains(VTABLE_PREFIX) && symbolName.contains(TypeInfoModel.STRUCTURE_NAME)) {
return true;
} return false;
}
private CodeBlock getRelocationMapInitializer() throws Exception {
Iterator<Relocation> relocations = currentProgram.getRelocationTable().getRelocations();
List<CodeBlock> blocks = new LinkedList<>();
while (relocations.hasNext()) {
Relocation relocation = relocations.next();
if (validRelocationSymbol(relocation.getSymbolName())) {
blocks.add(
CodeBlock.builder().add(
"getEntry(0x$LL, $S)",
relocation.getAddress().toString(), relocation.getSymbolName()
).build());
}
}
return CodeBlock.builder()
.add(MAP_OF_ENTRIES)
.indent()
.add(CodeBlock.join(blocks, ",\n"))
.unindent()
.add("\n)")
.build();
}
private CodeBlock getFunctionArrayInitializer() throws Exception {
List<CodeBlock> blocks = new LinkedList<>();
for (Function function : functionSet) {
blocks.add(
CodeBlock.builder().add(
"0x$LL",
function.getEntryPoint().toString()).build());
}
return CodeBlock.builder()
.add("new Long[]{\n")
.indent()
.add(CodeBlock.join(blocks, ",\n"))
.add("\n}")
.build();
}
private MethodSpec makeGetter(String methodName, String field, TypeName type) {
return MethodSpec.methodBuilder(methodName)
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(type)
.addStatement("return $L", field)
.build();
}
private MethodSpec makeConstructor() {
return MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addException(Exception.class)
.addStatement(
"super($S, $S)",
currentProgram.getLanguage().getLanguageID().toString(),
currentProgram.getCompilerSpec().getCompilerSpecID().toString()
)
.build();
}
private MethodSpec makeSetupMemory() {
MemoryBlock codeBlock = getFunctionBlock();
MemoryBlock dataBlock = getDataBlock();
MethodSpec.Builder builder = MethodSpec.methodBuilder("setupMemory")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.addStatement(
CREATE_MEMORY,
codeBlock.getName(),
codeBlock.getStart().toString(),
codeBlock.getSize())
.addStatement(
CREATE_MEMORY,
dataBlock.getName(),
dataBlock.getStart().toString(),
dataBlock.getSize());
if (GnuUtils.hasFunctionDescriptors(currentProgram)) {
MemoryBlock block = getFunctionDescriptorBlock();
builder = builder.addStatement(
CREATE_MEMORY,
block.getName(),
block.getStart().toString(),
block.getSize()
);
}
return builder.build();
}
private MemoryBlock getFunctionBlock() {
for (Function function : functionSet) {
return getMemoryBlock(function.getEntryPoint());
}
return null;
}
private MemoryBlock getDataBlock() {
for (TypeInfo type : tiMap.keySet()) {
return getMemoryBlock(type.getAddress());
}
return null;
}
private void populateMaps() throws Exception {
ProgramClassTypeInfoManager manager = CppClassAnalyzerUtils.getManager(currentProgram);
int pointerSize = currentProgram.getDefaultPointerSize();
SymbolTable table = currentProgram.getSymbolTable();
Listing listing = currentProgram.getListing();
Memory mem = currentProgram.getMemory();
for (Symbol symbol : table.getSymbols(TypeInfo.SYMBOL_NAME)) {
TypeInfo type = null;
try {
type = manager.getTypeInfo(symbol.getAddress());
} catch (UnresolvedClassTypeInfoException e) {
continue;
}
if (type == null) {
println("TypeInfo at "+symbol.getAddress().toString()+" is null");
continue;
}
DataType dt = type.getDataType();
Data data = DataUtilities.createData(
currentProgram, type.getAddress(), dt,
dt.getLength(), false, CLEAR_ALL_CONFLICT_DATA);
if (data.isStructure() && ((Structure) data.getDataType()).hasFlexibleArrayComponent()) {
MemoryBufferImpl buf = new MemoryBufferImpl(
mem, data.getAddress());
Data flexData = listing.getDataAt(data.getAddress().add(data.getLength()));
int length = data.getLength();
if (flexData != null) {
length += flexData.getLength();
}
byte[] bytes = new byte[length];
buf.getBytes(bytes, 0);
tiMap.put(type, bytes);
} else {
tiMap.put(type, data.getBytes());
}
Address nameAddress = getAbsoluteAddress(
currentProgram, symbol.getAddress().add(pointerSize));
nameMap.put(type.getTypeName(), nameAddress);
if (type instanceof ClassTypeInfo) {
ClassTypeInfo classType = (ClassTypeInfo) type;
GnuVtable vtable = (GnuVtable) classType.getVtable();
if (!Vtable.isValid(vtable)) {
continue;
}
MemoryBufferImpl buf = new MemoryBufferImpl(
mem, vtable.getAddress());
byte[] bytes = new byte[vtable.getLength()];
buf.getBytes(bytes, 0);
vtableMap.put(vtable, bytes);
for (Function[] functionTable : vtable.getFunctionTables()) {
for (Function function : functionTable) {
if (function != null) {
functionSet.add(function);
}
}
}
}
}
for (Symbol symbol : table.getSymbols(VttModel.SYMBOL_NAME)) {
VttModel vtt = new VttModel(currentProgram, symbol.getAddress());
if (!vtt.isValid()) {
printerr(symbol.getParentNamespace().getName()+"'s vtt is invalid");
continue;
}
DataType dt = vtt.getDataType();
Data data = DataUtilities.createData(
currentProgram, vtt.getAddress(), dt,
dt.getLength(), false, CLEAR_ALL_CONFLICT_DATA);
vttMap.put(vtt, data.getBytes());
}
}
public static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for(byte b: a)
sb.append(String.format("%02x", b));
return sb.toString();
}
}
| 5,805 |
406 | <filename>src/main/java/org/broad/igv/sam/reader/SamIndexer.java
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.broad.igv.sam.reader;
import org.broad.igv.ui.util.IndexCreatorDialog;
import javax.swing.*;
import java.io.File;
/**
* Created by IntelliJ IDEA.
* @author jrobinso
* @since: Dec 6, 2009
*/
public class SamIndexer extends AlignmentIndexer {
final static int FLAG_COL = 1;
final static int READ_UNMAPPED_FLAG = 0x4;
public SamIndexer(File samFile, JProgressBar progressBar, IndexCreatorDialog.SamIndexWorker worker) {
super(samFile, progressBar, worker);
}
int getAlignmentStart(String[] fields) throws NumberFormatException {
// Get alignmetn start and verify file is sorted.
int alignmentStart = Integer.parseInt(fields[3].trim()) - 1;
return alignmentStart;
}
int getAlignmentLength(String[] fields) throws NumberFormatException {
String cigarString = fields[5];
return SamUtils.getPaddedReferenceLength(cigarString);
}
String getChromosome(String[] fields) {
return fields[2];
}
@Override
boolean isMapped(String[] fields) {
int flags = Integer.parseInt(fields[FLAG_COL]);
return (flags & READ_UNMAPPED_FLAG) == 0;
}
}
| 762 |
3,348 | /**
* 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.heron.common.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.Duration;
import org.junit.Assert;
import org.junit.Test;
import org.apache.commons.io.IOUtils;
import org.apache.heron.common.basics.ByteAmount;
public class SystemConfigTest {
private static final String RESOURCE_LOC = "/heron/common/tests/resources/sysconfig.yaml";
@Test
public void testReadConfig() throws IOException {
InputStream inputStream = getClass().getResourceAsStream(RESOURCE_LOC);
if (inputStream == null) {
throw new RuntimeException("Sample output file not found");
}
File file = File.createTempFile("system_temp", "yaml");
file.deleteOnExit();
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
outputStream.close();
SystemConfig systemConfig = SystemConfig.newBuilder(true)
.putAll(file.getAbsolutePath(), true)
.build();
Assert.assertEquals("log-files", systemConfig.getHeronLoggingDirectory());
Assert.assertEquals(ByteAmount.fromMegabytes(100), systemConfig.getHeronLoggingMaximumSize());
Assert.assertEquals(5, systemConfig.getHeronLoggingMaximumFiles());
Assert.assertEquals(Duration.ofSeconds(60), systemConfig.getHeronMetricsExportInterval());
}
}
| 664 |
1,443 | {
"copyright": "<NAME>",
"url": "http://rezartisan.com",
"email": "<EMAIL>",
"format": "html",
"gravatar": true
}
| 53 |
839 | <reponame>kimjand/cxf<filename>rt/bindings/soap/src/test/java/org/apache/cxf/binding/soap/RPCOutInterceptorTest.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.cxf.binding.soap;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.cxf.binding.soap.interceptor.RPCOutInterceptor;
import org.apache.cxf.jaxb.JAXBDataBinding;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.service.model.ServiceInfo;
import org.apache.cxf.staxutils.DepthXMLStreamReader;
import org.apache.cxf.staxutils.StaxUtils;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class RPCOutInterceptorTest extends TestBase {
private static final String TNS = "http://apache.org/hello_world_rpclit";
private static final String OPNAME = "sendReceiveData";
private ByteArrayOutputStream baos = new ByteArrayOutputStream(64 * 1024);
private IMocksControl control = EasyMock.createNiceControl();
@Before
public void setUp() throws Exception {
super.setUp();
ServiceInfo si = getMockedServiceModel(this.getClass()
.getResource("/wsdl_soap/hello_world_rpc_lit.wsdl")
.toString());
BindingInfo bi = si.getBinding(new QName(TNS, "Greeter_SOAPBinding_RPCLit"));
BindingOperationInfo boi = bi.getOperation(new QName(TNS, OPNAME));
boi.getOperationInfo().getOutput().getMessagePartByIndex(0).setIndex(0);
soapMessage.getExchange().put(BindingOperationInfo.class, boi);
control.reset();
Service service = control.createMock(Service.class);
EasyMock.expect(service.isEmpty()).andReturn(true).anyTimes();
JAXBDataBinding dataBinding = new JAXBDataBinding(MyComplexStruct.class);
service.getDataBinding();
EasyMock.expectLastCall().andReturn(dataBinding).anyTimes();
service.getServiceInfos();
List<ServiceInfo> list = Arrays.asList(si);
EasyMock.expectLastCall().andReturn(list).anyTimes();
soapMessage.getExchange().put(Service.class, service);
soapMessage.getExchange().put(Message.SCHEMA_VALIDATION_ENABLED, Boolean.FALSE);
control.replay();
MyComplexStruct mcs = new MyComplexStruct();
mcs.setElem1("elem1");
mcs.setElem2("elem2");
mcs.setElem3(45);
MessageContentsList param = new MessageContentsList();
param.add(mcs);
soapMessage.setContent(List.class, param);
}
@After
public void tearDown() throws Exception {
baos.close();
}
@Test
public void testWriteOutbound() throws Exception {
RPCOutInterceptor interceptor = new RPCOutInterceptor();
soapMessage.setContent(XMLStreamWriter.class, XMLOutputFactory.newInstance().createXMLStreamWriter(
baos));
soapMessage.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
interceptor.handleMessage(soapMessage);
assertNull(soapMessage.getContent(Exception.class));
soapMessage.getContent(XMLStreamWriter.class).flush();
baos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr = StaxUtils.createXMLStreamReader(bais);
DepthXMLStreamReader reader = new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit", "sendReceiveData"), reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName(null, "in"), reader.getName());
StaxUtils.toNextText(reader);
assertEquals("elem1", reader.getText());
}
@Test
public void testWriteInbound() throws Exception {
RPCOutInterceptor interceptor = new RPCOutInterceptor();
soapMessage.setContent(XMLStreamWriter.class, XMLOutputFactory.newInstance().createXMLStreamWriter(
baos));
interceptor.handleMessage(soapMessage);
assertNull(soapMessage.getContent(Exception.class));
soapMessage.getContent(XMLStreamWriter.class).flush();
baos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr = StaxUtils.createXMLStreamReader(bais);
DepthXMLStreamReader reader = new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit", "sendReceiveDataResponse"), reader
.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName(null, "out"), reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit/types", "elem1"), reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextText(reader);
assertEquals("elem1", reader.getText());
}
} | 2,408 |
3,269 | <gh_stars>1000+
# Time: O(n)
# Space: O(1)
import collections
import string
class Solution(object):
def minDeletions(self, s):
"""
:type s: str
:rtype: int
"""
count = collections.Counter(s)
result = 0
lookup = set()
for c in string.ascii_lowercase:
for i in reversed(xrange(1, count[c]+1)):
if i not in lookup:
lookup.add(i)
break
result += 1
return result
| 283 |
721 | <gh_stars>100-1000
/*
* Copyright 2011, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib.Code.Format;
import org.jf.dexlib.Code.Instruction;
import org.jf.dexlib.Code.InstructionWithReference;
import org.jf.dexlib.Code.Opcode;
import org.jf.dexlib.Code.SingleRegisterInstruction;
import org.jf.dexlib.DexFile;
import org.jf.dexlib.Item;
import org.jf.dexlib.TypeIdItem;
import org.jf.dexlib.Util.AnnotatedOutput;
import org.jf.dexlib.Util.NumberUtils;
public class Instruction41c extends InstructionWithJumboReference implements SingleRegisterInstruction {
public static final InstructionFactory Factory = new Factory();
private short regA;
public Instruction41c(Opcode opcode, int regA, Item referencedItem) {
super(opcode, referencedItem);
if (regA >= 1 << 16) {
throw new RuntimeException("The register number must be less than v65536");
}
if (opcode == Opcode.NEW_INSTANCE_JUMBO) {
assert referencedItem instanceof TypeIdItem;
if (((TypeIdItem)referencedItem).getTypeDescriptor().charAt(0) != 'L') {
throw new RuntimeException("Only class references can be used with the new-instance/jumbo opcode");
}
}
this.regA = (short)regA;
}
private Instruction41c(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) {
super(dexFile, opcode, buffer, bufferIndex);
if (opcode == Opcode.NEW_INSTANCE_JUMBO &&
((TypeIdItem)this.getReferencedItem()).getTypeDescriptor().charAt(0) != 'L') {
throw new RuntimeException("Only class references can be used with the new-instance/jumbo opcode");
}
this.regA = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 6);
}
protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) {
out.writeByte(0xFF);
out.writeByte(opcode.value);
out.writeInt(getReferencedItem().getIndex());
out.writeShort(getRegisterA());
}
public Format getFormat() {
return Format.Format41c;
}
public int getRegisterA() {
return regA & 0xFFFF;
}
private static class Factory implements InstructionFactory {
public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) {
return new Instruction41c(dexFile, opcode, buffer, bufferIndex);
}
}
}
| 1,365 |
435 | <filename>MediumProject/Example/src3/subsrc2/f4.c
#include "f4.h"
int f4(int a, int b) { return a; } | 45 |
1,454 | <filename>test/WebJobs.Script.Tests.Integration/TestScripts/OutOfDateExtension/bin/extensions.json
{
"extensions":[
{ "name": "AzureStorage", "typeName":"Microsoft.Azure.WebJobs.Extensions.Storage.AzureStorageWebJobsStartup, Microsoft.Azure.WebJobs.Extensions.Storage, Version=3.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"},
{ "name": "ServiceBus", "typeName":"Microsoft.Azure.WebJobs.ServiceBus.ServiceBusWebJobsStartup, Microsoft.Azure.WebJobs.ServiceBus, Version=4.2.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"},
{ "name": "DurableTask", "typeName":"Microsoft.Azure.WebJobs.Extensions.DurableTask.DurableTaskWebJobsStartup, Microsoft.Azure.WebJobs.Extensions.DurableTask, Version=2.0.0.0, Culture=neutral, PublicKeyToken=014045d636e89289"}
]
} | 294 |
348 | {"nom":"Saint-Jean-du-Corail-des-Bois","dpt":"Manche","inscrits":64,"abs":12,"votants":52,"blancs":8,"nuls":2,"exp":42,"res":[{"panneau":"1","voix":22},{"panneau":"2","voix":20}]} | 77 |
834 | #include <stdlib.h>
#include <setjmp.h>
#include <math.h>
#include <string.h>
#include "vm.h"
#include "gc.h"
#include "object.h"
#include "lib.h"
#include "string.h"
#include "exception.h"
static js_instruction_t insns[] = {
{ "undefined", OPERAND_NONE },
{ "ret", OPERAND_NONE },
{ "pushnum", OPERAND_NUMBER },
{ "add", OPERAND_NONE },
{ "pushglobal", OPERAND_STRING },
{ "pushstr", OPERAND_STRING },
{ "methcall", OPERAND_UINT32 },
{ "setvar", OPERAND_UINT32_UINT32 },
{ "pushvar", OPERAND_UINT32_UINT32 },
{ "true", OPERAND_NONE },
{ "false", OPERAND_NONE },
{ "null", OPERAND_NONE },
{ "jmp", OPERAND_UINT32 },
{ "jit", OPERAND_UINT32 },
{ "jif", OPERAND_UINT32 },
{ "sub", OPERAND_NONE },
{ "mul", OPERAND_NONE },
{ "div", OPERAND_NONE },
{ "setglobal", OPERAND_STRING },
{ "close", OPERAND_UINT32 },
{ "call", OPERAND_UINT32 },
{ "setcallee", OPERAND_UINT32 },
{ "setarg", OPERAND_UINT32_UINT32 },
{ "lt", OPERAND_NONE },
{ "lte", OPERAND_NONE },
{ "gt", OPERAND_NONE },
{ "gte", OPERAND_NONE },
{ "pop", OPERAND_NONE },
{ "array", OPERAND_UINT32 },
{ "newcall", OPERAND_UINT32 },
{ "throw", OPERAND_NONE },
{ "member", OPERAND_STRING },
{ "dup", OPERAND_NONE },
{ "this", OPERAND_NONE },
{ "setprop", OPERAND_STRING },
{ "tst", OPERAND_NONE },
{ "tld", OPERAND_NONE },
{ "index", OPERAND_NONE },
{ "setindex", OPERAND_NONE },
{ "object", OPERAND_UINT32 },
{ "typeof", OPERAND_NONE },
{ "seq", OPERAND_NONE },
{ "typeofg", OPERAND_STRING },
{ "sal", OPERAND_NONE },
{ "or", OPERAND_NONE },
{ "xor", OPERAND_NONE },
{ "and", OPERAND_NONE },
{ "slr", OPERAND_NONE },
{ "not", OPERAND_NONE },
{ "bitnot", OPERAND_NONE },
{ "line", OPERAND_UINT32 },
{ "debugger", OPERAND_NONE },
{ "instanceof", OPERAND_NONE },
{ "negate", OPERAND_NONE },
{ "try", OPERAND_UINT32_UINT32 },
{ "poptry", OPERAND_NONE },
{ "catch", OPERAND_UINT32 },
{ "catchg", OPERAND_STRING },
{ "popcatch", OPERAND_NONE },
{ "finally", OPERAND_NONE },
{ "popfinally", OPERAND_NONE },
{ "closenamed", OPERAND_UINT32_STRING },
{ "delete", OPERAND_NONE },
{ "mod", OPERAND_NONE },
{ "arguments", OPERAND_UINT32 },
{ "dupn", OPERAND_UINT32 },
{ "enum", OPERAND_NONE },
{ "enumnext", OPERAND_NONE },
{ "jend", OPERAND_UINT32 },
{ "enumpop", OPERAND_NONE },
{ "eq", OPERAND_NONE },
};
js_instruction_t* js_instruction(uint32_t opcode)
{
if(opcode >= sizeof(insns) / sizeof(insns[0])) {
return NULL;
}
return &insns[opcode];
}
static void* stack_limit;
void js_vm_set_stack_limit(void* stack_limit_)
{
stack_limit = stack_limit_;
}
js_vm_t* js_vm_new()
{
js_vm_t* vm = js_alloc(sizeof(js_vm_t));
// this proto/constructor is fixed up later by js_lib_initialize
vm->global_scope = js_scope_make_global(vm, js_value_make_object(js_value_undefined(), js_value_undefined()));
js_object_put(vm->global_scope->global_object, js_cstring("global"), vm->global_scope->global_object);
js_lib_initialize(vm);
return vm;
}
static int comparison_oper(VAL left, VAL right)
{
double l, r;
if(js_value_get_type(left) == JS_T_STRING && js_value_get_type(right) == JS_T_STRING) {
return js_string_cmp(&js_value_get_pointer(left)->string, &js_value_get_pointer(right)->string);
} else {
l = js_value_get_double(js_to_number(left));
r = js_value_get_double(js_to_number(right));
if(l < r) {
return -1;
} else if(l > r) {
return 1;
} else {
return 0;
}
}
}
/* @TODO: bounds checking here */
#define NEXT_UINT32() (L->INSNS[L->IP++])
#define NEXT_DOUBLE() (L->IP += 2, *(double*)&L->INSNS[L->IP - 2])
#define NEXT_STRING() (L->image->strings[NEXT_UINT32()])
/*static int popped_under_zero_hack() {
js_panic("popped SP < 0");
}*/
#define PUSH(v) do { \
if(L->SP >= L->SMAX) { \
L->SMAX *= 2; \
if(L->STACK_CSTACK) L->STACK = memcpy(js_alloc(L->SMAX / 2 * sizeof(VAL)), L->STACK, L->SMAX / 2 * sizeof(VAL)); \
L->STACK = js_realloc(L->STACK, sizeof(VAL) * L->SMAX); \
} \
L->STACK[L->SP++] = (v); \
} while(false)
#define POP() (L->STACK[--L->SP/* < 0 ? popped_under_zero_hack() : L->SP*/])
#define PEEK() (L->STACK[L->SP - 1])
static uint32_t global_instruction_counter = 0;
struct exception_frame {
uint32_t catch;
uint32_t finally;
struct exception_frame* prev;
};
struct enum_frame {
js_string_t** keys;
uint32_t count;
uint32_t index;
struct enum_frame* prev;
};
struct vm_locals {
js_vm_t* vm;
js_image_t* image;
uint32_t section;
js_scope_t* scope;
VAL this;
uint32_t argc;
VAL* argv;
uint32_t IP;
uint32_t* INSNS;
int32_t SP;
int32_t SMAX;
bool STACK_CSTACK;
VAL* STACK;
VAL temp_slot;
uint32_t current_line;
bool exception_thrown;
bool return_after_finally;
bool will_return;
VAL return_val;
VAL return_after_finally_val;
VAL exception;
struct exception_frame* exception_stack;
js_exception_handler_t handler;
struct enum_frame* enum_stack;
};
static VAL vm_exec(struct vm_locals* L);
int kprintf();
VAL js_vm_exec(js_vm_t* vm, js_image_t* image, uint32_t section, js_scope_t* scope, VAL this, uint32_t argc, VAL* argv)
{
VAL fast_stack[32];
struct vm_locals L;
L.vm = vm;
L.image = image;
L.section = section;
L.scope = scope;
L.this = this;
L.argc = argc;
L.argv = argv;
L.IP = 0;
L.INSNS = image->sections[section].instructions;
L.SP = 0;
L.SMAX = sizeof(fast_stack) / sizeof(VAL);
L.STACK_CSTACK = true;
L.STACK = fast_stack;
L.temp_slot = js_value_undefined();
L.current_line = 1;
L.exception_stack = NULL;
L.exception_thrown = false;
L.return_after_finally = false;
L.will_return = false;
L.return_val = js_value_undefined();
L.return_after_finally_val = js_value_undefined();
L.exception = js_value_undefined();
L.enum_stack = NULL;
if((intptr_t)&L < (intptr_t)stack_limit) {
js_throw_error(vm->lib.RangeError, "Stack overflow");
}
L.handler.previous = js_current_exception_handler();
js_set_exception_handler(&L.handler);
VAL retn = vm_exec(&L);
js_set_exception_handler(L.handler.previous);
return retn;
}
static VAL vm_exec(struct vm_locals* L)
{
uint32_t opcode;
if(setjmp(L->handler.env)) {
// exception was thrown
L->exception_thrown = true;
L->exception = L->handler.exception;
if(js_value_is_object(L->handler.exception)) {
js_string_t* trace = js_value_get_pointer(L->handler.exception)->object.stack_trace;
trace = js_string_concat(trace, js_string_format("\n at %s:%d", L->image->strings[L->image->name]->buff, L->current_line));
js_value_get_pointer(L->handler.exception)->object.stack_trace = trace;
}
if(L->exception_stack) {
if(L->exception_stack->catch) {
L->IP = L->exception_stack->catch;
} else {
L->IP = L->exception_stack->finally;
}
} else {
js_set_exception_handler(L->handler.previous);
js_throw(L->handler.exception);
}
}
while(1) {
if(++global_instruction_counter >= VM_CYCLES_PER_COLLECTION) {
global_instruction_counter = 0;
js_gc_run();
}
if(L->will_return) {
return L->return_val;
}
opcode = NEXT_UINT32();
switch(opcode) {
case JS_OP_UNDEFINED: {
PUSH(js_value_undefined());
break;
}
case JS_OP_RET: {
if(L->exception_stack) {
L->return_after_finally_val = POP();
L->return_after_finally = true;
L->IP = L->exception_stack->finally;
} else {
return POP();
}
break;
}
case JS_OP_PUSHNUM: {
double d = NEXT_DOUBLE();
PUSH(js_value_make_double(d));
break;
}
case JS_OP_ADD: {
VAL r = js_to_primitive(POP());
VAL l = js_to_primitive(POP());
if(js_value_get_type(l) == JS_T_STRING || js_value_get_type(r) == JS_T_STRING) {
js_string_t* sl = &js_value_get_pointer(js_to_string(l))->string;
js_string_t* sr = &js_value_get_pointer(js_to_string(r))->string;
PUSH(js_value_wrap_string(js_string_concat(sl, sr)));
} else {
PUSH(js_value_make_double(js_value_get_double(js_to_number(l)) + js_value_get_double(js_to_number(r))));
}
break;
}
case JS_OP_PUSHGLOBAL: {
js_string_t* var = NEXT_STRING();
PUSH(js_scope_get_global_var(L->scope, var));
break;
}
case JS_OP_PUSHSTR: {
js_string_t* str = NEXT_STRING();
PUSH(js_value_wrap_string(str));
break;
}
case JS_OP_METHCALL: {
uint32_t i, argc = NEXT_UINT32();
VAL argv[argc];
VAL method, obj, fn;
for(i = 0; i < argc; i++) {
argv[argc - i - 1] = POP();
}
method = POP();
obj = POP();
if(js_value_is_primitive(obj)) {
obj = js_to_object(L->vm, obj);
}
fn = js_object_get(obj, js_to_js_string_t(method));
if(js_value_get_type(fn) != JS_T_FUNCTION) {
js_throw_error(L->vm->lib.TypeError, "called non callable");
}
PUSH(js_call(fn, obj, argc, argv));
break;
}
case JS_OP_SETVAR: {
uint32_t idx = NEXT_UINT32();
uint32_t sc = NEXT_UINT32();
js_scope_set_var(L->scope, idx, sc, PEEK());
break;
}
case JS_OP_PUSHVAR: {
uint32_t idx = NEXT_UINT32();
uint32_t sc = NEXT_UINT32();
PUSH(js_scope_get_var(L->scope, idx, sc));
break;
}
case JS_OP_TRUE: {
PUSH(js_value_true());
break;
}
case JS_OP_FALSE: {
PUSH(js_value_false());
break;
}
case JS_OP_NULL: {
PUSH(js_value_null());
break;
}
case JS_OP_JMP: {
uint32_t next = NEXT_UINT32();
L->IP = next;
break;
}
case JS_OP_JIT: {
uint32_t next = NEXT_UINT32();
if(js_value_is_truthy(POP())) {
L->IP = next;
}
break;
}
case JS_OP_JIF: {
uint32_t next = NEXT_UINT32();
if(!js_value_is_truthy(POP())) {
L->IP = next;
}
break;
}
case JS_OP_SUB: {
VAL r = js_to_number(POP());
VAL l = js_to_number(POP());
PUSH(js_value_make_double(js_value_get_double(js_to_number(l)) - js_value_get_double(js_to_number(r))));
break;
}
case JS_OP_MUL: {
VAL r = js_to_number(POP());
VAL l = js_to_number(POP());
PUSH(js_value_make_double(js_value_get_double(js_to_number(l)) * js_value_get_double(js_to_number(r))));
break;
}
case JS_OP_DIV: {
VAL r = js_to_number(POP());
VAL l = js_to_number(POP());
PUSH(js_value_make_double(js_value_get_double(js_to_number(l)) / js_value_get_double(js_to_number(r))));
break;
}
case JS_OP_SETGLOBAL: {
js_string_t* str = NEXT_STRING();
js_scope_set_global_var(L->scope, str, PEEK());
break;
}
case JS_OP_CLOSE: {
uint32_t sect = NEXT_UINT32();
PUSH(js_value_make_function(L->vm, L->image, sect, L->scope));
break;
}
case JS_OP_CALL: {
uint32_t i, argc = NEXT_UINT32();
VAL argv[argc];
VAL fn;
for(i = 0; i < argc; i++) {
argv[argc - i - 1] = POP();
}
fn = POP();
if(js_value_get_type(fn) != JS_T_FUNCTION) {
js_throw_error(L->vm->lib.TypeError, "called non callable");
}
PUSH(js_call(fn, L->vm->global_scope->global_object, argc, argv));
break;
}
case JS_OP_SETCALLEE: {
uint32_t idx = NEXT_UINT32();
if(L->scope->parent) { /* not global scope... */
js_scope_set_var(L->scope, idx, 0, L->scope->locals.callee);
}
break;
}
case JS_OP_SETARG: {
uint32_t var = NEXT_UINT32();
uint32_t arg = NEXT_UINT32();
if(L->scope->parent) { /* not global scope... */
if(arg >= L->argc) {
js_scope_set_var(L->scope, var, 0, js_value_undefined());
} else {
js_scope_set_var(L->scope, var, 0, L->argv[arg]);
}
}
break;
}
case JS_OP_LT: {
VAL right = POP();
VAL left = POP();
PUSH(js_value_make_boolean(comparison_oper(left, right) < 0));
break;
}
case JS_OP_LTE: {
VAL right = POP();
VAL left = POP();
PUSH(js_value_make_boolean(comparison_oper(left, right) <= 0));
break;
}
case JS_OP_GT: {
VAL right = POP();
VAL left = POP();
PUSH(js_value_make_boolean(comparison_oper(left, right) > 0));
break;
}
case JS_OP_GTE: {
VAL right = POP();
VAL left = POP();
PUSH(js_value_make_boolean(comparison_oper(left, right) >= 0));
break;
}
case JS_OP_POP: {
(void)POP();
break;
}
case JS_OP_ARRAY: {
uint32_t i, count = NEXT_UINT32();
VAL items[count];
for(i = 0; i < count; i++) {
items[count - i - 1] = POP();
}
PUSH(js_make_array(L->vm, count, items));
break;
}
case JS_OP_NEWCALL: {
uint32_t i, argc = NEXT_UINT32();
VAL argv[argc];
VAL fn;
for(i = 0; i < argc; i++) {
argv[argc - i - 1] = POP();
}
fn = POP();
if(js_value_get_type(fn) != JS_T_FUNCTION) {
js_throw_error(L->vm->lib.TypeError, "constructed non callable");
}
PUSH(js_construct(fn, argc, argv));
break;
}
case JS_OP_THROW: {
js_throw(POP());
break;
};
case JS_OP_MEMBER: {
js_string_t* member = NEXT_STRING();
VAL obj = POP();
if(js_value_is_primitive(obj)) {
obj = js_to_object(L->vm, obj);
}
PUSH(js_object_get(obj, member));
break;
}
case JS_OP_DUP: {
VAL v = PEEK();
PUSH(v);
break;
}
case JS_OP_THIS: {
PUSH(L->this);
break;
}
case JS_OP_SETPROP: {
VAL val = POP();
VAL obj = POP();
if(js_value_is_primitive(obj)) {
obj = js_to_object(L->vm, obj);
}
js_object_put(obj, NEXT_STRING(), val);
PUSH(val);
break;
}
case JS_OP_TST: {
L->temp_slot = POP();
break;
}
case JS_OP_TLD: {
PUSH(L->temp_slot);
break;
}
case JS_OP_INDEX: {
VAL index = js_to_string(POP());
VAL object = POP();
if(js_value_is_primitive(object)) {
object = js_to_object(L->vm, object);
}
PUSH(js_object_get(object, &js_value_get_pointer(index)->string));
break;
}
case JS_OP_SETINDEX: {
VAL val = POP();
VAL idx = js_to_string(POP());
VAL obj = POP();
if(js_value_is_primitive(obj)) {
obj = js_to_object(L->vm, obj);
}
js_object_put(obj, js_to_js_string_t(idx), val);
PUSH(val);
break;
}
case JS_OP_OBJECT: {
uint32_t i, items = NEXT_UINT32();
VAL obj = js_make_object(L->vm);
for(i = 0; i < items; i++) {
VAL val = POP();
VAL key = js_to_string(POP());
js_object_put(obj, js_to_js_string_t(key), val);
}
PUSH(obj);
break;
}
case JS_OP_TYPEOF: {
VAL val = POP();
PUSH(js_typeof(val));
break;
}
case JS_OP_SEQ: {
VAL r = POP();
VAL l = POP();
PUSH(js_value_make_boolean(js_seq(l, r)));
break;
}
case JS_OP_TYPEOFG: {
js_string_t* var = NEXT_STRING();
if(js_scope_global_var_exists(L->scope, var)) {
PUSH(js_typeof(js_scope_get_global_var(L->scope, var)));
} else {
PUSH(js_value_make_cstring("undefined"));
}
break;
}
case JS_OP_SAL: {
uint32_t r = js_to_uint32(POP());
uint32_t l = js_to_uint32(POP());
PUSH(js_value_make_double(l << r));
break;
}
case JS_OP_OR: {
uint32_t r = js_to_uint32(POP());
uint32_t l = js_to_uint32(POP());
PUSH(js_value_make_double(l | r));
break;
}
case JS_OP_XOR: {
uint32_t r = js_to_uint32(POP());
uint32_t l = js_to_uint32(POP());
PUSH(js_value_make_double(l ^ r));
break;
}
case JS_OP_AND: {
uint32_t r = js_to_uint32(POP());
uint32_t l = js_to_uint32(POP());
PUSH(js_value_make_double(l & r));
break;
}
case JS_OP_SLR: {
uint32_t r = js_to_uint32(POP());
uint32_t l = js_to_uint32(POP());
PUSH(js_value_make_double(l >> r));
break;
}
case JS_OP_NOT: {
VAL v = POP();
PUSH(js_value_make_boolean(!js_value_is_truthy(v)));
break;
}
case JS_OP_BITNOT: {
uint32_t x = js_to_uint32(POP());
PUSH(js_value_make_double(~x));
break;
}
case JS_OP_LINE: {
L->current_line = NEXT_UINT32();
break;
}
case JS_OP_DEBUGGER: {
js_panic("DEBUGGER");
break;
}
case JS_OP_INSTANCEOF: {
VAL class = POP();
VAL obj = POP();
if(js_value_get_type(class) != JS_T_FUNCTION) {
js_throw_error(L->vm->lib.TypeError, "expected a function in instanceof check");
}
if(js_value_is_primitive(obj)) {
PUSH(js_value_false());
} else {
PUSH(js_value_make_boolean(js_value_get_pointer(js_value_get_pointer(obj)->object.class) == js_value_get_pointer(class)));
}
break;
}
case JS_OP_NEGATE: {
double d = js_value_get_double(js_to_number(POP()));
PUSH(js_value_make_double(-d));
break;
}
case JS_OP_TRY: {
uint32_t catch = NEXT_UINT32();
uint32_t finally = NEXT_UINT32();
struct exception_frame* frame = js_alloc(sizeof(struct exception_frame));
frame->catch = catch;
frame->finally = finally;
frame->prev = L->exception_stack;
L->exception_stack = frame;
break;
}
case JS_OP_POPTRY: {
struct exception_frame* frame = L->exception_stack;
L->IP = frame->finally;
L->exception_stack = frame->prev;
break;
}
case JS_OP_CATCH: {
L->exception_stack->catch = 0;
js_scope_set_var(L->scope, NEXT_UINT32(), 0, L->exception);
L->exception = js_value_undefined();
L->exception_thrown = false;
break;
}
case JS_OP_CATCHG: {
L->exception_stack->catch = 0;
js_scope_set_global_var(L->scope, NEXT_STRING(), L->exception);
L->exception = js_value_undefined();
L->exception_thrown = false;
break;
}
case JS_OP_POPCATCH: {
L->IP = L->exception_stack->finally;
break;
}
case JS_OP_FINALLY: {
break;
}
case JS_OP_POPFINALLY: {
if(L->exception_thrown) {
js_throw(L->exception);
}
if(L->return_after_finally) {
L->return_after_finally = false;
L->will_return = true;
L->return_val = L->return_after_finally_val;
L->return_after_finally_val = js_value_undefined();
}
break;
}
case JS_OP_CLOSENAMED: {
uint32_t sect = NEXT_UINT32();
js_string_t* name = NEXT_STRING();
VAL function = js_value_make_function(L->vm, L->image, sect, L->scope);
((js_function_t*)js_value_get_pointer(function))->name = name;
PUSH(function);
break;
}
case JS_OP_DELETE: {
VAL index = js_to_string(POP());
VAL object = POP();
if(js_value_is_primitive(object)) {
object = js_to_object(L->vm, object);
}
PUSH(js_value_make_boolean(js_object_delete(object, js_to_js_string_t(index))));
break;
}
case JS_OP_MOD: {
VAL r = js_to_number(POP());
VAL l = js_to_number(POP());
PUSH(js_value_make_double(fmod(js_value_get_double(js_to_number(l)), js_value_get_double(js_to_number(r)))));
break;
}
case JS_OP_ARGUMENTS: {
uint32_t idx = NEXT_UINT32();
VAL arguments = js_make_array(L->vm, L->argc, L->argv);
js_object_put(arguments, js_cstring("callee"), L->scope->locals.callee);
js_scope_set_var(L->scope, idx, 0, arguments);
break;
}
case JS_OP_DUPN: {
uint32_t n = NEXT_UINT32();
VAL dup[n];
uint32_t i;
for(i = 0; i < n; i++) {
dup[i] = POP();
}
for(i = n; i > 0; i--) {
PUSH(dup[i - 1]);
}
for(i = n; i > 0; i--) {
PUSH(dup[i - 1]);
}
break;
}
case JS_OP_ENUM: {
struct enum_frame* frame = js_alloc(sizeof(struct enum_frame));
frame->prev = L->enum_stack;
frame->index = 0;
frame->keys = js_object_keys(js_to_object(L->vm, POP()), &frame->count);
L->enum_stack = frame;
break;
}
case JS_OP_ENUMNEXT: {
PUSH(js_value_wrap_string(L->enum_stack->keys[L->enum_stack->index++]));
break;
}
case JS_OP_JEND: {
uint32_t ip = NEXT_UINT32();
if(L->enum_stack->index == L->enum_stack->count) {
L->IP = ip;
}
break;
}
case JS_OP_ENUMPOP: {
L->enum_stack = L->enum_stack->prev;
break;
}
case JS_OP_EQ: {
VAL r = POP();
VAL l = POP();
PUSH(js_value_make_boolean(js_eq(L->vm, l, r)));
break;
}
default:
/* @TODO proper-ify this */
js_panic("unknown opcode %u\n", opcode);
}
}
}
| 16,903 |
2,174 | package ceui.lisa.standard;
import ceui.lisa.interfaces.ListShow;
import io.reactivex.Observable;
public abstract class Repository<Bean> {
public abstract Observable<ListShow<Bean>> initApi();
}
| 70 |
398 | <filename>credit/src/main/java/de/n26/n26androidsamples/credit/presentation/dashboard/InRepaymentCardViewEntity.java<gh_stars>100-1000
package de.n26.n26androidsamples.credit.presentation.dashboard;
import com.google.auto.value.AutoValue;
import android.support.annotation.NonNull;
@AutoValue
abstract class InRepaymentCardViewEntity {
@NonNull
abstract String id();
@NonNull
abstract String title();
@NonNull
abstract String formattedAmount();
@NonNull
abstract String formattedPaidOutDate();
@NonNull
abstract String formattedTotalRepaid();
@NonNull
abstract String nextPaymentLabel();
@NonNull
abstract String formattedNextPayment();
static Builder builder() {
return new AutoValue_InRepaymentCardViewEntity.Builder();
}
@AutoValue.Builder
interface Builder {
Builder id(String id);
Builder title(String title);
Builder formattedAmount(String formattedAmount);
Builder formattedPaidOutDate(String formattedPaidOutDate);
Builder formattedTotalRepaid(String formattedTotalRepaid);
Builder nextPaymentLabel(String nextPaymentLabel);
Builder formattedNextPayment(String formattedNextPayment);
InRepaymentCardViewEntity build();
}
} | 434 |
435 | <reponame>amaajemyfren/data<filename>pycon-ar-2016/videos/pyconar-2016-desempolvando-mi-vieja-raspberrypi.json<gh_stars>100-1000
{
"copyright_text": "Standard YouTube License",
"description": "PyconAR 2016 - Bah\u00eda Blanca\n\nDesempolvando mi vieja raspberryPi por Diego Ramirez\n\nAudience level: Principiante\n\nDescripci\u00f3n\n\nMuchos habremos comprado una raspberry Pi y la terminamos guardando en un caj\u00f3n! El ecosistema de esta linda amiguita ha evolucionado enormemente y le podemos sacar el jugo, con el uso de 2 o tres modulos geniales para hacer IOT, robotica y domotica.\n\nResumen\n\nVamos a explorar un poco como, desde que yo empece mi proyecto de rob\u00f3tica y tenia que implementar todo desde 0, al estado del ecosistema actual de raspberryPi y python. Vamos a repasar y ver en Live coding los usos basicos de gpioZero 1.3 y Picamera 1.1 Cerrando con una demo de nuestra mascota \"Tornillo\" un robot casero hecho con una impresora 3d, una raspi con c\u00e1mara y el set de herramientas open source provistas por la comunidad.",
"duration": 3144,
"language": "spa",
"recorded": "2016-11-25",
"related_urls": [],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi/3LQC87utk9I/maxresdefault.jpg",
"title": "Desempolvando mi vieja raspberryPi",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=3LQC87utk9I"
}
]
}
| 574 |
1,350 | <filename>sdk/billing/azure-resourcemanager-billing/src/main/java/com/azure/resourcemanager/billing/implementation/ValidateAddressResponseImpl.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.billing.implementation;
import com.azure.resourcemanager.billing.fluent.models.ValidateAddressResponseInner;
import com.azure.resourcemanager.billing.models.AddressDetails;
import com.azure.resourcemanager.billing.models.AddressValidationStatus;
import com.azure.resourcemanager.billing.models.ValidateAddressResponse;
import java.util.Collections;
import java.util.List;
public final class ValidateAddressResponseImpl implements ValidateAddressResponse {
private ValidateAddressResponseInner innerObject;
private final com.azure.resourcemanager.billing.BillingManager serviceManager;
ValidateAddressResponseImpl(
ValidateAddressResponseInner innerObject, com.azure.resourcemanager.billing.BillingManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public AddressValidationStatus status() {
return this.innerModel().status();
}
public List<AddressDetails> suggestedAddresses() {
List<AddressDetails> inner = this.innerModel().suggestedAddresses();
if (inner != null) {
return Collections.unmodifiableList(inner);
} else {
return Collections.emptyList();
}
}
public String validationMessage() {
return this.innerModel().validationMessage();
}
public ValidateAddressResponseInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.billing.BillingManager manager() {
return this.serviceManager;
}
}
| 597 |
348 | <gh_stars>100-1000
{"nom":"Montaigut-le-Blanc","circ":"3ème circonscription","dpt":"Puy-de-Dôme","inscrits":665,"abs":382,"votants":283,"blancs":39,"nuls":13,"exp":231,"res":[{"nuance":"MDM","nom":"<NAME>","voix":132},{"nuance":"UDI","nom":"<NAME>","voix":99}]} | 111 |
663 | <filename>hazelcast/tests/test_check.py<gh_stars>100-1000
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
from .common import INSTANCE_MC_PYTHON
from .utils import assert_service_checks_ok
pytestmark = [pytest.mark.usefixtures('dd_environment')]
def test(aggregator, dd_run_check, hazelcast_check):
check = hazelcast_check(INSTANCE_MC_PYTHON)
dd_run_check(check)
assert_service_checks_ok(aggregator)
aggregator.assert_all_metrics_covered()
| 199 |
432 | <gh_stars>100-1000
/*
* Copyright (c) 2018-2021 <NAME>, m00nbsd.net
* All rights reserved.
*
* This code is part of the NVMM hypervisor.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "../nvmm.h"
#include "../nvmm_internal.h"
#include "nvmm_x86.h"
/*
* Code shared between x86-SVM and x86-VMX.
*/
const struct nvmm_x64_state nvmm_x86_reset_state = {
.segs = {
[NVMM_X64_SEG_ES] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 3,
.s = 1,
.p = 1,
}
},
[NVMM_X64_SEG_CS] = {
.selector = 0xF000,
.base = 0xFFFF0000,
.limit = 0xFFFF,
.attrib = {
.type = 3,
.s = 1,
.p = 1,
}
},
[NVMM_X64_SEG_SS] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 3,
.s = 1,
.p = 1,
}
},
[NVMM_X64_SEG_DS] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 3,
.s = 1,
.p = 1,
}
},
[NVMM_X64_SEG_FS] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 3,
.s = 1,
.p = 1,
}
},
[NVMM_X64_SEG_GS] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 3,
.s = 1,
.p = 1,
}
},
[NVMM_X64_SEG_GDT] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 2,
.s = 1,
.p = 1,
}
},
[NVMM_X64_SEG_IDT] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 2,
.s = 1,
.p = 1,
}
},
[NVMM_X64_SEG_LDT] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 2,
.s = 0,
.p = 1,
}
},
[NVMM_X64_SEG_TR] = {
.selector = 0x0000,
.base = 0x00000000,
.limit = 0xFFFF,
.attrib = {
.type = 3,
.s = 0,
.p = 1,
}
},
},
.gprs = {
[NVMM_X64_GPR_RAX] = 0x00000000,
[NVMM_X64_GPR_RCX] = 0x00000000,
[NVMM_X64_GPR_RDX] = 0x00000600,
[NVMM_X64_GPR_RBX] = 0x00000000,
[NVMM_X64_GPR_RSP] = 0x00000000,
[NVMM_X64_GPR_RBP] = 0x00000000,
[NVMM_X64_GPR_RSI] = 0x00000000,
[NVMM_X64_GPR_RDI] = 0x00000000,
[NVMM_X64_GPR_R8] = 0x00000000,
[NVMM_X64_GPR_R9] = 0x00000000,
[NVMM_X64_GPR_R10] = 0x00000000,
[NVMM_X64_GPR_R11] = 0x00000000,
[NVMM_X64_GPR_R12] = 0x00000000,
[NVMM_X64_GPR_R13] = 0x00000000,
[NVMM_X64_GPR_R14] = 0x00000000,
[NVMM_X64_GPR_R15] = 0x00000000,
[NVMM_X64_GPR_RIP] = 0x0000FFF0,
[NVMM_X64_GPR_RFLAGS] = 0x00000002,
},
.crs = {
[NVMM_X64_CR_CR0] = 0x60000010,
[NVMM_X64_CR_CR2] = 0x00000000,
[NVMM_X64_CR_CR3] = 0x00000000,
[NVMM_X64_CR_CR4] = 0x00000000,
[NVMM_X64_CR_CR8] = 0x00000000,
[NVMM_X64_CR_XCR0] = 0x00000001,
},
.drs = {
[NVMM_X64_DR_DR0] = 0x00000000,
[NVMM_X64_DR_DR1] = 0x00000000,
[NVMM_X64_DR_DR2] = 0x00000000,
[NVMM_X64_DR_DR3] = 0x00000000,
[NVMM_X64_DR_DR6] = 0xFFFF0FF0,
[NVMM_X64_DR_DR7] = 0x00000400,
},
.msrs = {
[NVMM_X64_MSR_EFER] = 0x00000000,
[NVMM_X64_MSR_STAR] = 0x00000000,
[NVMM_X64_MSR_LSTAR] = 0x00000000,
[NVMM_X64_MSR_CSTAR] = 0x00000000,
[NVMM_X64_MSR_SFMASK] = 0x00000000,
[NVMM_X64_MSR_KERNELGSBASE] = 0x00000000,
[NVMM_X64_MSR_SYSENTER_CS] = 0x00000000,
[NVMM_X64_MSR_SYSENTER_ESP] = 0x00000000,
[NVMM_X64_MSR_SYSENTER_EIP] = 0x00000000,
[NVMM_X64_MSR_PAT] = 0x0007040600070406,
[NVMM_X64_MSR_TSC] = 0,
},
.intr = {
.int_shadow = 0,
.int_window_exiting = 0,
.nmi_window_exiting = 0,
.evt_pending = 0,
},
.fpu = {
.fx_cw = 0x0040,
.fx_sw = 0x0000,
.fx_tw = 0x55,
.fx_zero = 0x55,
.fx_mxcsr = 0x1F80,
}
};
const struct nvmm_x86_cpuid_mask nvmm_cpuid_00000001 = {
.eax = ~0,
.ebx = ~0,
.ecx =
CPUID_0_01_ECX_SSE3 |
CPUID_0_01_ECX_PCLMULQDQ |
/* CPUID_0_01_ECX_DTES64 excluded */
/* CPUID_0_01_ECX_MONITOR excluded */
/* CPUID_0_01_ECX_DS_CPL excluded */
/* CPUID_0_01_ECX_VMX excluded */
/* CPUID_0_01_ECX_SMX excluded */
/* CPUID_0_01_ECX_EIST excluded */
/* CPUID_0_01_ECX_TM2 excluded */
CPUID_0_01_ECX_SSSE3 |
/* CPUID_0_01_ECX_CNXTID excluded */
/* CPUID_0_01_ECX_SDBG excluded */
CPUID_0_01_ECX_FMA |
CPUID_0_01_ECX_CX16 |
/* CPUID_0_01_ECX_XTPR excluded */
/* CPUID_0_01_ECX_PDCM excluded */
/* CPUID_0_01_ECX_PCID excluded, but re-included in VMX */
/* CPUID_0_01_ECX_DCA excluded */
CPUID_0_01_ECX_SSE41 |
CPUID_0_01_ECX_SSE42 |
/* CPUID_0_01_ECX_X2APIC excluded */
CPUID_0_01_ECX_MOVBE |
CPUID_0_01_ECX_POPCNT |
/* CPUID_0_01_ECX_TSC_DEADLINE excluded */
CPUID_0_01_ECX_AESNI |
CPUID_0_01_ECX_XSAVE |
CPUID_0_01_ECX_OSXSAVE |
/* CPUID_0_01_ECX_AVX excluded */
CPUID_0_01_ECX_F16C |
CPUID_0_01_ECX_RDRAND,
/* CPUID_0_01_ECX_RAZ excluded */
.edx =
CPUID_0_01_EDX_FPU |
CPUID_0_01_EDX_VME |
CPUID_0_01_EDX_DE |
CPUID_0_01_EDX_PSE |
CPUID_0_01_EDX_TSC |
CPUID_0_01_EDX_MSR |
CPUID_0_01_EDX_PAE |
/* CPUID_0_01_EDX_MCE excluded */
CPUID_0_01_EDX_CX8 |
CPUID_0_01_EDX_APIC |
CPUID_0_01_EDX_SEP |
/* CPUID_0_01_EDX_MTRR excluded */
CPUID_0_01_EDX_PGE |
/* CPUID_0_01_EDX_MCA excluded */
CPUID_0_01_EDX_CMOV |
CPUID_0_01_EDX_PAT |
CPUID_0_01_EDX_PSE36 |
/* CPUID_0_01_EDX_PSN excluded */
CPUID_0_01_EDX_CLFSH |
/* CPUID_0_01_EDX_DS excluded */
/* CPUID_0_01_EDX_ACPI excluded */
CPUID_0_01_EDX_MMX |
CPUID_0_01_EDX_FXSR |
CPUID_0_01_EDX_SSE |
CPUID_0_01_EDX_SSE2 |
CPUID_0_01_EDX_SS |
CPUID_0_01_EDX_HTT |
/* CPUID_0_01_EDX_TM excluded */
CPUID_0_01_EDX_PBE
};
const struct nvmm_x86_cpuid_mask nvmm_cpuid_00000007 = {
.eax = ~0,
.ebx =
CPUID_0_07_EBX_FSGSBASE |
/* CPUID_0_07_EBX_TSC_ADJUST excluded */
/* CPUID_0_07_EBX_SGX excluded */
CPUID_0_07_EBX_BMI1 |
/* CPUID_0_07_EBX_HLE excluded */
/* CPUID_0_07_EBX_AVX2 excluded */
CPUID_0_07_EBX_FDPEXONLY |
CPUID_0_07_EBX_SMEP |
CPUID_0_07_EBX_BMI2 |
CPUID_0_07_EBX_ERMS |
/* CPUID_0_07_EBX_INVPCID excluded, but re-included in VMX */
/* CPUID_0_07_EBX_RTM excluded */
/* CPUID_0_07_EBX_QM excluded */
CPUID_0_07_EBX_FPUCSDS |
/* CPUID_0_07_EBX_MPX excluded */
/* CPUID_0_07_EBX_PQE excluded */
/* CPUID_0_07_EBX_AVX512F excluded */
/* CPUID_0_07_EBX_AVX512DQ excluded */
CPUID_0_07_EBX_RDSEED |
CPUID_0_07_EBX_ADX |
CPUID_0_07_EBX_SMAP |
/* CPUID_0_07_EBX_AVX512_IFMA excluded */
CPUID_0_07_EBX_CLFLUSHOPT |
CPUID_0_07_EBX_CLWB,
/* CPUID_0_07_EBX_PT excluded */
/* CPUID_0_07_EBX_AVX512PF excluded */
/* CPUID_0_07_EBX_AVX512ER excluded */
/* CPUID_0_07_EBX_AVX512CD excluded */
/* CPUID_0_07_EBX_SHA excluded */
/* CPUID_0_07_EBX_AVX512BW excluded */
/* CPUID_0_07_EBX_AVX512VL excluded */
.ecx =
CPUID_0_07_ECX_PREFETCHWT1 |
/* CPUID_0_07_ECX_AVX512_VBMI excluded */
CPUID_0_07_ECX_UMIP |
/* CPUID_0_07_ECX_PKU excluded */
/* CPUID_0_07_ECX_OSPKE excluded */
/* CPUID_0_07_ECX_WAITPKG excluded */
/* CPUID_0_07_ECX_AVX512_VBMI2 excluded */
/* CPUID_0_07_ECX_CET_SS excluded */
CPUID_0_07_ECX_GFNI |
CPUID_0_07_ECX_VAES |
CPUID_0_07_ECX_VPCLMULQDQ |
/* CPUID_0_07_ECX_AVX512_VNNI excluded */
/* CPUID_0_07_ECX_AVX512_BITALG excluded */
/* CPUID_0_07_ECX_AVX512_VPOPCNTDQ excluded */
/* CPUID_0_07_ECX_LA57 excluded */
/* CPUID_0_07_ECX_MAWAU excluded */
/* CPUID_0_07_ECX_RDPID excluded */
CPUID_0_07_ECX_CLDEMOTE |
CPUID_0_07_ECX_MOVDIRI |
CPUID_0_07_ECX_MOVDIR64B,
/* CPUID_0_07_ECX_SGXLC excluded */
/* CPUID_0_07_ECX_PKS excluded */
.edx =
/* CPUID_0_07_EDX_AVX512_4VNNIW excluded */
/* CPUID_0_07_EDX_AVX512_4FMAPS excluded */
CPUID_0_07_EDX_FSREP_MOV |
/* CPUID_0_07_EDX_AVX512_VP2INTERSECT excluded */
/* CPUID_0_07_EDX_SRBDS_CTRL excluded */
CPUID_0_07_EDX_MD_CLEAR |
/* CPUID_0_07_EDX_TSX_FORCE_ABORT excluded */
CPUID_0_07_EDX_SERIALIZE |
/* CPUID_0_07_EDX_HYBRID excluded */
/* CPUID_0_07_EDX_TSXLDTRK excluded */
/* CPUID_0_07_EDX_CET_IBT excluded */
/* CPUID_0_07_EDX_IBRS excluded */
/* CPUID_0_07_EDX_STIBP excluded */
/* CPUID_0_07_EDX_L1D_FLUSH excluded */
CPUID_0_07_EDX_ARCH_CAP
/* CPUID_0_07_EDX_CORE_CAP excluded */
/* CPUID_0_07_EDX_SSBD excluded */
};
const struct nvmm_x86_cpuid_mask nvmm_cpuid_80000001 = {
.eax = ~0,
.ebx = ~0,
.ecx =
CPUID_8_01_ECX_LAHF |
CPUID_8_01_ECX_CMPLEGACY |
/* CPUID_8_01_ECX_SVM excluded */
/* CPUID_8_01_ECX_EAPIC excluded */
CPUID_8_01_ECX_ALTMOVCR8 |
CPUID_8_01_ECX_ABM |
CPUID_8_01_ECX_SSE4A |
CPUID_8_01_ECX_MISALIGNSSE |
CPUID_8_01_ECX_3DNOWPF |
/* CPUID_8_01_ECX_OSVW excluded */
/* CPUID_8_01_ECX_IBS excluded */
CPUID_8_01_ECX_XOP |
/* CPUID_8_01_ECX_SKINIT excluded */
/* CPUID_8_01_ECX_WDT excluded */
/* CPUID_8_01_ECX_LWP excluded */
CPUID_8_01_ECX_FMA4 |
CPUID_8_01_ECX_TCE |
/* CPUID_8_01_ECX_NODEID excluded */
CPUID_8_01_ECX_TBM |
CPUID_8_01_ECX_TOPOEXT,
/* CPUID_8_01_ECX_PCEC excluded */
/* CPUID_8_01_ECX_PCENB excluded */
/* CPUID_8_01_ECX_DBE excluded */
/* CPUID_8_01_ECX_PERFTSC excluded */
/* CPUID_8_01_ECX_PERFEXTLLC excluded */
/* CPUID_8_01_ECX_MWAITX excluded */
.edx =
CPUID_8_01_EDX_FPU |
CPUID_8_01_EDX_VME |
CPUID_8_01_EDX_DE |
CPUID_8_01_EDX_PSE |
CPUID_8_01_EDX_TSC |
CPUID_8_01_EDX_MSR |
CPUID_8_01_EDX_PAE |
/* CPUID_8_01_EDX_MCE excluded */
CPUID_8_01_EDX_CX8 |
CPUID_8_01_EDX_APIC |
CPUID_8_01_EDX_SYSCALL |
/* CPUID_8_01_EDX_MTRR excluded */
CPUID_8_01_EDX_PGE |
/* CPUID_8_01_EDX_MCA excluded */
CPUID_8_01_EDX_CMOV |
CPUID_8_01_EDX_PAT |
CPUID_8_01_EDX_PSE36 |
CPUID_8_01_EDX_XD |
CPUID_8_01_EDX_MMXEXT |
CPUID_8_01_EDX_MMX |
CPUID_8_01_EDX_FXSR |
CPUID_8_01_EDX_FFXSR |
CPUID_8_01_EDX_PAGE1GB |
/* CPUID_8_01_EDX_RDTSCP excluded */
CPUID_8_01_EDX_LM |
CPUID_8_01_EDX_3DNOWEXT |
CPUID_8_01_EDX_3DNOW
};
const struct nvmm_x86_cpuid_mask nvmm_cpuid_80000007 = {
.eax = 0,
.ebx = 0,
.ecx = 0,
.edx =
/* CPUID_8_07_EDX_TS excluded */
/* CPUID_8_07_EDX_FID excluded */
/* CPUID_8_07_EDX_VID excluded */
/* CPUID_8_07_EDX_TTP excluded */
/* CPUID_8_07_EDX_TM excluded */
/* CPUID_8_07_EDX_100MHzSteps excluded */
/* CPUID_8_07_EDX_HwPstate excluded */
CPUID_8_07_EDX_TscInvariant,
/* CPUID_8_07_EDX_CPB excluded */
/* CPUID_8_07_EDX_EffFreqRO excluded */
/* CPUID_8_07_EDX_ProcFeedbackIntf excluded */
/* CPUID_8_07_EDX_ProcPowerReport excluded */
};
const struct nvmm_x86_cpuid_mask nvmm_cpuid_80000008 = {
.eax = ~0,
.ebx =
CPUID_8_08_EBX_CLZERO |
/* CPUID_8_08_EBX_InstRetCntMsr excluded */
CPUID_8_08_EBX_RstrFpErrPtrs |
/* CPUID_8_08_EBX_INVLPGB excluded */
/* CPUID_8_08_EBX_RDPRU excluded */
/* CPUID_8_08_EBX_MCOMMIT excluded */
CPUID_8_08_EBX_WBNOINVD,
/* CPUID_8_08_EBX_IBPB excluded */
/* CPUID_8_08_EBX_INT_WBINVD excluded */
/* CPUID_8_08_EBX_IBRS excluded */
/* CPUID_8_08_EBX_EferLmsleUnsupp excluded */
/* CPUID_8_08_EBX_INVLPGBnestedPg excluded */
/* CPUID_8_08_EBX_STIBP excluded */
/* CPUID_8_08_EBX_IBRS_ALWAYSON excluded */
/* CPUID_8_08_EBX_STIBP_ALWAYSON excluded */
/* CPUID_8_08_EBX_PREFER_IBRS excluded */
/* CPUID_8_08_EBX_SSBD excluded */
/* CPUID_8_08_EBX_VIRT_SSBD excluded */
/* CPUID_8_08_EBX_SSB_NO excluded */
.ecx = 0,
.edx = 0
};
bool
nvmm_x86_pat_validate(uint64_t val)
{
uint8_t *pat = (uint8_t *)&val;
size_t i;
for (i = 0; i < 8; i++) {
if (__predict_false(pat[i] & ~__BITS(2,0)))
return false;
if (__predict_false(pat[i] == 2 || pat[i] == 3))
return false;
}
return true;
}
uint32_t
nvmm_x86_xsave_size(uint64_t xcr0)
{
uint32_t size;
if (xcr0 & XCR0_SSE) {
size = 512; /* x87 + SSE */
} else {
size = 108; /* x87 */
}
size += 64; /* XSAVE header */
return size;
}
| 7,443 |
418 | <reponame>GIRIME262/3Dpose_ssl
#ifndef CAFFE_HEATMAP_HPP_
#define CAFFE_HEATMAP_HPP_
#include <string>
#include <vector>
#include <utility>
#include "caffe/layer.hpp"
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe
{
template<typename Dtype>
class DataHeatmapLayer: public BasePrefetchingDataLayer<Dtype>
{
public:
explicit DataHeatmapLayer(const LayerParameter& param)
: BasePrefetchingDataLayer<Dtype>(param) {}
virtual ~DataHeatmapLayer();
virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "DataHeatmap"; }
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual void load_batch(Batch<Dtype>* batch);
shared_ptr<Caffe::RNG> prefetch_rng_;
virtual void ShuffleImages();
// Global vars
shared_ptr<Caffe::RNG> rng_data_;
int cur_img_;
string root_img_dir_;
// vector of (image, label) pairs
vector< pair<string, pair<vector<float>, vector<float> > > > img_label_list_;
};
}
#endif /* CAFFE_HEATMAP_HPP_ */ | 556 |
2,151 | /*
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ar.core.examples.c.helloar;
import android.hardware.display.DisplayManager;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
/**
* This is a simple example that shows how to create an augmented reality (AR) application using the
* ARCore C API.
*/
public class HelloArActivity extends AppCompatActivity
implements GLSurfaceView.Renderer, DisplayManager.DisplayListener {
private static final String TAG = HelloArActivity.class.getSimpleName();
private static final int SNACKBAR_UPDATE_INTERVAL_MILLIS = 1000; // In milliseconds.
private GLSurfaceView mSurfaceView;
private boolean mViewportChanged = false;
private int mViewportWidth;
private int mViewportHeight;
// Opaque native pointer to the native application instance.
private long mNativeApplication;
private GestureDetector mGestureDetector;
private Snackbar mLoadingMessageSnackbar;
private Handler mPlaneStatusCheckingHandler;
private final Runnable mPlaneStatusCheckingRunnable =
new Runnable() {
@Override
public void run() {
// The runnable is executed on main UI thread.
try {
if (JniInterface.hasDetectedPlanes(mNativeApplication)) {
if (mLoadingMessageSnackbar != null) {
mLoadingMessageSnackbar.dismiss();
}
mLoadingMessageSnackbar = null;
} else {
mPlaneStatusCheckingHandler.postDelayed(
mPlaneStatusCheckingRunnable, SNACKBAR_UPDATE_INTERVAL_MILLIS);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = (GLSurfaceView) findViewById(R.id.surfaceview);
// Set up tap listener.
mGestureDetector =
new GestureDetector(
this,
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(final MotionEvent e) {
mSurfaceView.queueEvent(
new Runnable() {
@Override
public void run() {
JniInterface.onTouched(mNativeApplication, e.getX(), e.getY());
}
});
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
});
mSurfaceView.setOnTouchListener(
new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
});
// Set up renderer.
mSurfaceView.setPreserveEGLContextOnPause(true);
mSurfaceView.setEGLContextClientVersion(2);
mSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); // Alpha used for plane blending.
mSurfaceView.setRenderer(this);
mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
JniInterface.assetManager = getAssets();
mNativeApplication = JniInterface.createNativeApplication(getAssets());
mPlaneStatusCheckingHandler = new Handler();
}
@Override
protected void onResume() {
super.onResume();
// ARCore requires camera permissions to operate. If we did not yet obtain runtime
// permission on Android M and above, now is a good time to ask the user for it.
if (!CameraPermissionHelper.hasCameraPermission(this)) {
CameraPermissionHelper.requestCameraPermission(this);
return;
}
JniInterface.onResume(mNativeApplication, getApplicationContext(), this);
mSurfaceView.onResume();
mLoadingMessageSnackbar =
Snackbar.make(
HelloArActivity.this.findViewById(android.R.id.content),
"Searching for surfaces...",
Snackbar.LENGTH_INDEFINITE);
// Set the snackbar background to light transparent black color.
mLoadingMessageSnackbar.getView().setBackgroundColor(0xbf323232);
mLoadingMessageSnackbar.show();
mPlaneStatusCheckingHandler.postDelayed(
mPlaneStatusCheckingRunnable, SNACKBAR_UPDATE_INTERVAL_MILLIS);
// Listen to display changed events to detect 180° rotation, which does not cause a config
// change or view resize.
getSystemService(DisplayManager.class).registerDisplayListener(this, null);
}
@Override
public void onPause() {
super.onPause();
mSurfaceView.onPause();
JniInterface.onPause(mNativeApplication);
mPlaneStatusCheckingHandler.removeCallbacks(mPlaneStatusCheckingRunnable);
getSystemService(DisplayManager.class).unregisterDisplayListener(this);
}
@Override
public void onDestroy() {
super.onDestroy();
// Synchronized to avoid racing onDrawFrame.
synchronized (this) {
JniInterface.destroyNativeApplication(mNativeApplication);
mNativeApplication = 0;
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
// Standard Android full-screen functionality.
getWindow()
.getDecorView()
.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
JniInterface.onGlSurfaceCreated(mNativeApplication);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
mViewportWidth = width;
mViewportHeight = height;
mViewportChanged = true;
}
@Override
public void onDrawFrame(GL10 gl) {
// Synchronized to avoid racing onDestroy.
synchronized (this) {
if (mNativeApplication == 0) {
return;
}
if (mViewportChanged) {
int displayRotation = getWindowManager().getDefaultDisplay().getRotation();
JniInterface.onDisplayGeometryChanged(
mNativeApplication, displayRotation, mViewportWidth, mViewportHeight);
mViewportChanged = false;
}
JniInterface.onGlSurfaceDrawFrame(mNativeApplication);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) {
if (!CameraPermissionHelper.hasCameraPermission(this)) {
Toast.makeText(this, "Camera permission is needed to run this application", Toast.LENGTH_LONG)
.show();
if (!CameraPermissionHelper.shouldShowRequestPermissionRationale(this)) {
// Permission denied with checking "Do not ask again".
CameraPermissionHelper.launchPermissionSettings(this);
}
finish();
}
}
// DisplayListener methods
@Override
public void onDisplayAdded(int displayId) {}
@Override
public void onDisplayRemoved(int displayId) {}
@Override
public void onDisplayChanged(int displayId) {
mViewportChanged = true;
}
}
| 3,268 |
20,995 | <filename>third_party/jsoncpp/generated/version.h
// DO NOT EDIT. This file (and "version") is a template used by the build system
// (either CMake or Meson) to generate a "version.h" header file.
#ifndef JSON_VERSION_H_INCLUDED
#define JSON_VERSION_H_INCLUDED
#define JSONCPP_VERSION_STRING "1.9.0"
#define JSONCPP_VERSION_MAJOR 1
#define JSONCPP_VERSION_MINOR 9
#define JSONCPP_VERSION_PATCH 0
#define JSONCPP_VERSION_QUALIFIER
#define JSONCPP_VERSION_HEXA \
((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | \
(JSONCPP_VERSION_PATCH << 8))
#ifdef JSONCPP_USING_SECURE_MEMORY
#undef JSONCPP_USING_SECURE_MEMORY
#endif
#define JSONCPP_USING_SECURE_MEMORY 0
// If non-zero, the library zeroes any memory that it has allocated before
// it frees its memory.
#endif // JSON_VERSION_H_INCLUDED
| 346 |
3,508 | <filename>src/main/java/com/fishercoder/solutions/_1352.java
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
public class _1352 {
public static class Solution1 {
/**
* credit: https://leetcode.com/problems/product-of-the-last-k-numbers/discuss/510260/JavaC%2B%2BPython-Prefix-Product
*/
public static class ProductOfNumbers {
List<Integer> list;
public ProductOfNumbers() {
add(0);
}
public void add(int num) {
if (num > 0) {
list.add(list.get(list.size() - 1) * num);
} else {
list = new ArrayList<>();
list.add(1);
}
}
public int getProduct(int k) {
int size = list.size();
return k >= size ? 0 : (list.get(size - 1) / list.get(size - k - 1));
}
}
}
}
| 532 |
1,668 | <reponame>DoNnMyTh/ralph
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('operations', '0007_auto_20170328_1728'),
]
operations = [
migrations.AlterField(
model_name='operation',
name='assignee',
field=models.ForeignKey(verbose_name='assignee', blank=True, to=settings.AUTH_USER_MODEL, null=True, related_name='operations', on_delete=django.db.models.deletion.PROTECT),
),
]
| 266 |
608 | <filename>vstgui/uidescription/viewcreator/layeredviewcontainercreator.cpp
// This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "layeredviewcontainercreator.h"
#include "../../lib/clayeredviewcontainer.h"
#include "../detail/uiviewcreatorattributes.h"
#include "../uiattributes.h"
#include "../uiviewcreator.h"
#include "../uiviewfactory.h"
//------------------------------------------------------------------------
namespace VSTGUI {
namespace UIViewCreator {
//-----------------------------------------------------------------------------
LayeredViewContainerCreator::LayeredViewContainerCreator ()
{
UIViewFactory::registerViewCreator (*this);
}
//------------------------------------------------------------------------
IdStringPtr LayeredViewContainerCreator::getViewName () const
{
return kCLayeredViewContainer;
}
//------------------------------------------------------------------------
IdStringPtr LayeredViewContainerCreator::getBaseViewName () const
{
return kCViewContainer;
}
//------------------------------------------------------------------------
UTF8StringPtr LayeredViewContainerCreator::getDisplayName () const
{
return "Layered View Container";
}
//------------------------------------------------------------------------
CView* LayeredViewContainerCreator::create (const UIAttributes& attributes,
const IUIDescription* description) const
{
return new CLayeredViewContainer (CRect (0, 0, 100, 100));
}
//------------------------------------------------------------------------
bool LayeredViewContainerCreator::apply (CView* view, const UIAttributes& attributes,
const IUIDescription* description) const
{
auto* lvc = dynamic_cast<CLayeredViewContainer*> (view);
if (lvc == nullptr)
return false;
int32_t zIndex;
if (attributes.getIntegerAttribute (kAttrZIndex, zIndex))
lvc->setZIndex (static_cast<uint32_t> (zIndex));
return true;
}
//------------------------------------------------------------------------
bool LayeredViewContainerCreator::getAttributeNames (StringList& attributeNames) const
{
attributeNames.emplace_back (kAttrZIndex);
return true;
}
//------------------------------------------------------------------------
auto LayeredViewContainerCreator::getAttributeType (const string& attributeName) const -> AttrType
{
if (attributeName == kAttrZIndex)
return kIntegerType;
return kUnknownType;
}
//------------------------------------------------------------------------
bool LayeredViewContainerCreator::getAttributeValue (CView* view, const string& attributeName,
string& stringValue,
const IUIDescription* desc) const
{
auto* lvc = dynamic_cast<CLayeredViewContainer*> (view);
if (lvc == nullptr)
return false;
if (attributeName == kAttrZIndex)
{
stringValue = UIAttributes::integerToString (static_cast<int32_t> (lvc->getZIndex ()));
return true;
}
return false;
}
//------------------------------------------------------------------------
} // UIViewCreator
} // VSTGUI
| 990 |
1,198 | <reponame>dherbst/lullaby<gh_stars>1000+
/*
Copyright 2017-2019 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lullaby/modules/flatbuffers/mathfu_fb_conversions.h"
#include "gtest/gtest.h"
namespace lull {
namespace {
TEST(MathfuFbConversions, MathfuVec2FromFbVec2) {
std::unique_ptr<Vec2> in(new Vec2(1, 2));
std::unique_ptr<mathfu::vec2> out(new mathfu::vec2());
MathfuVec2FromFbVec2(in.get(), out.get());
EXPECT_EQ(1, out->x);
EXPECT_EQ(2, out->y);
}
TEST(MathfuFbConversions, MathfuVec2iFromFbVec2i) {
std::unique_ptr<Vec2i> in(new Vec2i(1, 2));
std::unique_ptr<mathfu::vec2i> out(new mathfu::vec2i());
MathfuVec2iFromFbVec2i(in.get(), out.get());
EXPECT_EQ(1, out->x);
EXPECT_EQ(2, out->y);
}
TEST(MathfuFbConversions, MathfuVec3FromFbVec3) {
std::unique_ptr<Vec3> in(new Vec3(1, 2, 3));
std::unique_ptr<mathfu::vec3> out(new mathfu::vec3());
MathfuVec3FromFbVec3(in.get(), out.get());
EXPECT_EQ(1, out->x);
EXPECT_EQ(2, out->y);
EXPECT_EQ(3, out->z);
}
TEST(MathfuFbConversions, MathfuVec4FromFbVec4) {
std::unique_ptr<Vec4> in(new Vec4(1, 2, 3, 4));
std::unique_ptr<mathfu::vec4> out(new mathfu::vec4());
MathfuVec4FromFbVec4(in.get(), out.get());
EXPECT_EQ(1, out->x);
EXPECT_EQ(2, out->y);
EXPECT_EQ(3, out->z);
EXPECT_EQ(4, out->w);
}
TEST(MathfuFbConversions, MathfuQuatFromFbQuat) {
// In lull, scalar is first; in fb, it is last.
const mathfu::quat value = mathfu::quat(1, 2, 3, 4).Normalized();
std::unique_ptr<Quat> in(new Quat(value[1], value[2], value[3], value[0]));
std::unique_ptr<mathfu::quat> out(new mathfu::quat());
MathfuQuatFromFbQuat(in.get(), out.get());
EXPECT_EQ(value.scalar(), out->scalar());
EXPECT_EQ(value.vector().x, out->vector().x);
EXPECT_EQ(value.vector().y, out->vector().y);
EXPECT_EQ(value.vector().z, out->vector().z);
}
TEST(MathfuFbConversions, MathfuQuatFromFbVec3) {
// In lull, scalar is first; in fb, it is last.
std::unique_ptr<Vec3> in(new Vec3(1, 2, 3));
std::unique_ptr<mathfu::quat> out(new mathfu::quat());
MathfuQuatFromFbVec3(in.get(), out.get());
EXPECT_NEAR(0.999471, out->scalar(), kDefaultEpsilon);
EXPECT_NEAR(0.00826538, out->vector().x, kDefaultEpsilon);
EXPECT_NEAR(0.0176742, out->vector().y, kDefaultEpsilon);
EXPECT_NEAR(0.0260197, out->vector().z, kDefaultEpsilon);
}
TEST(MathfuFbConversions, MathfuQuatFromFbVec4) {
// In lull, scalar is first; in fb, it is last.
std::unique_ptr<Vec4> in(new Vec4(1, 2, 3, 4));
std::unique_ptr<mathfu::quat> out(new mathfu::quat());
MathfuQuatFromFbVec4(in.get(), out.get());
EXPECT_EQ(4, out->scalar());
EXPECT_EQ(1, out->vector().x);
EXPECT_EQ(2, out->vector().y);
EXPECT_EQ(3, out->vector().z);
}
TEST(MathfuFbConversions, MathfuVec4FromFbColor) {
std::unique_ptr<Color> in(new Color(1, 2, 3, 4));
std::unique_ptr<mathfu::vec4> out(new mathfu::vec4());
MathfuVec4FromFbColor(in.get(), out.get());
EXPECT_EQ(1, out->x);
EXPECT_EQ(2, out->y);
EXPECT_EQ(3, out->z);
EXPECT_EQ(4, out->w);
}
TEST(MathfuFbConversions, MathfuVec4FromFbColorHex) {
std::unique_ptr<mathfu::vec4> out(new mathfu::vec4());
MathfuVec4FromFbColorHex("#336699", out.get());
EXPECT_NEAR(0.2f, out->x, kDefaultEpsilon);
EXPECT_NEAR(0.4f, out->y, kDefaultEpsilon);
EXPECT_NEAR(0.6f, out->z, kDefaultEpsilon);
EXPECT_NEAR(1.0f, out->w, kDefaultEpsilon);
MathfuVec4FromFbColorHex("#33669900", out.get());
EXPECT_NEAR(0.2f, out->x, kDefaultEpsilon);
EXPECT_NEAR(0.4f, out->y, kDefaultEpsilon);
EXPECT_NEAR(0.6f, out->z, kDefaultEpsilon);
EXPECT_NEAR(0.0f, out->w, kDefaultEpsilon);
}
TEST(MathfuFbConversions, AabbFromFbAabb) {
std::unique_ptr<AabbDef> in(new AabbDef(Vec3(1, 2, 3), Vec3(4, 5, 6)));
std::unique_ptr<Aabb> out(new Aabb());
AabbFromFbAabb(in.get(), out.get());
EXPECT_EQ(1, out->min.x);
EXPECT_EQ(2, out->min.y);
EXPECT_EQ(3, out->min.z);
EXPECT_EQ(4, out->max.x);
EXPECT_EQ(5, out->max.y);
EXPECT_EQ(6, out->max.z);
}
TEST(MathfuFbConversions, AabbFromFbRect) {
Rect in(1, 2, 3, 4);
Aabb out;
AabbFromFbRect(&in, &out);
EXPECT_EQ(1, out.min.x);
EXPECT_EQ(2, out.min.y);
EXPECT_EQ(0, out.min.z);
EXPECT_EQ(4, out.max.x);
EXPECT_EQ(6, out.max.y);
EXPECT_EQ(0, out.max.z);
}
TEST(MathfuFbConversions, Color4ubFromFbColor) {
std::unique_ptr<Color> in(
new Color(0, 128.0f / 255.0f, 196.0f / 255.0f, 1.0f));
std::unique_ptr<Color4ub> out(new Color4ub());
Color4ubFromFbColor(in.get(), out.get());
EXPECT_EQ(0, out->r);
EXPECT_EQ(128, out->g);
EXPECT_EQ(196, out->b);
EXPECT_EQ(255, out->a);
}
} // namespace
} // namespace lull
| 2,333 |
10,876 | {
"name": "libodb-mysql",
"version": "2.4.0",
"port-version": 9,
"description": "MySQL support for the ODB ORM library",
"homepage": "https://www.codesynthesis.com/products/odb/",
"dependencies": [
"libmysql",
"libodb"
]
}
| 105 |
2,092 | #include <ck_ring.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "../../common.h"
#ifndef ITERATIONS
#define ITERATIONS (128000)
#endif
struct entry {
int tid;
int value;
};
int
main(int argc, char *argv[])
{
int i, r, size;
uint64_t s, e, e_a, d_a;
struct entry entry = {0, 0};
ck_ring_buffer_t *buf;
ck_ring_t ring;
if (argc != 2) {
ck_error("Usage: latency <size>\n");
}
size = atoi(argv[1]);
if (size <= 4 || (size & (size - 1))) {
ck_error("ERROR: Size must be a power of 2 greater than 4.\n");
}
buf = malloc(sizeof(ck_ring_buffer_t) * size);
if (buf == NULL) {
ck_error("ERROR: Failed to allocate buffer\n");
}
ck_ring_init(&ring, size);
e_a = d_a = s = e = 0;
for (r = 0; r < ITERATIONS; r++) {
for (i = 0; i < size / 4; i += 4) {
s = rdtsc();
ck_ring_enqueue_spsc(&ring, buf, &entry);
ck_ring_enqueue_spsc(&ring, buf, &entry);
ck_ring_enqueue_spsc(&ring, buf, &entry);
ck_ring_enqueue_spsc(&ring, buf, &entry);
e = rdtsc();
}
e_a += (e - s) / 4;
for (i = 0; i < size / 4; i += 4) {
s = rdtsc();
ck_ring_dequeue_spsc(&ring, buf, &entry);
ck_ring_dequeue_spsc(&ring, buf, &entry);
ck_ring_dequeue_spsc(&ring, buf, &entry);
ck_ring_dequeue_spsc(&ring, buf, &entry);
e = rdtsc();
}
d_a += (e - s) / 4;
}
printf("spsc %10d %16" PRIu64 " %16" PRIu64 "\n", size, e_a / ITERATIONS, d_a / ITERATIONS);
e_a = d_a = s = e = 0;
for (r = 0; r < ITERATIONS; r++) {
for (i = 0; i < size / 4; i += 4) {
s = rdtsc();
ck_ring_enqueue_spmc(&ring, buf, &entry);
ck_ring_enqueue_spmc(&ring, buf, &entry);
ck_ring_enqueue_spmc(&ring, buf, &entry);
ck_ring_enqueue_spmc(&ring, buf, &entry);
e = rdtsc();
}
e_a += (e - s) / 4;
for (i = 0; i < size / 4; i += 4) {
s = rdtsc();
ck_ring_dequeue_spmc(&ring, buf, &entry);
ck_ring_dequeue_spmc(&ring, buf, &entry);
ck_ring_dequeue_spmc(&ring, buf, &entry);
ck_ring_dequeue_spmc(&ring, buf, &entry);
e = rdtsc();
}
d_a += (e - s) / 4;
}
printf("spmc %10d %16" PRIu64 " %16" PRIu64 "\n", size, e_a / ITERATIONS, d_a / ITERATIONS);
ck_ring_init(&ring, size);
e_a = d_a = s = e = 0;
for (r = 0; r < ITERATIONS; r++) {
for (i = 0; i < size / 4; i += 4) {
s = rdtsc();
ck_ring_enqueue_mpsc(&ring, buf, &entry);
ck_ring_enqueue_mpsc(&ring, buf, &entry);
ck_ring_enqueue_mpsc(&ring, buf, &entry);
ck_ring_enqueue_mpsc(&ring, buf, &entry);
e = rdtsc();
}
e_a += (e - s) / 4;
for (i = 0; i < size / 4; i += 4) {
s = rdtsc();
ck_ring_dequeue_mpsc(&ring, buf, &entry);
ck_ring_dequeue_mpsc(&ring, buf, &entry);
ck_ring_dequeue_mpsc(&ring, buf, &entry);
ck_ring_dequeue_mpsc(&ring, buf, &entry);
e = rdtsc();
}
d_a += (e - s) / 4;
}
printf("mpsc %10d %16" PRIu64 " %16" PRIu64 "\n", size, e_a / ITERATIONS, d_a / ITERATIONS);
ck_ring_init(&ring, size);
e_a = d_a = s = e = 0;
for (r = 0; r < ITERATIONS; r++) {
for (i = 0; i < size / 4; i += 4) {
s = rdtsc();
ck_ring_enqueue_mpmc(&ring, buf, &entry);
ck_ring_enqueue_mpmc(&ring, buf, &entry);
ck_ring_enqueue_mpmc(&ring, buf, &entry);
ck_ring_enqueue_mpmc(&ring, buf, &entry);
e = rdtsc();
}
e_a += (e - s) / 4;
for (i = 0; i < size / 4; i += 4) {
s = rdtsc();
ck_ring_dequeue_mpmc(&ring, buf, &entry);
ck_ring_dequeue_mpmc(&ring, buf, &entry);
ck_ring_dequeue_mpmc(&ring, buf, &entry);
ck_ring_dequeue_mpmc(&ring, buf, &entry);
e = rdtsc();
}
d_a += (e - s) / 4;
}
printf("mpmc %10d %16" PRIu64 " %16" PRIu64 "\n", size, e_a / ITERATIONS, d_a / ITERATIONS);
return (0);
}
| 1,834 |
1,959 | package com.xamarin.android;
public class DataHandler {
DataListener listener;
public void setOnDataListener (DataListener listener)
{
this.listener = listener;
}
public void send ()
{
if (listener == null)
return;
byte start = (byte) 'J';
byte[][] data = new byte[][]{
new byte[]{ (byte) (start + 11), (byte) (start + 12), (byte) (start + 13) },
new byte[]{ (byte) (start + 21), (byte) (start + 22), (byte) (start + 23) },
new byte[]{ (byte) (start + 31), (byte) (start + 32), (byte) (start + 33) },
};
listener.onDataReceived ("fromNode", "fromChannel", "payloadType", data);
for (int i = 0; i < data.length; ++i)
for (int j = 0; j < data [i].length; ++j) {
int expected = ((i+1)*10) + (j+1);
if (data [i][j] != ((i+1)*10) + (j+1))
throw new Error ("Value mismatch! Should be '" + expected +
"'; was '" + data [i][j] + "'.");
}
}
}
| 376 |
1,561 | <reponame>radetsky/themis
#
# Copyright (c) 2015 Cossack Labs Limited
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
#
"""
echo client for rabbitMQ
"""
import pika
import uuid
from pythemis import ssession
client_private = b"\x52\x45\x43\x32\x00\x00\x00\x2d\x51\xf4\xaa\x72\x00\x9f\x0f\x09\xce\xbe\x09\x33\xc2\x5e\x9a\x05\x99\x53\x9d\xb2\x32\xa2\x34\x64\x7a\xde\xde\x83\x8f\x65\xa9\x2a\x14\x6d\xaa\x90\x01"
server_public = b"\x55\x45\x43\x32\x00\x00\x00\x2d\x75\x58\x33\xd4\x02\x12\xdf\x1f\xe9\xea\x48\x11\xe1\xf9\x71\x8e\x24\x11\xcb\xfd\xc0\xa3\x6e\xd6\xac\x88\xb6\x44\xc2\x9a\x24\x84\xee\x50\x4c\x3e\xa0"
session = ssession.SSession(
b"client", client_private,
ssession.SimpleMemoryTransport(b'server', server_public))
class SsessionRpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
self.channel = self.connection.channel()
result = self.channel.queue_declare('ssession_queue_client', exclusive=True)
self.callback_queue = result.method.queue
self.channel.basic_consume(self.callback_queue, self.on_response, auto_ack=False)
def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id:
# unwrap response message
self.response = session.unwrap(body)
def call(self, message):
self.response = None
self.corr_id = str(uuid.uuid4())
self.channel.basic_publish(
exchange='',
routing_key='ssession_queue_server',
properties=pika.BasicProperties(
reply_to=self.callback_queue,
correlation_id=self.corr_id,
),
body=message)
while self.response is None:
self.connection.process_data_events()
return self.response
ssession_rpc = SsessionRpcClient()
# make and send session initialisation message and get unwrapped reply message
response = ssession_rpc.call(session.connect_request())
while not session.is_established():
# send response message to client as is and get new unwrapped reply message
response = ssession_rpc.call(response)
for i in range(5):
# encrypt,send information message and get unwrapped reply message
print(
ssession_rpc.call(
session.wrap("This is test message #{}!".format(i).encode('utf-8'))
).decode('utf-8'))
| 1,238 |
2,151 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.sync;
import android.accounts.Account;
import android.content.Context;
import android.os.Bundle;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.Callback;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.Feature;
import org.chromium.components.signin.AccountManagerFacade;
import org.chromium.components.signin.ChromeSigninController;
import org.chromium.components.signin.test.util.AccountHolder;
import org.chromium.components.signin.test.util.FakeAccountManagerDelegate;
import org.chromium.components.sync.AndroidSyncSettings.AndroidSyncSettingsObserver;
import org.chromium.components.sync.test.util.MockSyncContentResolverDelegate;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tests for AndroidSyncSettings.
*/
@RunWith(BaseJUnit4ClassRunner.class)
public class AndroidSyncSettingsTest {
private static class CountingMockSyncContentResolverDelegate
extends MockSyncContentResolverDelegate {
private final AtomicInteger mGetMasterSyncAutomaticallyCalls = new AtomicInteger();
private final AtomicInteger mGetSyncAutomaticallyCalls = new AtomicInteger();
private final AtomicInteger mGetIsSyncableCalls = new AtomicInteger();
private final AtomicInteger mSetIsSyncableCalls = new AtomicInteger();
private final AtomicInteger mSetSyncAutomaticallyCalls = new AtomicInteger();
private final AtomicInteger mRemovePeriodicSyncCalls = new AtomicInteger();
@Override
public boolean getMasterSyncAutomatically() {
mGetMasterSyncAutomaticallyCalls.getAndIncrement();
return super.getMasterSyncAutomatically();
}
@Override
public boolean getSyncAutomatically(Account account, String authority) {
mGetSyncAutomaticallyCalls.getAndIncrement();
return super.getSyncAutomatically(account, authority);
}
@Override
public int getIsSyncable(Account account, String authority) {
mGetIsSyncableCalls.getAndIncrement();
return super.getIsSyncable(account, authority);
}
@Override
public void setIsSyncable(Account account, String authority, int syncable) {
mSetIsSyncableCalls.getAndIncrement();
super.setIsSyncable(account, authority, syncable);
}
@Override
public void setSyncAutomatically(Account account, String authority, boolean sync) {
mSetSyncAutomaticallyCalls.getAndIncrement();
super.setSyncAutomatically(account, authority, sync);
}
@Override
public void removePeriodicSync(Account account, String authority, Bundle extras) {
mRemovePeriodicSyncCalls.getAndIncrement();
super.removePeriodicSync(account, authority, extras);
}
}
private static class MockSyncSettingsObserver implements AndroidSyncSettingsObserver {
private boolean mReceivedNotification;
public void clearNotification() {
mReceivedNotification = false;
}
public boolean receivedNotification() {
return mReceivedNotification;
}
@Override
public void androidSyncSettingsChanged() {
mReceivedNotification = true;
}
}
private Context mContext;
private CountingMockSyncContentResolverDelegate mSyncContentResolverDelegate;
private String mAuthority;
private Account mAccount;
private Account mAlternateAccount;
private MockSyncSettingsObserver mSyncSettingsObserver;
private FakeAccountManagerDelegate mAccountManager;
private CallbackHelper mCallbackHelper;
private int mNumberOfCallsToWait;
@Before
public void setUp() throws Exception {
mNumberOfCallsToWait = 0;
mCallbackHelper = new CallbackHelper();
mContext = InstrumentationRegistry.getTargetContext();
setupTestAccounts();
// Set signed in account to mAccount before initializing AndroidSyncSettings to let
// AndroidSyncSettings establish correct assumptions.
ChromeSigninController.get().setSignedInAccountName(mAccount.name);
mSyncContentResolverDelegate = new CountingMockSyncContentResolverDelegate();
overrideAndroidSyncSettings();
mAuthority = AndroidSyncSettings.getContractAuthority(mContext);
Assert.assertEquals(1, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority));
mSyncSettingsObserver = new MockSyncSettingsObserver();
AndroidSyncSettings.registerObserver(mContext, mSyncSettingsObserver);
}
/**
* Overrides AndroidSyncSettings passing mSyncContentResolverDelegate and waits for settings
* changes to propagate to ContentResolverDelegate.
*/
private void overrideAndroidSyncSettings() throws Exception {
AndroidSyncSettings.overrideForTests(mContext, mSyncContentResolverDelegate,
(Boolean result) -> {
mCallbackHelper.notifyCalled();
});
mNumberOfCallsToWait++;
mCallbackHelper.waitForCallback(0, mNumberOfCallsToWait);
}
private void setupTestAccounts() {
mAccountManager = new FakeAccountManagerDelegate(
FakeAccountManagerDelegate.DISABLE_PROFILE_DATA_SOURCE);
AccountManagerFacade.overrideAccountManagerFacadeForTests(mAccountManager);
mAccount = addTestAccount("<EMAIL>");
mAlternateAccount = addTestAccount("<EMAIL>");
}
private Account addTestAccount(String name) {
Account account = AccountManagerFacade.createAccountFromName(name);
AccountHolder holder = AccountHolder.builder(account).alwaysAccept(true).build();
mAccountManager.addAccountHolderBlocking(holder);
return account;
}
@After
public void tearDown() throws Exception {
if (mNumberOfCallsToWait > 0) mCallbackHelper.waitForCallback(0, mNumberOfCallsToWait);
}
private void enableChromeSyncOnUiThread() {
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
AndroidSyncSettings.enableChromeSync(mContext);
}
});
}
private void disableChromeSyncOnUiThread() {
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
AndroidSyncSettings.disableChromeSync(mContext);
}
});
}
private void updateAccountSync(Account account) throws InterruptedException, TimeoutException {
updateAccount(account);
mCallbackHelper.waitForCallback(0, mNumberOfCallsToWait);
}
private void updateAccount(Account account) {
updateAccountWithCallback(account, (Boolean result) -> {
mCallbackHelper.notifyCalled();
});
}
private void updateAccountWithCallback(Account account, Callback<Boolean> callback) {
AndroidSyncSettings.updateAccount(mContext, account, callback);
mNumberOfCallsToWait++;
}
@Test
@SmallTest
@Feature({"Sync"})
public void testAccountInitialization() throws InterruptedException, TimeoutException {
// mAccount was set to be syncable and not have periodic syncs.
Assert.assertEquals(1, mSyncContentResolverDelegate.mSetIsSyncableCalls.get());
Assert.assertEquals(1, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls.get());
updateAccountSync(null);
// mAccount was set to be not syncable.
Assert.assertEquals(2, mSyncContentResolverDelegate.mSetIsSyncableCalls.get());
Assert.assertEquals(1, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls.get());
updateAccount(mAlternateAccount);
// mAlternateAccount was set to be syncable and not have periodic syncs.
Assert.assertEquals(3, mSyncContentResolverDelegate.mSetIsSyncableCalls.get());
Assert.assertEquals(2, mSyncContentResolverDelegate.mRemovePeriodicSyncCalls.get());
}
@Test
@SmallTest
@Feature({"Sync"})
public void testToggleMasterSyncFromSettings() throws InterruptedException {
mSyncContentResolverDelegate.setMasterSyncAutomatically(true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertTrue(
"master sync should be set", AndroidSyncSettings.isMasterSyncEnabled(mContext));
mSyncContentResolverDelegate.setMasterSyncAutomatically(false);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertFalse(
"master sync should be unset", AndroidSyncSettings.isMasterSyncEnabled(mContext));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testToggleChromeSyncFromSettings() throws InterruptedException {
// Turn on syncability.
mSyncContentResolverDelegate.setMasterSyncAutomatically(true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
// First sync
mSyncContentResolverDelegate.setIsSyncable(mAccount, mAuthority, 1);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
mSyncContentResolverDelegate.setSyncAutomatically(mAccount, mAuthority, true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertTrue("sync should be set", AndroidSyncSettings.isSyncEnabled(mContext));
Assert.assertTrue("sync should be set for chrome app",
AndroidSyncSettings.isChromeSyncEnabled(mContext));
// Disable sync automatically for the app
mSyncContentResolverDelegate.setSyncAutomatically(mAccount, mAuthority, false);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertFalse("sync should be unset", AndroidSyncSettings.isSyncEnabled(mContext));
Assert.assertFalse("sync should be unset for chrome app",
AndroidSyncSettings.isChromeSyncEnabled(mContext));
// Re-enable sync
mSyncContentResolverDelegate.setSyncAutomatically(mAccount, mAuthority, true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertTrue("sync should be re-enabled", AndroidSyncSettings.isSyncEnabled(mContext));
Assert.assertTrue("sync should be set for chrome app",
AndroidSyncSettings.isChromeSyncEnabled(mContext));
// Disabled from master sync
mSyncContentResolverDelegate.setMasterSyncAutomatically(false);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertFalse("sync should be disabled due to master sync",
AndroidSyncSettings.isSyncEnabled(mContext));
Assert.assertFalse("master sync should be disabled",
AndroidSyncSettings.isMasterSyncEnabled(mContext));
Assert.assertTrue("sync should be set for chrome app",
AndroidSyncSettings.isChromeSyncEnabled(mContext));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testToggleAccountSyncFromApplication() throws InterruptedException {
// Turn on syncability.
mSyncContentResolverDelegate.setMasterSyncAutomatically(true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
enableChromeSyncOnUiThread();
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertTrue("account should be synced", AndroidSyncSettings.isSyncEnabled(mContext));
disableChromeSyncOnUiThread();
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertFalse(
"account should not be synced", AndroidSyncSettings.isSyncEnabled(mContext));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testToggleSyncabilityForMultipleAccounts() throws InterruptedException {
// Turn on syncability.
mSyncContentResolverDelegate.setMasterSyncAutomatically(true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
enableChromeSyncOnUiThread();
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertTrue("account should be synced", AndroidSyncSettings.isSyncEnabled(mContext));
updateAccount(mAlternateAccount);
enableChromeSyncOnUiThread();
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertTrue(
"alternate account should be synced", AndroidSyncSettings.isSyncEnabled(mContext));
disableChromeSyncOnUiThread();
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertFalse("alternate account should not be synced",
AndroidSyncSettings.isSyncEnabled(mContext));
updateAccount(mAccount);
Assert.assertTrue(
"account should still be synced", AndroidSyncSettings.isSyncEnabled(mContext));
// Ensure we don't erroneously re-use cached data.
updateAccount(null);
Assert.assertFalse(
"null account should not be synced", AndroidSyncSettings.isSyncEnabled(mContext));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testSyncSettingsCaching() throws InterruptedException {
// Turn on syncability.
mSyncContentResolverDelegate.setMasterSyncAutomatically(true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
enableChromeSyncOnUiThread();
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertTrue("account should be synced", AndroidSyncSettings.isSyncEnabled(mContext));
int masterSyncAutomaticallyCalls =
mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls.get();
int isSyncableCalls = mSyncContentResolverDelegate.mGetIsSyncableCalls.get();
int getSyncAutomaticallyAcalls =
mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls.get();
// Do a bunch of reads.
AndroidSyncSettings.isMasterSyncEnabled(mContext);
AndroidSyncSettings.isSyncEnabled(mContext);
AndroidSyncSettings.isChromeSyncEnabled(mContext);
// Ensure values were read from cache.
Assert.assertEquals(masterSyncAutomaticallyCalls,
mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls.get());
Assert.assertEquals(
isSyncableCalls, mSyncContentResolverDelegate.mGetIsSyncableCalls.get());
Assert.assertEquals(getSyncAutomaticallyAcalls,
mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls.get());
// Do a bunch of reads for alternate account.
updateAccount(mAlternateAccount);
AndroidSyncSettings.isMasterSyncEnabled(mContext);
AndroidSyncSettings.isSyncEnabled(mContext);
AndroidSyncSettings.isChromeSyncEnabled(mContext);
// Ensure settings were only fetched once.
Assert.assertEquals(masterSyncAutomaticallyCalls + 1,
mSyncContentResolverDelegate.mGetMasterSyncAutomaticallyCalls.get());
Assert.assertEquals(
isSyncableCalls + 1, mSyncContentResolverDelegate.mGetIsSyncableCalls.get());
Assert.assertEquals(getSyncAutomaticallyAcalls + 1,
mSyncContentResolverDelegate.mGetSyncAutomaticallyCalls.get());
}
@Test
@SmallTest
@Feature({"Sync"})
public void testGetContractAuthority() throws Exception {
Assert.assertEquals("The contract authority should be the package name.",
InstrumentationRegistry.getTargetContext().getPackageName(),
AndroidSyncSettings.getContractAuthority(mContext));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testAndroidSyncSettingsPostsNotifications() throws InterruptedException {
// Turn on syncability.
mSyncContentResolverDelegate.setMasterSyncAutomatically(true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
mSyncSettingsObserver.clearNotification();
AndroidSyncSettings.enableChromeSync(mContext);
Assert.assertTrue("enableChromeSync should trigger observers",
mSyncSettingsObserver.receivedNotification());
mSyncSettingsObserver.clearNotification();
updateAccount(mAlternateAccount);
Assert.assertTrue("switching to account with different settings should notify",
mSyncSettingsObserver.receivedNotification());
mSyncSettingsObserver.clearNotification();
updateAccount(mAccount);
Assert.assertTrue("switching to account with different settings should notify",
mSyncSettingsObserver.receivedNotification());
mSyncSettingsObserver.clearNotification();
AndroidSyncSettings.enableChromeSync(mContext);
Assert.assertFalse("enableChromeSync shouldn't trigger observers",
mSyncSettingsObserver.receivedNotification());
mSyncSettingsObserver.clearNotification();
AndroidSyncSettings.disableChromeSync(mContext);
Assert.assertTrue("disableChromeSync should trigger observers",
mSyncSettingsObserver.receivedNotification());
mSyncSettingsObserver.clearNotification();
AndroidSyncSettings.disableChromeSync(mContext);
Assert.assertFalse("disableChromeSync shouldn't observers",
mSyncSettingsObserver.receivedNotification());
}
@Test
@SmallTest
@Feature({"Sync"})
public void testIsSyncableOnSigninAndNotOnSignout()
throws InterruptedException, TimeoutException {
Assert.assertEquals(1, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority));
updateAccountWithCallback(null, (Boolean result) -> {
Assert.assertTrue(result);
mCallbackHelper.notifyCalled();
});
mCallbackHelper.waitForCallback(0, mNumberOfCallsToWait);
Assert.assertEquals(0, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority));
updateAccount(mAccount);
Assert.assertEquals(1, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority));
}
/**
* Regression test for crbug.com/475299.
*/
@Test
@SmallTest
@Feature({"Sync"})
public void testSyncableIsAlwaysSetWhenEnablingSync() throws InterruptedException {
// Setup bad state.
mSyncContentResolverDelegate.setMasterSyncAutomatically(true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
mSyncContentResolverDelegate.setIsSyncable(mAccount, mAuthority, 1);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
mSyncContentResolverDelegate.setSyncAutomatically(mAccount, mAuthority, true);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
mSyncContentResolverDelegate.setIsSyncable(mAccount, mAuthority, 0);
mSyncContentResolverDelegate.waitForLastNotificationCompleted();
Assert.assertTrue(mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority) == 0);
Assert.assertTrue(mSyncContentResolverDelegate.getSyncAutomatically(mAccount, mAuthority));
// Ensure bug is fixed.
enableChromeSyncOnUiThread();
Assert.assertEquals(1, mSyncContentResolverDelegate.getIsSyncable(mAccount, mAuthority));
// Should still be enabled.
Assert.assertTrue(mSyncContentResolverDelegate.getSyncAutomatically(mAccount, mAuthority));
}
}
| 7,331 |
5,169 | <reponame>Gantios/Specs<filename>Specs/2/9/6/MAWishfulButtonFramework/1.0.0/MAWishfulButtonFramework.podspec.json
{
"name": "MAWishfulButtonFramework",
"version": "1.0.0",
"summary": "MAWishfulButtonFramework is a user friendly, easy to integrate custon UIKit Button generator and add life to apps with subtle animations.",
"description": "With 7 category of buttons, users can generate button with text, image or combination of both. The buttons have the capability to have any shape square, rounded or circular, with or without border and shadow. It also has the gradient colored background or border unlike the usual single colored ones.",
"homepage": "https://github.com/natashamalam/MAWishfulButtonFramework",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "10.0"
},
"swift_versions": "5.0",
"source": {
"git": "https://github.com/natashamalam/MAWishfulButtonFramework.git",
"tag": "1.0.0"
},
"source_files": "MAWishfulButtonFramework/**/*",
"exclude_files": "MAWishfulButtonFramework/**/*.plist",
"swift_version": "5.0"
}
| 374 |
649 | <reponame>MaTriXy/android-data-binding-recyclerview
package net.droidlabs.mvvmdemo.viewmodel;
import net.droidlabs.mvvmdemo.model.User;
public class SuperUserViewModel extends UserViewModel
{
public SuperUserViewModel(User model)
{
super(model);
}
public String getGroup()
{
return "Droid";
}
}
| 140 |
7,353 | /**
* @file PacketPassInterface.h
* @author <NAME> <<EMAIL>>
*
* @section LICENSE
*
* 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 author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
*
* Interface allowing a packet sender to pass data packets to a packet receiver.
*/
#ifndef BADVPN_FLOW_PACKETPASSINTERFACE_H
#define BADVPN_FLOW_PACKETPASSINTERFACE_H
#include <stdint.h>
#include <stddef.h>
#include <misc/debug.h>
#include <base/DebugObject.h>
#include <base/BPending.h>
#define PPI_STATE_NONE 1
#define PPI_STATE_OPERATION_PENDING 2
#define PPI_STATE_BUSY 3
#define PPI_STATE_DONE_PENDING 4
typedef void (*PacketPassInterface_handler_send) (void *user, uint8_t *data, int data_len);
typedef void (*PacketPassInterface_handler_requestcancel) (void *user);
typedef void (*PacketPassInterface_handler_done) (void *user);
typedef struct {
// provider data
int mtu;
PacketPassInterface_handler_send handler_operation;
PacketPassInterface_handler_requestcancel handler_requestcancel;
void *user_provider;
// user data
PacketPassInterface_handler_done handler_done;
void *user_user;
// operation job
BPending job_operation;
uint8_t *job_operation_data;
int job_operation_len;
// requestcancel job
BPending job_requestcancel;
// done job
BPending job_done;
// state
int state;
int cancel_requested;
DebugObject d_obj;
} PacketPassInterface;
static void PacketPassInterface_Init (PacketPassInterface *i, int mtu, PacketPassInterface_handler_send handler_operation, void *user, BPendingGroup *pg);
static void PacketPassInterface_Free (PacketPassInterface *i);
static void PacketPassInterface_EnableCancel (PacketPassInterface *i, PacketPassInterface_handler_requestcancel handler_requestcancel);
static void PacketPassInterface_Done (PacketPassInterface *i);
static int PacketPassInterface_GetMTU (PacketPassInterface *i);
static void PacketPassInterface_Sender_Init (PacketPassInterface *i, PacketPassInterface_handler_done handler_done, void *user);
static void PacketPassInterface_Sender_Send (PacketPassInterface *i, uint8_t *data, int data_len);
static void PacketPassInterface_Sender_RequestCancel (PacketPassInterface *i);
static int PacketPassInterface_HasCancel (PacketPassInterface *i);
void _PacketPassInterface_job_operation (PacketPassInterface *i);
void _PacketPassInterface_job_requestcancel (PacketPassInterface *i);
void _PacketPassInterface_job_done (PacketPassInterface *i);
void PacketPassInterface_Init (PacketPassInterface *i, int mtu, PacketPassInterface_handler_send handler_operation, void *user, BPendingGroup *pg)
{
ASSERT(mtu >= 0)
// init arguments
i->mtu = mtu;
i->handler_operation = handler_operation;
i->handler_requestcancel = NULL;
i->user_provider = user;
// set no user
i->handler_done = NULL;
// init jobs
BPending_Init(&i->job_operation, pg, (BPending_handler)_PacketPassInterface_job_operation, i);
BPending_Init(&i->job_requestcancel, pg, (BPending_handler)_PacketPassInterface_job_requestcancel, i);
BPending_Init(&i->job_done, pg, (BPending_handler)_PacketPassInterface_job_done, i);
// set state
i->state = PPI_STATE_NONE;
DebugObject_Init(&i->d_obj);
}
void PacketPassInterface_Free (PacketPassInterface *i)
{
DebugObject_Free(&i->d_obj);
// free jobs
BPending_Free(&i->job_done);
BPending_Free(&i->job_requestcancel);
BPending_Free(&i->job_operation);
}
void PacketPassInterface_EnableCancel (PacketPassInterface *i, PacketPassInterface_handler_requestcancel handler_requestcancel)
{
ASSERT(!i->handler_requestcancel)
ASSERT(!i->handler_done)
ASSERT(handler_requestcancel)
i->handler_requestcancel = handler_requestcancel;
}
void PacketPassInterface_Done (PacketPassInterface *i)
{
ASSERT(i->state == PPI_STATE_BUSY)
DebugObject_Access(&i->d_obj);
// unset requestcancel job
BPending_Unset(&i->job_requestcancel);
// schedule done
BPending_Set(&i->job_done);
// set state
i->state = PPI_STATE_DONE_PENDING;
}
int PacketPassInterface_GetMTU (PacketPassInterface *i)
{
DebugObject_Access(&i->d_obj);
return i->mtu;
}
void PacketPassInterface_Sender_Init (PacketPassInterface *i, PacketPassInterface_handler_done handler_done, void *user)
{
ASSERT(handler_done)
ASSERT(!i->handler_done)
DebugObject_Access(&i->d_obj);
i->handler_done = handler_done;
i->user_user = user;
}
void PacketPassInterface_Sender_Send (PacketPassInterface *i, uint8_t *data, int data_len)
{
ASSERT(data_len >= 0)
ASSERT(data_len <= i->mtu)
ASSERT(!(data_len > 0) || data)
ASSERT(i->state == PPI_STATE_NONE)
ASSERT(i->handler_done)
DebugObject_Access(&i->d_obj);
// schedule operation
i->job_operation_data = data;
i->job_operation_len = data_len;
BPending_Set(&i->job_operation);
// set state
i->state = PPI_STATE_OPERATION_PENDING;
i->cancel_requested = 0;
}
void PacketPassInterface_Sender_RequestCancel (PacketPassInterface *i)
{
ASSERT(i->state == PPI_STATE_OPERATION_PENDING || i->state == PPI_STATE_BUSY || i->state == PPI_STATE_DONE_PENDING)
ASSERT(i->handler_requestcancel)
DebugObject_Access(&i->d_obj);
// ignore multiple cancel requests
if (i->cancel_requested) {
return;
}
// remember we requested cancel
i->cancel_requested = 1;
if (i->state == PPI_STATE_OPERATION_PENDING) {
// unset operation job
BPending_Unset(&i->job_operation);
// set done job
BPending_Set(&i->job_done);
// set state
i->state = PPI_STATE_DONE_PENDING;
} else if (i->state == PPI_STATE_BUSY) {
// set requestcancel job
BPending_Set(&i->job_requestcancel);
}
}
int PacketPassInterface_HasCancel (PacketPassInterface *i)
{
DebugObject_Access(&i->d_obj);
return !!i->handler_requestcancel;
}
#endif
| 2,754 |
5,169 | <reponame>Gantios/Specs
{
"name": "SmyteSDK-Test",
"version": "0.1.0",
"summary": "An SDK for integrating Smyte.com API into your iOS Project.",
"description": "This is the test framework for SmyteSDK.",
"homepage": "http://www.smyte.com",
"license": "Commercial",
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "http://github.com/Smyte/Smyte-iOS-SDK.git",
"tag": "1.0.0"
},
"source_files": [
"Classes",
"SmyteSDK.framework/**/*.*"
],
"exclude_files": "Classes/Exclude",
"pod_target_xcconfig": {
"SWIFT_VERSION": "3"
}
}
| 278 |
712 | <filename>src/Vulkan/DebugUtils.cpp
#include "DebugUtils.hpp"
#include "Utilities/Exception.hpp"
namespace Vulkan {
DebugUtils::DebugUtils(VkInstance instance)
: vkSetDebugUtilsObjectNameEXT_(reinterpret_cast<PFN_vkSetDebugUtilsObjectNameEXT>(vkGetInstanceProcAddr(instance, "vkSetDebugUtilsObjectNameEXT")))
{
#ifndef NDEBUG
if (vkSetDebugUtilsObjectNameEXT_ == nullptr)
{
Throw(std::runtime_error("failed to get address of 'vkSetDebugUtilsObjectNameEXT'"));
}
#endif
}
} | 182 |
473 | #!/usr/bin/env python
from generator.actions import Actions
import random
import struct
import ctypes
import string
MAX_USER_PLAYLISTS = 10
def kaprica_mixin(self):
if hasattr(self, 'xlat_seed'):
return
def xlat_seed(seed):
def hash_string(seed):
H = 0x314abc86
for c in seed:
H = (H * 37) & 0xffffffff
H ^= ord(c)
H = ((H << 13) ^ (H >> 19)) & 0xffffffff
return H
def hash_iterate(H):
H = (H * 3) & 0xffffffff
H = ((H << 13) ^ (H >> 19) ^ (H >> 21)) & 0xffffffff
return H
xmap = list(xrange(256))
xmap_inv = list(xrange(256))
state = hash_string(seed)
for i in xrange(255, 0, -1):
j = state % i
state = hash_iterate(state)
xmap[i], xmap[j] = xmap[j], xmap[i]
for i in xrange(256):
xmap_inv[xmap[i]] = i
self.xlat_map = xmap
self.xlat_map_inv = xmap_inv
self.xlat_seed = xlat_seed
self.xlat_map = None
self.xlat_map_inv = None
def xlat_string(s, inverse=False):
if inverse:
return ''.join([chr(self.xlat_map_inv[ord(c)]) for c in s])
return ''.join([chr(self.xlat_map[ord(c)]) for c in s])
self.xlat_string = xlat_string
def read(delim=None, length=None, expect=None):
if self.xlat_map:
if delim:
delim = self.xlat_string(delim)
if expect:
expect = self.xlat_string(expect)
return self._original_read(delim=delim, length=length, expect=expect)
self._original_read = self.read
self.read = read
def write(s):
if self.xlat_map:
if s:
s = self.xlat_string(s)
return self._original_write(s)
self._original_write = self.write
self.write = write
def random_word(max_size=8, min_size=3):
if random.randint(0,4):
characters = string.letters + string.digits
else:
characters = string.letters
max_size = max_size if max_size >= min_size else min_size
max_size = random.randint(min_size, max_size)
word = ("".join(random.choice(characters) for c in range(max_size))).upper()
return word
def random_text(pad_size=0, max_words=5, min_words=1):
max_words = max_words if max_words >= min_words else min_words
text = ''
for x in xrange(random.randint(min_words, max_words)):
text += random_word() + ' '
if not pad_size:
return text
text = text[:pad_size] if len(text) >= pad_size else text + '\x00' * (pad_size - len(text))
return text
def random_file_name():
filename = ''
for x in xrange(random.randint(0,5)):
filename += '/' + random_filename()
return filename
pack_str = lambda x: struct.pack("{0}s".format(len(x)), x)
pack_bytes = lambda x: struct.pack("{0}B".format(len(x)), *x)
byte_str = lambda x: "\\x%02x" % int(x)
class SongTag(object):
def __init__(self, song_id, title=None, artist=None, album=None, year=None, comment=None):
self.header = "CTG"
self.title = title if title else random_text(pad_size=30)
self.artist = artist if artist else random_text(pad_size=30)
self.album = album if album else random_text(pad_size=30)
self.year = year if year else 1970 + random.randint(0,45)
self.comment = comment if comment else random_text(pad_size=30)
self.has_track = '\x00'
self.track = random.randint(1,20)
self.unused = '\x00'
self.song_id = song_id
def serialize(self):
tag_ser = pack_str(self.header)
tag_ser += pack_str(self.title)
tag_ser += pack_str(self.artist)
tag_ser += pack_str(self.album)
tag_ser += struct.pack('H', self.year)
tag_ser += pack_str(self.comment)
tag_ser += pack_str(self.has_track)
tag_ser += struct.pack('b', self.track)
tag_ser += pack_str(self.unused)
return tag_ser
@classmethod
def random(cls, song_id, all_songs):
if (len(all_songs) and random.randint(0,4) == 0):
song = all_songs[random.randint(0, len(all_songs) -1)]
matched_field_choice = random.randint(0,1)
if matched_field_choice == 0:
return cls(song_id, artist=song.tag.artist)
elif matched_field_choice == 1:
return cls(song_id, artist=song.tag.artist, album=song.tag.album, year=song.tag.year)
else:
return cls(song_id)
bitrates = [0, 320000, 256000, 224000, 192000, 160000, 128000, 112000, 96000, 80000, 64000, 56000, 48000, 40000, 32000]
freqs = [44100, 48000, 32000]
class SongFrame(object):
def __init__(self, layer, sfreq, num_frames_left):
self.hdr = [0xFF, 0xF0, 0x00]
self.hdr[1] |= 0x08
self.hdr[1] |= layer << 1
self.hdr[2] |= random.randint(1,14) << 4
self.hdr[2] |= sfreq << 2
self.num_frames_left = num_frames_left
self.data = []
data_len = (self.samples_per_frame() / 8 * self.bitrate()) / self.freq()
data_len = data_len if data_len % 4 == 0 else data_len + (4 - (data_len % 4))
for x in xrange(data_len):
self.data.append(random.randint(0,255))
def layer(self):
return (self.hdr[1] & 0x06) >> 1
def samples_per_frame(self):
if (self.layer()) == 1:
return 384
if (self.layer()) == 2:
return 1152
if (self.layer()) == 3:
return 1152
return 0
def bitrate(self):
return bitrates[(self.hdr[2] & 0xF0) >> 4]
def freq(self):
return freqs[(self.hdr[2] & 0x0C) >> 2]
def serialize(self):
frame_ser = pack_bytes(self.hdr)
frame_ser += struct.pack('H', self.num_frames_left)
frame_ser += pack_bytes(self.data)
return frame_ser
@classmethod
def random(cls):
song_frames = []
num_frames_left = random.randint(1,10)
layer = random.randint(1,3)
sfreq = random.randint(0,2)
for x in reversed(xrange(num_frames_left)):
song_frames.append(cls(layer, sfreq, x))
return song_frames
class Song(object):
def __init__(self, tag, frames):
self.tag = tag
self.frames = frames
def remix_song(self, state, magic_page):
idx = state['remix_idx']
for i in xrange(len(self.frames)):
for j in xrange(len(self.frames[i].data)):
multiplier = struct.unpack('<B', magic_page[idx])[0]
data_val = self.frames[i].data[j]
data_val = (data_val * multiplier) % 256
self.frames[i].data[j] = data_val
idx = (idx + 33) % 4096
state['remix_idx'] = idx
def serialize(self):
song_ser = ''
for frame in self.frames:
song_ser += frame.serialize()
song_ser += self.tag.serialize()
return song_ser
def read_song(self, read_fn):
read_fn("Song ID: %d\x02" % self.tag.song_id)
read_fn("Title: %s\x02" % self.tag.title)
read_fn("Artist: %s\x02" % self.tag.artist)
read_fn("Album: %s\x02" % self.tag.album)
read_fn("Year: %d\x02" % self.tag.year)
read_fn("Track #: %d\x02" % self.tag.track)
read_fn("----------\x02")
def read_frames(self, read_fn):
read_fn("---Raw Frames---\x02")
for frame in self.frames:
for x in frame.data:
read_fn(byte_str(x))
read_fn("\x02----------------\x02")
@classmethod
def random(cls, song_id, all_songs):
return cls(SongTag.random(song_id, all_songs), SongFrame.random())
class Playlist(object):
def __init__(self):
self.songs = []
def add_song(self, song):
self.songs.append(song)
def remove_song(self, song_id):
for i in xrange(len(self.songs)):
if self.songs[i].tag.song_id == song_id:
self.songs.pop(i)
return True
return False
def find_song(self, song_id):
for i in xrange(len(self.songs)):
if self.songs[i].tag.song_id == song_id:
return self.songs[i]
return None
def remix_song(self, song_id, state, magic_page):
for i in xrange(len(self.songs)):
if self.songs[i].tag.song_id == song_id:
self.songs[i].remix_song(state, magic_page)
return True
return False
def read_songs(self, read_fn):
for song in self.songs:
song.read_song(read_fn)
def read_song_frames(self, song_idx, read_fn):
song = self.find_song(song_idx)
if song:
song.read_frames(read_fn)
def read_playlist(self, read_fn, playlist_id):
read_fn("Playlist ID: %d\x02" % playlist_id)
read_fn("Number of songs added to playlist: %d\x02" % len(self.songs))
class OneAmp(Actions):
def _read(self, data):
self.read(length=len(data), expect=data)
def start(self):
#self.delay(100)
kaprica_mixin(self)
self.xlat_seed('393748225')
self.state['remix_idx'] = ctypes.c_uint32(struct.unpack('<B', self.magic_page[2])[0]).value
self._playlists = []
self._master_playlist = Playlist()
self._cur_playlist = self._master_playlist
self._song_id_idx = 0
self._read("--One Amp--\x02")
self._read("\x02\x02")
def master_menu(self):
self._read("Main Menu:\x02")
self._read("1. Add Song To Library\x02")
self._read("2. Delete Song From Library\x02")
self._read("3. Select Playlist\x02")
self._read("4. List Songs\x02")
self._read("5. Sort By Song ID (Default Sort)\x02")
self._read("6. Sort By Song Title\x02")
self._read("7. Sort By Artist and Album\x02")
self._read("8. Sort By Artist and Song Title\x02")
self._read("9. Sort By Album\x02")
self._read("10. Sort By Album and Song Title\x02")
self._read("11. Remix Track\x02")
self._read("12. Create Playlist\x02")
self._read("13. Delete Playlist\x02")
self._read("14. List Playlists\x02")
self._read("15. Exit\x02")
self._read("[::] ")
def playlist_menu(self):
self._read("Main Menu:\x02")
self._read("1. Add Song To Playlist\x02")
self._read("2. Delete Song From Playlist\x02")
self._read("3. Return to Main Library\x02")
self._read("4. List Songs\x02")
self._read("5. Sort By Song ID (Default Sort)\x02")
self._read("6. Sort By Song Title\x02")
self._read("7. Sort By Artist and Album\x02")
self._read("8. Sort By Artist and Song Title\x02")
self._read("9. Sort By Album\x02")
self._read("10. Sort By Album and Song Title\x02")
self._read("11. Remix Track\x02")
self._read("12. List All Songs In Library\x02")
self._read("13. Exit\x02")
self._read("[::] ")
def master_add_song(self):
self.write('1\x02')
song = Song.random(self._song_id_idx, self._master_playlist.songs)
self._song_id_idx += 1
self._master_playlist.add_song(song)
self.write(song.serialize())
self._read("Added song to library\x02")
def master_remove_song(self):
self.write('2\x02')
self._read("Enter Song ID to delete from library\x02")
self._read("[::] ")
song_idx = random.randint(0, 2*len(self._master_playlist.songs))
self.write('{0}\x02'.format(song_idx))
if self._master_playlist.remove_song(song_idx):
for x in xrange(len(self._playlists)):
self._playlists[x].remove_song(song_idx)
self._read("Successfully removed song from library\x02")
else:
self._read("Could not remove song from library\x02")
def master_select_playlist(self):
self.write('3\x02')
self._read("Select Playlist ID\x02")
self._read("[::] ")
if not len(self._playlists):
self.write('0\x02')
self._read("Bad Playlist ID\x02")
self.master_menu()
self.master_create_new_playlist()
self.master_menu()
self.write('3\x02')
self._read("Select Playlist ID\x02")
self._read("[::] ")
playlist_idx = random.randint(0, len(self._playlists) - 1)
self.write('{0}\x02'.format(playlist_idx))
self._cur_playlist = self._playlists[playlist_idx]
def playlist_add_song(self):
self.write('1\x02')
self._read("Enter Song ID to add to playlist\x02")
self._read("[::] ")
song_idx = random.randint(0, len(self._master_playlist.songs) + 10)
self.write('{0}\x02'.format(song_idx))
song = self._master_playlist.find_song(song_idx)
already_added = self._cur_playlist.find_song(song_idx)
if song and not already_added:
self._cur_playlist.add_song(song)
self._read("Added song to playlist\x02")
else:
self._read("Could not add song to playlist\x02")
def playlist_delete_song(self):
self.write('2\x02')
self._read("Enter Song ID to delete from playlist\x02")
self._read("[::] ")
if len(self._cur_playlist.songs) and random.randint(0,3) == 0:
song_idx = self._cur_playlist.songs[random.randint(0, len(self._cur_playlist.songs)-1)].tag.song_id
else:
song_idx = random.randint(0, 2*len(self._master_playlist.songs))
self.write('{0}\x02'.format(song_idx))
if self._cur_playlist.remove_song(song_idx):
self._read("Successfully removed song from playlist\x02")
else:
self._read("Could not remove song from playlist\x02")
def playlist_select_master(self):
self.write('3\x02')
self._cur_playlist = self._master_playlist
def list_all_songs(self):
self.write('4\x02')
self._cur_playlist.read_songs(self._read)
def sort_playlist_by_song_id(self):
self.write('5\x02')
self._cur_playlist.songs.sort(key=lambda song: song.tag.song_id)
self._read("Successfully sorted list by Song ID\x02")
def sort_playlist_by_song_title(self):
self.write('6\x02')
self._cur_playlist.songs.sort(key=lambda song: song.tag.title)
self._read("Successfully sorted list by Song Title\x02")
def remix_song(self):
self.write('11\x02')
self._read("Enter Song ID to remix\x02")
self._read("[::] ")
song_idx = random.randint(0, 2*len(self._master_playlist.songs))
self.write('{0}\x02'.format(song_idx))
if self._cur_playlist.find_song(song_idx):
self._read("Original Track Data:\x02")
self._master_playlist.read_song_frames(song_idx, self._read)
self._master_playlist.remix_song(song_idx, self.state, self.magic_page)
self._read("Successfully remixed song\x02")
self._read("Printing New Track Data:\x02")
self._master_playlist.read_song_frames(song_idx, self._read)
else:
self._read("Could not remix track\x02")
def master_create_new_playlist(self):
self.write('12\x02')
if len(self._playlists) < MAX_USER_PLAYLISTS:
self._read("Created a new playlist with ID [%d]\x02" % len(self._playlists))
self._playlists.append(Playlist())
else:
self._read("Maximum number of playlists reached\x02")
def master_delete_playlist(self):
self.write('13\x02')
self._read("Enter Playlist ID to delete")
self._read("[::] ")
playlist_idx = random.randint(0, 2*len(self._playlists))
self.write('{0}\x02'.format(playlist_idx))
if playlist_idx < len(self._playlists):
self._playlists.pop(playlist_idx)
self._read("Deleted Playlist ID: %d\x02" % playlist_idx)
else:
self._read("Bad Playlist ID\x02")
def master_print_all_playlists(self):
self.write('14\x02')
for idx, playlist in enumerate(self._playlists):
playlist.read_playlist(self._read, idx)
def playlist_all_library_songs(self):
self.write('12\x02')
self._master_playlist.read_songs(self._read)
def exit(self):
if self._cur_playlist == self._master_playlist:
self.write('15\x02')
else:
self.write('13\x02')
self._read("--Exited One Amp--\x02")
def master_list_all_songs(self):
self.list_all_songs()
def master_sort_playlist_by_song_id(self):
self.sort_playlist_by_song_id()
def master_sort_playlist_by_song_title(self):
self.sort_playlist_by_song_title()
def master_remix_song(self):
self.remix_song()
def playlist_sort_playlist_by_song_id(self):
self.sort_playlist_by_song_id()
def playlist_sort_playlist_by_song_title(self):
self.sort_playlist_by_song_title()
def playlist_remix_song(self):
self.remix_song()
| 8,287 |
988 | package com.mojang.datafixers.util;
import java.util.function.BiFunction;
import java.util.function.Function;
public interface Function4<T1, T2, T3, T4, R> {
R apply(T1 t1, T2 t2, T3 t3, T4 t4);
default Function<T1, Function3<T2, T3, T4, R>> curry() {
return t1 -> (t2, t3, t4) -> apply(t1, t2, t3, t4);
}
default BiFunction<T1, T2, BiFunction<T3, T4, R>> curry2() {
return (t1, t2) -> (t3, t4) -> apply(t1, t2, t3, t4);
}
default Function3<T1, T2, T3, Function<T4, R>> curry3() {
return (t1, t2, t3) -> t4 -> apply(t1, t2, t3, t4);
}
}
| 299 |
562 | #include <ecos/ecos.h>
#include <stdio.h>
int main(void) {
printf("ECOS version %s\n", ECOS_ver());
return 0;
}
| 58 |
2,151 | // Copyright 2018 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 IOS_CHROME_BROWSER_UI_TABLE_VIEW_TABLE_VIEW_ANIMATOR_H_
#define IOS_CHROME_BROWSER_UI_TABLE_VIEW_TABLE_VIEW_ANIMATOR_H_
#import <UIKit/UIKit.h>
// TableViewAnimator implements an animation that slides the presented view in
// from the trailing edge of the screen.
@interface TableViewAnimator : NSObject<UIViewControllerAnimatedTransitioning>
// YES if this animator is presenting a view controller, NO if it is dismissing
// one.
@property(nonatomic, assign) BOOL presenting;
@end
#endif // IOS_CHROME_BROWSER_UI_TABLE_VIEW_TABLE_VIEW_ANIMATOR_H_
| 234 |
4,313 | {
"compilerOptions": {
"strict": true,
"sourceMap": true,
"target": "ES2018",
"alwaysStrict": true,
"outDir": "../out"
},
"files": [
"background.ts",
"debuggee.ts",
"interception.ts",
"request.ts",
"load.ts",
],
} | 114 |
310 | <gh_stars>100-1000
{
"name": "YoruFukurou",
"description": "A Twitter client for the Mac.",
"url": "https://sites.google.com/site/yorufukurou/"
} | 61 |
575 | <gh_stars>100-1000
// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file BuiltinTopicKey.hpp
*
*/
#ifndef FASTDDS_DDS_BUILTIN_TOPIC_BUILTINTOPICKEY_HPP
#define FASTDDS_DDS_BUILTIN_TOPIC_BUILTINTOPICKEY_HPP
#include <stdint.h>
namespace eprosima {
namespace fastdds {
namespace dds {
namespace builtin {
// following API definition:
// #define BUILTIN_TOPIC_KEY_TYPE_NATIVE uint32_t
struct BuiltinTopicKey_t
{
// BUILTIN_TOPIC_KEY_TYPE_NATIVE = long type
//!Value
uint32_t value[3];
};
} // builtin
} // dds
} // fastdds
} // eprosima
#endif // FASTDDS_DDS_BUILTIN_TOPIC_BUILTINTOPICKEY_HPP
| 429 |
348 | <gh_stars>100-1000
{"nom":"Vieux","circ":"6ème circonscription","dpt":"Calvados","inscrits":513,"abs":227,"votants":286,"blancs":40,"nuls":12,"exp":234,"res":[{"nuance":"REM","nom":"<NAME>","voix":171},{"nuance":"FN","nom":"<NAME>","voix":63}]} | 98 |
461 | <filename>habu/cli/cmd_config_show.py
#!/usr/bin/env python3
import json
import click
from habu.lib.loadcfg import loadcfg
@click.command()
@click.option('-k', '--show-keys', is_flag=True, default=False, help='Show also the key values')
@click.option('--option', nargs=2, help='Write to the config(KEY VALUE)')
def cmd_config_show(option, show_keys):
"""Show the current config.
Note: By default, the options with 'KEY' in their name are shadowed.
Example:
\b
$ habu.config.show
{
"DNS_SERVER": "8.8.8.8",
"FERNET_KEY": "*************"
}
"""
habucfg = loadcfg()
if not show_keys:
for key in habucfg.keys():
if 'KEY' in key:
habucfg[key] = '*************'
print(json.dumps(habucfg, indent=4, sort_keys=True, default=str))
if __name__ == '__main__':
cmd_config_show()
| 377 |
1,275 | <filename>sdk/tests/c_tests/readdir_test.c
/*
* Amazon FPGA Hardware Development Kit
*
* Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Amazon Software License (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/asl/
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
* implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fpga_pci.h>
#include <fpga_mgmt.h>
#include <utils/lcd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fpga_mgmt_tests.h"
static void *test_slot_spec(void *arg);
static void *test_all_slot_specs(void *arg);
struct thread
{
/* thread information */
pthread_t thread;
int id;
/* thread arguments */
struct fpga_slot_spec *spec_array;
int slot;
/* thread result */
int rc;
char message[256];
};
/* copied from fpga_pci_sysfs.c */
#if defined(_BSD_SOURCE) || defined(_SVID_SOURCE)
# define USE_READDIR_R
#endif
int fpga_mgmt_test_readdir(unsigned int num_threads)
{
int rc;
int num_slots;
struct thread *threads = NULL;
#if defined(USE_READDIR_R)
log_info("Using readdir_r because glibc is old.");
#else
log_info("Using readdir because readdir_r is deprecated.");
#endif
struct fpga_slot_spec spec_array[FPGA_SLOT_MAX];
memset(spec_array, 0, sizeof(spec_array));
rc = fpga_pci_get_all_slot_specs(spec_array, sizeof_array(spec_array));
fail_on(rc, out, "fpga_pci_get_all_slot_specs failed");
num_slots = FPGA_SLOT_MAX;
for (int i = 0; i < FPGA_SLOT_MAX; ++i) {
if (spec_array[i].map[FPGA_APP_PF].vendor_id == 0) {
num_slots = i;
break;
}
}
if (num_threads == 0) {
num_threads = 512;
}
if (num_threads > 4096) {
num_threads = 4096;
}
threads = calloc(num_threads, sizeof(struct thread));
void *(*thread_start_funcs[2])(void *) = {
test_slot_spec, test_all_slot_specs };
for (int i = 0; i < num_threads; ++i) {
threads[i].id = i;
threads[i].spec_array = spec_array;
threads[i].slot = (i % (num_slots * 2)) / 2;
rc = pthread_create(&threads[i].thread, NULL, thread_start_funcs[i % 2],
&threads[i]);
fail_on(rc, out, "failed to create a thread");
}
bool test_passed = true;
for (int i = 0; i < num_threads; ++i) {
void *thread_result;
rc = pthread_join(threads[i].thread, &thread_result);
fail_on(rc, out, "pthread_join failed");
if (&threads[i] != thread_result) {
log_error("the result wasn't expected on # %d\n", i);
}
struct thread *thread = thread_result;
if (thread->rc != 0) {
log_error("thread id: %d failed with: %s\n", thread->id,
thread->message);
test_passed = false;
}
}
log_info("test completed with %d threads, result: %s\n", num_threads,
(test_passed) ? "passed" : "failed");
if (!test_passed) {
rc = -1;
}
out:
if (threads != NULL) {
free(threads);
}
return rc;
}
static void show_slot_spec(struct fpga_slot_spec *spec, char *message, int size)
{
snprintf(message, size, "dbdf: %04x:%02x:%02x.%x\n", (int) spec->map[0].domain,
(int) spec->map[0].bus, (int) spec->map[0].dev, (int) spec->map[0].func);
}
static void *test_slot_spec(void *arg)
{
int rc;
struct fpga_slot_spec spec;
struct thread *thread = arg;
rc = fpga_pci_get_slot_spec(thread->slot, &spec);
if (rc != 0) {
snprintf(thread->message, sizeof(thread->message),
"unabled to read slot spec on slot %d", thread->slot);
goto out;
}
if (memcmp(&spec, &thread->spec_array[thread->slot], sizeof(spec)) != 0) {
rc = -1;
show_slot_spec(&spec, thread->message, sizeof(thread->message));
}
out:
thread->rc = rc;
return thread;
}
static void *test_all_slot_specs(void *arg)
{
int rc;
struct thread *thread = arg;
struct fpga_slot_spec spec_array[FPGA_SLOT_MAX];
memset(spec_array, 0, sizeof(spec_array));
rc = fpga_pci_get_all_slot_specs(spec_array, sizeof_array(spec_array));
if (rc != 0) {
snprintf(thread->message, sizeof(thread->message),
"unabled to read all slot specs");
goto out;
}
if (memcmp(spec_array, thread->spec_array, sizeof(spec_array)) != 0) {
rc = -1;
snprintf(thread->message, sizeof(thread->message),
"slot spec array failed comparison test");
}
out:
thread->rc = rc;
return thread;
}
| 2,149 |
988 | <reponame>JoachimRohde/netbeans
/*
* 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.api.db.sql.support;
import org.junit.Test;
import org.netbeans.api.db.sql.support.SQLIdentifiers.Quoter;
import static org.junit.Assert.*;
public class SQLIdentifiersTest {
@Test
public void testQuoterFromNull() {
// Without DatabaseMetaData a fallback quoter is returned, that
// unquotes all popular identifier quotes (SQL-99, mssql and mysql) and
// quotes with SQL-99 quotes (")
Quoter quoter = SQLIdentifiers.createQuoter(null);
assertNotNull(quoter);
assertEquals("hello\"", quoter.unquote("hello\""));
assertEquals("\"hello", quoter.unquote("\"hello"));
assertEquals("hello", quoter.unquote("\"hello\""));
assertEquals("hello`", quoter.unquote("hello`"));
assertEquals("`hello", quoter.unquote("`hello"));
assertEquals("hello", quoter.unquote("`hello`"));
assertEquals("hello]", quoter.unquote("hello]"));
assertEquals("[hello", quoter.unquote("[hello"));
assertEquals("hello", quoter.unquote("[hello]"));
assertEquals("hello", quoter.quoteIfNeeded("hello"));
assertEquals("\"hello world\"", quoter.quoteIfNeeded("hello world"));
assertEquals("\"hello\"", quoter.quoteAlways("hello"));
}
}
| 715 |
3,266 | <reponame>DanielMabadeje/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials<filename>java/java2py/antlr-3.1.3/runtime/ObjC/Framework/examples/treerewrite/TreeRewriteParser.h
// $ANTLR 3.1b1 TreeRewrite.g 2007-11-04 03:34:43
#import <Cocoa/Cocoa.h>
#import <ANTLR/ANTLR.h>
#pragma mark Tokens
#define TreeRewriteParser_INT 4
#define TreeRewriteParser_WS 5
#define TreeRewriteParser_EOF -1
#pragma mark Dynamic Global Scopes
#pragma mark Dynamic Rule Scopes
#pragma mark Rule Return Scopes
@interface TreeRewriteParser_rule_return : ANTLRParserRuleReturnScope {
id tree;
}
- (id) tree;
- (void) setTree:(id)aTree;
@end
@interface TreeRewriteParser_subrule_return : ANTLRParserRuleReturnScope {
id tree;
}
- (id) tree;
- (void) setTree:(id)aTree;
@end
@interface TreeRewriteParser : ANTLRParser {
id<ANTLRTreeAdaptor> treeAdaptor;
}
- (TreeRewriteParser_rule_return *) rule;
- (TreeRewriteParser_subrule_return *) subrule;
- (id<ANTLRTreeAdaptor>) treeAdaptor;
- (void) setTreeAdaptor:(id<ANTLRTreeAdaptor>)theTreeAdaptor;
@end | 413 |
1,217 | <gh_stars>1000+
#pragma once
#include "OpenGL/OpenGLGraphicsManager.hpp"
#include "OpenGL/OpenGLPipelineStateManager.hpp"
namespace My {
GraphicsManager* g_pGraphicsManager =
static_cast<GraphicsManager*>(new OpenGLGraphicsManager);
IPipelineStateManager* g_pPipelineStateManager =
static_cast<IPipelineStateManager*>(new OpenGLPipelineStateManager);
} // namespace My
| 125 |
981 | <gh_stars>100-1000
/*******************************************************************
* File automatically generated by rebuild_wrappers.py (v2.1.0.16) *
*******************************************************************/
#ifndef __wrappedlibmDEFS_H_
#define __wrappedlibmDEFS_H_
#endif // __wrappedlibmDEFS_H_
| 85 |
785 | <reponame>itzujun/Baby<gh_stars>100-1000
package com.ozj.baby.mvp.views.home.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.avos.avoscloud.AVAnalytics;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ozj.baby.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* Created by YX201603-6 on 2016/4/27.
*/
public class DetailFragment extends Fragment implements RequestListener<String, GlideDrawable> {
@BindView(R.id.iv_photo)
ImageView ivPhoto;
private String mImgUrl;
private Unbinder unbinder;
public static DetailFragment newInstance(String url) {
Bundle args = new Bundle();
args.putString("mImgUrl", url);
DetailFragment fragment = new DetailFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mImgUrl = getArguments().getString("mImgUrl");
}
}
@Override
public void onResume() {
super.onResume();
Glide.with(getActivity()).load(mImgUrl).diskCacheStrategy(DiskCacheStrategy.ALL).listener(this).into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
AVAnalytics.onFragmentStart("DetailFragment");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail_zoom, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onPause() {
super.onPause();
AVAnalytics.onFragmentEnd("DetailFragment");
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return true;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
ivPhoto.setImageDrawable(resource);
return true;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
public ImageView getSharedElement() {
return ivPhoto;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@OnClick(R.id.iv_photo)
public void onClick() {
getActivity().onBackPressed();
}
}
| 1,200 |
1,438 | <reponame>YunWisdom/Dex
package com.dexvis.util;
public class ConsoleLogger
{
public void println(String msg)
{
System.err.println(msg);
}
}
| 62 |
3,793 | /*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr <NAME> < >, Worcester, UK.
All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 24/01/2003
This is the header file for an implementation of a random data pool based on
the use of an external entropy function (inspired by <NAME> work).
*/
#ifndef _PRNG_H
#define _PRNG_H
#include "sha1.h"
#define PRNG_POOL_LEN 256 /* minimum random pool size */
#define PRNG_MIN_MIX 20 /* min initial pool mixing iterations */
/* ensure that pool length is a multiple of the SHA1 digest size */
#define PRNG_POOL_SIZE (SHA1_DIGEST_SIZE * (1 + (PRNG_POOL_LEN - 1) / SHA1_DIGEST_SIZE))
#if defined(__cplusplus)
extern "C"
{
#endif
/* A function for providing entropy is a parameter in the prng_init() */
/* call. This function has the following form and returns a maximum */
/* of 'len' bytes of pseudo random data in the buffer 'buf'. It can */
/* return less than 'len' bytes but will be repeatedly called for more */
/* data in this case. */
typedef int (*prng_entropy_fn)(unsigned char buf[], unsigned int len);
typedef struct
{ unsigned char rbuf[PRNG_POOL_SIZE]; /* the random pool */
unsigned char obuf[PRNG_POOL_SIZE]; /* pool output buffer */
unsigned int pos; /* output buffer position */
prng_entropy_fn entropy; /* entropy function pointer */
} prng_ctx;
/* initialise the random stream generator */
void prng_init(prng_entropy_fn fun, prng_ctx ctx[1]);
/* obtain random bytes from the generator */
void prng_rand(unsigned char data[], unsigned int data_len, prng_ctx ctx[1]);
/* close the random stream generator */
void prng_end(prng_ctx ctx[1]);
#if defined(__cplusplus)
}
#endif
#endif
| 953 |
313 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.testkit.model.eviction;
import java.util.Collections;
import java.util.List;
import com.netflix.titus.api.jobmanager.model.job.Job;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor.JobDescriptorExt;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.AvailabilityPercentageLimitDisruptionBudgetPolicy;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.Day;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudgetPolicy;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudgetRate;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.PercentagePerHourDisruptionBudgetRate;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.RatePerIntervalDisruptionBudgetRate;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.RatePercentagePerIntervalDisruptionBudgetRate;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.RelocationLimitDisruptionBudgetPolicy;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.SelfManagedDisruptionBudgetPolicy;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.TimeWindow;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.UnhealthyTasksLimitDisruptionBudgetPolicy;
import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.UnlimitedDisruptionBudgetRate;
import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt;
import com.netflix.titus.testkit.model.job.JobDescriptorGenerator;
import com.netflix.titus.testkit.model.job.JobGenerator;
public final class DisruptionBudgetGenerator {
public static AvailabilityPercentageLimitDisruptionBudgetPolicy percentageOfHealthyPolicy(double percentage) {
return AvailabilityPercentageLimitDisruptionBudgetPolicy.newBuilder()
.withPercentageOfHealthyContainers(percentage)
.build();
}
public static UnhealthyTasksLimitDisruptionBudgetPolicy numberOfHealthyPolicy(int limit) {
return UnhealthyTasksLimitDisruptionBudgetPolicy.newBuilder()
.withLimitOfUnhealthyContainers(limit)
.build();
}
public static RelocationLimitDisruptionBudgetPolicy perTaskRelocationLimitPolicy(int limit) {
return RelocationLimitDisruptionBudgetPolicy.newBuilder()
.withLimit(limit)
.build();
}
public static SelfManagedDisruptionBudgetPolicy selfManagedPolicy(long relocationTimeMs) {
return SelfManagedDisruptionBudgetPolicy.newBuilder()
.withRelocationTimeMs(relocationTimeMs)
.build();
}
public static PercentagePerHourDisruptionBudgetRate hourlyRatePercentage(int rate) {
return PercentagePerHourDisruptionBudgetRate.newBuilder()
.withMaxPercentageOfContainersRelocatedInHour(rate)
.build();
}
public static RatePerIntervalDisruptionBudgetRate ratePerInterval(long intervalMs, int rate) {
return RatePerIntervalDisruptionBudgetRate.newBuilder()
.withIntervalMs(intervalMs)
.withLimitPerInterval(rate)
.build();
}
public static RatePercentagePerIntervalDisruptionBudgetRate ratePercentagePerInterval(long intervalMs, double percentageRate) {
return RatePercentagePerIntervalDisruptionBudgetRate.newBuilder()
.withIntervalMs(intervalMs)
.withPercentageLimitPerInterval(percentageRate)
.build();
}
public static UnlimitedDisruptionBudgetRate unlimitedRate() {
return UnlimitedDisruptionBudgetRate.newBuilder().build();
}
public static TimeWindow officeHourTimeWindow() {
return TimeWindow.newBuilder()
.withDays(Day.weekdays())
.withwithHourlyTimeWindows(8, 17)
.withTimeZone("PST")
.build();
}
public static DisruptionBudget budget(DisruptionBudgetPolicy policy,
DisruptionBudgetRate rate,
List<TimeWindow> timeWindows) {
return DisruptionBudget.newBuilder()
.withDisruptionBudgetPolicy(policy)
.withDisruptionBudgetRate(rate)
.withContainerHealthProviders(Collections.emptyList())
.withTimeWindows(timeWindows)
.build();
}
public static DisruptionBudget budgetSelfManagedBasic() {
return budget(selfManagedPolicy(60_000), unlimitedRate(), Collections.emptyList());
}
public static JobDescriptor<BatchJobExt> newBatchJobDescriptor(int desired, DisruptionBudget budget) {
return JobDescriptorGenerator.batchJobDescriptor(desired).toBuilder()
.withDisruptionBudget(budget)
.build();
}
public static Job<BatchJobExt> newBatchJob(int desired, DisruptionBudget budget) {
return JobGenerator.batchJobs(newBatchJobDescriptor(desired, budget)).getValue();
}
public static <E extends JobDescriptorExt> JobDescriptor<E> exceptBudget(JobDescriptor<E> jobDescriptor, DisruptionBudget budget) {
return jobDescriptor.toBuilder().withDisruptionBudget(budget).build();
}
public static <E extends JobDescriptorExt> Job<E> exceptBudget(Job<E> job, DisruptionBudget budget) {
return job.toBuilder().withJobDescriptor(exceptBudget(job.getJobDescriptor(), budget)).build();
}
public static <E extends JobDescriptorExt> JobDescriptor<E> exceptPolicy(JobDescriptor<E> jobDescriptor, DisruptionBudgetPolicy policy) {
return exceptBudget(jobDescriptor, jobDescriptor.getDisruptionBudget().toBuilder().withDisruptionBudgetPolicy(policy).build());
}
public static <E extends JobDescriptorExt> Job<E> exceptPolicy(Job<E> job, DisruptionBudgetPolicy policy) {
return exceptBudget(job, job.getJobDescriptor().getDisruptionBudget().toBuilder().withDisruptionBudgetPolicy(policy).build());
}
public static <E extends JobDescriptorExt> JobDescriptor<E> exceptRate(JobDescriptor<E> jobDescriptor, DisruptionBudgetRate rate) {
return exceptBudget(jobDescriptor, jobDescriptor.getDisruptionBudget().toBuilder().withDisruptionBudgetRate(rate).build());
}
public static <E extends JobDescriptorExt> Job<E> exceptRate(Job<E> job, DisruptionBudgetRate rate) {
return exceptBudget(job, job.getJobDescriptor().getDisruptionBudget().toBuilder().withDisruptionBudgetRate(rate).build());
}
}
| 2,654 |
1,056 | <filename>ide/editor.document/src/org/netbeans/modules/editor/lib2/document/DocumentInternalUtils.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.netbeans.modules.editor.lib2.document;
import javax.swing.text.Document;
import javax.swing.text.Element;
import org.netbeans.lib.editor.util.CharSequenceUtilities;
/**
*
* @author <NAME>
*/
public class DocumentInternalUtils {
private DocumentInternalUtils() {
// no instances
}
public static Element customElement(Document doc, int startOffset, int endOffset) {
return new CustomRootElement(doc, startOffset, endOffset);
}
private static final class CustomElement extends AbstractPositionElement {
CustomElement(Element parent, int startOffset, int endOffset) {
super(parent, startOffset, endOffset);
CharSequenceUtilities.checkIndexesValid(startOffset, endOffset,
parent.getDocument().getLength() + 1);
}
@Override
public String getName() {
return "CustomElement";
}
}
private static final class CustomRootElement extends AbstractRootElement<CustomElement> {
private final CustomElement customElement;
public CustomRootElement(Document doc, int startOffset, int endOffset) {
super(doc);
customElement = new CustomElement(this, startOffset, endOffset);
}
@Override
public String getName() {
return "CustomRootElement";
}
@Override
public Element getElement(int index) {
if (index == 0) {
return customElement;
} else {
return null;
}
}
@Override
public int getElementCount() {
return 1;
}
}
}
| 912 |
396 | import logging
import traceback
import requests
import settings
from functions.smtp.send_email import send_email
from slack_functions import slack_post_message
from functions.pagerduty.send_pagerduty import send_pagerduty
skyline_app = 'thunder'
skyline_app_logger = '%sLog' % skyline_app
logger = logging.getLogger(skyline_app_logger)
skyline_app_logfile = '%s/%s.log' % (settings.LOG_PATH, skyline_app)
def thunder_alert(alert_via, subject, body):
"""
"""
logger = logging.getLogger(skyline_app_logger)
message_sent = False
if alert_via == 'alert_via_smtp':
send_smtp_alert = False
try:
if settings.THUNDER_OPTS['alert_via_smtp']:
send_smtp_alert = True
to = settings.THUNDER_OPTS['smtp_recipients'][0]
cc = []
for i in settings.THUNDER_OPTS['smtp_recipients']:
if i != to:
cc.append(i)
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed to determine alert_via_smtp settings - %s' % e)
if send_smtp_alert:
try:
message_sent = send_email(skyline_app, to, cc, subject, str(body))
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed to send smtp messages - %s' % e)
if message_sent:
logger.info('thunder_alert :: smtp message sent - %s' % subject)
if alert_via == 'alert_via_slack':
try:
if settings.THUNDER_OPTS['alert_via_slack']:
message = '*%s*\n%s' % (subject, body)
message_sent = slack_post_message(skyline_app,
settings.THUNDER_OPTS['slack_channel'],
'None', message)
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed to send slack message - %s' % e)
if message_sent:
logger.info('thunder_alert :: slack message sent - %s' % subject)
if alert_via == 'alert_via_pagerduty':
try:
if settings.THUNDER_OPTS['alert_via_pagerduty']:
message = '%s %s' % (subject, body)
message_sent = send_pagerduty(skyline_app, message, log=True)
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed to determine alert_via_smtp settings - %s' % e)
if message_sent:
logger.info('thunder_alert :: slack message sent - %s' % subject)
alert_via_http = False
alerter_endpoint = None
thunder_alert_token = None
if isinstance(alert_via, dict):
try:
alert_via_http = alert_via['alert_via_http']
if alert_via_http:
alerter_endpoint = alert_via['thunder_alert_endpoint']
thunder_alert_token = alert_via['thunder_alert_token']
alert_data_dict = alert_via['alert_data_dict']
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed to determine alert_via settings - %s - %s' % (
str(alert_via), e))
if alerter_endpoint and thunder_alert_token and alert_data_dict:
connect_timeout = 5
read_timeout = 20
use_timeout = (int(connect_timeout), int(read_timeout))
response = None
try:
# response = requests.post(alerter_endpoint, data=alert_data, headers=headers, timeout=use_timeout)
response = requests.post(alerter_endpoint, json=alert_data_dict, timeout=use_timeout)
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed to post alert to %s - %s' % (
str(alerter_endpoint), e))
try:
if response.status_code != 200:
logger.warning('warning :: thunder_alert :: %s responded with status code %s and reason %s' % (
str(alerter_endpoint), str(response.status_code),
str(response.reason)))
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed determine response.status_code - %s' % e)
try:
if response.status_code == 400:
response_str = None
try:
response_str = str(response.json())
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed determine response.status_code - %s' % e)
logger.info('thunder_alert :: 400 response - %s' % (
str(response_str)))
except Exception as e:
logger.error(traceback.format_exc())
logger.error('error :: thunder_alert :: failed determine response.status_code - %s' % e)
if response:
if response.status_code == 200:
logger.info('thunder_alert :: alert sent to %s - %s' % (
# str(alerter_endpoint), str(alert_data_dict['status'])))
str(alerter_endpoint), str(response.status_code)))
message_sent = True
if message_sent:
logger.info('thunder_alert :: external thunder message sent')
return message_sent
| 2,627 |
575 | // Copyright (c) 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu/vulkan/vulkan_fence_helper.h"
#include "base/bind.h"
#include "base/logging.h"
#include "gpu/vulkan/vulkan_device_queue.h"
#include "gpu/vulkan/vulkan_function_pointers.h"
namespace gpu {
VulkanFenceHelper::FenceHandle::FenceHandle() = default;
VulkanFenceHelper::FenceHandle::FenceHandle(VkFence fence,
uint64_t generation_id)
: fence_(fence), generation_id_(generation_id) {}
VulkanFenceHelper::FenceHandle::FenceHandle(const FenceHandle& other) = default;
VulkanFenceHelper::FenceHandle& VulkanFenceHelper::FenceHandle::operator=(
const FenceHandle& other) = default;
VulkanFenceHelper::VulkanFenceHelper(VulkanDeviceQueue* device_queue)
: device_queue_(device_queue) {}
VulkanFenceHelper::~VulkanFenceHelper() {
DCHECK(tasks_pending_fence_.empty());
DCHECK(cleanup_tasks_.empty());
}
void VulkanFenceHelper::Destroy() {
PerformImmediateCleanup();
}
// TODO(ericrk): Handle recycling fences.
VkResult VulkanFenceHelper::GetFence(VkFence* fence) {
VkFenceCreateInfo create_info{
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
};
return vkCreateFence(device_queue_->GetVulkanDevice(), &create_info,
nullptr /* pAllocator */, fence);
}
VulkanFenceHelper::FenceHandle VulkanFenceHelper::EnqueueFence(VkFence fence) {
FenceHandle handle(fence, next_generation_++);
cleanup_tasks_.emplace_back(handle, std::move(tasks_pending_fence_));
tasks_pending_fence_ = std::vector<CleanupTask>();
return handle;
}
bool VulkanFenceHelper::Wait(FenceHandle handle,
uint64_t timeout_in_nanoseconds) {
if (HasPassed(handle))
return true;
VkResult result =
vkWaitForFences(device_queue_->GetVulkanDevice(), 1, &handle.fence_, true,
timeout_in_nanoseconds);
// After waiting, we can process cleanup tasks.
ProcessCleanupTasks();
return result == VK_SUCCESS;
}
bool VulkanFenceHelper::HasPassed(FenceHandle handle) {
// Process cleanup tasks which advances our |current_generation_|.
ProcessCleanupTasks();
return current_generation_ >= handle.generation_id_;
}
void VulkanFenceHelper::EnqueueCleanupTaskForSubmittedWork(CleanupTask task) {
tasks_pending_fence_.emplace_back(std::move(task));
}
void VulkanFenceHelper::ProcessCleanupTasks(uint64_t retired_generation_id) {
VkDevice device = device_queue_->GetVulkanDevice();
if (!retired_generation_id)
retired_generation_id = current_generation_;
// Iterate over our pending cleanup fences / tasks, advancing
// |current_generation_| as far as possible.
for (const auto& tasks_for_fence : cleanup_tasks_) {
// Callback based tasks have no actual fence to wait on, keep checking
// future fences, as a callback may be delayed.
if (tasks_for_fence.UsingCallback())
continue;
VkResult result = vkGetFenceStatus(device, tasks_for_fence.fence);
if (result == VK_NOT_READY) {
retired_generation_id =
std::min(retired_generation_id, tasks_for_fence.generation_id - 1);
break;
}
if (result == VK_SUCCESS) {
retired_generation_id =
std::max(tasks_for_fence.generation_id, retired_generation_id);
continue;
}
DLOG(ERROR) << "vkGetFenceStatus() failed: " << result;
PerformImmediateCleanup();
return;
}
current_generation_ = retired_generation_id;
// Runs any cleanup tasks for generations that have passed. Create a temporary
// vector of tasks to run to avoid reentrancy issues.
std::vector<CleanupTask> tasks_to_run;
while (!cleanup_tasks_.empty()) {
TasksForFence& tasks_for_fence = cleanup_tasks_.front();
if (tasks_for_fence.generation_id > current_generation_)
break;
if (tasks_for_fence.fence != VK_NULL_HANDLE) {
DCHECK_EQ(vkGetFenceStatus(device, tasks_for_fence.fence), VK_SUCCESS);
vkDestroyFence(device, tasks_for_fence.fence, nullptr);
}
tasks_to_run.insert(tasks_to_run.end(),
std::make_move_iterator(tasks_for_fence.tasks.begin()),
std::make_move_iterator(tasks_for_fence.tasks.end()));
cleanup_tasks_.pop_front();
}
for (auto& task : tasks_to_run)
std::move(task).Run(device_queue_, false /* device_lost */);
}
VulkanFenceHelper::FenceHandle VulkanFenceHelper::GenerateCleanupFence() {
if (tasks_pending_fence_.empty())
return FenceHandle();
VkFence fence = VK_NULL_HANDLE;
VkResult result = GetFence(&fence);
if (result != VK_SUCCESS) {
PerformImmediateCleanup();
return FenceHandle();
}
result = vkQueueSubmit(device_queue_->GetVulkanQueue(), 0, nullptr, fence);
if (result != VK_SUCCESS) {
vkDestroyFence(device_queue_->GetVulkanDevice(), fence, nullptr);
PerformImmediateCleanup();
return FenceHandle();
}
return EnqueueFence(fence);
}
base::OnceClosure VulkanFenceHelper::CreateExternalCallback() {
// No need to do callback tracking if there are no cleanup tasks to run.
if (tasks_pending_fence_.empty())
return base::OnceClosure();
// Get a generation ID for this callback and associate existing cleanup
// tasks.
uint64_t generation_id = next_generation_++;
cleanup_tasks_.emplace_back(generation_id, std::move(tasks_pending_fence_));
tasks_pending_fence_ = std::vector<CleanupTask>();
return base::BindOnce(
[](base::WeakPtr<VulkanFenceHelper> fence_helper,
uint64_t generation_id) {
if (!fence_helper)
return;
// If |current_generation_| is ahead of the callback's
// |generation_id|, the callback came late. Ignore it.
if (generation_id > fence_helper->current_generation_) {
fence_helper->ProcessCleanupTasks(generation_id);
}
},
weak_factory_.GetWeakPtr(), generation_id);
}
void VulkanFenceHelper::EnqueueSemaphoreCleanupForSubmittedWork(
VkSemaphore semaphore) {
if (semaphore == VK_NULL_HANDLE)
return;
EnqueueSemaphoresCleanupForSubmittedWork({semaphore});
}
void VulkanFenceHelper::EnqueueSemaphoresCleanupForSubmittedWork(
std::vector<VkSemaphore> semaphores) {
if (semaphores.empty())
return;
EnqueueCleanupTaskForSubmittedWork(base::BindOnce(
[](std::vector<VkSemaphore> semaphores, VulkanDeviceQueue* device_queue,
bool /* is_lost */) {
for (VkSemaphore semaphore : semaphores) {
vkDestroySemaphore(device_queue->GetVulkanDevice(), semaphore,
nullptr);
}
},
std::move(semaphores)));
}
void VulkanFenceHelper::EnqueueImageCleanupForSubmittedWork(
VkImage image,
VkDeviceMemory memory) {
if (image == VK_NULL_HANDLE && memory == VK_NULL_HANDLE)
return;
EnqueueCleanupTaskForSubmittedWork(base::BindOnce(
[](VkImage image, VkDeviceMemory memory, VulkanDeviceQueue* device_queue,
bool /* is_lost */) {
if (image != VK_NULL_HANDLE)
vkDestroyImage(device_queue->GetVulkanDevice(), image, nullptr);
if (memory != VK_NULL_HANDLE)
vkFreeMemory(device_queue->GetVulkanDevice(), memory, nullptr);
},
image, memory));
}
void VulkanFenceHelper::EnqueueBufferCleanupForSubmittedWork(
VkBuffer buffer,
VmaAllocation allocation) {
if (buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
return;
DCHECK(buffer != VK_NULL_HANDLE);
DCHECK(allocation != VK_NULL_HANDLE);
EnqueueCleanupTaskForSubmittedWork(base::BindOnce(
[](VkBuffer buffer, VmaAllocation allocation,
VulkanDeviceQueue* device_queue, bool /* is_lost */) {
vma::DestroyBuffer(device_queue->vma_allocator(), buffer, allocation);
},
buffer, allocation));
}
void VulkanFenceHelper::PerformImmediateCleanup() {
if (cleanup_tasks_.empty() && tasks_pending_fence_.empty())
return;
// We want to run all tasks immediately, so just use vkQueueWaitIdle which
// ensures that all fences have passed.
// Even if exclusively using callbacks, the callbacks use WeakPtr and will
// not keep this class alive, so it's important to wait / run all cleanup
// immediately.
VkResult result = vkQueueWaitIdle(device_queue_->GetVulkanQueue());
// Wait can only fail for three reasons - device loss, host OOM, device OOM.
// If we hit an OOM, treat this as a crash. There isn't a great way to
// recover from this.
CHECK(result == VK_SUCCESS || result == VK_ERROR_DEVICE_LOST);
bool device_lost = result == VK_ERROR_DEVICE_LOST;
// We're going to destroy all fences below, so we should consider them as
// passed.
current_generation_ = next_generation_ - 1;
// Run all cleanup tasks. Create a temporary vector of tasks to run to avoid
// reentrancy issues.
std::vector<CleanupTask> tasks_to_run;
while (!cleanup_tasks_.empty()) {
auto& tasks_for_fence = cleanup_tasks_.front();
vkDestroyFence(device_queue_->GetVulkanDevice(), tasks_for_fence.fence,
nullptr);
tasks_to_run.insert(tasks_to_run.end(),
std::make_move_iterator(tasks_for_fence.tasks.begin()),
std::make_move_iterator(tasks_for_fence.tasks.end()));
cleanup_tasks_.pop_front();
}
tasks_to_run.insert(tasks_to_run.end(),
std::make_move_iterator(tasks_pending_fence_.begin()),
std::make_move_iterator(tasks_pending_fence_.end()));
tasks_pending_fence_.clear();
for (auto& task : tasks_to_run)
std::move(task).Run(device_queue_, device_lost);
}
VulkanFenceHelper::TasksForFence::TasksForFence(FenceHandle handle,
std::vector<CleanupTask> tasks)
: fence(handle.fence_),
generation_id(handle.generation_id_),
tasks(std::move(tasks)) {}
VulkanFenceHelper::TasksForFence::TasksForFence(uint64_t generation_id,
std::vector<CleanupTask> tasks)
: generation_id(generation_id), tasks(std::move(tasks)) {}
VulkanFenceHelper::TasksForFence::~TasksForFence() = default;
VulkanFenceHelper::TasksForFence::TasksForFence(TasksForFence&& other) =
default;
} // namespace gpu
| 4,056 |
1,233 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.config.DefaultSettableConfig;
import com.netflix.mantis.discovery.proto.JobDiscoveryInfo;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.ipc.http.HttpClient;
import io.mantisrx.publish.DefaultObjectMapper;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration;
import io.mantisrx.publish.internal.discovery.mantisapi.DefaultMantisApiClient;
import io.mantisrx.publish.internal.discovery.mantisapi.MantisApiClient;
import io.mantisrx.publish.internal.discovery.proto.JobSchedulingInfo;
import io.mantisrx.publish.internal.discovery.proto.MantisJobState;
import io.mantisrx.publish.internal.discovery.proto.WorkerAssignments;
import io.mantisrx.publish.internal.discovery.proto.WorkerHost;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MantisJobDiscoveryTest {
private static final Logger logger = LoggerFactory.getLogger(MantisJobDiscoveryTest.class);
private final Map<String, String> streamJobClusterMap = new HashMap<>();
@Rule
public WireMockRule mantisApi = new WireMockRule(options().dynamicPort());
private MrePublishConfiguration config;
private MantisJobDiscovery jobDiscovery;
public MantisJobDiscoveryTest() {
streamJobClusterMap.put(StreamType.DEFAULT_EVENT_STREAM, "RequestEventSubTrackerTestJobCluster");
streamJobClusterMap.put(StreamType.LOG_EVENT_STREAM, "LogEventSubTrackerTestJobCluster");
}
private MrePublishConfiguration testConfig() {
DefaultSettableConfig settableConfig = new DefaultSettableConfig();
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.DEFAULT_EVENT_STREAM, streamJobClusterMap.get(StreamType.DEFAULT_EVENT_STREAM));
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.LOG_EVENT_STREAM, streamJobClusterMap.get(StreamType.LOG_EVENT_STREAM));
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.SUBS_REFRESH_INTERVAL_SEC_PROP, 30);
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.JOB_DISCOVERY_REFRESH_INTERVAL_SEC_PROP, 1);
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.DISCOVERY_API_HOSTNAME_PROP, "127.0.0.1");
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.DISCOVERY_API_PORT_PROP, mantisApi.port());
PropertyRepository propertyRepository = DefaultPropertyFactory.from(settableConfig);
return new SampleArchaiusMrePublishConfiguration(propertyRepository);
}
@BeforeEach
public void setup() {
mantisApi.start();
config = testConfig();
Registry registry = new DefaultRegistry();
MantisApiClient mantisApiClient = new DefaultMantisApiClient(config, HttpClient.create(registry));
this.jobDiscovery = new MantisJobDiscoveryCachingImpl(config, registry, mantisApiClient);
}
@AfterEach
public void teardown() {
mantisApi.shutdown();
}
@Test
public void testJobDiscoveryFetch() throws IOException {
String jobCluster = "MantisJobDiscoveryTestJobCluster";
String jobId = jobCluster + "-1";
JobSchedulingInfo jobSchedulingInfo = new JobSchedulingInfo(jobId, Collections.singletonMap(1, new WorkerAssignments(1, 1, Collections.singletonMap(1,
new WorkerHost("127.0.0.1", 0, Collections.emptyList(), MantisJobState.Started, 1, 7777, 7151)
))));
// JobDiscoveryInfo jobDiscoveryInfo = new JobDiscoveryInfo(jobCluster, jobId,
// Collections.singletonMap(1, new StageWorkers(jobCluster, jobId, 1, Arrays.asList(
// new MantisWorker("127.0.0.1", 7151)
// ))));
// worker 1 subs list
mantisApi.stubFor(get("/jobClusters/discoveryInfo/" + jobCluster)
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(jobSchedulingInfo)))
);
Optional<JobDiscoveryInfo> currentJobWorkers = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertTrue(currentJobWorkers.isPresent());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().size(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().size());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getCustomPort(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().get(0).getPort());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getHost(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().get(0).getHost());
}
@Test
public void testJobDiscoveryFetchFailureHandlingAfterSuccess() throws IOException, InterruptedException {
String jobCluster = "MantisJobDiscoveryTestJobCluster";
String jobId = jobCluster + "-1";
JobSchedulingInfo jobSchedulingInfo = new JobSchedulingInfo(jobId, Collections.singletonMap(1, new WorkerAssignments(1, 1, Collections.singletonMap(1,
new WorkerHost("127.0.0.1", 0, Collections.emptyList(), MantisJobState.Started, 1, 7777, 7151)
))));
// JobDiscoveryInfo jobDiscoveryInfo = new JobDiscoveryInfo(jobCluster, jobId,
// Collections.singletonMap(1, new StageWorkers(jobCluster, jobId, 1, Arrays.asList(
// new MantisWorker("127.0.0.1", 7151)
// ))));
// worker 1 subs list
mantisApi.stubFor(get("/jobClusters/discoveryInfo/" + jobCluster)
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(jobSchedulingInfo)))
);
Optional<JobDiscoveryInfo> currentJobWorkers = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertTrue(currentJobWorkers.isPresent());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().size(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().size());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getCustomPort(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().get(0).getPort());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getHost(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().get(0).getHost());
logger.info("sleep to force a refresh after configured interval");
Thread.sleep((config.jobDiscoveryRefreshIntervalSec() + 1) * 1000);
mantisApi.stubFor(get("/jobClusters/discoveryInfo/" + jobCluster)
.willReturn(aResponse()
.withStatus(503)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(jobSchedulingInfo)))
);
Optional<JobDiscoveryInfo> currentJobWorkers2 = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertTrue(currentJobWorkers2.isPresent());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().size(), currentJobWorkers2.get().getIngestStageWorkers().getWorkers().size());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getCustomPort(), currentJobWorkers2.get().getIngestStageWorkers().getWorkers().get(0).getPort());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getHost(), currentJobWorkers2.get().getIngestStageWorkers().getWorkers().get(0).getHost());
logger.info("sleep to let async refresh complete");
Thread.sleep(1000);
mantisApi.verify(2, getRequestedFor(urlMatching("/jobClusters/discoveryInfo/" + jobCluster)));
// should continue serving old Job Discovery data after a 503
Optional<JobDiscoveryInfo> currentJobWorkers3 = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertTrue(currentJobWorkers3.isPresent());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().size(), currentJobWorkers3.get().getIngestStageWorkers().getWorkers().size());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getCustomPort(), currentJobWorkers3.get().getIngestStageWorkers().getWorkers().get(0).getPort());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getHost(), currentJobWorkers3.get().getIngestStageWorkers().getWorkers().get(0).getHost());
}
@Test
public void testJobDiscoveryFetch4XXRespHandling() throws InterruptedException {
String jobCluster = "MantisJobDiscoveryTestJobCluster";
// worker 1 subs list
mantisApi.stubFor(get("/jobClusters/discoveryInfo/" + jobCluster)
.willReturn(aResponse()
.withStatus(404)
.withBody("")
));
int iterations = 3;
for (int i = 0; i < iterations; i++) {
Optional<JobDiscoveryInfo> currentJobWorkers = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertFalse(currentJobWorkers.isPresent());
Thread.sleep((config.jobDiscoveryRefreshIntervalSec() + 1) * 1000);
}
mantisApi.verify(iterations, getRequestedFor(urlMatching("/jobClusters/discoveryInfo/" + jobCluster)));
}
}
| 4,277 |
4,457 | //
// AAPlotBandsElement.h
// AAChartKitDemo
//
// Created by AnAn on 2018/12/23.
// Copyright © 2018 <NAME>. All rights reserved.
//*************** ...... SOURCE CODE ...... ***************
//***...................................................***
//*** https://github.com/AAChartModel/AAChartKit ***
//*** https://github.com/AAChartModel/AAChartKit-Swift ***
//***...................................................***
//*************** ...... SOURCE CODE ...... ***************
/*
* -------------------------------------------------------------------------------
*
* 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔
*
* Please contact me on GitHub,if there are any problems encountered in use.
* GitHub Issues : https://github.com/AAChartModel/AAChartKit/issues
* -------------------------------------------------------------------------------
* And if you want to contribute for this project, please contact me as well
* GitHub : https://github.com/AAChartModel
* StackOverflow : https://stackoverflow.com/users/12302132/codeforu
* JianShu : https://www.jianshu.com/u/f1e6753d4254
* SegmentFault : https://segmentfault.com/u/huanghunbieguan
*
* -------------------------------------------------------------------------------
*/
//borderColor: null
//borderWidth: 边框宽度
//className: 类名
//color: 样式
//events: 事件
//from: 开始值
//id: 编号
//innerRadius: null
//label: {标签}
//outerRadius: 100%
//thickness: 10
//to: 结束值
//zIndex
#import <Foundation/Foundation.h>
@interface AAPlotBandsElement : NSObject
AAPropStatementAndPropSetFuncStatement(copy, AAPlotBandsElement, NSString *, borderColor)
AAPropStatementAndPropSetFuncStatement(strong, AAPlotBandsElement, NSNumber *, borderWidth)
AAPropStatementAndPropSetFuncStatement(copy, AAPlotBandsElement, NSString *, className)
AAPropStatementAndPropSetFuncStatement(copy, AAPlotBandsElement, NSString *, color)
AAPropStatementAndPropSetFuncStatement(strong, AAPlotBandsElement, NSNumber *, from)
AAPropStatementAndPropSetFuncStatement(strong, AAPlotBandsElement, NSDictionary *, label)
AAPropStatementAndPropSetFuncStatement(strong, AAPlotBandsElement, NSNumber *, to)
AAPropStatementAndPropSetFuncStatement(assign, AAPlotBandsElement, NSUInteger , zIndex)
@end
| 732 |
2,885 | import os
import re
def read_version():
with open(os.path.join('freezegun', '__init__.py')) as f:
m = re.search(r'''__version__\s*=\s*['"]([^'"]*)['"]''', f.read())
if m:
return m.group(1)
raise ValueError("couldn't find version")
def create_tag():
from subprocess import call
version = read_version()
errno = call(['git', 'tag', '--annotate', version, '--message', 'Version %s' % version])
if errno == 0:
print("Added tag for version %s" % version)
if __name__ == '__main__':
create_tag()
| 242 |
1,338 | <gh_stars>1000+
//------------------------------------------------------------------------------
// LocalTestObject.h
//
//------------------------------------------------------------------------------
#ifndef LOCALTESTOBJECT_H
#define LOCALTESTOBJECT_H
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
#include <Message.h>
#include <Archivable.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
class TIOTest : public BArchivable
{
public:
TIOTest(int32 i);
int32 GetData() { return data; }
// All the archiving-related stuff
TIOTest(BMessage* archive);
status_t Archive(BMessage* archive, bool deep = true);
static TIOTest* Instantiate(BMessage* archive);
private:
int32 data;
};
#endif //LOCALTESTOBJECT_H
/*
* $Log $
*
* $Id $
*
*/
| 259 |
1,738 | <reponame>brianherrera/lumberyard<filename>dev/Code/Framework/AzCore/Tests/Serialization/Json/JsonSerializationTests.h
/*
* 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.
*
*/
#pragma once
#include <AzCore/Serialization/Json/JsonSerialization.h>
#include <AzCore/std/smart_ptr/make_shared.h>
#include <AzCore/std/smart_ptr/shared_ptr.h>
#include <Tests/Serialization/Json/BaseJsonSerializerFixture.h>
#include <Tests/Serialization/Json/TestCases_Base.h>
namespace JsonSerializationTests
{
namespace A
{
struct Inherited
: public BaseClass
{
AZ_RTTI(Inherited, "{E7829F37-C577-4F2B-A85B-6F331548354C}", BaseClass);
~Inherited() override = default;
};
}
namespace B
{
struct Inherited
: public BaseClass
{
AZ_RTTI(Inherited, "{0DF033C4-3EEC-4F61-8B79-59FE31545029}", BaseClass);
~Inherited() override = default;
};
}
namespace C
{
struct Inherited
{
AZ_RTTI(Inherited, "{682089DB-9794-4590-87A4-9AF70BD1C202}");
virtual ~Inherited() = default;
};
}
struct ConflictingNameTestClass
{
AZ_RTTI(ConflictingNameTestClass, "{370EFD10-781B-47BF-B0A1-6FC4E9D55CBC}");
virtual ~ConflictingNameTestClass() = default;
AZStd::shared_ptr<BaseClass> m_pointer;
ConflictingNameTestClass()
{
m_pointer = AZStd::make_shared<A::Inherited>();
}
};
struct EmptyClass
{
AZ_RTTI(EmptyClass, "{9E69A37B-22BD-4E3F-9A80-63D902966591}");
virtual ~EmptyClass() = default;
};
struct ClassWithPointerToUnregisteredClass
{
AZ_RTTI(ClassWithPointerToUnregisteredClass, "{7CBA9A8F-8576-456E-B4C0-DE5797D54694}");
EmptyClass* m_ptr;
ClassWithPointerToUnregisteredClass()
: m_ptr(new EmptyClass())
{
}
virtual ~ClassWithPointerToUnregisteredClass()
{
delete m_ptr;
m_ptr = nullptr;
}
};
class JsonSerializationTests
: public BaseJsonSerializerFixture
{
};
} // namespace JsonSerializationTests
| 1,195 |
380 | <reponame>tanisha-bhadani/hacktoberfest2021-1
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Comparator;
/**
*
*
* @author <NAME>
* @version 11-10-2020
*/
public class TrainStation
{
private String city;
private ArrayList<Train> trains;
public TrainStation(String city)
{
this.city = city;
trains = new ArrayList<Train>();
}
/**
* this method adds trains tot the ArrayList trains
*/
public void addTrain(Train t) {
trains.add(t);
}
/**
* Method will return the number of trains that starts or ends in the
* city of the Trainstation
*/
public int connectingTrains() {
int result = 0;
for(Train t : trains) {
if(city.equals(t.getDeparture()) || city.equals(t.getDestiantion())) {
result ++;
}
}
return result;
}
/**
* This method returns the chepest train go to a spesific destination
*/
public Train cheapTrainTo(String destination) {
Train result = null;
for(Train t : trains) {
if(destination.equals(t.getDestiantion())) {
if(result == null || result.getPrice() > t.getPrice()) {
result = t;
}
}
}
return result;
}
/**
* This method prints out all trains in the ArrayList trains
* in sorted order after the departurs in alphabeticly order
* if they have the same departures then it wil sort after price
* from lovest til highest
*/
public void printTrainStation() {
Collections.sort(trains);
System.out.println("The trainstaion in " + city + " has following trains:");
for(Train t : trains) {
System.out.println(t);
}
}
/**
* This method will return all trains that starts in a given place
* going to the Trainstations city.
*/
public List<Train> trainsFrom(String departure) {
return trains.stream()
.filter(t -> t.getDeparture().equals(departure) && t.getDestiantion().equals(city))
.collect(Collectors.toList());
}
/**
* This method returns the cheapest train strating in the Trainstations
* city, and ends in a given destination
*/
public Train cheapTrain(String destination) {
return trains.stream()
.filter(t -> t.getDeparture().equals(city) && t.getDestiantion().equals(destination))
.min(Comparator.comparing(t -> t.getPrice()))
.orElse(null);
}
}
| 1,098 |
333 | """
A package for managing the distributed execution of long running jobs.
"""
| 17 |
14,668 | // Copyright 2021 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 "media/fuchsia/audio/fake_audio_device_enumerator.h"
#include "base/logging.h"
namespace media {
FakeAudioDeviceEnumerator::FakeAudioDeviceEnumerator(vfs::PseudoDir* pseudo_dir)
: binding_(pseudo_dir, this) {}
FakeAudioDeviceEnumerator::~FakeAudioDeviceEnumerator() = default;
void FakeAudioDeviceEnumerator::GetDevices(GetDevicesCallback callback) {
std::vector<fuchsia::media::AudioDeviceInfo> result = {
{
.name = "input",
.unique_id = "input",
.token_id = 1,
.is_input = true,
.is_default = true,
},
{
.name = "output",
.unique_id = "output",
.token_id = 2,
.is_input = false,
.is_default = true,
},
};
callback(std::move(result));
}
void FakeAudioDeviceEnumerator::NotImplemented_(const std::string& name) {
LOG(FATAL) << "Reached non-implemented " << name;
}
} // namespace media
| 453 |
2,062 | #include <litc.h>
static char buf[512];
int main(int argc, char **argv)
{
char *fn = "/bigfile.txt";
int fd;
if ((fd = open(fn, O_RDONLY, 0)) < 0)
errx(-1, "open");
int i;
int ret;
int blks = 1000;
for (i = 0; i < blks; i++) {
printf("read %d\n", i);
size_t c = sizeof(buf);
size_t e = c;
if ((ret = read(fd, buf, c)) != e) {
printf("read failed %d\n", ret);
return -1;
}
int j;
for (j = 0; j < sizeof(buf); j++)
if (buf[j] != 'A')
errx(-1, "mismatch!");
}
if (close(fd))
errx(-1, "close");
return 0;
}
| 280 |
954 | package com.jdon.util;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* RequestUtil utility class Good ol' copy-n-paste from <event
* href="http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt">
* http://www.javaworld.com/javaworld/jw-02-2002/ssl/utilityclass.txt</event> which
* is referenced in the following article: <event
* href="http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html">
* http://www.javaworld.com/javaworld/jw-02-2002/jw-0215-ssl.html</event>
*/
public class RequestUtil {
private static final String STOWED_REQUEST_ATTRIBS = "ssl.redirect.attrib.stowed";
private static final String JDON_AUTOLOGIN_COOKIE = "jdon.autologin";
// "Tweakable" parameters for the cookie password encoding. NOTE: changing
// these and recompiling this class will essentially invalidate old cookies.
private final static int ENCODE_XORMASK = 0x5A;
private final static char ENCODE_DELIMETER = '\002';
private final static char ENCODE_CHAR_OFFSET1 = 'A';
private final static char ENCODE_CHAR_OFFSET2 = 'h';
/**
* Creates query String from request body parameters
*/
public static String getRequestParameters(HttpServletRequest aRequest) {
// set the ALGORIGTHM as defined for the application
// ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM);
Map m = aRequest.getParameterMap();
return createQueryStringFromMap(m, "&").toString();
}
/**
* Builds event query string from event given map of parameters
*
* @param m
* A map of parameters
* @param ampersand
* String to use for ampersands (e.g. "&" or "&" )
*
* @return query string (with no leading "?")
*/
public static StringBuilder createQueryStringFromMap(Map m, String ampersand) {
StringBuilder aReturn = new StringBuilder("");
Set aEntryS = m.entrySet();
Iterator aEntryI = aEntryS.iterator();
while (aEntryI.hasNext()) {
Map.Entry aEntry = (Map.Entry) aEntryI.next();
Object o = aEntry.getValue();
if (o == null) {
append(aEntry.getKey(), "", aReturn, ampersand);
} else if (o instanceof String) {
append(aEntry.getKey(), o, aReturn, ampersand);
} else if (o instanceof String[]) {
String[] aValues = (String[]) o;
for (int i = 0; i < aValues.length; i++) {
append(aEntry.getKey(), aValues[i], aReturn, ampersand);
}
} else {
append(aEntry.getKey(), o, aReturn, ampersand);
}
}
return aReturn;
}
/**
* Appends new key and value pair to query string
*
* @param key
* parameter name
* @param value
* value of parameter
* @param queryString
* existing query string
* @param ampersand
* string to use for ampersand (e.g. "&" or "&")
*
* @return query string (with no leading "?")
*/
private static StringBuilder append(Object key, Object value, StringBuilder queryString, String ampersand) {
if (queryString.length() > 0) {
queryString.append(ampersand);
}
// Use encodeURL from Struts' RequestUtils class - it's JDK 1.3 and 1.4
// compliant
queryString.append(encodeURL(key.toString()));
queryString.append("=");
queryString.append(encodeURL(value.toString()));
return queryString;
}
/**
* Stores request attributes in session
*
* @param aRequest
* the current request
*/
public static void stowRequestAttributes(HttpServletRequest aRequest) {
if (aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null) {
return;
}
Enumeration e = aRequest.getAttributeNames();
Map map = new HashMap();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
map.put(name, aRequest.getAttribute(name));
}
aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, map);
}
/**
* Returns request attributes from session to request
*
* @param aRequest
* DOCUMENT ME!
*/
public static void reclaimRequestAttributes(HttpServletRequest aRequest) {
Map map = (Map) aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS);
if (map == null) {
return;
}
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String name = (String) itr.next();
aRequest.setAttribute(name, map.get(name));
}
aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
}
public static void saveAuthCookie(HttpServletResponse response, String username, String password) {
// Save the cookie value for 1 month
setCookie(response, JDON_AUTOLOGIN_COOKIE, encodePasswordCookie(username, password), "/");
}
public static String[] getAuthCookie(HttpServletRequest request) {
Cookie cookie = getCookie(request, JDON_AUTOLOGIN_COOKIE);
String[] values = null;
if (cookie != null) {
try {
values = decodePasswordCookie(cookie.getValue());
} catch (Exception e) {
System.err.print("getAuthCookie() err:" + e);
}
}
return values;
}
/**
* Convenience method to set event cookie
*
* @param response
* @param name
* @param value
* @param path
* @return HttpServletResponse
*/
public static void setCookie(HttpServletResponse response, String name, String value, String path) {
Cookie cookie = new Cookie(name, value);
cookie.setSecure(false);
cookie.setPath(path);
cookie.setMaxAge(3600 * 24 * 30); // 30 days
response.addCookie(cookie);
}
/**
* Convenience method to get event cookie by name
*
* @param request
* the current request
* @param name
* the name of the cookie to find
*
* @return the cookie (if found), null if not found
*/
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
Cookie returnCookie = null;
if (cookies == null) {
return returnCookie;
}
for (int i = 0; i < cookies.length; i++) {
Cookie thisCookie = cookies[i];
if (thisCookie.getName().equals(name)) {
// cookies with no value do me no good!
if (!thisCookie.getValue().equals("")) {
returnCookie = thisCookie;
break;
}
}
}
return returnCookie;
}
/**
* Convenience method for deleting event cookie by name
*
* @param response
* the current web response
* @param cookie
* the cookie to delete
*
* @return the modified response
*/
public static void deleteCookie(HttpServletResponse response, Cookie cookie, String path) {
if (cookie != null) {
// Delete the cookie by setting its maximum age to zero
cookie.setMaxAge(0);
cookie.setPath(path);
response.addCookie(cookie);
}
}
/**
* Convenience method to get the application's URL based on request
* variables.
*/
public static String getAppURL(HttpServletRequest request) {
StringBuffer url = new StringBuffer();
int port = request.getServerPort();
if (port < 0) {
port = 80; // Work around java.net.URL bug
}
String scheme = request.getScheme();
url.append(scheme);
url.append("://");
url.append(request.getServerName());
if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
url.append(':');
url.append(port);
}
return url.toString();
}
public static String encodeURL(String url) {
return encodeURL(url, "UTF-8");
}
/**
* Use the new URLEncoder.encode() method from Java 1.4 if available, else
* use the old deprecated version. This method uses reflection to find the
* appropriate method; if the reflection operations throw exceptions, this
* will return the url encoded with the old URLEncoder.encode() method.
*
* @param enc
* The character encoding the urlencode is performed on.
* @return String The encoded url.
*/
public static String encodeURL(String url, String enc) {
try {
if (enc == null || enc.length() == 0) {
enc = "UTF-8";
}
return URLEncoder.encode(url, enc);
} catch (Exception e) {
System.err.print(e);
}
return null;
}
/**
* Builds event cookie string containing event username and password.
* <p>
*
* Note: with open source this is not really secure, but it prevents users
* from snooping the cookie file of others and by changing the XOR mask and
* character offsets, you can easily tweak results.
*
* @param username
* The username.
* @param password
* The password.
* @return String encoding the input parameters, an empty string if one of
* the arguments equals <code>null</code>.
*/
private static String encodePasswordCookie(String username, String password) {
StringBuffer buf = new StringBuffer();
if (username != null && password != null) {
byte[] bytes = (username + ENCODE_DELIMETER + password).getBytes();
int b;
for (int n = 0; n < bytes.length; n++) {
b = bytes[n] ^ (ENCODE_XORMASK + n);
buf.append((char) (ENCODE_CHAR_OFFSET1 + (b & 0x0F)));
buf.append((char) (ENCODE_CHAR_OFFSET2 + ((b >> 4) & 0x0F)));
}
}
return buf.toString();
}
/**
* Unrafels event cookie string containing event username and password.
*
* @param value
* The cookie value.
* @return String[] containing the username at index 0 and the password at
* index 1, or <code>{ null, null }</code> if cookieVal equals
* <code>null</code> or the empty string.
*/
private static String[] decodePasswordCookie(String cookieVal) {
// check that the cookie value isn't null or zero-length
if (cookieVal == null || cookieVal.length() <= 0) {
return null;
}
// unrafel the cookie value
char[] chars = cookieVal.toCharArray();
byte[] bytes = new byte[chars.length / 2];
int b;
for (int n = 0, m = 0; n < bytes.length; n++) {
b = chars[m++] - ENCODE_CHAR_OFFSET1;
b |= (chars[m++] - ENCODE_CHAR_OFFSET2) << 4;
bytes[n] = (byte) (b ^ (ENCODE_XORMASK + n));
}
cookieVal = new String(bytes);
int pos = cookieVal.indexOf(ENCODE_DELIMETER);
String username = (pos < 0) ? "" : cookieVal.substring(0, pos);
String password = (pos < 0) ? "" : cookieVal.substring(pos + 1);
return new String[] { username, password };
}
}
| 4,194 |
1,269 | package com.module.chiclaim.com.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
private Fragment mFragmentAnimation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.module.chiclaim.com.fragment.R.layout.activity_main);
}
public void fragmentLifecycle(View view) {
startActivity(new Intent(this, FragmentLifecycleActivity.class));
}
public void fragmentForResult(View view) {
startActivity(new Intent(this, ActivityTestFragmentResult.class));
}
private void showFragment(@NonNull FragmentManager fragmentManager, @NonNull Fragment fragment, int frameId) {
//Log.e("Lifecycle", "MainActivity fragment.isAdded() : " + fragment.isAdded() + ", " + fragment);
FragmentTransaction ft = fragmentManager.beginTransaction();
if (fragment.isAdded()) {
ft.show(fragment);
} else {
ft.add(frameId, fragment);
}
ft.commitAllowingStateLoss();
}
public void goDrawerLayout(View view) {
startActivity(new Intent(this, DrawerLayoutActivity.class));
}
public void goViewPager(View view) {
startActivity(new Intent(this, ViewPagerActivity.class));
}
public void fragmentAnimation(View view) {
if (mFragmentAnimation == null) {
mFragmentAnimation = new FragmentAnimation();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.fragment_expand, R.anim.fragment_collapse);
if (mFragmentAnimation.isVisible()) {
findViewById(R.id.fragment_container).setVisibility(View.GONE);
transaction.hide(mFragmentAnimation);
} else {
findViewById(R.id.fragment_container).setVisibility(View.VISIBLE);
if (mFragmentAnimation.isAdded()) {
transaction.show(mFragmentAnimation);
} else {
transaction.add(R.id.fragment_container, mFragmentAnimation);
}
}
transaction.commit();
}
}
| 963 |
22,688 | /******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/third_party_perception/third_party_perception_smartereye.h"
#include <memory>
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/util/message_util.h"
#include "modules/third_party_perception/common/third_party_perception_gflags.h"
#include "modules/third_party_perception/tools/conversion_smartereye.h"
namespace apollo {
namespace third_party_perception {
using apollo::perception::PerceptionObstacles;
ThirdPartyPerceptionSmartereye::ThirdPartyPerceptionSmartereye(
apollo::cyber::Node* const node) :ThirdPartyPerception(node) {
smartereye_obstacles_reader_ =
node_->CreateReader<apollo::drivers::SmartereyeObstacles>(
FLAGS_smartereye_obstacles_topic,
[this](const std::shared_ptr<
apollo::drivers::SmartereyeObstacles> &message) {
OnSmartereye(*message.get());
});
smartereye_lanemark_reader_ =
node_->CreateReader<apollo::drivers::SmartereyeLanemark>(
FLAGS_smartereye_lanemark_topic,
[this](const std::shared_ptr<
apollo::drivers::SmartereyeLanemark> &message) {
OnSmartereyeLanemark(*message.get());
});
}
void ThirdPartyPerceptionSmartereye::OnSmartereye(
const apollo::drivers::SmartereyeObstacles& message) {
ADEBUG << "Received smartereye data: run smartereye callback.";
std::lock_guard<std::mutex> lock(third_party_perception_mutex_);
eye_obstacles_ = conversion_smartereye::SmartereyeToPerceptionObstacles(
message, smartereye_lanemark_, localization_, chassis_);
}
void ThirdPartyPerceptionSmartereye::OnSmartereyeLanemark(
const apollo::drivers::SmartereyeLanemark& message) {
ADEBUG << "Received smartereye data: run smartereye callback.";
std::lock_guard<std::mutex> lock(third_party_perception_mutex_);
smartereye_lanemark_.CopyFrom(message);
}
bool ThirdPartyPerceptionSmartereye::Process(
PerceptionObstacles* const response) {
ADEBUG << "Timer is triggered: publish PerceptionObstacles";
CHECK_NOTNULL(response);
std::lock_guard<std::mutex> lock(third_party_perception_mutex_);
*response = eye_obstacles_;
common::util::FillHeader(FLAGS_third_party_perception_node_name, response);
eye_obstacles_.Clear();
return true;
}
} // namespace third_party_perception
} // namespace apollo
| 1,016 |
778 | //--------------------------------------------------------------------------------------------------------------------//
// //
// Tuplex: Blazing Fast Python Data Science //
// //
// //
// (c) 2017 - 2021, Tuplex team //
// Created by <NAME> on 8/31/2021 //
// License: Apache 2.0 //
//--------------------------------------------------------------------------------------------------------------------//
#ifndef TUPLEX_TIMESTAMP_H
#define TUPLEX_TIMESTAMP_H
#ifdef BUILD_WITH_ORC
namespace tuplex { namespace orc {
/*!
* Implementation of OrcBatch for orc Timestamp types.
*/
class TimestampBatch : public OrcBatch {
public:
TimestampBatch() = delete;
TimestampBatch(::orc::ColumnVectorBatch *orcBatch, uint64_t numRows, bool isOption) : _orcBatch(
static_cast<::orc::TimestampVectorBatch *>(orcBatch)) {
_orcBatch->numElements = numRows;
_orcBatch->hasNulls = isOption;
}
void setData(int64_t value, uint64_t row) {
_orcBatch->data[row] = value;
auto nanos = value * 1000000000;
if (nanos != 0 && nanos / value != 1000000000) {
nanos = 2147483647;
}
_orcBatch->nanoseconds[row] = nanos;
}
void setData(tuplex::Deserializer &ds, uint64_t col, uint64_t row) override {
if (row == _orcBatch->capacity) {
_orcBatch->resize(_orcBatch->capacity * scaleFactor());
}
auto notNull = !ds.isNull(col);
_orcBatch->notNull[row] = notNull;
if (notNull) {
auto value = ds.getInt(col);
setData(value, row);
}
}
void setData(tuplex::Field field, uint64_t row) override {
if (row == _orcBatch->capacity) {
_orcBatch->resize(_orcBatch->capacity * scaleFactor());
}
auto notNull = !field.isNull();
_orcBatch->notNull[row] = notNull;
if (notNull) {
auto value = field.getInt();
setData(value, row);
}
}
void setBatch(::orc::ColumnVectorBatch *newBatch) override {
_orcBatch = static_cast<::orc::TimestampVectorBatch *>(newBatch);
}
void getField(Serializer &serializer, uint64_t row) override {
using namespace tuplex;
if (_orcBatch->hasNulls) {
if (_orcBatch->notNull[row]) {
serializer.append(option<int>(_orcBatch->data[row]));
} else {
serializer.append(option<int>::none);
}
} else {
serializer.append(_orcBatch->data[row]);
}
}
tuplex::Field getField(uint64_t row) override {
using namespace tuplex;
if (_orcBatch->hasNulls) {
if (_orcBatch->notNull[row]) {
return Field(option<int64_t>(_orcBatch->data[row]));
} else {
return Field(option<int64_t>::none);
}
} else {
return Field(_orcBatch->data[row]);
}
}
private:
::orc::TimestampVectorBatch *_orcBatch;
};
}}
#endif
#endif //TUPLEX_TIMESTAMP_H
| 2,034 |
679 | <reponame>Grosskopf/openoffice
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <flddropdown.hxx>
#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif
#include <svl/poolitem.hxx>
#ifndef _UNOFLDMID_H
#include <unofldmid.h>
#endif
#include <unoprnms.hxx>
using namespace com::sun::star;
using rtl::OUString;
using std::vector;
static String aEmptyString;
SwDropDownFieldType::SwDropDownFieldType()
: SwFieldType(RES_DROPDOWN)
{
}
SwDropDownFieldType::~SwDropDownFieldType()
{
}
SwFieldType * SwDropDownFieldType::Copy() const
{
return new SwDropDownFieldType;
}
SwDropDownField::SwDropDownField(SwFieldType * pTyp)
: SwField(pTyp, 0, LANGUAGE_SYSTEM)
{
}
SwDropDownField::SwDropDownField(const SwDropDownField & rSrc)
: SwField(rSrc.GetTyp(), rSrc.GetFormat(), rSrc.GetLanguage()),
aValues(rSrc.aValues), aSelectedItem(rSrc.aSelectedItem),
aName(rSrc.aName), aHelp(rSrc.aHelp), aToolTip(rSrc.aToolTip)
{
}
SwDropDownField::~SwDropDownField()
{
}
String SwDropDownField::Expand() const
{
String sSelect = GetSelectedItem();
if(!sSelect.Len())
{
vector<String>::const_iterator aIt = aValues.begin();
if ( aIt != aValues.end())
sSelect = *aIt;
}
//if still no list value is available a default text of 10 spaces is to be set
if(!sSelect.Len())
sSelect.AppendAscii ( RTL_CONSTASCII_STRINGPARAM (" "));
return sSelect;
}
SwField * SwDropDownField::Copy() const
{
return new SwDropDownField(*this);
}
const String & SwDropDownField::GetPar1() const
{
return GetSelectedItem();
}
String SwDropDownField::GetPar2() const
{
return GetName();
}
void SwDropDownField::SetPar1(const String & rStr)
{
SetSelectedItem(rStr);
}
void SwDropDownField::SetPar2(const String & rName)
{
SetName(rName);
}
void SwDropDownField::SetItems(const vector<String> & rItems)
{
aValues = rItems;
aSelectedItem = aEmptyString;
}
void SwDropDownField::SetItems(const uno::Sequence<OUString> & rItems)
{
aValues.clear();
sal_Int32 aCount = rItems.getLength();
for (int i = 0; i < aCount; i++)
aValues.push_back(rItems[i]);
aSelectedItem = aEmptyString;
}
uno::Sequence<OUString> SwDropDownField::GetItemSequence() const
{
uno::Sequence<OUString> aSeq( aValues.size() );
OUString* pSeq = aSeq.getArray();
int i = 0;
vector<String>::const_iterator aIt;
for (aIt = aValues.begin(); aIt != aValues.end(); aIt++)
{
pSeq[i] = rtl::OUString(*aIt);
i++;
}
return aSeq;
}
const String & SwDropDownField::GetSelectedItem() const
{
return aSelectedItem;
}
const String & SwDropDownField::GetName() const
{
return aName;
}
const String & SwDropDownField::GetHelp() const
{
return aHelp;
}
const String & SwDropDownField::GetToolTip() const
{
return aToolTip;
}
sal_Bool SwDropDownField::SetSelectedItem(const String & rItem)
{
vector<String>::const_iterator aIt =
std::find(aValues.begin(), aValues.end(), rItem);
if (aIt != aValues.end())
aSelectedItem = *aIt;
else
aSelectedItem = String();
return (aIt != aValues.end());
}
void SwDropDownField::SetName(const String & rName)
{
aName = rName;
}
void SwDropDownField::SetHelp(const String & rHelp)
{
aHelp = rHelp;
}
void SwDropDownField::SetToolTip(const String & rToolTip)
{
aToolTip = rToolTip;
}
sal_Bool SwDropDownField::QueryValue(::uno::Any &rVal, sal_uInt16 nWhich) const
{
nWhich &= ~CONVERT_TWIPS;
switch( nWhich )
{
case FIELD_PROP_PAR1:
rVal <<= rtl::OUString(GetSelectedItem());
break;
case FIELD_PROP_PAR2:
rVal <<= rtl::OUString(GetName());
break;
case FIELD_PROP_PAR3:
rVal <<= rtl::OUString(GetHelp());
break;
case FIELD_PROP_PAR4:
rVal <<= rtl::OUString(GetToolTip());
break;
case FIELD_PROP_STRINGS:
rVal <<= GetItemSequence();
break;
default:
DBG_ERROR("illegal property");
}
return sal_True;
}
sal_Bool SwDropDownField::PutValue(const uno::Any &rVal,
sal_uInt16 nWhich)
{
switch( nWhich )
{
case FIELD_PROP_PAR1:
{
String aTmpStr;
::GetString( rVal, aTmpStr );
SetSelectedItem(aTmpStr);
}
break;
case FIELD_PROP_PAR2:
{
String aTmpStr;
::GetString( rVal, aTmpStr );
SetName(aTmpStr);
}
break;
case FIELD_PROP_PAR3:
{
String aTmpStr;
::GetString( rVal, aTmpStr );
SetHelp(aTmpStr);
}
break;
case FIELD_PROP_PAR4:
{
String aTmpStr;
::GetString( rVal, aTmpStr );
SetToolTip(aTmpStr);
}
break;
case FIELD_PROP_STRINGS:
{
uno::Sequence<OUString> aSeq;
rVal >>= aSeq;
SetItems(aSeq);
}
break;
default:
DBG_ERROR("illegal property");
}
return sal_True;
}
| 2,631 |
1,895 | package com.baomidou.samples.performance.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.samples.performance.entity.Student;
/**
* 学生Mapper层
* @author nieqiurong 2018/8/11 20:21.
*/
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
| 130 |
1,391 | <filename>src/lib9/fmt/fmtfdflush.c
/* Copyright (c) 2002-2006 <NAME>; see LICENSE */
#include <stdarg.h>
#include <unistd.h>
#include "plan9.h"
#include "fmt.h"
#include "fmtdef.h"
/*
* generic routine for flushing a formatting buffer
* to a file descriptor
*/
int
__fmtFdFlush(Fmt *f)
{
int n;
n = (char*)f->to - (char*)f->start;
if(n && write((uintptr)f->farg, f->start, n) != n)
return 0;
f->to = f->start;
return 1;
}
| 192 |
3,702 | <reponame>impira/yugabyte-db<filename>managed/src/main/java/com/yugabyte/yw/commissioner/tasks/subtasks/CreateAlertDefinitions.java
// Copyright (c) YugaByte, Inc.
package com.yugabyte.yw.commissioner.tasks.subtasks;
import com.yugabyte.yw.commissioner.BaseTaskDependencies;
import com.yugabyte.yw.commissioner.tasks.UniverseTaskBase;
import com.yugabyte.yw.forms.UniverseTaskParams;
import com.yugabyte.yw.models.AlertConfiguration;
import com.yugabyte.yw.models.Customer;
import com.yugabyte.yw.models.Universe;
import com.yugabyte.yw.models.filters.AlertConfigurationFilter;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CreateAlertDefinitions extends UniverseTaskBase {
@Inject
public CreateAlertDefinitions(BaseTaskDependencies baseTaskDependencies) {
super(baseTaskDependencies);
}
protected UniverseTaskParams taskParams() {
return (UniverseTaskParams) taskParams;
}
@Override
public String getName() {
return super.getName() + "(" + taskParams().universeUUID + ")";
}
@Override
public void run() {
try {
log.info("Running {}", getName());
Universe universe = Universe.getOrBadRequest(taskParams().universeUUID);
Customer customer = Customer.get(universe.customerId);
AlertConfigurationFilter filter =
AlertConfigurationFilter.builder()
.customerUuid(customer.getUuid())
.targetType(AlertConfiguration.TargetType.UNIVERSE)
.build();
List<AlertConfiguration> configurations =
alertConfigurationService
.list(filter)
.stream()
.filter(group -> group.getTarget().isAll())
.collect(Collectors.toList());
// Just need to save - service will create definition itself.
alertConfigurationService.save(configurations);
} catch (Exception e) {
String msg = getName() + " failed with exception " + e.getMessage();
log.warn(msg, e.getMessage());
throw new RuntimeException(msg, e);
}
}
}
| 798 |
536 | <filename>src/main/java/freemarker/ext/beans/MemberSelectorListMemberAccessPolicy.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 freemarker.ext.beans;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
import freemarker.template.utility.ClassUtil;
import freemarker.template.utility.NullArgumentException;
/**
* Superclass for member-selector-list-based member access policies, like {@link WhitelistMemberAccessPolicy}.
*
* <p>There are two ways you can add members to the member selector list:
* <ul>
* <li>Via a list of member selectors passed to the constructor
* <li>Via annotation (concrete type depends on subclass)
* </ul>
*
* <p>Members are identified with the following data (with the example of
* {@code com.example.MyClass.myMethod(int, int)}):
* <ul>
* <li>Upper bound class ({@code com.example.MyClass} in the example)
* <li>Member name ({@code myMethod} in the example), except for constructors where it's unused
* <li>Parameter types ({@code int, int} in the example), except for fields where it's unused
* </ul>
*
* <p>If a method or field is matched in the upper bound type, it will be automatically matched in all subtypes of that.
* It's called "upper bound" type, because the member will only be matched in classes that are {@code instanceof}
* the upper bound class. That restriction stands even if the member was inherited from another type (class or
* interface), and it wasn't even overridden in the upper bound type; the member won't be matched in the
* type where it was inherited from, if that type is more generic than the upper bound type.
*
* <p>The above inheritance rule doesn't apply to constructors. That's consistent with the fact constructors aren't
* inherited in Java (or pretty much any other language). So for example, if you add {@code com.example.A.A()} to
* the member selector list, and {@code B extends A}, then {@code com.example.B.B()} is still not matched by that list.
* If you want it to be matched, you have to add {@code com.example.B.B()} to list explicitly.
*
* <p>Note that the return type of methods aren't used in any way. If {@code myMethod(int, int)} has multiple variants
* with different return types (which is possible on the bytecode level) but the same parameter types, then all
* variants of it is matched, or none is. Similarly, the type of fields isn't used either, only the name of the field
* matters.
*
* @since 2.3.30
*/
public abstract class MemberSelectorListMemberAccessPolicy implements MemberAccessPolicy {
enum ListType {
/** Only matched members will be exposed. */
WHITELIST,
/** Matched members will not be exposed. */
BLACKLIST
}
private final ListType listType;
private final MethodMatcher methodMatcher;
private final ConstructorMatcher constructorMatcher;
private final FieldMatcher fieldMatcher;
private final Class<? extends Annotation> matchAnnotation;
/**
* A condition that matches some type members. See {@link MemberSelectorListMemberAccessPolicy} documentation for more.
* Exactly one of these will be non-{@code null}:
* {@link #getMethod()}, {@link #getConstructor()}, {@link #getField()}.
*
* @since 2.3.30
*/
public final static class MemberSelector {
private final Class<?> upperBoundType;
private final Method method;
private final Constructor<?> constructor;
private final Field field;
/**
* Use if you want to match methods similar to the specified one, in types that are {@code instanceof} of
* the specified upper bound type. When methods are matched, only the name and the parameter types matter.
*/
public MemberSelector(Class<?> upperBoundType, Method method) {
NullArgumentException.check("upperBoundType", upperBoundType);
NullArgumentException.check("method", method);
this.upperBoundType = upperBoundType;
this.method = method;
this.constructor = null;
this.field = null;
}
/**
* Use if you want to match constructors similar to the specified one, in types that are {@code instanceof} of
* the specified upper bound type. When constructors are matched, only the parameter types matter.
*/
public MemberSelector(Class<?> upperBoundType, Constructor<?> constructor) {
NullArgumentException.check("upperBoundType", upperBoundType);
NullArgumentException.check("constructor", constructor);
this.upperBoundType = upperBoundType;
this.method = null;
this.constructor = constructor;
this.field = null;
}
/**
* Use if you want to match fields similar to the specified one, in types that are {@code instanceof} of
* the specified upper bound type. When fields are matched, only the name matters.
*/
public MemberSelector(Class<?> upperBoundType, Field field) {
NullArgumentException.check("upperBoundType", upperBoundType);
NullArgumentException.check("field", field);
this.upperBoundType = upperBoundType;
this.method = null;
this.constructor = null;
this.field = field;
}
/**
* Not {@code null}.
*/
public Class<?> getUpperBoundType() {
return upperBoundType;
}
/**
* Maybe {@code null};
* set if the selector matches methods similar to the returned one.
*/
public Method getMethod() {
return method;
}
/**
* Maybe {@code null};
* set if the selector matches constructors similar to the returned one.
*/
public Constructor<?> getConstructor() {
return constructor;
}
/**
* Maybe {@code null};
* set if the selector matches fields similar to the returned one.
*/
public Field getField() {
return field;
}
/**
* Parses a member selector that was specified with a string.
*
* @param classLoader
* Used to resolve class names in the member selectors. Generally you want to pick a class that belongs to
* you application (not to a 3rd party library, like FreeMarker), and then call
* {@link Class#getClassLoader()} on that. Note that the resolution of the classes is not lazy, and so the
* {@link ClassLoader} won't be stored after this method returns.
* @param memberSelectorString
* Describes the member (method, constructor, field) which you want to whitelist. Starts with the full
* qualified name of the member, like {@code com.example.MyClass.myMember}. Unless it's a field, the
* name is followed by comma separated list of the parameter types inside parentheses, like in
* {@code com.example.MyClass.myMember(java.lang.String, boolean)}. The parameter type names must be
* also full qualified names, except primitive type names. Array types must be indicated with one or
* more {@code []}-s after the type name. Varargs arguments shouldn't be marked with {@code ...}, but with
* {@code []}. In the member name, like {@code com.example.MyClass.myMember}, the class refers to the so
* called "upper bound class". Regarding that and inheritance rules see the class level documentation.
*
* @throws ClassNotFoundException If a type referred in the member selector can't be found.
* @throws NoSuchMethodException If the method or constructor referred in the member selector can't be found.
* @throws NoSuchFieldException If the field referred in the member selector can't be found.
*/
public static MemberSelector parse(String memberSelectorString, ClassLoader classLoader) throws
ClassNotFoundException, NoSuchMethodException, NoSuchFieldException {
if (memberSelectorString.contains("<") || memberSelectorString.contains(">")
|| memberSelectorString.contains("...") || memberSelectorString.contains(";")) {
throw new IllegalArgumentException(
"Malformed whitelist entry (shouldn't contain \"<\", \">\", \"...\", or \";\"): "
+ memberSelectorString);
}
String cleanedStr = memberSelectorString.trim().replaceAll("\\s*([\\.,\\(\\)\\[\\]])\\s*", "$1");
int postMemberNameIdx;
boolean hasArgList;
{
int openParenIdx = cleanedStr.indexOf('(');
hasArgList = openParenIdx != -1;
postMemberNameIdx = hasArgList ? openParenIdx : cleanedStr.length();
}
final int postClassDotIdx = cleanedStr.lastIndexOf('.', postMemberNameIdx);
if (postClassDotIdx == -1) {
throw new IllegalArgumentException("Malformed whitelist entry (missing dot): " + memberSelectorString);
}
Class<?> upperBoundClass;
String upperBoundClassStr = cleanedStr.substring(0, postClassDotIdx);
if (!isWellFormedClassName(upperBoundClassStr)) {
throw new IllegalArgumentException("Malformed whitelist entry (malformed upper bound class name): "
+ memberSelectorString);
}
upperBoundClass = classLoader.loadClass(upperBoundClassStr);
String memberName = cleanedStr.substring(postClassDotIdx + 1, postMemberNameIdx);
if (!isWellFormedJavaIdentifier(memberName)) {
throw new IllegalArgumentException(
"Malformed whitelist entry (malformed member name): " + memberSelectorString);
}
if (hasArgList) {
if (cleanedStr.charAt(cleanedStr.length() - 1) != ')') {
throw new IllegalArgumentException("Malformed whitelist entry (should end with ')'): "
+ memberSelectorString);
}
String argsSpec = cleanedStr.substring(postMemberNameIdx + 1, cleanedStr.length() - 1);
StringTokenizer tok = new StringTokenizer(argsSpec, ",");
int argCount = tok.countTokens();
Class<?>[] argTypes = new Class[argCount];
for (int i = 0; i < argCount; i++) {
String argClassName = tok.nextToken();
int arrayDimensions = 0;
while (argClassName.endsWith("[]")) {
arrayDimensions++;
argClassName = argClassName.substring(0, argClassName.length() - 2);
}
Class<?> argClass;
Class<?> primArgClass = ClassUtil.resolveIfPrimitiveTypeName(argClassName);
if (primArgClass != null) {
argClass = primArgClass;
} else {
if (!isWellFormedClassName(argClassName)) {
throw new IllegalArgumentException(
"Malformed whitelist entry (malformed argument class name): " + memberSelectorString);
}
argClass = classLoader.loadClass(argClassName);
}
argTypes[i] = ClassUtil.getArrayClass(argClass, arrayDimensions);
}
return memberName.equals(upperBoundClass.getSimpleName())
? new MemberSelector(upperBoundClass, upperBoundClass.getConstructor(argTypes))
: new MemberSelector(upperBoundClass, upperBoundClass.getMethod(memberName, argTypes));
} else {
return new MemberSelector(upperBoundClass, upperBoundClass.getField(memberName));
}
}
/**
* Convenience method to parse all member selectors in the collection (see {@link #parse(String, ClassLoader)}),
* while also filtering out blank and comment lines; see {@link #parse(String, ClassLoader)},
* and {@link #isIgnoredLine(String)}.
*
* @param ignoreMissingClassOrMember If {@code true}, members selectors that throw exceptions because the
* referred type or member can't be found will be silently ignored. If {@code true}, same exceptions
* will be just thrown by this method.
*/
public static List<MemberSelector> parse(
Collection<String> memberSelectors, boolean ignoreMissingClassOrMember, ClassLoader classLoader)
throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException {
List<MemberSelector> parsedMemberSelectors = new ArrayList<>(memberSelectors.size());
for (String memberSelector : memberSelectors) {
if (!isIgnoredLine(memberSelector)) {
try {
parsedMemberSelectors.add(parse(memberSelector, classLoader));
} catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
if (!ignoreMissingClassOrMember) {
throw e;
}
}
}
}
return parsedMemberSelectors;
}
/**
* A line is ignored if it's blank or a comment. A line is be blank if it doesn't contain non-whitespace
* character. A line is a comment if it starts with {@code #}, or {@code //} (ignoring any amount of
* preceding whitespace).
*/
public static boolean isIgnoredLine(String line) {
String trimmedLine = line.trim();
return trimmedLine.length() == 0 || trimmedLine.startsWith("#") || trimmedLine.startsWith("//");
}
}
/**
* @param memberSelectors
* List of member selectors; see {@link MemberSelectorListMemberAccessPolicy} class-level documentation for
* more.
* @param listType
* Decides the "color" of the list
* @param matchAnnotation
*/
MemberSelectorListMemberAccessPolicy(
Collection<? extends MemberSelector> memberSelectors, ListType listType,
Class<? extends Annotation> matchAnnotation) {
this.listType = listType;
this.matchAnnotation = matchAnnotation;
methodMatcher = new MethodMatcher();
constructorMatcher = new ConstructorMatcher();
fieldMatcher = new FieldMatcher();
for (MemberSelector memberSelector : memberSelectors) {
Class<?> upperBoundClass = memberSelector.upperBoundType;
if (memberSelector.constructor != null) {
constructorMatcher.addMatching(upperBoundClass, memberSelector.constructor);
} else if (memberSelector.method != null) {
methodMatcher.addMatching(upperBoundClass, memberSelector.method);
} else if (memberSelector.field != null) {
fieldMatcher.addMatching(upperBoundClass, memberSelector.field);
} else {
throw new AssertionError();
}
}
}
@Override
public final ClassMemberAccessPolicy forClass(final Class<?> contextClass) {
return new ClassMemberAccessPolicy() {
@Override
public boolean isMethodExposed(Method method) {
return matchResultToIsExposedResult(
methodMatcher.matches(contextClass, method)
|| matchAnnotation != null
&& _MethodUtil.getInheritableAnnotation(contextClass, method, matchAnnotation)
!= null);
}
@Override
public boolean isConstructorExposed(Constructor<?> constructor) {
return matchResultToIsExposedResult(
constructorMatcher.matches(contextClass, constructor)
|| matchAnnotation != null
&& _MethodUtil.getInheritableAnnotation(contextClass, constructor, matchAnnotation)
!= null);
}
@Override
public boolean isFieldExposed(Field field) {
return matchResultToIsExposedResult(
fieldMatcher.matches(contextClass, field)
|| matchAnnotation != null
&& _MethodUtil.getInheritableAnnotation(contextClass, field, matchAnnotation)
!= null);
}
};
}
private boolean matchResultToIsExposedResult(boolean matches) {
if (listType == ListType.WHITELIST) {
return matches;
}
if (listType == ListType.BLACKLIST) {
return !matches;
}
throw new AssertionError();
}
private static boolean isWellFormedClassName(String s) {
if (s.length() == 0) {
return false;
}
int identifierStartIdx = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (i == identifierStartIdx) {
if (!Character.isJavaIdentifierStart(c)) {
return false;
}
} else if (c == '.' && i != s.length() - 1) {
identifierStartIdx = i + 1;
} else {
if (!Character.isJavaIdentifierPart(c)) {
return false;
}
}
}
return true;
}
private static boolean isWellFormedJavaIdentifier(String s) {
if (s.length() == 0) {
return false;
}
if (!Character.isJavaIdentifierStart(s.charAt(0))) {
return false;
}
for (int i = 1; i < s.length(); i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
return false;
}
}
return true;
}
}
| 7,950 |
571 | <gh_stars>100-1000
/***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#include "ForaValueArrayCodegen.hpp"
#include "ForaValueArraySpaceRequirements.hppml"
#include "NativeLayoutType.hppml"
#include "../../Judgment/JudgmentOnValue.hppml"
#include "../../../core/SymbolExport.hpp"
#include "../../../core/Logging.hpp"
#include "../../Native/NativeCode.hppml"
#include "../../Native/NativeTypeFor.hpp"
#include "../../Native/NativeExpressionBuilder.hppml"
#include "../../Native/TypedNativeExpression.hppml"
#include "../../Native/TypedNativeLibraryFunction.hpp"
#include "DestructorsAndConstructors.hppml"
#include "TypedForaValueTypecasting.hppml"
using TypedFora::Abi::ForaValueArray;
NativeType NativeTypeForImpl<ForaValueArray>::get()
{
NativeType packedValues =
NativeType::Composite("VTablePtr", NativeType::uword().ptr()) +
NativeType::Composite("mIsWriteable", NativeType::uword()) +
NativeType::Composite("mOwningMemoryPool", NativeType::Nothing().ptr()) +
NativeType::Composite("mDataPtr", NativeType::uint8().ptr()) +
NativeType::Composite("mBytesReserved", NativeType::uword()) +
NativeType::Composite("mOffsetTablePtr", NativeType::Integer(8, false).ptr().ptr()) +
NativeType::Composite("mPerValueOffsetOrOffsetTableCountAllocated", NativeType::uword()) +
NativeType::Composite("mJudgmentLookupTable", NativeTypeFor<JudgmentOnValue>::get().ptr()) +
NativeType::Composite("mJudgmentLookupTableSize", NativeType::uword()) +
NativeType::Composite("mPerValueJudgments", NativeType::Nothing().ptr()) +
NativeType::Composite("mPerValueJudgmentsAllocated", NativeType::uword()) +
NativeType::Composite("mValueCount", NativeType::uword());
return packedValues +
NativeType::Composite(
"mPadding",
NativeType::Array(
NativeType::Integer(8,false),
sizeof(ForaValueArray) - packedValues.packedSize()
)
)
;
}
namespace TypedFora {
namespace Abi {
namespace ForaValueArrayCodegen {
NativeExpression isWriteableExpression(
const NativeExpression& valueArrayPointerExpr
)
{
lassert(*valueArrayPointerExpr.type() == NativeTypeFor<ForaValueArray>::get().ptr());
return valueArrayPointerExpr["mIsWriteable"].load();
}
NativeExpression sizeExpression(
const NativeExpression& valueArrayPointerExpr
)
{
lassert(*valueArrayPointerExpr.type() == NativeTypeFor<ForaValueArray>::get().ptr());
return valueArrayPointerExpr["mValueCount"].load();
}
NativeExpression usingOffsetTableExpression(
const NativeExpression& valueArrayPointerExpr
)
{
lassert(*valueArrayPointerExpr.type() == NativeTypeFor<ForaValueArray>::get().ptr());
return
valueArrayPointerExpr["mOffsetTablePtr"].load().isNotNull();
}
NativeExpression offsetForExpression(
const NativeExpression& valueArrayPointerExpr,
const NativeExpression& indexExpr
)
{
lassert_dump(
*valueArrayPointerExpr.type() == NativeTypeFor<ForaValueArray>::get().ptr(),
"Expected ForaValueArray* but got "
<< prettyPrintString(*valueArrayPointerExpr.type())
);
lassert(indexExpr.type()->isInteger());
return NativeExpression::If(
usingOffsetTableExpression(valueArrayPointerExpr),
//use the offset table
valueArrayPointerExpr["mOffsetTablePtr"].load()[indexExpr].load(),
//use the stride table
valueArrayPointerExpr["mDataPtr"].load()
[valueArrayPointerExpr["mPerValueOffsetOrOffsetTableCountAllocated"].load() * indexExpr]
);
}
NativeExpression jovForExpression(
const NativeExpression& valueArrayPointerExpr,
const NativeExpression& indexExpr
)
{
lassert(*valueArrayPointerExpr.type() == NativeTypeFor<ForaValueArray>::get().ptr());
lassert(indexExpr.type()->isInteger());
return NativeExpression::If(
valueArrayPointerExpr["mJudgmentLookupTable"].load(),
NativeExpression::If(
valueArrayPointerExpr["mJudgmentLookupTableSize"].load() == NativeExpression::ConstantULong(1),
valueArrayPointerExpr["mJudgmentLookupTable"].load()[0].load(),
valueArrayPointerExpr["mJudgmentLookupTable"].load()
[valueArrayPointerExpr["mPerValueJudgments"].load()
.cast(NativeType::Integer(8,false).ptr(),false)
[indexExpr].load()
].load()
),
valueArrayPointerExpr["mPerValueJudgments"].load().cast(
NativeTypeFor<JudgmentOnValue>::get().ptr(),
false
)[indexExpr].load()
);
}
extern "C" {
BSA_DLLEXPORT
void FORA_clib_foraValueArray_AppendUsingData(
ForaValueArray* array,
uint8_t* data,
const JudgmentOnValue& inJudgment
)
{
array->append(inJudgment, data, 1, 0);
}
BSA_DLLEXPORT
void FORA_clib_foraValueArray_AppendUsingImplval(
ForaValueArray* array,
const ImplValContainer& inIVC
)
{
array->append(inIVC);
}
}
//a semi-direct fast append occurs when we have per-value judgments allocated, and enough
//room to write directly into the system
NativeExpression isSemiDirectFastAppendableExpression(
const NativeExpression& valueArrayPointerExpr,
const JudgmentOnValue& valueJmt
)
{
return
valueArrayPointerExpr["mJudgmentLookupTableSize"].load().isNull()
&& valueArrayPointerExpr["mPerValueJudgments"].load().isNotNull()
&& (valueArrayPointerExpr["mPerValueJudgmentsAllocated"].load() >
valueArrayPointerExpr["mValueCount"].load())
&& (
NativeExpression::If(
valueArrayPointerExpr["mOffsetTablePtr"].load().isNull(),
//not using an offset table. make sure we're smaller than the offset!
( (valueArrayPointerExpr["mValueCount"].load() + NativeExpression::ConstantULong(1)) *
valueArrayPointerExpr["mPerValueOffsetOrOffsetTableCountAllocated"].load() <=
valueArrayPointerExpr["mBytesReserved"].load()
) &&
valueArrayPointerExpr["mPerValueOffsetOrOffsetTableCountAllocated"].load() >=
NativeExpression::ConstantULong(PackedForaValues::strideFor(valueJmt))
,
//using an offset table, so we need to check that we have both space in the
//data table and also in the offset table
((valueArrayPointerExpr["mOffsetTablePtr"].load()
[valueArrayPointerExpr["mValueCount"].load()].load()[
NativeExpression::ConstantInt32(PackedForaValues::strideFor(valueJmt))
]).cast(NativeTypeFor<size_t>::get(), false)
<=
(valueArrayPointerExpr["mDataPtr"].load()[
valueArrayPointerExpr["mBytesReserved"].load()
])
.cast(NativeTypeFor<size_t>::get(), false)
)
&& (valueArrayPointerExpr["mPerValueOffsetOrOffsetTableCountAllocated"].load() >
valueArrayPointerExpr["mValueCount"].load())
)
);
}
NativeExpression semiDirectFastAppendExpression(
const NativeExpression& valueArrayPointerExpr,
const NativeExpression& dataToAppendExpr,
const JudgmentOnValue& valueJmt
)
{
lassert(*valueJmt.vectorElementJOV() == valueJmt);
JOV storageJOV = JudgmentOnValue::OfType(*valueJmt.type());
//we can directly append this value to the end of the array
NativeExpressionBuilder builder;
NativeExpression targetPtr = builder.add(
NativeExpression::If(
usingOffsetTableExpression(valueArrayPointerExpr),
//use the offset table
valueArrayPointerExpr["mOffsetTablePtr"].load()
[valueArrayPointerExpr["mValueCount"].load()].load(),
//use the stride table
valueArrayPointerExpr["mDataPtr"].load()[
(valueArrayPointerExpr["mPerValueOffsetOrOffsetTableCountAllocated"].load() *
valueArrayPointerExpr["mValueCount"].load()).cast(NativeType::int32(), false)
]
)
);
//store a duplicated copy of the value
builder.add(
targetPtr.cast(nativeLayoutType(storageJOV).ptr(), false)
.store(
TypedFora::Abi::duplicate(
dataToAppendExpr,
valueJmt,
storageJOV
)
)
);
//update the judgment table
builder.add(
valueArrayPointerExpr["mPerValueJudgments"].load()
.cast(NativeTypeFor<JudgmentOnValue*>::get(), false)
[valueArrayPointerExpr["mValueCount"].load()]
.store(jovAsNativeConstant(valueJmt))
);
//increment mValueCount
builder.add(
valueArrayPointerExpr["mValueCount"].store(
valueArrayPointerExpr["mValueCount"].load() +
NativeExpression::ConstantULong(1)
)
);
//update the offset table
builder.add(
NativeExpression::If(
valueArrayPointerExpr["mOffsetTablePtr"].load().isNotNull(),
valueArrayPointerExpr["mOffsetTablePtr"].load()
[valueArrayPointerExpr["mValueCount"].load()]
.store(targetPtr[NativeExpression::ConstantInt32(PackedForaValues::strideFor(valueJmt))])
,
NativeExpression::Nothing()
)
);
return builder(NativeExpression());
}
//a "direct" fast append occurs when we don't have to do anything but write the value and update
//the count.
NativeExpression isDirectFastAppendableExpression(
const NativeExpression& valueArrayPointerExpr,
const JudgmentOnValue& valueJmt
)
{
return
NativeExpression::If(
(valueArrayPointerExpr["mJudgmentLookupTableSize"].load() == NativeExpression::ConstantULong(1)),
(valueArrayPointerExpr["mJudgmentLookupTable"].load().load() == jovAsNativeConstant(valueJmt))
&& ( (valueArrayPointerExpr["mValueCount"].load() + NativeExpression::ConstantULong(1)) *
valueArrayPointerExpr["mPerValueOffsetOrOffsetTableCountAllocated"].load() <=
valueArrayPointerExpr["mBytesReserved"].load()
),
NativeExpression::Constant(NativeConstant::Bool(false))
);
}
NativeExpression directFastAppendExpression(
const NativeExpression& valueArrayPointerExpr,
const NativeExpression& dataToAppendExpr,
const JudgmentOnValue& valueJmt
)
{
lassert(valueJmt.type());
JOV storageJOV = JudgmentOnValue::OfType(*valueJmt.type());
//we can directly append this value to the end of the array
NativeExpressionBuilder builder;
NativeExpression offsetExpr = builder.add(
valueArrayPointerExpr["mValueCount"].load() *
valueArrayPointerExpr["mPerValueOffsetOrOffsetTableCountAllocated"].load()
);
NativeExpression targetPtr = builder.add(
valueArrayPointerExpr["mDataPtr"].load()
[offsetExpr]
);
//store a duplicated copy of the value
builder.add(
targetPtr.cast(nativeLayoutType(storageJOV).ptr(), false)
.store(
TypedFora::Abi::duplicate(
dataToAppendExpr,
valueJmt,
storageJOV
)
)
);
builder.add(
valueArrayPointerExpr["mValueCount"].store(
valueArrayPointerExpr["mValueCount"].load() +
NativeExpression::ConstantULong(1)
)
);
return builder(NativeExpression());
}
NativeExpression appendExpression(
const NativeExpression& valueArrayPointerExpr,
const NativeExpression& dataToAppendExpr,
const JudgmentOnValue& valueJmt
)
{
lassert(valueJmt.isValidVectorElementJOV());
return NativeExpression::If(
isDirectFastAppendableExpression(valueArrayPointerExpr, valueJmt),
directFastAppendExpression(valueArrayPointerExpr, dataToAppendExpr, valueJmt) >>
NativeExpression::Constant(NativeConstant::Bool(true)),
NativeExpression::If(
isSemiDirectFastAppendableExpression(valueArrayPointerExpr, valueJmt),
semiDirectFastAppendExpression(valueArrayPointerExpr, dataToAppendExpr, valueJmt) >>
NativeExpression::Constant(NativeConstant::Bool(true)),
NativeExpression::Constant(NativeConstant::Bool(false)),
.999999
),
.999999
);
}
}
}
}
| 4,360 |
1,068 | <reponame>systemmonkey42/KiTTY<gh_stars>1000+
/*
* PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#define PUTTY_DO_GLOBALS /* actually _define_ globals */
#include "putty.h"
#include "storage.h"
#include "tree234.h"
#include "winsecur.h"
#ifdef MOD_PERSO
// Flag pour le fonctionnement en mode "portable" (gestion par fichiers)
extern int IniFileFlag ;
// Flag permettant la gestion de l'arborscence (dossier=folder) dans le cas d'un savemode=dir
extern int DirectoryBrowseFlag ;
#include "../../kitty_crypt.c"
#include "../../kitty_commun.h"
int GetPuttyFlag() { return 1 ; }
size_t win_seat_output_local(Seat *seat, bool is_stderr, const void *data, size_t len) { return 0 ; }
int get_param( const char * val ) {
if( !stricmp( val, "INIFILE" ) ) { return IniFileFlag ; }
else if( !stricmp( val, "DIRECTORYBROWSE" ) ) { return DirectoryBrowseFlag ; }
return 0 ;
}
void SetPasswordInConfig( char * password ) {
int len ;
if( password!=NULL ) {
len = strlen( password ) ;
if( len > 126 ) len = 126 ;
}
}
void SetUsernameInConfig( char * username ) {
int len ;
if( username!=NULL ) {
len = strlen( username ) ;
if( len > 126 ) len = 126 ;
}
}
void debug_logevent( const char *fmt, ... ) {
va_list ap;
char *buf;
va_start(ap, fmt);
buf = dupvprintf(fmt, ap) ;
va_end(ap);
printf(buf) ;
free(buf);
}
#endif
#ifdef MOD_PROXY
#include "kitty_proxy.h"
#endif
#define WM_AGENT_CALLBACK (WM_APP + 4)
struct agent_callback {
void (*callback)(void *, void *, int);
void *callback_ctx;
void *data;
int len;
};
void cmdline_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
console_print_error_msg_fmt_v("plink", fmt, ap);
va_end(ap);
exit(1);
}
HANDLE inhandle, outhandle, errhandle;
struct handle *stdin_handle, *stdout_handle, *stderr_handle;
handle_sink stdout_hs, stderr_hs;
StripCtrlChars *stdout_scc, *stderr_scc;
BinarySink *stdout_bs, *stderr_bs;
DWORD orig_console_mode;
WSAEVENT netevent;
static Backend *backend;
Conf *conf;
static void plink_echoedit_update(Seat *seat, bool echo, bool edit)
{
/* Update stdin read mode to reflect changes in line discipline. */
DWORD mode;
mode = ENABLE_PROCESSED_INPUT;
if (echo)
mode = mode | ENABLE_ECHO_INPUT;
else
mode = mode & ~ENABLE_ECHO_INPUT;
if (edit)
mode = mode | ENABLE_LINE_INPUT;
else
mode = mode & ~ENABLE_LINE_INPUT;
SetConsoleMode(inhandle, mode);
}
static size_t plink_output(
Seat *seat, bool is_stderr, const void *data, size_t len)
{
BinarySink *bs = is_stderr ? stderr_bs : stdout_bs;
put_data(bs, data, len);
return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
}
static bool plink_eof(Seat *seat)
{
handle_write_eof(stdout_handle);
return false; /* do not respond to incoming EOF with outgoing */
}
static int plink_get_userpass_input(Seat *seat, prompts_t *p, bufchain *input)
{
int ret;
ret = cmdline_get_passwd_input(p);
if (ret == -1)
ret = console_get_userpass_input(p);
return ret;
}
static const SeatVtable plink_seat_vt = {
plink_output,
plink_eof,
plink_get_userpass_input,
nullseat_notify_remote_exit,
console_connection_fatal,
nullseat_update_specials_menu,
nullseat_get_ttymode,
nullseat_set_busy_status,
console_verify_ssh_host_key,
console_confirm_weak_crypto_primitive,
console_confirm_weak_cached_hostkey,
nullseat_is_never_utf8,
plink_echoedit_update,
nullseat_get_x_display,
nullseat_get_windowid,
nullseat_get_window_pixel_size,
console_stripctrl_new,
console_set_trust_status,
};
static Seat plink_seat[1] = {{ &plink_seat_vt }};
static DWORD main_thread_id;
void agent_schedule_callback(void (*callback)(void *, void *, int),
void *callback_ctx, void *data, int len)
{
struct agent_callback *c = snew(struct agent_callback);
c->callback = callback;
c->callback_ctx = callback_ctx;
c->data = data;
c->len = len;
PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
}
/*
* Short description of parameters.
*/
static void usage(void)
{
printf("Plink: command-line connection utility\n");
printf("%s\n", ver);
printf("Usage: plink [options] [user@]host [command]\n");
printf(" (\"host\" can also be a PuTTY saved session name)\n");
printf("Options:\n");
printf(" -V print version information and exit\n");
printf(" -pgpfp print PGP key fingerprints and exit\n");
printf(" -v show verbose messages\n");
printf(" -load sessname Load settings from saved session\n");
printf(" -ssh -telnet -rlogin -raw -serial\n");
printf(" force use of a particular protocol\n");
printf(" -P port connect to specified port\n");
printf(" -l user connect with specified username\n");
printf(" -batch disable all interactive prompts\n");
printf(" -proxycmd command\n");
printf(" use 'command' as local proxy\n");
printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
printf(" Specify the serial configuration (serial only)\n");
printf("The following options only apply to SSH connections:\n");
printf(" -pw passw login with specified password\n");
printf(" -D [listen-IP:]listen-port\n");
printf(" Dynamic SOCKS-based port forwarding\n");
printf(" -L [listen-IP:]listen-port:host:port\n");
printf(" Forward local port to remote address\n");
printf(" -R [listen-IP:]listen-port:host:port\n");
printf(" Forward remote port to local address\n");
printf(" -X -x enable / disable X11 forwarding\n");
printf(" -A -a enable / disable agent forwarding\n");
printf(" -t -T enable / disable pty allocation\n");
printf(" -1 -2 force use of particular protocol version\n");
printf(" -4 -6 force use of IPv4 or IPv6\n");
printf(" -C enable compression\n");
printf(" -i key private key file for user authentication\n");
printf(" -noagent disable use of Pageant\n");
printf(" -agent enable use of Pageant\n");
printf(" -noshare disable use of connection sharing\n");
printf(" -share enable use of connection sharing\n");
printf(" -hostkey aa:bb:cc:...\n");
printf(" manually specify a host key (may be repeated)\n");
printf(" -sanitise-stderr, -sanitise-stdout, "
"-no-sanitise-stderr, -no-sanitise-stdout\n");
printf(" do/don't strip control chars from standard "
"output/error\n");
printf(" -no-antispoof omit anti-spoofing prompt after "
"authentication\n");
printf(" -m file read remote command(s) from file\n");
printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
printf(" -N don't start a shell/command (SSH-2 only)\n");
printf(" -nc host:port\n");
printf(" open tunnel in place of session (SSH-2 only)\n");
printf(" -sshlog file\n");
printf(" -sshrawlog file\n");
printf(" log protocol details to a file\n");
printf(" -shareexists\n");
printf(" test whether a connection-sharing upstream exists\n");
#ifdef MOD_PERSO
printf(" -auto-store-sshkey\n");
printf(" store automatically the servers ssh keys\n");
#endif
exit(1);
}
static void version(void)
{
char *buildinfo_text = buildinfo("\n");
printf("plink: %s\n%s\n", ver, buildinfo_text);
sfree(buildinfo_text);
exit(0);
}
char *do_select(SOCKET skt, bool enable)
{
int events;
if (enable) {
events = (FD_CONNECT | FD_READ | FD_WRITE |
FD_OOB | FD_CLOSE | FD_ACCEPT);
} else {
events = 0;
}
if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
switch (p_WSAGetLastError()) {
case WSAENETDOWN:
return "Network is down";
default:
return "WSAEventSelect(): unknown error";
}
}
return NULL;
}
size_t stdin_gotdata(struct handle *h, const void *data, size_t len, int err)
{
if (err) {
char buf[4096];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
buf, lenof(buf), NULL);
buf[lenof(buf)-1] = '\0';
if (buf[strlen(buf)-1] == '\n')
buf[strlen(buf)-1] = '\0';
fprintf(stderr, "Unable to read from standard input: %s\n", buf);
cleanup_exit(0);
}
noise_ultralight(NOISE_SOURCE_IOLEN, len);
if (backend_connected(backend)) {
if (len > 0) {
return backend_send(backend, data, len);
} else {
backend_special(backend, SS_EOF, 0);
return 0;
}
} else
return 0;
}
void stdouterr_sent(struct handle *h, size_t new_backlog, int err)
{
if (err) {
char buf[4096];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
buf, lenof(buf), NULL);
buf[lenof(buf)-1] = '\0';
if (buf[strlen(buf)-1] == '\n')
buf[strlen(buf)-1] = '\0';
fprintf(stderr, "Unable to write to standard %s: %s\n",
(h == stdout_handle ? "output" : "error"), buf);
cleanup_exit(0);
}
if (backend_connected(backend)) {
backend_unthrottle(backend, (handle_backlog(stdout_handle) +
handle_backlog(stderr_handle)));
}
}
const bool share_can_be_downstream = true;
const bool share_can_be_upstream = true;
#ifdef MOD_PORTKNOCKING
int ManagePortKnocking( char* host, char *portknockseq ) ;
#endif
#ifdef MOD_PERSO
char * AutoCommand = NULL ;
void ManageAutocommand( struct handle *h ) {
char c = '\n' ;
while( strlen(AutoCommand) > 0 ) {
c = (char)AutoCommand[0] ;
if( c=='\\' ) {
if( AutoCommand[1]=='n' ) stdin_gotdata(h, "\n", 1, 0 ) ;
AutoCommand++ ;
c = '\n' ;
}
else stdin_gotdata(h, AutoCommand, 1, 0 ) ;
AutoCommand++ ;
}
if( c != '\n' ) stdin_gotdata(h, "\n", 1, 0 ) ;
}
int plink_main(int argc, char **argv) ;
int main(int argc, char **argv) {
int arc=0, ret=0, i ;
char **arv ;
IniFileFlag = 0 ;
DirectoryBrowseFlag = 0 ;
arv=(char**)malloc( argc*sizeof(char*) ) ;
for( i=0 ; i<argc ; i++ ) {
if( !strcmp(argv[i],"-folder" ) && (i<(argc-1)) ) {
i++ ;
printf( "Switching folder to %s\n", argv[i] ) ;
printf( "%s\n",SetSessPath( argv[i] ) );
SetSessPath( argv[i] ) ;
} else {
arv[arc]=(char*)malloc( strlen(argv[i]) +1 ) ;
strcpy(arv[arc],argv[i]) ;
arc++ ;
}
}
ret = plink_main( arc, arv ) ;
for( i=0 ; i<arc ; i++ ) free( arv[i] ) ;
free( arv ) ;
return ret ;
}
#endif
#ifdef MOD_PERSO
int plink_main(int argc, char **argv)
{
LoadParametersLight() ;
#else
int main(int argc, char **argv)
{
#endif
bool sending;
SOCKET *sklist;
size_t skcount, sksize;
int exitcode;
bool errors;
bool use_subsystem = false;
bool just_test_share_exists = false;
enum TriState sanitise_stdout = AUTO, sanitise_stderr = AUTO;
unsigned long now, next, then;
const struct BackendVtable *vt;
dll_hijacking_protection();
sklist = NULL;
skcount = sksize = 0;
/*
* Initialise port and protocol to sensible defaults. (These
* will be overridden by more or less anything.)
*/
default_protocol = PROT_SSH;
default_port = 22;
flags = 0;
cmdline_tooltype |=
(TOOLTYPE_HOST_ARG |
TOOLTYPE_HOST_ARG_CAN_BE_SESSION |
TOOLTYPE_HOST_ARG_PROTOCOL_PREFIX |
TOOLTYPE_HOST_ARG_FROM_LAUNCHABLE_LOAD);
/*
* Process the command line.
*/
conf = conf_new();
do_defaults(NULL, conf);
loaded_session = false;
default_protocol = conf_get_int(conf, CONF_protocol);
default_port = conf_get_int(conf, CONF_port);
errors = false;
{
/*
* Override the default protocol if PLINK_PROTOCOL is set.
*/
char *p = getenv("PLINK_PROTOCOL");
if (p) {
const struct BackendVtable *vt = backend_vt_from_name(p);
if (vt) {
default_protocol = vt->protocol;
default_port = vt->default_port;
conf_set_int(conf, CONF_protocol, default_protocol);
conf_set_int(conf, CONF_port, default_port);
}
}
}
while (--argc) {
char *p = *++argv;
int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
1, conf);
if (ret == -2) {
fprintf(stderr,
"plink: option \"%s\" requires an argument\n", p);
errors = true;
} else if (ret == 2) {
--argc, ++argv;
} else if (ret == 1) {
continue;
} else if (!strcmp(p, "-batch")) {
console_batch_mode = true;
} else if (!strcmp(p, "-s")) {
/* Save status to write to conf later. */
use_subsystem = true;
} else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
version();
} else if (!strcmp(p, "--help")) {
usage();
} else if (!strcmp(p, "-pgpfp")) {
pgp_fingerprints();
exit(1);
} else if (!strcmp(p, "-shareexists")) {
just_test_share_exists = true;
} else if (!strcmp(p, "-sanitise-stdout") ||
!strcmp(p, "-sanitize-stdout")) {
sanitise_stdout = FORCE_ON;
} else if (!strcmp(p, "-no-sanitise-stdout") ||
!strcmp(p, "-no-sanitize-stdout")) {
sanitise_stdout = FORCE_OFF;
} else if (!strcmp(p, "-sanitise-stderr") ||
!strcmp(p, "-sanitize-stderr")) {
sanitise_stderr = FORCE_ON;
} else if (!strcmp(p, "-no-sanitise-stderr") ||
!strcmp(p, "-no-sanitize-stderr")) {
sanitise_stderr = FORCE_OFF;
} else if (!strcmp(p, "-no-antispoof")) {
console_antispoof_prompt = false;
} else if (*p != '-') {
strbuf *cmdbuf = strbuf_new();
while (argc > 0) {
if (cmdbuf->len > 0)
put_byte(cmdbuf, ' '); /* add space separator */
put_datapl(cmdbuf, ptrlen_from_asciz(p));
if (--argc > 0)
p = *++argv;
}
conf_set_str(conf, CONF_remote_cmd, cmdbuf->s);
conf_set_str(conf, CONF_remote_cmd2, "");
conf_set_bool(conf, CONF_nopty, true); /* command => no tty */
strbuf_free(cmdbuf);
break; /* done with cmdline */
} else {
fprintf(stderr, "plink: unknown option \"%s\"\n", p);
errors = true;
}
}
if (errors)
return 1;
if (!cmdline_host_ok(conf)) {
usage();
}
prepare_session(conf);
/*
* Perform command-line overrides on session configuration.
*/
cmdline_run_saved(conf);
/*
* Apply subsystem status.
*/
if (use_subsystem)
conf_set_bool(conf, CONF_ssh_subsys, true);
if (!*conf_get_str(conf, CONF_remote_cmd) &&
!*conf_get_str(conf, CONF_remote_cmd2) &&
!*conf_get_str(conf, CONF_ssh_nc_host))
flags |= FLAG_INTERACTIVE;
/*
* Select protocol. This is farmed out into a table in a
* separate file to enable an ssh-free variant.
*/
vt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol));
if (vt == NULL) {
fprintf(stderr,
"Internal fault: Unsupported protocol found\n");
return 1;
}
sk_init();
if (p_WSAEventSelect == NULL) {
fprintf(stderr, "Plink requires WinSock 2\n");
return 1;
}
/*
* Plink doesn't provide any way to add forwardings after the
* connection is set up, so if there are none now, we can safely set
* the "simple" flag.
*/
if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
!conf_get_bool(conf, CONF_x11_forward) &&
!conf_get_bool(conf, CONF_agentfwd) &&
!conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
conf_set_bool(conf, CONF_ssh_simple, true);
logctx = log_init(default_logpolicy, conf);
if (just_test_share_exists) {
if (!vt->test_for_upstream) {
fprintf(stderr, "Connection sharing not supported for connection "
"type '%s'\n", vt->name);
return 1;
}
if (vt->test_for_upstream(conf_get_str(conf, CONF_host),
conf_get_int(conf, CONF_port), conf))
return 0;
else
return 1;
}
#ifdef MOD_PROXY
if( GetProxySelectionFlag() ) {
LoadProxyInfo( conf, conf_get_str(conf,CONF_proxyselection) ) ;
}
#endif
#ifdef MOD_PORTKNOCKING
ManagePortKnocking(conf_get_str(conf,CONF_host),conf_get_str(conf,CONF_portknockingoptions));
#endif
if (restricted_acl) {
lp_eventlog(default_logpolicy, "Running with restricted process ACL");
}
inhandle = GetStdHandle(STD_INPUT_HANDLE);
outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
errhandle = GetStdHandle(STD_ERROR_HANDLE);
/*
* Turn off ECHO and LINE input modes. We don't care if this
* call fails, because we know we aren't necessarily running in
* a console.
*/
GetConsoleMode(inhandle, &orig_console_mode);
SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
/*
* Pass the output handles to the handle-handling subsystem.
* (The input one we leave until we're through the
* authentication process.)
*/
stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
handle_sink_init(&stdout_hs, stdout_handle);
handle_sink_init(&stderr_hs, stderr_handle);
stdout_bs = BinarySink_UPCAST(&stdout_hs);
stderr_bs = BinarySink_UPCAST(&stderr_hs);
/*
* Decide whether to sanitise control sequences out of standard
* output and standard error.
*
* If we weren't given a command-line override, we do this if (a)
* the fd in question is pointing at a console, and (b) we aren't
* trying to allocate a terminal as part of the session.
*
* (Rationale: the risk of control sequences is that they cause
* confusion when sent to a local console, so if there isn't one,
* no problem. Also, if we allocate a remote terminal, then we
* sent a terminal type, i.e. we told it what kind of escape
* sequences we _like_, i.e. we were expecting to receive some.)
*/
if (sanitise_stdout == FORCE_ON ||
(sanitise_stdout == AUTO && is_console_handle(outhandle) &&
conf_get_bool(conf, CONF_nopty))) {
stdout_scc = stripctrl_new(stdout_bs, true, L'\0');
stdout_bs = BinarySink_UPCAST(stdout_scc);
}
if (sanitise_stderr == FORCE_ON ||
(sanitise_stderr == AUTO && is_console_handle(errhandle) &&
conf_get_bool(conf, CONF_nopty))) {
stderr_scc = stripctrl_new(stderr_bs, true, L'\0');
stderr_bs = BinarySink_UPCAST(stderr_scc);
}
/*
* Start up the connection.
*/
netevent = CreateEvent(NULL, false, false, NULL);
{
const char *error;
char *realhost;
/* nodelay is only useful if stdin is a character device (console) */
bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) &&
(GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
error = backend_init(vt, plink_seat, &backend, logctx, conf,
conf_get_str(conf, CONF_host),
conf_get_int(conf, CONF_port),
&realhost, nodelay,
conf_get_bool(conf, CONF_tcp_keepalives));
if (error) {
fprintf(stderr, "Unable to open connection:\n%s", error);
return 1;
}
sfree(realhost);
}
main_thread_id = GetCurrentThreadId();
sending = false;
now = GETTICKCOUNT();
while (1) {
int nhandles;
HANDLE *handles;
int n;
DWORD ticks;
if (!sending && backend_sendok(backend)) {
stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
0);
sending = true;
}
if (toplevel_callback_pending()) {
ticks = 0;
next = now;
} else if (run_timers(now, &next)) {
then = now;
now = GETTICKCOUNT();
if (now - then > next - then)
ticks = 0;
else
ticks = next - now;
} else {
ticks = INFINITE;
/* no need to initialise next here because we can never
* get WAIT_TIMEOUT */
}
handles = handle_get_events(&nhandles);
handles = sresize(handles, nhandles+1, HANDLE);
handles[nhandles] = netevent;
n = MsgWaitForMultipleObjects(nhandles+1, handles, false, ticks,
QS_POSTMESSAGE);
if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
handle_got_event(handles[n - WAIT_OBJECT_0]);
} else if (n == WAIT_OBJECT_0 + nhandles) {
WSANETWORKEVENTS things;
SOCKET socket;
int i, socketstate;
/*
* We must not call select_result() for any socket
* until we have finished enumerating within the tree.
* This is because select_result() may close the socket
* and modify the tree.
*/
/* Count the active sockets. */
i = 0;
for (socket = first_socket(&socketstate);
socket != INVALID_SOCKET;
socket = next_socket(&socketstate)) i++;
/* Expand the buffer if necessary. */
sgrowarray(sklist, sksize, i);
/* Retrieve the sockets into sklist. */
skcount = 0;
for (socket = first_socket(&socketstate);
socket != INVALID_SOCKET;
socket = next_socket(&socketstate)) {
sklist[skcount++] = socket;
}
/* Now we're done enumerating; go through the list. */
for (i = 0; i < skcount; i++) {
WPARAM wp;
socket = sklist[i];
wp = (WPARAM) socket;
if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
static const struct { int bit, mask; } eventtypes[] = {
{FD_CONNECT_BIT, FD_CONNECT},
{FD_READ_BIT, FD_READ},
{FD_CLOSE_BIT, FD_CLOSE},
{FD_OOB_BIT, FD_OOB},
{FD_WRITE_BIT, FD_WRITE},
{FD_ACCEPT_BIT, FD_ACCEPT},
};
int e;
noise_ultralight(NOISE_SOURCE_IOID, socket);
for (e = 0; e < lenof(eventtypes); e++)
if (things.lNetworkEvents & eventtypes[e].mask) {
LPARAM lp;
int err = things.iErrorCode[eventtypes[e].bit];
lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
select_result(wp, lp);
}
}
}
} else if (n == WAIT_OBJECT_0 + nhandles + 1) {
MSG msg;
while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
PM_REMOVE)) {
struct agent_callback *c = (struct agent_callback *)msg.lParam;
c->callback(c->callback_ctx, c->data, c->len);
sfree(c);
}
}
run_toplevel_callbacks();
if (n == WAIT_TIMEOUT) {
now = next;
} else {
now = GETTICKCOUNT();
}
sfree(handles);
if (sending)
handle_unthrottle(stdin_handle, backend_sendbuffer(backend));
if (!backend_connected(backend) &&
handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
break; /* we closed the connection */
}
exitcode = backend_exitcode(backend);
if (exitcode < 0) {
fprintf(stderr, "Remote process exit code unavailable\n");
exitcode = 1; /* this is an error condition */
}
cleanup_exit(exitcode);
return 0; /* placate compiler warning */
}
| 10,882 |
7,482 | <filename>bsp/imx6sx/iMX6_Platform_SDK/sdk/include/mx6sdl/registers/regssdmaarm.h
/*
* Copyright (c) 2012, Freescale Semiconductor, Inc.
* All rights reserved.
*
* THIS SOFTWARE IS PROVIDED BY FREESCALE "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 FREESCALE 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.
*/
/*
* WARNING! DO NOT EDIT THIS FILE DIRECTLY!
*
* This file was generated automatically and any changes may be lost.
*/
#ifndef __HW_SDMAARM_REGISTERS_H__
#define __HW_SDMAARM_REGISTERS_H__
#include "regs.h"
/*
* i.MX6SDL SDMAARM
*
* SDMA
*
* Registers defined in this header file:
* - HW_SDMAARM_MC0PTR - ARM platform Channel 0 Pointer
* - HW_SDMAARM_INTR - Channel Interrupts
* - HW_SDMAARM_STOP_STAT - Channel Stop/Channel Status
* - HW_SDMAARM_HSTART - Channel Start
* - HW_SDMAARM_EVTOVR - Channel Event Override
* - HW_SDMAARM_DSPOVR - Channel BP Override
* - HW_SDMAARM_HOSTOVR - Channel ARM platform Override
* - HW_SDMAARM_EVTPEND - Channel Event Pending
* - HW_SDMAARM_RESET - Reset Register
* - HW_SDMAARM_EVTERR - DMA Request Error Register
* - HW_SDMAARM_INTRMASK - Channel ARM platform Interrupt Mask
* - HW_SDMAARM_PSW - Schedule Status
* - HW_SDMAARM_EVTERRDBG - DMA Request Error Register
* - HW_SDMAARM_CONFIG - Configuration Register
* - HW_SDMAARM_SDMA_LOCK - SDMA LOCK
* - HW_SDMAARM_ONCE_ENB - OnCE Enable
* - HW_SDMAARM_ONCE_DATA - OnCE Data Register
* - HW_SDMAARM_ONCE_INSTR - OnCE Instruction Register
* - HW_SDMAARM_ONCE_STAT - OnCE Status Register
* - HW_SDMAARM_ONCE_CMD - OnCE Command Register
* - HW_SDMAARM_ILLINSTADDR - Illegal Instruction Trap Address
* - HW_SDMAARM_CHN0ADDR - Channel 0 Boot Address
* - HW_SDMAARM_EVT_MIRROR - DMA Requests
* - HW_SDMAARM_EVT_MIRROR2 - DMA Requests 2
* - HW_SDMAARM_XTRIG_CONF1 - Cross-Trigger Events Configuration Register 1
* - HW_SDMAARM_XTRIG_CONF2 - Cross-Trigger Events Configuration Register 2
* - HW_SDMAARM_SDMA_CHNPRIn - Channel Priority Registers
* - HW_SDMAARM_CHNENBLn - Channel Enable RAM
*
* - hw_sdmaarm_t - Struct containing all module registers.
*/
//! @name Module base addresses
//@{
#ifndef REGS_SDMAARM_BASE
#define HW_SDMAARM_INSTANCE_COUNT (1) //!< Number of instances of the SDMAARM module.
#define REGS_SDMAARM_BASE (0x020ec000) //!< Base address for SDMAARM.
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_MC0PTR - ARM platform Channel 0 Pointer
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_MC0PTR - ARM platform Channel 0 Pointer (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_mc0ptr
{
reg32_t U;
struct _hw_sdmaarm_mc0ptr_bitfields
{
unsigned MC0PTR : 32; //!< [31:0] Channel 0 Pointer contains the 32-bit address, in ARM platform memory, of channel 0 control block (the boot channel).
} B;
} hw_sdmaarm_mc0ptr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_MC0PTR register
*/
//@{
#define HW_SDMAARM_MC0PTR_ADDR (REGS_SDMAARM_BASE + 0x0)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_MC0PTR (*(volatile hw_sdmaarm_mc0ptr_t *) HW_SDMAARM_MC0PTR_ADDR)
#define HW_SDMAARM_MC0PTR_RD() (HW_SDMAARM_MC0PTR.U)
#define HW_SDMAARM_MC0PTR_WR(v) (HW_SDMAARM_MC0PTR.U = (v))
#define HW_SDMAARM_MC0PTR_SET(v) (HW_SDMAARM_MC0PTR_WR(HW_SDMAARM_MC0PTR_RD() | (v)))
#define HW_SDMAARM_MC0PTR_CLR(v) (HW_SDMAARM_MC0PTR_WR(HW_SDMAARM_MC0PTR_RD() & ~(v)))
#define HW_SDMAARM_MC0PTR_TOG(v) (HW_SDMAARM_MC0PTR_WR(HW_SDMAARM_MC0PTR_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_MC0PTR bitfields
*/
/*! @name Register SDMAARM_MC0PTR, field MC0PTR[31:0] (RW)
*
* Channel 0 Pointer contains the 32-bit address, in ARM platform memory, of channel 0 control block
* (the boot channel). Appendix A fully describes the SDMA Application Programming Interface (API).
* The ARM platform has a read/write access and the SDMA has a read-only access.
*/
//@{
#define BP_SDMAARM_MC0PTR_MC0PTR (0) //!< Bit position for SDMAARM_MC0PTR_MC0PTR.
#define BM_SDMAARM_MC0PTR_MC0PTR (0xffffffff) //!< Bit mask for SDMAARM_MC0PTR_MC0PTR.
//! @brief Get value of SDMAARM_MC0PTR_MC0PTR from a register value.
#define BG_SDMAARM_MC0PTR_MC0PTR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_MC0PTR_MC0PTR) >> BP_SDMAARM_MC0PTR_MC0PTR)
//! @brief Format value for bitfield SDMAARM_MC0PTR_MC0PTR.
#define BF_SDMAARM_MC0PTR_MC0PTR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_MC0PTR_MC0PTR) & BM_SDMAARM_MC0PTR_MC0PTR)
#ifndef __LANGUAGE_ASM__
//! @brief Set the MC0PTR field to a new value.
#define BW_SDMAARM_MC0PTR_MC0PTR(v) (HW_SDMAARM_MC0PTR_WR((HW_SDMAARM_MC0PTR_RD() & ~BM_SDMAARM_MC0PTR_MC0PTR) | BF_SDMAARM_MC0PTR_MC0PTR(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_INTR - Channel Interrupts
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_INTR - Channel Interrupts (W1C)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_intr
{
reg32_t U;
struct _hw_sdmaarm_intr_bitfields
{
unsigned HI : 32; //!< [31:0] The ARM platform Interrupts register contains the 32 HI[i] bits.
} B;
} hw_sdmaarm_intr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_INTR register
*/
//@{
#define HW_SDMAARM_INTR_ADDR (REGS_SDMAARM_BASE + 0x4)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_INTR (*(volatile hw_sdmaarm_intr_t *) HW_SDMAARM_INTR_ADDR)
#define HW_SDMAARM_INTR_RD() (HW_SDMAARM_INTR.U)
#define HW_SDMAARM_INTR_WR(v) (HW_SDMAARM_INTR.U = (v))
#define HW_SDMAARM_INTR_SET(v) (HW_SDMAARM_INTR_WR(HW_SDMAARM_INTR_RD() | (v)))
#define HW_SDMAARM_INTR_CLR(v) (HW_SDMAARM_INTR_WR(HW_SDMAARM_INTR_RD() & ~(v)))
#define HW_SDMAARM_INTR_TOG(v) (HW_SDMAARM_INTR_WR(HW_SDMAARM_INTR_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_INTR bitfields
*/
/*! @name Register SDMAARM_INTR, field HI[31:0] (W1C)
*
* The ARM platform Interrupts register contains the 32 HI[i] bits. If any bit is set, it will cause
* an interrupt to the ARM platform. This register is a "write-ones" register to the ARM platform.
* When the ARM platform sets a bit in this register the corresponding HI[i] bit is cleared. The
* interrupt service routine should clear individual channel bits when their interrupts are
* serviced, failure to do so will cause continuous interrupts. The SDMA is responsible for setting
* the HI[i] bit corresponding to the current channel when the corresponding done instruction is
* executed.
*/
//@{
#define BP_SDMAARM_INTR_HI (0) //!< Bit position for SDMAARM_INTR_HI.
#define BM_SDMAARM_INTR_HI (0xffffffff) //!< Bit mask for SDMAARM_INTR_HI.
//! @brief Get value of SDMAARM_INTR_HI from a register value.
#define BG_SDMAARM_INTR_HI(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_INTR_HI) >> BP_SDMAARM_INTR_HI)
//! @brief Format value for bitfield SDMAARM_INTR_HI.
#define BF_SDMAARM_INTR_HI(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_INTR_HI) & BM_SDMAARM_INTR_HI)
#ifndef __LANGUAGE_ASM__
//! @brief Set the HI field to a new value.
#define BW_SDMAARM_INTR_HI(v) (HW_SDMAARM_INTR_WR((HW_SDMAARM_INTR_RD() & ~BM_SDMAARM_INTR_HI) | BF_SDMAARM_INTR_HI(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_STOP_STAT - Channel Stop/Channel Status
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_STOP_STAT - Channel Stop/Channel Status (W1C)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_stop_stat
{
reg32_t U;
struct _hw_sdmaarm_stop_stat_bitfields
{
unsigned HE : 32; //!< [31:0] This 32-bit register gives access to the ARM platform Enable bits.
} B;
} hw_sdmaarm_stop_stat_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_STOP_STAT register
*/
//@{
#define HW_SDMAARM_STOP_STAT_ADDR (REGS_SDMAARM_BASE + 0x8)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_STOP_STAT (*(volatile hw_sdmaarm_stop_stat_t *) HW_SDMAARM_STOP_STAT_ADDR)
#define HW_SDMAARM_STOP_STAT_RD() (HW_SDMAARM_STOP_STAT.U)
#define HW_SDMAARM_STOP_STAT_WR(v) (HW_SDMAARM_STOP_STAT.U = (v))
#define HW_SDMAARM_STOP_STAT_SET(v) (HW_SDMAARM_STOP_STAT_WR(HW_SDMAARM_STOP_STAT_RD() | (v)))
#define HW_SDMAARM_STOP_STAT_CLR(v) (HW_SDMAARM_STOP_STAT_WR(HW_SDMAARM_STOP_STAT_RD() & ~(v)))
#define HW_SDMAARM_STOP_STAT_TOG(v) (HW_SDMAARM_STOP_STAT_WR(HW_SDMAARM_STOP_STAT_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_STOP_STAT bitfields
*/
/*! @name Register SDMAARM_STOP_STAT, field HE[31:0] (W1C)
*
* This 32-bit register gives access to the ARM platform Enable bits. There is one bit for every
* channel. This register is a "write-ones" register to the ARM platform. When the ARM platform
* writes 1 in bit i of this register, it clears the HE[i] and HSTART[i] bits. Reading this register
* yields the current state of the HE[i] bits.
*/
//@{
#define BP_SDMAARM_STOP_STAT_HE (0) //!< Bit position for SDMAARM_STOP_STAT_HE.
#define BM_SDMAARM_STOP_STAT_HE (0xffffffff) //!< Bit mask for SDMAARM_STOP_STAT_HE.
//! @brief Get value of SDMAARM_STOP_STAT_HE from a register value.
#define BG_SDMAARM_STOP_STAT_HE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_STOP_STAT_HE) >> BP_SDMAARM_STOP_STAT_HE)
//! @brief Format value for bitfield SDMAARM_STOP_STAT_HE.
#define BF_SDMAARM_STOP_STAT_HE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_STOP_STAT_HE) & BM_SDMAARM_STOP_STAT_HE)
#ifndef __LANGUAGE_ASM__
//! @brief Set the HE field to a new value.
#define BW_SDMAARM_STOP_STAT_HE(v) (HW_SDMAARM_STOP_STAT_WR((HW_SDMAARM_STOP_STAT_RD() & ~BM_SDMAARM_STOP_STAT_HE) | BF_SDMAARM_STOP_STAT_HE(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_HSTART - Channel Start
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_HSTART - Channel Start (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_hstart
{
reg32_t U;
struct _hw_sdmaarm_hstart_bitfields
{
unsigned HSTART_HE : 32; //!< [31:0] The HSTART_HE registers are 32 bits wide with one bit for every channel.
} B;
} hw_sdmaarm_hstart_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_HSTART register
*/
//@{
#define HW_SDMAARM_HSTART_ADDR (REGS_SDMAARM_BASE + 0xc)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_HSTART (*(volatile hw_sdmaarm_hstart_t *) HW_SDMAARM_HSTART_ADDR)
#define HW_SDMAARM_HSTART_RD() (HW_SDMAARM_HSTART.U)
#define HW_SDMAARM_HSTART_WR(v) (HW_SDMAARM_HSTART.U = (v))
#define HW_SDMAARM_HSTART_SET(v) (HW_SDMAARM_HSTART_WR(HW_SDMAARM_HSTART_RD() | (v)))
#define HW_SDMAARM_HSTART_CLR(v) (HW_SDMAARM_HSTART_WR(HW_SDMAARM_HSTART_RD() & ~(v)))
#define HW_SDMAARM_HSTART_TOG(v) (HW_SDMAARM_HSTART_WR(HW_SDMAARM_HSTART_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_HSTART bitfields
*/
/*! @name Register SDMAARM_HSTART, field HSTART_HE[31:0] (W1C)
*
* The HSTART_HE registers are 32 bits wide with one bit for every channel. When a bit is written to
* 1, it enables the corresponding channel. Two physical registers are accessed with that address
* (HSTART and HE), which enables the ARM platform to trigger a channel a second time before the
* first trigger is processed. This register is a "write-ones" register to the ARM platform. Neither
* HSTART[i] bit can be set while the corresponding HE[i] bit is cleared. When the ARM platform
* tries to set the HSTART[i] bit by writing a one (if the corresponding HE[i] bit is clear), the
* bit in the HSTART[i] register will remain cleared and the HE[i] bit will be set. If the
* corresponding HE[i] bit was already set, the HSTART[i] bit will be set. The next time the SDMA
* channel i attempts to clear the HE[i] bit by means of a done instruction, the bit in the
* HSTART[i] register will be cleared and the HE[i] bit will take the old value of the HSTART[i]
* bit. Reading this register yields the current state of the HSTART[i] bits. This mechanism enables
* the ARM platform to pipeline two HSTART commands per channel.
*/
//@{
#define BP_SDMAARM_HSTART_HSTART_HE (0) //!< Bit position for SDMAARM_HSTART_HSTART_HE.
#define BM_SDMAARM_HSTART_HSTART_HE (0xffffffff) //!< Bit mask for SDMAARM_HSTART_HSTART_HE.
//! @brief Get value of SDMAARM_HSTART_HSTART_HE from a register value.
#define BG_SDMAARM_HSTART_HSTART_HE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_HSTART_HSTART_HE) >> BP_SDMAARM_HSTART_HSTART_HE)
//! @brief Format value for bitfield SDMAARM_HSTART_HSTART_HE.
#define BF_SDMAARM_HSTART_HSTART_HE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_HSTART_HSTART_HE) & BM_SDMAARM_HSTART_HSTART_HE)
#ifndef __LANGUAGE_ASM__
//! @brief Set the HSTART_HE field to a new value.
#define BW_SDMAARM_HSTART_HSTART_HE(v) (HW_SDMAARM_HSTART_WR((HW_SDMAARM_HSTART_RD() & ~BM_SDMAARM_HSTART_HSTART_HE) | BF_SDMAARM_HSTART_HSTART_HE(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_EVTOVR - Channel Event Override
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_EVTOVR - Channel Event Override (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_evtovr
{
reg32_t U;
struct _hw_sdmaarm_evtovr_bitfields
{
unsigned EO : 32; //!< [31:0] The Channel Event Override register contains the 32 EO[i] bits.
} B;
} hw_sdmaarm_evtovr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_EVTOVR register
*/
//@{
#define HW_SDMAARM_EVTOVR_ADDR (REGS_SDMAARM_BASE + 0x10)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_EVTOVR (*(volatile hw_sdmaarm_evtovr_t *) HW_SDMAARM_EVTOVR_ADDR)
#define HW_SDMAARM_EVTOVR_RD() (HW_SDMAARM_EVTOVR.U)
#define HW_SDMAARM_EVTOVR_WR(v) (HW_SDMAARM_EVTOVR.U = (v))
#define HW_SDMAARM_EVTOVR_SET(v) (HW_SDMAARM_EVTOVR_WR(HW_SDMAARM_EVTOVR_RD() | (v)))
#define HW_SDMAARM_EVTOVR_CLR(v) (HW_SDMAARM_EVTOVR_WR(HW_SDMAARM_EVTOVR_RD() & ~(v)))
#define HW_SDMAARM_EVTOVR_TOG(v) (HW_SDMAARM_EVTOVR_WR(HW_SDMAARM_EVTOVR_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_EVTOVR bitfields
*/
/*! @name Register SDMAARM_EVTOVR, field EO[31:0] (RW)
*
* The Channel Event Override register contains the 32 EO[i] bits. A bit set in this register causes
* the SDMA to ignore DMA requests when scheduling the corresponding channel.
*/
//@{
#define BP_SDMAARM_EVTOVR_EO (0) //!< Bit position for SDMAARM_EVTOVR_EO.
#define BM_SDMAARM_EVTOVR_EO (0xffffffff) //!< Bit mask for SDMAARM_EVTOVR_EO.
//! @brief Get value of SDMAARM_EVTOVR_EO from a register value.
#define BG_SDMAARM_EVTOVR_EO(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_EVTOVR_EO) >> BP_SDMAARM_EVTOVR_EO)
//! @brief Format value for bitfield SDMAARM_EVTOVR_EO.
#define BF_SDMAARM_EVTOVR_EO(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_EVTOVR_EO) & BM_SDMAARM_EVTOVR_EO)
#ifndef __LANGUAGE_ASM__
//! @brief Set the EO field to a new value.
#define BW_SDMAARM_EVTOVR_EO(v) (HW_SDMAARM_EVTOVR_WR((HW_SDMAARM_EVTOVR_RD() & ~BM_SDMAARM_EVTOVR_EO) | BF_SDMAARM_EVTOVR_EO(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_DSPOVR - Channel BP Override
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_DSPOVR - Channel BP Override (RW)
*
* Reset value: 0xffffffff
*/
typedef union _hw_sdmaarm_dspovr
{
reg32_t U;
struct _hw_sdmaarm_dspovr_bitfields
{
unsigned DO : 32; //!< [31:0] This register is reserved.
} B;
} hw_sdmaarm_dspovr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_DSPOVR register
*/
//@{
#define HW_SDMAARM_DSPOVR_ADDR (REGS_SDMAARM_BASE + 0x14)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_DSPOVR (*(volatile hw_sdmaarm_dspovr_t *) HW_SDMAARM_DSPOVR_ADDR)
#define HW_SDMAARM_DSPOVR_RD() (HW_SDMAARM_DSPOVR.U)
#define HW_SDMAARM_DSPOVR_WR(v) (HW_SDMAARM_DSPOVR.U = (v))
#define HW_SDMAARM_DSPOVR_SET(v) (HW_SDMAARM_DSPOVR_WR(HW_SDMAARM_DSPOVR_RD() | (v)))
#define HW_SDMAARM_DSPOVR_CLR(v) (HW_SDMAARM_DSPOVR_WR(HW_SDMAARM_DSPOVR_RD() & ~(v)))
#define HW_SDMAARM_DSPOVR_TOG(v) (HW_SDMAARM_DSPOVR_WR(HW_SDMAARM_DSPOVR_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_DSPOVR bitfields
*/
/*! @name Register SDMAARM_DSPOVR, field DO[31:0] (RW)
*
* This register is reserved. All DO bits should be set to the reset value of 1. A setting of 0 will
* prevent SDMA channels from starting according to the condition described in .
*
* Values:
* - 0 - - Reserved
* - 1 - - Reset value.
*/
//@{
#define BP_SDMAARM_DSPOVR_DO (0) //!< Bit position for SDMAARM_DSPOVR_DO.
#define BM_SDMAARM_DSPOVR_DO (0xffffffff) //!< Bit mask for SDMAARM_DSPOVR_DO.
//! @brief Get value of SDMAARM_DSPOVR_DO from a register value.
#define BG_SDMAARM_DSPOVR_DO(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_DSPOVR_DO) >> BP_SDMAARM_DSPOVR_DO)
//! @brief Format value for bitfield SDMAARM_DSPOVR_DO.
#define BF_SDMAARM_DSPOVR_DO(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_DSPOVR_DO) & BM_SDMAARM_DSPOVR_DO)
#ifndef __LANGUAGE_ASM__
//! @brief Set the DO field to a new value.
#define BW_SDMAARM_DSPOVR_DO(v) (HW_SDMAARM_DSPOVR_WR((HW_SDMAARM_DSPOVR_RD() & ~BM_SDMAARM_DSPOVR_DO) | BF_SDMAARM_DSPOVR_DO(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_HOSTOVR - Channel ARM platform Override
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_HOSTOVR - Channel ARM platform Override (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_hostovr
{
reg32_t U;
struct _hw_sdmaarm_hostovr_bitfields
{
unsigned HO : 32; //!< [31:0] The Channel ARM platform Override register contains the 32 HO[i] bits.
} B;
} hw_sdmaarm_hostovr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_HOSTOVR register
*/
//@{
#define HW_SDMAARM_HOSTOVR_ADDR (REGS_SDMAARM_BASE + 0x18)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_HOSTOVR (*(volatile hw_sdmaarm_hostovr_t *) HW_SDMAARM_HOSTOVR_ADDR)
#define HW_SDMAARM_HOSTOVR_RD() (HW_SDMAARM_HOSTOVR.U)
#define HW_SDMAARM_HOSTOVR_WR(v) (HW_SDMAARM_HOSTOVR.U = (v))
#define HW_SDMAARM_HOSTOVR_SET(v) (HW_SDMAARM_HOSTOVR_WR(HW_SDMAARM_HOSTOVR_RD() | (v)))
#define HW_SDMAARM_HOSTOVR_CLR(v) (HW_SDMAARM_HOSTOVR_WR(HW_SDMAARM_HOSTOVR_RD() & ~(v)))
#define HW_SDMAARM_HOSTOVR_TOG(v) (HW_SDMAARM_HOSTOVR_WR(HW_SDMAARM_HOSTOVR_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_HOSTOVR bitfields
*/
/*! @name Register SDMAARM_HOSTOVR, field HO[31:0] (RW)
*
* The Channel ARM platform Override register contains the 32 HO[i] bits. A bit set in this register
* causes the SDMA to ignore the ARM platform enable bit (HE) when scheduling the corresponding
* channel.
*/
//@{
#define BP_SDMAARM_HOSTOVR_HO (0) //!< Bit position for SDMAARM_HOSTOVR_HO.
#define BM_SDMAARM_HOSTOVR_HO (0xffffffff) //!< Bit mask for SDMAARM_HOSTOVR_HO.
//! @brief Get value of SDMAARM_HOSTOVR_HO from a register value.
#define BG_SDMAARM_HOSTOVR_HO(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_HOSTOVR_HO) >> BP_SDMAARM_HOSTOVR_HO)
//! @brief Format value for bitfield SDMAARM_HOSTOVR_HO.
#define BF_SDMAARM_HOSTOVR_HO(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_HOSTOVR_HO) & BM_SDMAARM_HOSTOVR_HO)
#ifndef __LANGUAGE_ASM__
//! @brief Set the HO field to a new value.
#define BW_SDMAARM_HOSTOVR_HO(v) (HW_SDMAARM_HOSTOVR_WR((HW_SDMAARM_HOSTOVR_RD() & ~BM_SDMAARM_HOSTOVR_HO) | BF_SDMAARM_HOSTOVR_HO(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_EVTPEND - Channel Event Pending
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_EVTPEND - Channel Event Pending (W1C)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_evtpend
{
reg32_t U;
struct _hw_sdmaarm_evtpend_bitfields
{
unsigned EP : 32; //!< [31:0] The Channel Event Pending register contains the 32 EP[i] bits.
} B;
} hw_sdmaarm_evtpend_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_EVTPEND register
*/
//@{
#define HW_SDMAARM_EVTPEND_ADDR (REGS_SDMAARM_BASE + 0x1c)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_EVTPEND (*(volatile hw_sdmaarm_evtpend_t *) HW_SDMAARM_EVTPEND_ADDR)
#define HW_SDMAARM_EVTPEND_RD() (HW_SDMAARM_EVTPEND.U)
#define HW_SDMAARM_EVTPEND_WR(v) (HW_SDMAARM_EVTPEND.U = (v))
#define HW_SDMAARM_EVTPEND_SET(v) (HW_SDMAARM_EVTPEND_WR(HW_SDMAARM_EVTPEND_RD() | (v)))
#define HW_SDMAARM_EVTPEND_CLR(v) (HW_SDMAARM_EVTPEND_WR(HW_SDMAARM_EVTPEND_RD() & ~(v)))
#define HW_SDMAARM_EVTPEND_TOG(v) (HW_SDMAARM_EVTPEND_WR(HW_SDMAARM_EVTPEND_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_EVTPEND bitfields
*/
/*! @name Register SDMAARM_EVTPEND, field EP[31:0] (W1C)
*
* The Channel Event Pending register contains the 32 EP[i] bits. Reading this register enables the
* ARM platform to determine what channels are pending after the reception of a DMA request. Setting
* a bit in this register causes the SDMA to reevaluate scheduling as if a DMA request mapped on
* this channel had occurred. This is useful for starting up channels, so that initialization is
* done before awaiting the first request. The scheduler can also set bits in the EVTPEND register
* according to the received DMA requests. The EP[i] bit may be cleared by the done instruction when
* running the channel i script. This a "write-ones" mechanism: Writing a '0' does not clear the
* corresponding bit.
*/
//@{
#define BP_SDMAARM_EVTPEND_EP (0) //!< Bit position for SDMAARM_EVTPEND_EP.
#define BM_SDMAARM_EVTPEND_EP (0xffffffff) //!< Bit mask for SDMAARM_EVTPEND_EP.
//! @brief Get value of SDMAARM_EVTPEND_EP from a register value.
#define BG_SDMAARM_EVTPEND_EP(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_EVTPEND_EP) >> BP_SDMAARM_EVTPEND_EP)
//! @brief Format value for bitfield SDMAARM_EVTPEND_EP.
#define BF_SDMAARM_EVTPEND_EP(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_EVTPEND_EP) & BM_SDMAARM_EVTPEND_EP)
#ifndef __LANGUAGE_ASM__
//! @brief Set the EP field to a new value.
#define BW_SDMAARM_EVTPEND_EP(v) (HW_SDMAARM_EVTPEND_WR((HW_SDMAARM_EVTPEND_RD() & ~BM_SDMAARM_EVTPEND_EP) | BF_SDMAARM_EVTPEND_EP(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_RESET - Reset Register
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_RESET - Reset Register (RO)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_reset
{
reg32_t U;
struct _hw_sdmaarm_reset_bitfields
{
unsigned RESET : 1; //!< [0] When set, this bit causes the SDMA to be held in a software reset.
unsigned RESCHED : 1; //!< [1] When set, this bit forces the SDMA to reschedule as if a script had executed a done instruction.
unsigned RESERVED0 : 30; //!< [31:2] Reserved
} B;
} hw_sdmaarm_reset_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_RESET register
*/
//@{
#define HW_SDMAARM_RESET_ADDR (REGS_SDMAARM_BASE + 0x24)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_RESET (*(volatile hw_sdmaarm_reset_t *) HW_SDMAARM_RESET_ADDR)
#define HW_SDMAARM_RESET_RD() (HW_SDMAARM_RESET.U)
#endif
//@}
/*
* constants & macros for individual SDMAARM_RESET bitfields
*/
/*! @name Register SDMAARM_RESET, field RESET[0] (RO)
*
* When set, this bit causes the SDMA to be held in a software reset. The internal reset signal is
* held low 16 cycles; the RESET bit is automatically cleared when the internal reset signal rises.
*/
//@{
#define BP_SDMAARM_RESET_RESET (0) //!< Bit position for SDMAARM_RESET_RESET.
#define BM_SDMAARM_RESET_RESET (0x00000001) //!< Bit mask for SDMAARM_RESET_RESET.
//! @brief Get value of SDMAARM_RESET_RESET from a register value.
#define BG_SDMAARM_RESET_RESET(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_RESET_RESET) >> BP_SDMAARM_RESET_RESET)
//@}
/*! @name Register SDMAARM_RESET, field RESCHED[1] (RO)
*
* When set, this bit forces the SDMA to reschedule as if a script had executed a done instruction.
* This enables the ARM platform to recover from a runaway script on a channel by clearing its HE[i]
* bit via the STOP register, and then forcing a reschedule via the RESCHED bit. The RESCHED bit is
* cleared when the context switch starts.
*/
//@{
#define BP_SDMAARM_RESET_RESCHED (1) //!< Bit position for SDMAARM_RESET_RESCHED.
#define BM_SDMAARM_RESET_RESCHED (0x00000002) //!< Bit mask for SDMAARM_RESET_RESCHED.
//! @brief Get value of SDMAARM_RESET_RESCHED from a register value.
#define BG_SDMAARM_RESET_RESCHED(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_RESET_RESCHED) >> BP_SDMAARM_RESET_RESCHED)
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_EVTERR - DMA Request Error Register
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_EVTERR - DMA Request Error Register (RO)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_evterr
{
reg32_t U;
struct _hw_sdmaarm_evterr_bitfields
{
unsigned CHNERR : 32; //!< [31:0] This register is used by the SDMA to warn the ARM platform when an incoming DMA request was detected and it triggers a channel that is already pending or being serviced.
} B;
} hw_sdmaarm_evterr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_EVTERR register
*/
//@{
#define HW_SDMAARM_EVTERR_ADDR (REGS_SDMAARM_BASE + 0x28)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_EVTERR (*(volatile hw_sdmaarm_evterr_t *) HW_SDMAARM_EVTERR_ADDR)
#define HW_SDMAARM_EVTERR_RD() (HW_SDMAARM_EVTERR.U)
#endif
//@}
/*
* constants & macros for individual SDMAARM_EVTERR bitfields
*/
/*! @name Register SDMAARM_EVTERR, field CHNERR[31:0] (RO)
*
* This register is used by the SDMA to warn the ARM platform when an incoming DMA request was
* detected and it triggers a channel that is already pending or being serviced. This probably means
* there is an overflow of data for that channel. An interrupt is sent to the ARM platform if the
* corresponding channel bit is set in the INTRMASK register. This is a "write-ones" register for
* the scheduler. It is only able to set the flags. The flags are cleared when the register is read
* by the ARM platform or during SDMA reset. The CHNERR[i] bit is set when a DMA request that
* triggers channel i is received through the corresponding input pins and the EP[i] bit is already
* set; the EVTERR[i] bit is unaffected if the ARM platform tries to set the EP[i] bit, whereas,
* that EP[i] bit is already set.
*/
//@{
#define BP_SDMAARM_EVTERR_CHNERR (0) //!< Bit position for SDMAARM_EVTERR_CHNERR.
#define BM_SDMAARM_EVTERR_CHNERR (0xffffffff) //!< Bit mask for SDMAARM_EVTERR_CHNERR.
//! @brief Get value of SDMAARM_EVTERR_CHNERR from a register value.
#define BG_SDMAARM_EVTERR_CHNERR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_EVTERR_CHNERR) >> BP_SDMAARM_EVTERR_CHNERR)
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_INTRMASK - Channel ARM platform Interrupt Mask
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_INTRMASK - Channel ARM platform Interrupt Mask (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_intrmask
{
reg32_t U;
struct _hw_sdmaarm_intrmask_bitfields
{
unsigned HIMASK : 32; //!< [31:0] The Interrupt Mask Register contains 32 interrupt generation mask bits.
} B;
} hw_sdmaarm_intrmask_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_INTRMASK register
*/
//@{
#define HW_SDMAARM_INTRMASK_ADDR (REGS_SDMAARM_BASE + 0x2c)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_INTRMASK (*(volatile hw_sdmaarm_intrmask_t *) HW_SDMAARM_INTRMASK_ADDR)
#define HW_SDMAARM_INTRMASK_RD() (HW_SDMAARM_INTRMASK.U)
#define HW_SDMAARM_INTRMASK_WR(v) (HW_SDMAARM_INTRMASK.U = (v))
#define HW_SDMAARM_INTRMASK_SET(v) (HW_SDMAARM_INTRMASK_WR(HW_SDMAARM_INTRMASK_RD() | (v)))
#define HW_SDMAARM_INTRMASK_CLR(v) (HW_SDMAARM_INTRMASK_WR(HW_SDMAARM_INTRMASK_RD() & ~(v)))
#define HW_SDMAARM_INTRMASK_TOG(v) (HW_SDMAARM_INTRMASK_WR(HW_SDMAARM_INTRMASK_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_INTRMASK bitfields
*/
/*! @name Register SDMAARM_INTRMASK, field HIMASK[31:0] (RW)
*
* The Interrupt Mask Register contains 32 interrupt generation mask bits. If bit HIMASK[i] is set,
* the HI[i] bit is set and an interrupt is sent to the ARM platform when a DMA request error is
* detected on channel i (for example, EVTERR[i] is set).
*/
//@{
#define BP_SDMAARM_INTRMASK_HIMASK (0) //!< Bit position for SDMAARM_INTRMASK_HIMASK.
#define BM_SDMAARM_INTRMASK_HIMASK (0xffffffff) //!< Bit mask for SDMAARM_INTRMASK_HIMASK.
//! @brief Get value of SDMAARM_INTRMASK_HIMASK from a register value.
#define BG_SDMAARM_INTRMASK_HIMASK(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_INTRMASK_HIMASK) >> BP_SDMAARM_INTRMASK_HIMASK)
//! @brief Format value for bitfield SDMAARM_INTRMASK_HIMASK.
#define BF_SDMAARM_INTRMASK_HIMASK(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_INTRMASK_HIMASK) & BM_SDMAARM_INTRMASK_HIMASK)
#ifndef __LANGUAGE_ASM__
//! @brief Set the HIMASK field to a new value.
#define BW_SDMAARM_INTRMASK_HIMASK(v) (HW_SDMAARM_INTRMASK_WR((HW_SDMAARM_INTRMASK_RD() & ~BM_SDMAARM_INTRMASK_HIMASK) | BF_SDMAARM_INTRMASK_HIMASK(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_PSW - Schedule Status
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_PSW - Schedule Status (RO)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_psw
{
reg32_t U;
struct _hw_sdmaarm_psw_bitfields
{
unsigned CCR : 4; //!< [3:0] The Current Channel Register indicates the number of the channel that is being executed by the SDMA.
unsigned CCP : 4; //!< [7:4] The Current Channel Priority indicates the priority of the current active channel.
unsigned NCR : 5; //!< [12:8] The Next Channel Register indicates the number of the next scheduled pending channel with the highest priority.
unsigned NCP : 3; //!< [15:13] The Next Channel Priority gives the next pending channel priority.
unsigned RESERVED0 : 16; //!< [31:16] Reserved
} B;
} hw_sdmaarm_psw_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_PSW register
*/
//@{
#define HW_SDMAARM_PSW_ADDR (REGS_SDMAARM_BASE + 0x30)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_PSW (*(volatile hw_sdmaarm_psw_t *) HW_SDMAARM_PSW_ADDR)
#define HW_SDMAARM_PSW_RD() (HW_SDMAARM_PSW.U)
#endif
//@}
/*
* constants & macros for individual SDMAARM_PSW bitfields
*/
/*! @name Register SDMAARM_PSW, field CCR[3:0] (RO)
*
* The Current Channel Register indicates the number of the channel that is being executed by the
* SDMA. SDMA. In the case that the SDMA has finished running the channel and has entered sleep
* state, CCR will indicate the previous running channel.
*/
//@{
#define BP_SDMAARM_PSW_CCR (0) //!< Bit position for SDMAARM_PSW_CCR.
#define BM_SDMAARM_PSW_CCR (0x0000000f) //!< Bit mask for SDMAARM_PSW_CCR.
//! @brief Get value of SDMAARM_PSW_CCR from a register value.
#define BG_SDMAARM_PSW_CCR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_PSW_CCR) >> BP_SDMAARM_PSW_CCR)
//@}
/*! @name Register SDMAARM_PSW, field CCP[7:4] (RO)
*
* The Current Channel Priority indicates the priority of the current active channel. When the
* priority is 0, no channel is running: The SDMA is idle and the CCR value has no meaning. In the
* case that the SDMA has finished running the channel and has entered sleep state, CCP will
* indicate the priority of previous running channel.
*
* Values:
* - 0 - No running channel
* - 1 - Active channel priority
*/
//@{
#define BP_SDMAARM_PSW_CCP (4) //!< Bit position for SDMAARM_PSW_CCP.
#define BM_SDMAARM_PSW_CCP (0x000000f0) //!< Bit mask for SDMAARM_PSW_CCP.
//! @brief Get value of SDMAARM_PSW_CCP from a register value.
#define BG_SDMAARM_PSW_CCP(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_PSW_CCP) >> BP_SDMAARM_PSW_CCP)
//@}
/*! @name Register SDMAARM_PSW, field NCR[12:8] (RO)
*
* The Next Channel Register indicates the number of the next scheduled pending channel with the
* highest priority.
*/
//@{
#define BP_SDMAARM_PSW_NCR (8) //!< Bit position for SDMAARM_PSW_NCR.
#define BM_SDMAARM_PSW_NCR (0x00001f00) //!< Bit mask for SDMAARM_PSW_NCR.
//! @brief Get value of SDMAARM_PSW_NCR from a register value.
#define BG_SDMAARM_PSW_NCR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_PSW_NCR) >> BP_SDMAARM_PSW_NCR)
//@}
/*! @name Register SDMAARM_PSW, field NCP[15:13] (RO)
*
* The Next Channel Priority gives the next pending channel priority. When the priority is 0, it
* means there is no pending channel and the NCR value has no meaning.
*
* Values:
* - 0 - No running channel
* - 1 - Active channel priority
*/
//@{
#define BP_SDMAARM_PSW_NCP (13) //!< Bit position for SDMAARM_PSW_NCP.
#define BM_SDMAARM_PSW_NCP (0x0000e000) //!< Bit mask for SDMAARM_PSW_NCP.
//! @brief Get value of SDMAARM_PSW_NCP from a register value.
#define BG_SDMAARM_PSW_NCP(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_PSW_NCP) >> BP_SDMAARM_PSW_NCP)
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_EVTERRDBG - DMA Request Error Register
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_EVTERRDBG - DMA Request Error Register (RO)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_evterrdbg
{
reg32_t U;
struct _hw_sdmaarm_evterrdbg_bitfields
{
unsigned CHNERR : 32; //!< [31:0] This register is the same as EVTERR, except reading it does not clear its contents.
} B;
} hw_sdmaarm_evterrdbg_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_EVTERRDBG register
*/
//@{
#define HW_SDMAARM_EVTERRDBG_ADDR (REGS_SDMAARM_BASE + 0x34)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_EVTERRDBG (*(volatile hw_sdmaarm_evterrdbg_t *) HW_SDMAARM_EVTERRDBG_ADDR)
#define HW_SDMAARM_EVTERRDBG_RD() (HW_SDMAARM_EVTERRDBG.U)
#endif
//@}
/*
* constants & macros for individual SDMAARM_EVTERRDBG bitfields
*/
/*! @name Register SDMAARM_EVTERRDBG, field CHNERR[31:0] (RO)
*
* This register is the same as EVTERR, except reading it does not clear its contents. This address
* is meant to be used in debug mode. The ARM platform OnCE may check this register value without
* modifying it.
*/
//@{
#define BP_SDMAARM_EVTERRDBG_CHNERR (0) //!< Bit position for SDMAARM_EVTERRDBG_CHNERR.
#define BM_SDMAARM_EVTERRDBG_CHNERR (0xffffffff) //!< Bit mask for SDMAARM_EVTERRDBG_CHNERR.
//! @brief Get value of SDMAARM_EVTERRDBG_CHNERR from a register value.
#define BG_SDMAARM_EVTERRDBG_CHNERR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_EVTERRDBG_CHNERR) >> BP_SDMAARM_EVTERRDBG_CHNERR)
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_CONFIG - Configuration Register
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_CONFIG - Configuration Register (RW)
*
* Reset value: 0x00000003
*/
typedef union _hw_sdmaarm_config
{
reg32_t U;
struct _hw_sdmaarm_config_bitfields
{
unsigned CSM : 2; //!< [1:0] Selects the Context Switch Mode.
unsigned RESERVED0 : 2; //!< [3:2] Reserved
unsigned ACR : 1; //!< [4] ARM platform DMA / SDMA Core Clock Ratio.
unsigned RESERVED1 : 6; //!< [10:5] Reserved
unsigned RTDOBS : 1; //!< [11] Indicates if Real-Time Debug pins are used: They do not toggle by default in order to reduce power consumption.
unsigned DSPDMA : 1; //!< [12] This bit's function is reserved and should be configured as zero.
unsigned RESERVED2 : 19; //!< [31:13] Reserved
} B;
} hw_sdmaarm_config_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_CONFIG register
*/
//@{
#define HW_SDMAARM_CONFIG_ADDR (REGS_SDMAARM_BASE + 0x38)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_CONFIG (*(volatile hw_sdmaarm_config_t *) HW_SDMAARM_CONFIG_ADDR)
#define HW_SDMAARM_CONFIG_RD() (HW_SDMAARM_CONFIG.U)
#define HW_SDMAARM_CONFIG_WR(v) (HW_SDMAARM_CONFIG.U = (v))
#define HW_SDMAARM_CONFIG_SET(v) (HW_SDMAARM_CONFIG_WR(HW_SDMAARM_CONFIG_RD() | (v)))
#define HW_SDMAARM_CONFIG_CLR(v) (HW_SDMAARM_CONFIG_WR(HW_SDMAARM_CONFIG_RD() & ~(v)))
#define HW_SDMAARM_CONFIG_TOG(v) (HW_SDMAARM_CONFIG_WR(HW_SDMAARM_CONFIG_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_CONFIG bitfields
*/
/*! @name Register SDMAARM_CONFIG, field CSM[1:0] (RW)
*
* Selects the Context Switch Mode. The ARM platform has a read/write access. The SDMA cannot modify
* that register. The value at reset is 3, which selects the dynamic context switch by default. That
* register can be modified at anytime but the new context switch configuration will only be taken
* into account at the start of the next restore phase. NOTE: The first call to SDMA's channel 0
* Bootload script after reset should use static context switch mode to ensure the context RAM for
* channel 0 is initialized in the channel SAVE Phase. After Channel 0 is run once, then any of the
* dynamic context modes can be used.
*
* Values:
* - 0 - static
* - 1 - dynamic low power
* - 2 - dynamic with no loop
* - 3 - dynamic
*/
//@{
#define BP_SDMAARM_CONFIG_CSM (0) //!< Bit position for SDMAARM_CONFIG_CSM.
#define BM_SDMAARM_CONFIG_CSM (0x00000003) //!< Bit mask for SDMAARM_CONFIG_CSM.
//! @brief Get value of SDMAARM_CONFIG_CSM from a register value.
#define BG_SDMAARM_CONFIG_CSM(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_CONFIG_CSM) >> BP_SDMAARM_CONFIG_CSM)
//! @brief Format value for bitfield SDMAARM_CONFIG_CSM.
#define BF_SDMAARM_CONFIG_CSM(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_CONFIG_CSM) & BM_SDMAARM_CONFIG_CSM)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CSM field to a new value.
#define BW_SDMAARM_CONFIG_CSM(v) (HW_SDMAARM_CONFIG_WR((HW_SDMAARM_CONFIG_RD() & ~BM_SDMAARM_CONFIG_CSM) | BF_SDMAARM_CONFIG_CSM(v)))
#endif
//@}
/*! @name Register SDMAARM_CONFIG, field ACR[4] (RW)
*
* ARM platform DMA / SDMA Core Clock Ratio. Selects the clock ratio between ARM platform DMA
* interfaces (burst DMA and peripheral DMA ) and the internal SDMA core clock. The frequency
* selection is determined separately by the chip clock controller. This bit has to match the
* configuration of the chip clock controller that generates the clocks used in the SDMA.
*
* Values:
* - 0 - ARM platform DMA interface frequency equals twice core frequency
* - 1 - ARM platform DMA interface frequency equals core frequency
*/
//@{
#define BP_SDMAARM_CONFIG_ACR (4) //!< Bit position for SDMAARM_CONFIG_ACR.
#define BM_SDMAARM_CONFIG_ACR (0x00000010) //!< Bit mask for SDMAARM_CONFIG_ACR.
//! @brief Get value of SDMAARM_CONFIG_ACR from a register value.
#define BG_SDMAARM_CONFIG_ACR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_CONFIG_ACR) >> BP_SDMAARM_CONFIG_ACR)
//! @brief Format value for bitfield SDMAARM_CONFIG_ACR.
#define BF_SDMAARM_CONFIG_ACR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_CONFIG_ACR) & BM_SDMAARM_CONFIG_ACR)
#ifndef __LANGUAGE_ASM__
//! @brief Set the ACR field to a new value.
#define BW_SDMAARM_CONFIG_ACR(v) (HW_SDMAARM_CONFIG_WR((HW_SDMAARM_CONFIG_RD() & ~BM_SDMAARM_CONFIG_ACR) | BF_SDMAARM_CONFIG_ACR(v)))
#endif
//@}
/*! @name Register SDMAARM_CONFIG, field RTDOBS[11] (RW)
*
* Indicates if Real-Time Debug pins are used: They do not toggle by default in order to reduce
* power consumption.
*
* Values:
* - 0 - RTD pins disabled
* - 1 - RTD pins enabled
*/
//@{
#define BP_SDMAARM_CONFIG_RTDOBS (11) //!< Bit position for SDMAARM_CONFIG_RTDOBS.
#define BM_SDMAARM_CONFIG_RTDOBS (0x00000800) //!< Bit mask for SDMAARM_CONFIG_RTDOBS.
//! @brief Get value of SDMAARM_CONFIG_RTDOBS from a register value.
#define BG_SDMAARM_CONFIG_RTDOBS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_CONFIG_RTDOBS) >> BP_SDMAARM_CONFIG_RTDOBS)
//! @brief Format value for bitfield SDMAARM_CONFIG_RTDOBS.
#define BF_SDMAARM_CONFIG_RTDOBS(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_CONFIG_RTDOBS) & BM_SDMAARM_CONFIG_RTDOBS)
#ifndef __LANGUAGE_ASM__
//! @brief Set the RTDOBS field to a new value.
#define BW_SDMAARM_CONFIG_RTDOBS(v) (HW_SDMAARM_CONFIG_WR((HW_SDMAARM_CONFIG_RD() & ~BM_SDMAARM_CONFIG_RTDOBS) | BF_SDMAARM_CONFIG_RTDOBS(v)))
#endif
//@}
/*! @name Register SDMAARM_CONFIG, field DSPDMA[12] (RW)
*
* This bit's function is reserved and should be configured as zero.
*
* Values:
* - 0 - - Reset Value
* - 1 - - Reserved
*/
//@{
#define BP_SDMAARM_CONFIG_DSPDMA (12) //!< Bit position for SDMAARM_CONFIG_DSPDMA.
#define BM_SDMAARM_CONFIG_DSPDMA (0x00001000) //!< Bit mask for SDMAARM_CONFIG_DSPDMA.
//! @brief Get value of SDMAARM_CONFIG_DSPDMA from a register value.
#define BG_SDMAARM_CONFIG_DSPDMA(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_CONFIG_DSPDMA) >> BP_SDMAARM_CONFIG_DSPDMA)
//! @brief Format value for bitfield SDMAARM_CONFIG_DSPDMA.
#define BF_SDMAARM_CONFIG_DSPDMA(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_CONFIG_DSPDMA) & BM_SDMAARM_CONFIG_DSPDMA)
#ifndef __LANGUAGE_ASM__
//! @brief Set the DSPDMA field to a new value.
#define BW_SDMAARM_CONFIG_DSPDMA(v) (HW_SDMAARM_CONFIG_WR((HW_SDMAARM_CONFIG_RD() & ~BM_SDMAARM_CONFIG_DSPDMA) | BF_SDMAARM_CONFIG_DSPDMA(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_SDMA_LOCK - SDMA LOCK
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_SDMA_LOCK - SDMA LOCK (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_sdma_lock
{
reg32_t U;
struct _hw_sdmaarm_sdma_lock_bitfields
{
unsigned LOCK : 1; //!< [0] The LOCK bit is used to restrict access to update SDMA script memory through ROM channel zero scripts and through the OnCE interface under ARM platform control.
unsigned SRESET_LOCK_CLR : 1; //!< [1] The SRESET_LOCK_CLR bit determine if the LOCK bit is cleared on a software reset triggered by writing to the RESET register.
unsigned RESERVED0 : 30; //!< [31:2] Reserved
} B;
} hw_sdmaarm_sdma_lock_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_SDMA_LOCK register
*/
//@{
#define HW_SDMAARM_SDMA_LOCK_ADDR (REGS_SDMAARM_BASE + 0x3c)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_SDMA_LOCK (*(volatile hw_sdmaarm_sdma_lock_t *) HW_SDMAARM_SDMA_LOCK_ADDR)
#define HW_SDMAARM_SDMA_LOCK_RD() (HW_SDMAARM_SDMA_LOCK.U)
#define HW_SDMAARM_SDMA_LOCK_WR(v) (HW_SDMAARM_SDMA_LOCK.U = (v))
#define HW_SDMAARM_SDMA_LOCK_SET(v) (HW_SDMAARM_SDMA_LOCK_WR(HW_SDMAARM_SDMA_LOCK_RD() | (v)))
#define HW_SDMAARM_SDMA_LOCK_CLR(v) (HW_SDMAARM_SDMA_LOCK_WR(HW_SDMAARM_SDMA_LOCK_RD() & ~(v)))
#define HW_SDMAARM_SDMA_LOCK_TOG(v) (HW_SDMAARM_SDMA_LOCK_WR(HW_SDMAARM_SDMA_LOCK_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_SDMA_LOCK bitfields
*/
/*! @name Register SDMAARM_SDMA_LOCK, field LOCK[0] (RW)
*
* The LOCK bit is used to restrict access to update SDMA script memory through ROM channel zero
* scripts and through the OnCE interface under ARM platform control. The LOCK bit is set: The
* SDMA_LOCK, ONCE_ENB,CH0ADDR, and ILLINSTADDR registers cannot be written. These registers can be
* read, but writes are ignored. SDMA software executing out of ROM or RAM may check the LOCK bit in
* the LOCK register to determine if certain operations are allowed, such as up-loading new scripts.
* Once the LOCK bit is set to 1, only a reset can clear it. The LOCK bit is cleared by a hardware
* reset. LOCK is cleared by a software reset only if SRESET_LOCK_CLR is set.
*
* Values:
* - 0 - LOCK disengaged.
* - 1 - LOCK enabled.
*/
//@{
#define BP_SDMAARM_SDMA_LOCK_LOCK (0) //!< Bit position for SDMAARM_SDMA_LOCK_LOCK.
#define BM_SDMAARM_SDMA_LOCK_LOCK (0x00000001) //!< Bit mask for SDMAARM_SDMA_LOCK_LOCK.
//! @brief Get value of SDMAARM_SDMA_LOCK_LOCK from a register value.
#define BG_SDMAARM_SDMA_LOCK_LOCK(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_SDMA_LOCK_LOCK) >> BP_SDMAARM_SDMA_LOCK_LOCK)
//! @brief Format value for bitfield SDMAARM_SDMA_LOCK_LOCK.
#define BF_SDMAARM_SDMA_LOCK_LOCK(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_SDMA_LOCK_LOCK) & BM_SDMAARM_SDMA_LOCK_LOCK)
#ifndef __LANGUAGE_ASM__
//! @brief Set the LOCK field to a new value.
#define BW_SDMAARM_SDMA_LOCK_LOCK(v) (HW_SDMAARM_SDMA_LOCK_WR((HW_SDMAARM_SDMA_LOCK_RD() & ~BM_SDMAARM_SDMA_LOCK_LOCK) | BF_SDMAARM_SDMA_LOCK_LOCK(v)))
#endif
//@}
/*! @name Register SDMAARM_SDMA_LOCK, field SRESET_LOCK_CLR[1] (RW)
*
* The SRESET_LOCK_CLR bit determine if the LOCK bit is cleared on a software reset triggered by
* writing to the RESET register. This bit cannot be changed if LOCK=1. SREST_LOCK_CLR is cleared by
* conditions that clear the LOCK bit.
*
* Values:
* - 0 - Software Reset does not clear the LOCK bit.
* - 1 - Software Reset clears the LOCK bit.
*/
//@{
#define BP_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR (1) //!< Bit position for SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR.
#define BM_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR (0x00000002) //!< Bit mask for SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR.
//! @brief Get value of SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR from a register value.
#define BG_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR) >> BP_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR)
//! @brief Format value for bitfield SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR.
#define BF_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR) & BM_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR)
#ifndef __LANGUAGE_ASM__
//! @brief Set the SRESET_LOCK_CLR field to a new value.
#define BW_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR(v) (HW_SDMAARM_SDMA_LOCK_WR((HW_SDMAARM_SDMA_LOCK_RD() & ~BM_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR) | BF_SDMAARM_SDMA_LOCK_SRESET_LOCK_CLR(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_ONCE_ENB - OnCE Enable
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_ONCE_ENB - OnCE Enable (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_once_enb
{
reg32_t U;
struct _hw_sdmaarm_once_enb_bitfields
{
unsigned ENB : 1; //!< [0] The OnCE Enable register selects the OnCE control source: When cleared (0), the OnCE registers are accessed through the JTAG interface; when set (1), the OnCE registers may be accessed by the ARM platform through the addresses described, as follows.
unsigned RESERVED0 : 31; //!< [31:1] Reserved
} B;
} hw_sdmaarm_once_enb_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_ONCE_ENB register
*/
//@{
#define HW_SDMAARM_ONCE_ENB_ADDR (REGS_SDMAARM_BASE + 0x40)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_ONCE_ENB (*(volatile hw_sdmaarm_once_enb_t *) HW_SDMAARM_ONCE_ENB_ADDR)
#define HW_SDMAARM_ONCE_ENB_RD() (HW_SDMAARM_ONCE_ENB.U)
#define HW_SDMAARM_ONCE_ENB_WR(v) (HW_SDMAARM_ONCE_ENB.U = (v))
#define HW_SDMAARM_ONCE_ENB_SET(v) (HW_SDMAARM_ONCE_ENB_WR(HW_SDMAARM_ONCE_ENB_RD() | (v)))
#define HW_SDMAARM_ONCE_ENB_CLR(v) (HW_SDMAARM_ONCE_ENB_WR(HW_SDMAARM_ONCE_ENB_RD() & ~(v)))
#define HW_SDMAARM_ONCE_ENB_TOG(v) (HW_SDMAARM_ONCE_ENB_WR(HW_SDMAARM_ONCE_ENB_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_ONCE_ENB bitfields
*/
/*! @name Register SDMAARM_ONCE_ENB, field ENB[0] (RW)
*
* The OnCE Enable register selects the OnCE control source: When cleared (0), the OnCE registers
* are accessed through the JTAG interface; when set (1), the OnCE registers may be accessed by the
* ARM platform through the addresses described, as follows. After reset, the OnCE registers are
* accessed through the JTAG interface. Writing a 1 to ENB enables the ARM platform to access the
* ONCE_* as any other SDMA control register. When cleared (0), all the ONCE_xxx registers cannot be
* written. The value of ENB cannot be changed if the LOCK bit in the SDMA_LOCK register is set.
*/
//@{
#define BP_SDMAARM_ONCE_ENB_ENB (0) //!< Bit position for SDMAARM_ONCE_ENB_ENB.
#define BM_SDMAARM_ONCE_ENB_ENB (0x00000001) //!< Bit mask for SDMAARM_ONCE_ENB_ENB.
//! @brief Get value of SDMAARM_ONCE_ENB_ENB from a register value.
#define BG_SDMAARM_ONCE_ENB_ENB(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_ENB_ENB) >> BP_SDMAARM_ONCE_ENB_ENB)
//! @brief Format value for bitfield SDMAARM_ONCE_ENB_ENB.
#define BF_SDMAARM_ONCE_ENB_ENB(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_ONCE_ENB_ENB) & BM_SDMAARM_ONCE_ENB_ENB)
#ifndef __LANGUAGE_ASM__
//! @brief Set the ENB field to a new value.
#define BW_SDMAARM_ONCE_ENB_ENB(v) (HW_SDMAARM_ONCE_ENB_WR((HW_SDMAARM_ONCE_ENB_RD() & ~BM_SDMAARM_ONCE_ENB_ENB) | BF_SDMAARM_ONCE_ENB_ENB(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_ONCE_DATA - OnCE Data Register
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_ONCE_DATA - OnCE Data Register (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_once_data
{
reg32_t U;
struct _hw_sdmaarm_once_data_bitfields
{
unsigned DATA : 32; //!< [31:0] Data register of the OnCE JTAG controller.
} B;
} hw_sdmaarm_once_data_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_ONCE_DATA register
*/
//@{
#define HW_SDMAARM_ONCE_DATA_ADDR (REGS_SDMAARM_BASE + 0x44)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_ONCE_DATA (*(volatile hw_sdmaarm_once_data_t *) HW_SDMAARM_ONCE_DATA_ADDR)
#define HW_SDMAARM_ONCE_DATA_RD() (HW_SDMAARM_ONCE_DATA.U)
#define HW_SDMAARM_ONCE_DATA_WR(v) (HW_SDMAARM_ONCE_DATA.U = (v))
#define HW_SDMAARM_ONCE_DATA_SET(v) (HW_SDMAARM_ONCE_DATA_WR(HW_SDMAARM_ONCE_DATA_RD() | (v)))
#define HW_SDMAARM_ONCE_DATA_CLR(v) (HW_SDMAARM_ONCE_DATA_WR(HW_SDMAARM_ONCE_DATA_RD() & ~(v)))
#define HW_SDMAARM_ONCE_DATA_TOG(v) (HW_SDMAARM_ONCE_DATA_WR(HW_SDMAARM_ONCE_DATA_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_ONCE_DATA bitfields
*/
/*! @name Register SDMAARM_ONCE_DATA, field DATA[31:0] (RW)
*
* Data register of the OnCE JTAG controller. Refer to for information on this register.
*/
//@{
#define BP_SDMAARM_ONCE_DATA_DATA (0) //!< Bit position for SDMAARM_ONCE_DATA_DATA.
#define BM_SDMAARM_ONCE_DATA_DATA (0xffffffff) //!< Bit mask for SDMAARM_ONCE_DATA_DATA.
//! @brief Get value of SDMAARM_ONCE_DATA_DATA from a register value.
#define BG_SDMAARM_ONCE_DATA_DATA(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_DATA_DATA) >> BP_SDMAARM_ONCE_DATA_DATA)
//! @brief Format value for bitfield SDMAARM_ONCE_DATA_DATA.
#define BF_SDMAARM_ONCE_DATA_DATA(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_ONCE_DATA_DATA) & BM_SDMAARM_ONCE_DATA_DATA)
#ifndef __LANGUAGE_ASM__
//! @brief Set the DATA field to a new value.
#define BW_SDMAARM_ONCE_DATA_DATA(v) (HW_SDMAARM_ONCE_DATA_WR((HW_SDMAARM_ONCE_DATA_RD() & ~BM_SDMAARM_ONCE_DATA_DATA) | BF_SDMAARM_ONCE_DATA_DATA(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_ONCE_INSTR - OnCE Instruction Register
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_ONCE_INSTR - OnCE Instruction Register (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_once_instr
{
reg32_t U;
struct _hw_sdmaarm_once_instr_bitfields
{
unsigned INSTR : 16; //!< [15:0] Instruction register of the OnCE JTAG controller.
unsigned RESERVED0 : 16; //!< [31:16] Reserved
} B;
} hw_sdmaarm_once_instr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_ONCE_INSTR register
*/
//@{
#define HW_SDMAARM_ONCE_INSTR_ADDR (REGS_SDMAARM_BASE + 0x48)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_ONCE_INSTR (*(volatile hw_sdmaarm_once_instr_t *) HW_SDMAARM_ONCE_INSTR_ADDR)
#define HW_SDMAARM_ONCE_INSTR_RD() (HW_SDMAARM_ONCE_INSTR.U)
#define HW_SDMAARM_ONCE_INSTR_WR(v) (HW_SDMAARM_ONCE_INSTR.U = (v))
#define HW_SDMAARM_ONCE_INSTR_SET(v) (HW_SDMAARM_ONCE_INSTR_WR(HW_SDMAARM_ONCE_INSTR_RD() | (v)))
#define HW_SDMAARM_ONCE_INSTR_CLR(v) (HW_SDMAARM_ONCE_INSTR_WR(HW_SDMAARM_ONCE_INSTR_RD() & ~(v)))
#define HW_SDMAARM_ONCE_INSTR_TOG(v) (HW_SDMAARM_ONCE_INSTR_WR(HW_SDMAARM_ONCE_INSTR_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_ONCE_INSTR bitfields
*/
/*! @name Register SDMAARM_ONCE_INSTR, field INSTR[15:0] (RW)
*
* Instruction register of the OnCE JTAG controller. Refer to for information on this register.
*/
//@{
#define BP_SDMAARM_ONCE_INSTR_INSTR (0) //!< Bit position for SDMAARM_ONCE_INSTR_INSTR.
#define BM_SDMAARM_ONCE_INSTR_INSTR (0x0000ffff) //!< Bit mask for SDMAARM_ONCE_INSTR_INSTR.
//! @brief Get value of SDMAARM_ONCE_INSTR_INSTR from a register value.
#define BG_SDMAARM_ONCE_INSTR_INSTR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_INSTR_INSTR) >> BP_SDMAARM_ONCE_INSTR_INSTR)
//! @brief Format value for bitfield SDMAARM_ONCE_INSTR_INSTR.
#define BF_SDMAARM_ONCE_INSTR_INSTR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_ONCE_INSTR_INSTR) & BM_SDMAARM_ONCE_INSTR_INSTR)
#ifndef __LANGUAGE_ASM__
//! @brief Set the INSTR field to a new value.
#define BW_SDMAARM_ONCE_INSTR_INSTR(v) (HW_SDMAARM_ONCE_INSTR_WR((HW_SDMAARM_ONCE_INSTR_RD() & ~BM_SDMAARM_ONCE_INSTR_INSTR) | BF_SDMAARM_ONCE_INSTR_INSTR(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_ONCE_STAT - OnCE Status Register
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_ONCE_STAT - OnCE Status Register (RO)
*
* Reset value: 0x0000e000
*/
typedef union _hw_sdmaarm_once_stat
{
reg32_t U;
struct _hw_sdmaarm_once_stat_bitfields
{
unsigned ECDR : 3; //!< [2:0] Event Cell Debug Request.
unsigned RESERVED0 : 4; //!< [6:3] Reserved
unsigned MST : 1; //!< [7] This flag is raised when the OnCE is controlled from the ARM platform peripheral interface.
unsigned SWB : 1; //!< [8] This flag is raised when the SDMA has entered debug mode after a software breakpoint.
unsigned ODR : 1; //!< [9] This flag is raised when the SDMA has entered debug mode after a OnCE debug request.
unsigned EDR : 1; //!< [10] This flag is raised when the SDMA has entered debug mode after an external debug request.
unsigned RCV : 1; //!< [11] After each write access to the real time buffer (RTB), the RCV bit is set.
unsigned PST : 4; //!< [15:12] The Processor Status bits reflect the state of the SDMA RISC engine.
unsigned RESERVED1 : 16; //!< [31:16] Reserved
} B;
} hw_sdmaarm_once_stat_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_ONCE_STAT register
*/
//@{
#define HW_SDMAARM_ONCE_STAT_ADDR (REGS_SDMAARM_BASE + 0x4c)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_ONCE_STAT (*(volatile hw_sdmaarm_once_stat_t *) HW_SDMAARM_ONCE_STAT_ADDR)
#define HW_SDMAARM_ONCE_STAT_RD() (HW_SDMAARM_ONCE_STAT.U)
#endif
//@}
/*
* constants & macros for individual SDMAARM_ONCE_STAT bitfields
*/
/*! @name Register SDMAARM_ONCE_STAT, field ECDR[2:0] (RO)
*
* Event Cell Debug Request. If the debug request comes from the event cell, the reason for entering
* debug mode is given by the EDR bits. If all three bits of the EDR are reset, then it did not
* generate any debug request. If the cell did generate a debug request, then at least one of the
* EDR bits is set (the meaning of the encoding is given below). The encoding of the EDR bits is
* useful to find out more precisely why the debug request was generated. A debug request from an
* event cell is generated for a specific combination of the addra_cond, addrb_cond, and data_cond
* conditions. The value of those fields is given by the EDR bits.
*
* Values:
* - 0 - 1 matched addra_cond
* - 1 - 1 matched addrb_cond
* - 2 - 1 matched data_cond
*/
//@{
#define BP_SDMAARM_ONCE_STAT_ECDR (0) //!< Bit position for SDMAARM_ONCE_STAT_ECDR.
#define BM_SDMAARM_ONCE_STAT_ECDR (0x00000007) //!< Bit mask for SDMAARM_ONCE_STAT_ECDR.
//! @brief Get value of SDMAARM_ONCE_STAT_ECDR from a register value.
#define BG_SDMAARM_ONCE_STAT_ECDR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_STAT_ECDR) >> BP_SDMAARM_ONCE_STAT_ECDR)
//@}
/*! @name Register SDMAARM_ONCE_STAT, field MST[7] (RO)
*
* This flag is raised when the OnCE is controlled from the ARM platform peripheral interface.
*
* Values:
* - 0 - The JTAG interface controls the OnCE.
* - 1 - The ARM platform peripheral interface controls the OnCE.
*/
//@{
#define BP_SDMAARM_ONCE_STAT_MST (7) //!< Bit position for SDMAARM_ONCE_STAT_MST.
#define BM_SDMAARM_ONCE_STAT_MST (0x00000080) //!< Bit mask for SDMAARM_ONCE_STAT_MST.
//! @brief Get value of SDMAARM_ONCE_STAT_MST from a register value.
#define BG_SDMAARM_ONCE_STAT_MST(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_STAT_MST) >> BP_SDMAARM_ONCE_STAT_MST)
//@}
/*! @name Register SDMAARM_ONCE_STAT, field SWB[8] (RO)
*
* This flag is raised when the SDMA has entered debug mode after a software breakpoint.
*/
//@{
#define BP_SDMAARM_ONCE_STAT_SWB (8) //!< Bit position for SDMAARM_ONCE_STAT_SWB.
#define BM_SDMAARM_ONCE_STAT_SWB (0x00000100) //!< Bit mask for SDMAARM_ONCE_STAT_SWB.
//! @brief Get value of SDMAARM_ONCE_STAT_SWB from a register value.
#define BG_SDMAARM_ONCE_STAT_SWB(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_STAT_SWB) >> BP_SDMAARM_ONCE_STAT_SWB)
//@}
/*! @name Register SDMAARM_ONCE_STAT, field ODR[9] (RO)
*
* This flag is raised when the SDMA has entered debug mode after a OnCE debug request.
*/
//@{
#define BP_SDMAARM_ONCE_STAT_ODR (9) //!< Bit position for SDMAARM_ONCE_STAT_ODR.
#define BM_SDMAARM_ONCE_STAT_ODR (0x00000200) //!< Bit mask for SDMAARM_ONCE_STAT_ODR.
//! @brief Get value of SDMAARM_ONCE_STAT_ODR from a register value.
#define BG_SDMAARM_ONCE_STAT_ODR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_STAT_ODR) >> BP_SDMAARM_ONCE_STAT_ODR)
//@}
/*! @name Register SDMAARM_ONCE_STAT, field EDR[10] (RO)
*
* This flag is raised when the SDMA has entered debug mode after an external debug request.
*/
//@{
#define BP_SDMAARM_ONCE_STAT_EDR (10) //!< Bit position for SDMAARM_ONCE_STAT_EDR.
#define BM_SDMAARM_ONCE_STAT_EDR (0x00000400) //!< Bit mask for SDMAARM_ONCE_STAT_EDR.
//! @brief Get value of SDMAARM_ONCE_STAT_EDR from a register value.
#define BG_SDMAARM_ONCE_STAT_EDR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_STAT_EDR) >> BP_SDMAARM_ONCE_STAT_EDR)
//@}
/*! @name Register SDMAARM_ONCE_STAT, field RCV[11] (RO)
*
* After each write access to the real time buffer (RTB), the RCV bit is set. This bit is cleared
* after execution of an rbuffer command and on a JTAG reset.
*/
//@{
#define BP_SDMAARM_ONCE_STAT_RCV (11) //!< Bit position for SDMAARM_ONCE_STAT_RCV.
#define BM_SDMAARM_ONCE_STAT_RCV (0x00000800) //!< Bit mask for SDMAARM_ONCE_STAT_RCV.
//! @brief Get value of SDMAARM_ONCE_STAT_RCV from a register value.
#define BG_SDMAARM_ONCE_STAT_RCV(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_STAT_RCV) >> BP_SDMAARM_ONCE_STAT_RCV)
//@}
/*! @name Register SDMAARM_ONCE_STAT, field PST[15:12] (RO)
*
* The Processor Status bits reflect the state of the SDMA RISC engine. Its states are as follows:
* The "Program" state is the usual instruction execution cycle. The "Data" state is inserted when
* there are wait-states during a load or a store on the data bus (ld or st). The "Change of Flow"
* state is the second cycle of any instruction that breaks the sequence of instructions (jumps and
* channel switching instructions). The "Change of Flow in Loop" state is used when an error causes
* a hardware loop exit. The "Debug" state means the SDMA is in debug mode. The "Functional Unit"
* state is inserted when there are wait-states during a load or a store on the functional units bus
* (ldf or stf). In "Sleep" modes, no script is running (this is the RISC engine idle state). The
* "after Reset" is slightly different because no context restoring phase will happen when a channel
* is triggered: The script located at address 0 will be executed (boot operation). The "in Sleep"
* states are the same as above except they do not have any corresponding channel: They are used
* when entering debug mode after reset. The reason is that it is necessary to return to the "Sleep
* after Reset" state when leaving debug mode.
*
* Values:
* - 0 - Program
* - 1 - Data
* - 2 - Change of Flow
* - 3 - Change of Flow in Loop
* - 4 - Debug
* - 5 - Functional Unit
* - 6 - Sleep
* - 7 - Save
* - 8 - Program in Sleep
* - 9 - Data in Sleep
* - 10 - Change of Flow in Sleep
* - 11 - Change Flow in Loop in Sleep
* - 12 - Debug in Sleep
* - 13 - Functional Unit in Sleep
* - 14 - Sleep after Reset
* - 15 - Restore
*/
//@{
#define BP_SDMAARM_ONCE_STAT_PST (12) //!< Bit position for SDMAARM_ONCE_STAT_PST.
#define BM_SDMAARM_ONCE_STAT_PST (0x0000f000) //!< Bit mask for SDMAARM_ONCE_STAT_PST.
//! @brief Get value of SDMAARM_ONCE_STAT_PST from a register value.
#define BG_SDMAARM_ONCE_STAT_PST(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_STAT_PST) >> BP_SDMAARM_ONCE_STAT_PST)
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_ONCE_CMD - OnCE Command Register
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_ONCE_CMD - OnCE Command Register (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_once_cmd
{
reg32_t U;
struct _hw_sdmaarm_once_cmd_bitfields
{
unsigned CMD : 4; //!< [3:0] Writing to this register will cause the OnCE to execute the command that is written.
unsigned RESERVED0 : 28; //!< [31:4] Reserved
} B;
} hw_sdmaarm_once_cmd_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_ONCE_CMD register
*/
//@{
#define HW_SDMAARM_ONCE_CMD_ADDR (REGS_SDMAARM_BASE + 0x50)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_ONCE_CMD (*(volatile hw_sdmaarm_once_cmd_t *) HW_SDMAARM_ONCE_CMD_ADDR)
#define HW_SDMAARM_ONCE_CMD_RD() (HW_SDMAARM_ONCE_CMD.U)
#define HW_SDMAARM_ONCE_CMD_WR(v) (HW_SDMAARM_ONCE_CMD.U = (v))
#define HW_SDMAARM_ONCE_CMD_SET(v) (HW_SDMAARM_ONCE_CMD_WR(HW_SDMAARM_ONCE_CMD_RD() | (v)))
#define HW_SDMAARM_ONCE_CMD_CLR(v) (HW_SDMAARM_ONCE_CMD_WR(HW_SDMAARM_ONCE_CMD_RD() & ~(v)))
#define HW_SDMAARM_ONCE_CMD_TOG(v) (HW_SDMAARM_ONCE_CMD_WR(HW_SDMAARM_ONCE_CMD_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_ONCE_CMD bitfields
*/
/*! @name Register SDMAARM_ONCE_CMD, field CMD[3:0] (RW)
*
* Writing to this register will cause the OnCE to execute the command that is written. When needed,
* the ONCE_DATA and ONCE_INSTR registers should be loaded with the correct value before writing the
* command to that register. For a list of the OnCE commands and their usage, see . 7-15 reserved
*
* Values:
* - 0 - rstatus
* - 1 - dmov
* - 2 - exec_once
* - 3 - run_core
* - 4 - exec_core
* - 5 - debug_rqst
* - 6 - rbuffer
*/
//@{
#define BP_SDMAARM_ONCE_CMD_CMD (0) //!< Bit position for SDMAARM_ONCE_CMD_CMD.
#define BM_SDMAARM_ONCE_CMD_CMD (0x0000000f) //!< Bit mask for SDMAARM_ONCE_CMD_CMD.
//! @brief Get value of SDMAARM_ONCE_CMD_CMD from a register value.
#define BG_SDMAARM_ONCE_CMD_CMD(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ONCE_CMD_CMD) >> BP_SDMAARM_ONCE_CMD_CMD)
//! @brief Format value for bitfield SDMAARM_ONCE_CMD_CMD.
#define BF_SDMAARM_ONCE_CMD_CMD(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_ONCE_CMD_CMD) & BM_SDMAARM_ONCE_CMD_CMD)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CMD field to a new value.
#define BW_SDMAARM_ONCE_CMD_CMD(v) (HW_SDMAARM_ONCE_CMD_WR((HW_SDMAARM_ONCE_CMD_RD() & ~BM_SDMAARM_ONCE_CMD_CMD) | BF_SDMAARM_ONCE_CMD_CMD(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_ILLINSTADDR - Illegal Instruction Trap Address
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_ILLINSTADDR - Illegal Instruction Trap Address (RW)
*
* Reset value: 0x00000001
*/
typedef union _hw_sdmaarm_illinstaddr
{
reg32_t U;
struct _hw_sdmaarm_illinstaddr_bitfields
{
unsigned ILLINSTADDR : 14; //!< [13:0] The Illegal Instruction Trap Address is the address where the SDMA jumps when an illegal instruction is executed.
unsigned RESERVED0 : 18; //!< [31:14] Reserved
} B;
} hw_sdmaarm_illinstaddr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_ILLINSTADDR register
*/
//@{
#define HW_SDMAARM_ILLINSTADDR_ADDR (REGS_SDMAARM_BASE + 0x58)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_ILLINSTADDR (*(volatile hw_sdmaarm_illinstaddr_t *) HW_SDMAARM_ILLINSTADDR_ADDR)
#define HW_SDMAARM_ILLINSTADDR_RD() (HW_SDMAARM_ILLINSTADDR.U)
#define HW_SDMAARM_ILLINSTADDR_WR(v) (HW_SDMAARM_ILLINSTADDR.U = (v))
#define HW_SDMAARM_ILLINSTADDR_SET(v) (HW_SDMAARM_ILLINSTADDR_WR(HW_SDMAARM_ILLINSTADDR_RD() | (v)))
#define HW_SDMAARM_ILLINSTADDR_CLR(v) (HW_SDMAARM_ILLINSTADDR_WR(HW_SDMAARM_ILLINSTADDR_RD() & ~(v)))
#define HW_SDMAARM_ILLINSTADDR_TOG(v) (HW_SDMAARM_ILLINSTADDR_WR(HW_SDMAARM_ILLINSTADDR_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_ILLINSTADDR bitfields
*/
/*! @name Register SDMAARM_ILLINSTADDR, field ILLINSTADDR[13:0] (RW)
*
* The Illegal Instruction Trap Address is the address where the SDMA jumps when an illegal
* instruction is executed. It is 0x0001 after reset. The value of ILLINSTADDR cannot be changed if
* the LOCK bit in the SDMA_LOCK register is set.
*/
//@{
#define BP_SDMAARM_ILLINSTADDR_ILLINSTADDR (0) //!< Bit position for SDMAARM_ILLINSTADDR_ILLINSTADDR.
#define BM_SDMAARM_ILLINSTADDR_ILLINSTADDR (0x00003fff) //!< Bit mask for SDMAARM_ILLINSTADDR_ILLINSTADDR.
//! @brief Get value of SDMAARM_ILLINSTADDR_ILLINSTADDR from a register value.
#define BG_SDMAARM_ILLINSTADDR_ILLINSTADDR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_ILLINSTADDR_ILLINSTADDR) >> BP_SDMAARM_ILLINSTADDR_ILLINSTADDR)
//! @brief Format value for bitfield SDMAARM_ILLINSTADDR_ILLINSTADDR.
#define BF_SDMAARM_ILLINSTADDR_ILLINSTADDR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_ILLINSTADDR_ILLINSTADDR) & BM_SDMAARM_ILLINSTADDR_ILLINSTADDR)
#ifndef __LANGUAGE_ASM__
//! @brief Set the ILLINSTADDR field to a new value.
#define BW_SDMAARM_ILLINSTADDR_ILLINSTADDR(v) (HW_SDMAARM_ILLINSTADDR_WR((HW_SDMAARM_ILLINSTADDR_RD() & ~BM_SDMAARM_ILLINSTADDR_ILLINSTADDR) | BF_SDMAARM_ILLINSTADDR_ILLINSTADDR(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_CHN0ADDR - Channel 0 Boot Address
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_CHN0ADDR - Channel 0 Boot Address (RW)
*
* Reset value: 0x00000050
*/
typedef union _hw_sdmaarm_chn0addr
{
reg32_t U;
struct _hw_sdmaarm_chn0addr_bitfields
{
unsigned CHN0ADDR : 14; //!< [13:0] This 14-bit register is used by the boot code of the SDMA.
unsigned SMSZ : 1; //!< [14] The bit 14 (Scratch Memory Size) determines if scratch memory must be available after every channel context.
unsigned RESERVED0 : 17; //!< [31:15] Reserved
} B;
} hw_sdmaarm_chn0addr_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_CHN0ADDR register
*/
//@{
#define HW_SDMAARM_CHN0ADDR_ADDR (REGS_SDMAARM_BASE + 0x5c)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_CHN0ADDR (*(volatile hw_sdmaarm_chn0addr_t *) HW_SDMAARM_CHN0ADDR_ADDR)
#define HW_SDMAARM_CHN0ADDR_RD() (HW_SDMAARM_CHN0ADDR.U)
#define HW_SDMAARM_CHN0ADDR_WR(v) (HW_SDMAARM_CHN0ADDR.U = (v))
#define HW_SDMAARM_CHN0ADDR_SET(v) (HW_SDMAARM_CHN0ADDR_WR(HW_SDMAARM_CHN0ADDR_RD() | (v)))
#define HW_SDMAARM_CHN0ADDR_CLR(v) (HW_SDMAARM_CHN0ADDR_WR(HW_SDMAARM_CHN0ADDR_RD() & ~(v)))
#define HW_SDMAARM_CHN0ADDR_TOG(v) (HW_SDMAARM_CHN0ADDR_WR(HW_SDMAARM_CHN0ADDR_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_CHN0ADDR bitfields
*/
/*! @name Register SDMAARM_CHN0ADDR, field CHN0ADDR[13:0] (RW)
*
* This 14-bit register is used by the boot code of the SDMA. After reset, it points to the standard
* boot routine in ROM (channel 0 routine). By changing this address, you can perform a boot
* sequence with your own routine. The very first instructions of the boot code fetch the contents
* of this register (it is also mapped in the SDMA memory space) and jump to the given address. The
* reset value is 0x0050 (decimal 80). The value of CHN0ADDR cannot be changed if the LOCK bit in
* the SDMA_LOCK register is set.
*/
//@{
#define BP_SDMAARM_CHN0ADDR_CHN0ADDR (0) //!< Bit position for SDMAARM_CHN0ADDR_CHN0ADDR.
#define BM_SDMAARM_CHN0ADDR_CHN0ADDR (0x00003fff) //!< Bit mask for SDMAARM_CHN0ADDR_CHN0ADDR.
//! @brief Get value of SDMAARM_CHN0ADDR_CHN0ADDR from a register value.
#define BG_SDMAARM_CHN0ADDR_CHN0ADDR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_CHN0ADDR_CHN0ADDR) >> BP_SDMAARM_CHN0ADDR_CHN0ADDR)
//! @brief Format value for bitfield SDMAARM_CHN0ADDR_CHN0ADDR.
#define BF_SDMAARM_CHN0ADDR_CHN0ADDR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_CHN0ADDR_CHN0ADDR) & BM_SDMAARM_CHN0ADDR_CHN0ADDR)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CHN0ADDR field to a new value.
#define BW_SDMAARM_CHN0ADDR_CHN0ADDR(v) (HW_SDMAARM_CHN0ADDR_WR((HW_SDMAARM_CHN0ADDR_RD() & ~BM_SDMAARM_CHN0ADDR_CHN0ADDR) | BF_SDMAARM_CHN0ADDR_CHN0ADDR(v)))
#endif
//@}
/*! @name Register SDMAARM_CHN0ADDR, field SMSZ[14] (RW)
*
* The bit 14 (Scratch Memory Size) determines if scratch memory must be available after every
* channel context. After reset, it is equal to 0, which defines a RAM space of 24 words for each
* channel. All of this area stores the channel context. By setting this bit, 32 words are reserved
* for every channel context, which gives eight additional words that can be used by the channel
* script to store any type of data. Those words are never erased by the context switching
* mechanism. The value of SMSZ cannot be changed if the LOCK bit in the SDMA_LOCK register is set.
*
* Values:
* - 0 - 24 words per context
* - 1 - 32 words per context
*/
//@{
#define BP_SDMAARM_CHN0ADDR_SMSZ (14) //!< Bit position for SDMAARM_CHN0ADDR_SMSZ.
#define BM_SDMAARM_CHN0ADDR_SMSZ (0x00004000) //!< Bit mask for SDMAARM_CHN0ADDR_SMSZ.
//! @brief Get value of SDMAARM_CHN0ADDR_SMSZ from a register value.
#define BG_SDMAARM_CHN0ADDR_SMSZ(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_CHN0ADDR_SMSZ) >> BP_SDMAARM_CHN0ADDR_SMSZ)
//! @brief Format value for bitfield SDMAARM_CHN0ADDR_SMSZ.
#define BF_SDMAARM_CHN0ADDR_SMSZ(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_CHN0ADDR_SMSZ) & BM_SDMAARM_CHN0ADDR_SMSZ)
#ifndef __LANGUAGE_ASM__
//! @brief Set the SMSZ field to a new value.
#define BW_SDMAARM_CHN0ADDR_SMSZ(v) (HW_SDMAARM_CHN0ADDR_WR((HW_SDMAARM_CHN0ADDR_RD() & ~BM_SDMAARM_CHN0ADDR_SMSZ) | BF_SDMAARM_CHN0ADDR_SMSZ(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_EVT_MIRROR - DMA Requests
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_EVT_MIRROR - DMA Requests (RO)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_evt_mirror
{
reg32_t U;
struct _hw_sdmaarm_evt_mirror_bitfields
{
unsigned EVENTS : 32; //!< [31:0] This register reflects the DMA requests received by the SDMA for events 31-0.
} B;
} hw_sdmaarm_evt_mirror_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_EVT_MIRROR register
*/
//@{
#define HW_SDMAARM_EVT_MIRROR_ADDR (REGS_SDMAARM_BASE + 0x60)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_EVT_MIRROR (*(volatile hw_sdmaarm_evt_mirror_t *) HW_SDMAARM_EVT_MIRROR_ADDR)
#define HW_SDMAARM_EVT_MIRROR_RD() (HW_SDMAARM_EVT_MIRROR.U)
#endif
//@}
/*
* constants & macros for individual SDMAARM_EVT_MIRROR bitfields
*/
/*! @name Register SDMAARM_EVT_MIRROR, field EVENTS[31:0] (RO)
*
* This register reflects the DMA requests received by the SDMA for events 31-0. The ARM platform
* and the SDMA have a read-only access. There is one bit associated with each of 32 DMA request
* events. This information may be useful during debug of the blocks that generate the DMA requests.
* The EVT_MIRROR register is cleared following read access.
*
* Values:
* - 0 - DMA request event not pending
* - 1 - DMA request event pending
*/
//@{
#define BP_SDMAARM_EVT_MIRROR_EVENTS (0) //!< Bit position for SDMAARM_EVT_MIRROR_EVENTS.
#define BM_SDMAARM_EVT_MIRROR_EVENTS (0xffffffff) //!< Bit mask for SDMAARM_EVT_MIRROR_EVENTS.
//! @brief Get value of SDMAARM_EVT_MIRROR_EVENTS from a register value.
#define BG_SDMAARM_EVT_MIRROR_EVENTS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_EVT_MIRROR_EVENTS) >> BP_SDMAARM_EVT_MIRROR_EVENTS)
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_EVT_MIRROR2 - DMA Requests 2
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_EVT_MIRROR2 - DMA Requests 2 (RO)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_evt_mirror2
{
reg32_t U;
struct _hw_sdmaarm_evt_mirror2_bitfields
{
unsigned EVENTS : 16; //!< [15:0] This register reflects the DMA requests received by the SDMA for events 47-32.
unsigned RESERVED0 : 16; //!< [31:16] Reserved
} B;
} hw_sdmaarm_evt_mirror2_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_EVT_MIRROR2 register
*/
//@{
#define HW_SDMAARM_EVT_MIRROR2_ADDR (REGS_SDMAARM_BASE + 0x64)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_EVT_MIRROR2 (*(volatile hw_sdmaarm_evt_mirror2_t *) HW_SDMAARM_EVT_MIRROR2_ADDR)
#define HW_SDMAARM_EVT_MIRROR2_RD() (HW_SDMAARM_EVT_MIRROR2.U)
#endif
//@}
/*
* constants & macros for individual SDMAARM_EVT_MIRROR2 bitfields
*/
/*! @name Register SDMAARM_EVT_MIRROR2, field EVENTS[15:0] (RO)
*
* This register reflects the DMA requests received by the SDMA for events 47-32. The ARM platform
* and the SDMA have a read-only access. There is one bit associated with each of DMA request
* events. This information may be useful during debug of the blocks that generate the DMA requests.
* The EVT_MIRROR2 register is cleared following read access.
*
* Values:
* - 0 - - DMA request event not pending
* - 1- - DMA request event pending
*/
//@{
#define BP_SDMAARM_EVT_MIRROR2_EVENTS (0) //!< Bit position for SDMAARM_EVT_MIRROR2_EVENTS.
#define BM_SDMAARM_EVT_MIRROR2_EVENTS (0x0000ffff) //!< Bit mask for SDMAARM_EVT_MIRROR2_EVENTS.
//! @brief Get value of SDMAARM_EVT_MIRROR2_EVENTS from a register value.
#define BG_SDMAARM_EVT_MIRROR2_EVENTS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_EVT_MIRROR2_EVENTS) >> BP_SDMAARM_EVT_MIRROR2_EVENTS)
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_XTRIG_CONF1 - Cross-Trigger Events Configuration Register 1
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_XTRIG_CONF1 - Cross-Trigger Events Configuration Register 1 (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_xtrig_conf1
{
reg32_t U;
struct _hw_sdmaarm_xtrig_conf1_bitfields
{
unsigned NUM0 : 6; //!< [5:0] Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger event line number i .
unsigned CNF0 : 1; //!< [6] Configuration of the SDMA event line number i that is connected to the cross-trigger.
unsigned RESERVED0 : 1; //!< [7] Reserved
unsigned NUM1 : 6; //!< [13:8] Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger event line number i .
unsigned CNF1 : 1; //!< [14] Configuration of the SDMA event line number i that is connected to the cross-trigger.
unsigned RESERVED1 : 1; //!< [15] Reserved
unsigned NUM2 : 6; //!< [21:16] Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger event line number i .
unsigned CNF2 : 1; //!< [22] Configuration of the SDMA event line number i that is connected to the cross-trigger.
unsigned RESERVED2 : 1; //!< [23] Reserved
unsigned NUM3 : 6; //!< [29:24] Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger event line number i .
unsigned CNF3 : 1; //!< [30] Configuration of the SDMA event line number i that is connected to the cross-trigger.
unsigned RESERVED3 : 1; //!< [31] Reserved
} B;
} hw_sdmaarm_xtrig_conf1_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_XTRIG_CONF1 register
*/
//@{
#define HW_SDMAARM_XTRIG_CONF1_ADDR (REGS_SDMAARM_BASE + 0x70)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_XTRIG_CONF1 (*(volatile hw_sdmaarm_xtrig_conf1_t *) HW_SDMAARM_XTRIG_CONF1_ADDR)
#define HW_SDMAARM_XTRIG_CONF1_RD() (HW_SDMAARM_XTRIG_CONF1.U)
#define HW_SDMAARM_XTRIG_CONF1_WR(v) (HW_SDMAARM_XTRIG_CONF1.U = (v))
#define HW_SDMAARM_XTRIG_CONF1_SET(v) (HW_SDMAARM_XTRIG_CONF1_WR(HW_SDMAARM_XTRIG_CONF1_RD() | (v)))
#define HW_SDMAARM_XTRIG_CONF1_CLR(v) (HW_SDMAARM_XTRIG_CONF1_WR(HW_SDMAARM_XTRIG_CONF1_RD() & ~(v)))
#define HW_SDMAARM_XTRIG_CONF1_TOG(v) (HW_SDMAARM_XTRIG_CONF1_WR(HW_SDMAARM_XTRIG_CONF1_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_XTRIG_CONF1 bitfields
*/
/*! @name Register SDMAARM_XTRIG_CONF1, field NUM0[5:0] (RW)
*
* Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger
* event line number i .
*/
//@{
#define BP_SDMAARM_XTRIG_CONF1_NUM0 (0) //!< Bit position for SDMAARM_XTRIG_CONF1_NUM0.
#define BM_SDMAARM_XTRIG_CONF1_NUM0 (0x0000003f) //!< Bit mask for SDMAARM_XTRIG_CONF1_NUM0.
//! @brief Get value of SDMAARM_XTRIG_CONF1_NUM0 from a register value.
#define BG_SDMAARM_XTRIG_CONF1_NUM0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF1_NUM0) >> BP_SDMAARM_XTRIG_CONF1_NUM0)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF1_NUM0.
#define BF_SDMAARM_XTRIG_CONF1_NUM0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF1_NUM0) & BM_SDMAARM_XTRIG_CONF1_NUM0)
#ifndef __LANGUAGE_ASM__
//! @brief Set the NUM0 field to a new value.
#define BW_SDMAARM_XTRIG_CONF1_NUM0(v) (HW_SDMAARM_XTRIG_CONF1_WR((HW_SDMAARM_XTRIG_CONF1_RD() & ~BM_SDMAARM_XTRIG_CONF1_NUM0) | BF_SDMAARM_XTRIG_CONF1_NUM0(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF1, field CNF0[6] (RW)
*
* Configuration of the SDMA event line number i that is connected to the cross-trigger. It
* determines whether the event line pulse is generated by receiving a DMA request or by starting a
* channel script execution.
*
* Values:
* - 0 - channel
* - 1 - DMA request
*/
//@{
#define BP_SDMAARM_XTRIG_CONF1_CNF0 (6) //!< Bit position for SDMAARM_XTRIG_CONF1_CNF0.
#define BM_SDMAARM_XTRIG_CONF1_CNF0 (0x00000040) //!< Bit mask for SDMAARM_XTRIG_CONF1_CNF0.
//! @brief Get value of SDMAARM_XTRIG_CONF1_CNF0 from a register value.
#define BG_SDMAARM_XTRIG_CONF1_CNF0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF1_CNF0) >> BP_SDMAARM_XTRIG_CONF1_CNF0)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF1_CNF0.
#define BF_SDMAARM_XTRIG_CONF1_CNF0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF1_CNF0) & BM_SDMAARM_XTRIG_CONF1_CNF0)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CNF0 field to a new value.
#define BW_SDMAARM_XTRIG_CONF1_CNF0(v) (HW_SDMAARM_XTRIG_CONF1_WR((HW_SDMAARM_XTRIG_CONF1_RD() & ~BM_SDMAARM_XTRIG_CONF1_CNF0) | BF_SDMAARM_XTRIG_CONF1_CNF0(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF1, field NUM1[13:8] (RW)
*
* Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger
* event line number i .
*/
//@{
#define BP_SDMAARM_XTRIG_CONF1_NUM1 (8) //!< Bit position for SDMAARM_XTRIG_CONF1_NUM1.
#define BM_SDMAARM_XTRIG_CONF1_NUM1 (0x00003f00) //!< Bit mask for SDMAARM_XTRIG_CONF1_NUM1.
//! @brief Get value of SDMAARM_XTRIG_CONF1_NUM1 from a register value.
#define BG_SDMAARM_XTRIG_CONF1_NUM1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF1_NUM1) >> BP_SDMAARM_XTRIG_CONF1_NUM1)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF1_NUM1.
#define BF_SDMAARM_XTRIG_CONF1_NUM1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF1_NUM1) & BM_SDMAARM_XTRIG_CONF1_NUM1)
#ifndef __LANGUAGE_ASM__
//! @brief Set the NUM1 field to a new value.
#define BW_SDMAARM_XTRIG_CONF1_NUM1(v) (HW_SDMAARM_XTRIG_CONF1_WR((HW_SDMAARM_XTRIG_CONF1_RD() & ~BM_SDMAARM_XTRIG_CONF1_NUM1) | BF_SDMAARM_XTRIG_CONF1_NUM1(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF1, field CNF1[14] (RW)
*
* Configuration of the SDMA event line number i that is connected to the cross-trigger. It
* determines whether the event line pulse is generated by receiving a DMA request or by starting a
* channel script execution.
*
* Values:
* - 0 - channel
* - 1 - DMA request
*/
//@{
#define BP_SDMAARM_XTRIG_CONF1_CNF1 (14) //!< Bit position for SDMAARM_XTRIG_CONF1_CNF1.
#define BM_SDMAARM_XTRIG_CONF1_CNF1 (0x00004000) //!< Bit mask for SDMAARM_XTRIG_CONF1_CNF1.
//! @brief Get value of SDMAARM_XTRIG_CONF1_CNF1 from a register value.
#define BG_SDMAARM_XTRIG_CONF1_CNF1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF1_CNF1) >> BP_SDMAARM_XTRIG_CONF1_CNF1)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF1_CNF1.
#define BF_SDMAARM_XTRIG_CONF1_CNF1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF1_CNF1) & BM_SDMAARM_XTRIG_CONF1_CNF1)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CNF1 field to a new value.
#define BW_SDMAARM_XTRIG_CONF1_CNF1(v) (HW_SDMAARM_XTRIG_CONF1_WR((HW_SDMAARM_XTRIG_CONF1_RD() & ~BM_SDMAARM_XTRIG_CONF1_CNF1) | BF_SDMAARM_XTRIG_CONF1_CNF1(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF1, field NUM2[21:16] (RW)
*
* Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger
* event line number i .
*/
//@{
#define BP_SDMAARM_XTRIG_CONF1_NUM2 (16) //!< Bit position for SDMAARM_XTRIG_CONF1_NUM2.
#define BM_SDMAARM_XTRIG_CONF1_NUM2 (0x003f0000) //!< Bit mask for SDMAARM_XTRIG_CONF1_NUM2.
//! @brief Get value of SDMAARM_XTRIG_CONF1_NUM2 from a register value.
#define BG_SDMAARM_XTRIG_CONF1_NUM2(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF1_NUM2) >> BP_SDMAARM_XTRIG_CONF1_NUM2)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF1_NUM2.
#define BF_SDMAARM_XTRIG_CONF1_NUM2(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF1_NUM2) & BM_SDMAARM_XTRIG_CONF1_NUM2)
#ifndef __LANGUAGE_ASM__
//! @brief Set the NUM2 field to a new value.
#define BW_SDMAARM_XTRIG_CONF1_NUM2(v) (HW_SDMAARM_XTRIG_CONF1_WR((HW_SDMAARM_XTRIG_CONF1_RD() & ~BM_SDMAARM_XTRIG_CONF1_NUM2) | BF_SDMAARM_XTRIG_CONF1_NUM2(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF1, field CNF2[22] (RW)
*
* Configuration of the SDMA event line number i that is connected to the cross-trigger. It
* determines whether the event line pulse is generated by receiving a DMA request or by starting a
* channel script execution.
*
* Values:
* - 0 - channel
* - 1 - DMA request
*/
//@{
#define BP_SDMAARM_XTRIG_CONF1_CNF2 (22) //!< Bit position for SDMAARM_XTRIG_CONF1_CNF2.
#define BM_SDMAARM_XTRIG_CONF1_CNF2 (0x00400000) //!< Bit mask for SDMAARM_XTRIG_CONF1_CNF2.
//! @brief Get value of SDMAARM_XTRIG_CONF1_CNF2 from a register value.
#define BG_SDMAARM_XTRIG_CONF1_CNF2(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF1_CNF2) >> BP_SDMAARM_XTRIG_CONF1_CNF2)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF1_CNF2.
#define BF_SDMAARM_XTRIG_CONF1_CNF2(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF1_CNF2) & BM_SDMAARM_XTRIG_CONF1_CNF2)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CNF2 field to a new value.
#define BW_SDMAARM_XTRIG_CONF1_CNF2(v) (HW_SDMAARM_XTRIG_CONF1_WR((HW_SDMAARM_XTRIG_CONF1_RD() & ~BM_SDMAARM_XTRIG_CONF1_CNF2) | BF_SDMAARM_XTRIG_CONF1_CNF2(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF1, field NUM3[29:24] (RW)
*
* Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger
* event line number i .
*/
//@{
#define BP_SDMAARM_XTRIG_CONF1_NUM3 (24) //!< Bit position for SDMAARM_XTRIG_CONF1_NUM3.
#define BM_SDMAARM_XTRIG_CONF1_NUM3 (0x3f000000) //!< Bit mask for SDMAARM_XTRIG_CONF1_NUM3.
//! @brief Get value of SDMAARM_XTRIG_CONF1_NUM3 from a register value.
#define BG_SDMAARM_XTRIG_CONF1_NUM3(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF1_NUM3) >> BP_SDMAARM_XTRIG_CONF1_NUM3)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF1_NUM3.
#define BF_SDMAARM_XTRIG_CONF1_NUM3(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF1_NUM3) & BM_SDMAARM_XTRIG_CONF1_NUM3)
#ifndef __LANGUAGE_ASM__
//! @brief Set the NUM3 field to a new value.
#define BW_SDMAARM_XTRIG_CONF1_NUM3(v) (HW_SDMAARM_XTRIG_CONF1_WR((HW_SDMAARM_XTRIG_CONF1_RD() & ~BM_SDMAARM_XTRIG_CONF1_NUM3) | BF_SDMAARM_XTRIG_CONF1_NUM3(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF1, field CNF3[30] (RW)
*
* Configuration of the SDMA event line number i that is connected to the cross-trigger. It
* determines whether the event line pulse is generated by the reception of a DMA request or by the
* starting of a channel script execution.
*
* Values:
* - 0 - channel
* - 1 - DMA request
*/
//@{
#define BP_SDMAARM_XTRIG_CONF1_CNF3 (30) //!< Bit position for SDMAARM_XTRIG_CONF1_CNF3.
#define BM_SDMAARM_XTRIG_CONF1_CNF3 (0x40000000) //!< Bit mask for SDMAARM_XTRIG_CONF1_CNF3.
//! @brief Get value of SDMAARM_XTRIG_CONF1_CNF3 from a register value.
#define BG_SDMAARM_XTRIG_CONF1_CNF3(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF1_CNF3) >> BP_SDMAARM_XTRIG_CONF1_CNF3)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF1_CNF3.
#define BF_SDMAARM_XTRIG_CONF1_CNF3(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF1_CNF3) & BM_SDMAARM_XTRIG_CONF1_CNF3)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CNF3 field to a new value.
#define BW_SDMAARM_XTRIG_CONF1_CNF3(v) (HW_SDMAARM_XTRIG_CONF1_WR((HW_SDMAARM_XTRIG_CONF1_RD() & ~BM_SDMAARM_XTRIG_CONF1_CNF3) | BF_SDMAARM_XTRIG_CONF1_CNF3(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_XTRIG_CONF2 - Cross-Trigger Events Configuration Register 2
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_XTRIG_CONF2 - Cross-Trigger Events Configuration Register 2 (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_xtrig_conf2
{
reg32_t U;
struct _hw_sdmaarm_xtrig_conf2_bitfields
{
unsigned NUM4 : 6; //!< [5:0] Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger event line number i .
unsigned CNF4 : 1; //!< [6] Configuration of the SDMA event line number i that is connected to the cross-trigger.
unsigned RESERVED0 : 1; //!< [7] Reserved
unsigned NUM5 : 6; //!< [13:8] Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger event line number i .
unsigned CNF5 : 1; //!< [14] Configuration of the SDMA event line number i that is connected to the cross-trigger.
unsigned RESERVED1 : 1; //!< [15] Reserved
unsigned NUM6 : 6; //!< [21:16] Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger event line number i .
unsigned CNF6 : 1; //!< [22] Configuration of the SDMA event line number i that is connected to the cross-trigger.
unsigned RESERVED2 : 1; //!< [23] Reserved
unsigned NUM7 : 6; //!< [29:24] Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger event line number i .
unsigned CNF7 : 1; //!< [30] Configuration of the SDMA event line number i that is connected to the cross-trigger.
unsigned RESERVED3 : 1; //!< [31] Reserved
} B;
} hw_sdmaarm_xtrig_conf2_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_XTRIG_CONF2 register
*/
//@{
#define HW_SDMAARM_XTRIG_CONF2_ADDR (REGS_SDMAARM_BASE + 0x74)
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_XTRIG_CONF2 (*(volatile hw_sdmaarm_xtrig_conf2_t *) HW_SDMAARM_XTRIG_CONF2_ADDR)
#define HW_SDMAARM_XTRIG_CONF2_RD() (HW_SDMAARM_XTRIG_CONF2.U)
#define HW_SDMAARM_XTRIG_CONF2_WR(v) (HW_SDMAARM_XTRIG_CONF2.U = (v))
#define HW_SDMAARM_XTRIG_CONF2_SET(v) (HW_SDMAARM_XTRIG_CONF2_WR(HW_SDMAARM_XTRIG_CONF2_RD() | (v)))
#define HW_SDMAARM_XTRIG_CONF2_CLR(v) (HW_SDMAARM_XTRIG_CONF2_WR(HW_SDMAARM_XTRIG_CONF2_RD() & ~(v)))
#define HW_SDMAARM_XTRIG_CONF2_TOG(v) (HW_SDMAARM_XTRIG_CONF2_WR(HW_SDMAARM_XTRIG_CONF2_RD() ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_XTRIG_CONF2 bitfields
*/
/*! @name Register SDMAARM_XTRIG_CONF2, field NUM4[5:0] (RW)
*
* Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger
* event line number i .
*/
//@{
#define BP_SDMAARM_XTRIG_CONF2_NUM4 (0) //!< Bit position for SDMAARM_XTRIG_CONF2_NUM4.
#define BM_SDMAARM_XTRIG_CONF2_NUM4 (0x0000003f) //!< Bit mask for SDMAARM_XTRIG_CONF2_NUM4.
//! @brief Get value of SDMAARM_XTRIG_CONF2_NUM4 from a register value.
#define BG_SDMAARM_XTRIG_CONF2_NUM4(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF2_NUM4) >> BP_SDMAARM_XTRIG_CONF2_NUM4)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF2_NUM4.
#define BF_SDMAARM_XTRIG_CONF2_NUM4(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF2_NUM4) & BM_SDMAARM_XTRIG_CONF2_NUM4)
#ifndef __LANGUAGE_ASM__
//! @brief Set the NUM4 field to a new value.
#define BW_SDMAARM_XTRIG_CONF2_NUM4(v) (HW_SDMAARM_XTRIG_CONF2_WR((HW_SDMAARM_XTRIG_CONF2_RD() & ~BM_SDMAARM_XTRIG_CONF2_NUM4) | BF_SDMAARM_XTRIG_CONF2_NUM4(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF2, field CNF4[6] (RW)
*
* Configuration of the SDMA event line number i that is connected to the cross-trigger. It
* determines whether the event line pulse is generated by receiving a DMA request or by starting a
* channel script execution.
*
* Values:
* - 0 - channel
* - 1 - DMA request
*/
//@{
#define BP_SDMAARM_XTRIG_CONF2_CNF4 (6) //!< Bit position for SDMAARM_XTRIG_CONF2_CNF4.
#define BM_SDMAARM_XTRIG_CONF2_CNF4 (0x00000040) //!< Bit mask for SDMAARM_XTRIG_CONF2_CNF4.
//! @brief Get value of SDMAARM_XTRIG_CONF2_CNF4 from a register value.
#define BG_SDMAARM_XTRIG_CONF2_CNF4(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF2_CNF4) >> BP_SDMAARM_XTRIG_CONF2_CNF4)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF2_CNF4.
#define BF_SDMAARM_XTRIG_CONF2_CNF4(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF2_CNF4) & BM_SDMAARM_XTRIG_CONF2_CNF4)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CNF4 field to a new value.
#define BW_SDMAARM_XTRIG_CONF2_CNF4(v) (HW_SDMAARM_XTRIG_CONF2_WR((HW_SDMAARM_XTRIG_CONF2_RD() & ~BM_SDMAARM_XTRIG_CONF2_CNF4) | BF_SDMAARM_XTRIG_CONF2_CNF4(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF2, field NUM5[13:8] (RW)
*
* Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger
* event line number i .
*/
//@{
#define BP_SDMAARM_XTRIG_CONF2_NUM5 (8) //!< Bit position for SDMAARM_XTRIG_CONF2_NUM5.
#define BM_SDMAARM_XTRIG_CONF2_NUM5 (0x00003f00) //!< Bit mask for SDMAARM_XTRIG_CONF2_NUM5.
//! @brief Get value of SDMAARM_XTRIG_CONF2_NUM5 from a register value.
#define BG_SDMAARM_XTRIG_CONF2_NUM5(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF2_NUM5) >> BP_SDMAARM_XTRIG_CONF2_NUM5)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF2_NUM5.
#define BF_SDMAARM_XTRIG_CONF2_NUM5(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF2_NUM5) & BM_SDMAARM_XTRIG_CONF2_NUM5)
#ifndef __LANGUAGE_ASM__
//! @brief Set the NUM5 field to a new value.
#define BW_SDMAARM_XTRIG_CONF2_NUM5(v) (HW_SDMAARM_XTRIG_CONF2_WR((HW_SDMAARM_XTRIG_CONF2_RD() & ~BM_SDMAARM_XTRIG_CONF2_NUM5) | BF_SDMAARM_XTRIG_CONF2_NUM5(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF2, field CNF5[14] (RW)
*
* Configuration of the SDMA event line number i that is connected to the cross-trigger. It
* determines whether the event line pulse is generated by receiving a DMA request or by starting a
* channel script execution
*
* Values:
* - 0 - channel
* - 1 - DMA request
*/
//@{
#define BP_SDMAARM_XTRIG_CONF2_CNF5 (14) //!< Bit position for SDMAARM_XTRIG_CONF2_CNF5.
#define BM_SDMAARM_XTRIG_CONF2_CNF5 (0x00004000) //!< Bit mask for SDMAARM_XTRIG_CONF2_CNF5.
//! @brief Get value of SDMAARM_XTRIG_CONF2_CNF5 from a register value.
#define BG_SDMAARM_XTRIG_CONF2_CNF5(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF2_CNF5) >> BP_SDMAARM_XTRIG_CONF2_CNF5)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF2_CNF5.
#define BF_SDMAARM_XTRIG_CONF2_CNF5(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF2_CNF5) & BM_SDMAARM_XTRIG_CONF2_CNF5)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CNF5 field to a new value.
#define BW_SDMAARM_XTRIG_CONF2_CNF5(v) (HW_SDMAARM_XTRIG_CONF2_WR((HW_SDMAARM_XTRIG_CONF2_RD() & ~BM_SDMAARM_XTRIG_CONF2_CNF5) | BF_SDMAARM_XTRIG_CONF2_CNF5(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF2, field NUM6[21:16] (RW)
*
* Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger
* event line number i .
*/
//@{
#define BP_SDMAARM_XTRIG_CONF2_NUM6 (16) //!< Bit position for SDMAARM_XTRIG_CONF2_NUM6.
#define BM_SDMAARM_XTRIG_CONF2_NUM6 (0x003f0000) //!< Bit mask for SDMAARM_XTRIG_CONF2_NUM6.
//! @brief Get value of SDMAARM_XTRIG_CONF2_NUM6 from a register value.
#define BG_SDMAARM_XTRIG_CONF2_NUM6(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF2_NUM6) >> BP_SDMAARM_XTRIG_CONF2_NUM6)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF2_NUM6.
#define BF_SDMAARM_XTRIG_CONF2_NUM6(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF2_NUM6) & BM_SDMAARM_XTRIG_CONF2_NUM6)
#ifndef __LANGUAGE_ASM__
//! @brief Set the NUM6 field to a new value.
#define BW_SDMAARM_XTRIG_CONF2_NUM6(v) (HW_SDMAARM_XTRIG_CONF2_WR((HW_SDMAARM_XTRIG_CONF2_RD() & ~BM_SDMAARM_XTRIG_CONF2_NUM6) | BF_SDMAARM_XTRIG_CONF2_NUM6(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF2, field CNF6[22] (RW)
*
* Configuration of the SDMA event line number i that is connected to the cross-trigger. It
* determines whether the event line pulse is generated by receiving a DMA request or by starting a
* channel script execution.
*
* Values:
* - 0 - channel
* - 1 - DMA request
*/
//@{
#define BP_SDMAARM_XTRIG_CONF2_CNF6 (22) //!< Bit position for SDMAARM_XTRIG_CONF2_CNF6.
#define BM_SDMAARM_XTRIG_CONF2_CNF6 (0x00400000) //!< Bit mask for SDMAARM_XTRIG_CONF2_CNF6.
//! @brief Get value of SDMAARM_XTRIG_CONF2_CNF6 from a register value.
#define BG_SDMAARM_XTRIG_CONF2_CNF6(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF2_CNF6) >> BP_SDMAARM_XTRIG_CONF2_CNF6)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF2_CNF6.
#define BF_SDMAARM_XTRIG_CONF2_CNF6(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF2_CNF6) & BM_SDMAARM_XTRIG_CONF2_CNF6)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CNF6 field to a new value.
#define BW_SDMAARM_XTRIG_CONF2_CNF6(v) (HW_SDMAARM_XTRIG_CONF2_WR((HW_SDMAARM_XTRIG_CONF2_RD() & ~BM_SDMAARM_XTRIG_CONF2_CNF6) | BF_SDMAARM_XTRIG_CONF2_CNF6(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF2, field NUM7[29:24] (RW)
*
* Contains the number of the DMA request or channel that triggers the pulse on the cross-trigger
* event line number i .
*/
//@{
#define BP_SDMAARM_XTRIG_CONF2_NUM7 (24) //!< Bit position for SDMAARM_XTRIG_CONF2_NUM7.
#define BM_SDMAARM_XTRIG_CONF2_NUM7 (0x3f000000) //!< Bit mask for SDMAARM_XTRIG_CONF2_NUM7.
//! @brief Get value of SDMAARM_XTRIG_CONF2_NUM7 from a register value.
#define BG_SDMAARM_XTRIG_CONF2_NUM7(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF2_NUM7) >> BP_SDMAARM_XTRIG_CONF2_NUM7)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF2_NUM7.
#define BF_SDMAARM_XTRIG_CONF2_NUM7(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF2_NUM7) & BM_SDMAARM_XTRIG_CONF2_NUM7)
#ifndef __LANGUAGE_ASM__
//! @brief Set the NUM7 field to a new value.
#define BW_SDMAARM_XTRIG_CONF2_NUM7(v) (HW_SDMAARM_XTRIG_CONF2_WR((HW_SDMAARM_XTRIG_CONF2_RD() & ~BM_SDMAARM_XTRIG_CONF2_NUM7) | BF_SDMAARM_XTRIG_CONF2_NUM7(v)))
#endif
//@}
/*! @name Register SDMAARM_XTRIG_CONF2, field CNF7[30] (RW)
*
* Configuration of the SDMA event line number i that is connected to the cross-trigger. It
* determines whether the event line pulse is generated by receiving a DMA request or by starting a
* channel script execution.
*
* Values:
* - 0 - channel
* - 1 - DMA request
*/
//@{
#define BP_SDMAARM_XTRIG_CONF2_CNF7 (30) //!< Bit position for SDMAARM_XTRIG_CONF2_CNF7.
#define BM_SDMAARM_XTRIG_CONF2_CNF7 (0x40000000) //!< Bit mask for SDMAARM_XTRIG_CONF2_CNF7.
//! @brief Get value of SDMAARM_XTRIG_CONF2_CNF7 from a register value.
#define BG_SDMAARM_XTRIG_CONF2_CNF7(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_XTRIG_CONF2_CNF7) >> BP_SDMAARM_XTRIG_CONF2_CNF7)
//! @brief Format value for bitfield SDMAARM_XTRIG_CONF2_CNF7.
#define BF_SDMAARM_XTRIG_CONF2_CNF7(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_XTRIG_CONF2_CNF7) & BM_SDMAARM_XTRIG_CONF2_CNF7)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CNF7 field to a new value.
#define BW_SDMAARM_XTRIG_CONF2_CNF7(v) (HW_SDMAARM_XTRIG_CONF2_WR((HW_SDMAARM_XTRIG_CONF2_RD() & ~BM_SDMAARM_XTRIG_CONF2_CNF7) | BF_SDMAARM_XTRIG_CONF2_CNF7(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_SDMA_CHNPRIn - Channel Priority Registers
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_SDMA_CHNPRIn - Channel Priority Registers (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_sdma_chnprin
{
reg32_t U;
struct _hw_sdmaarm_sdma_chnprin_bitfields
{
unsigned CHNPRIN : 3; //!< [2:0] This contains the priority of channel number n .
unsigned RESERVED0 : 29; //!< [31:3] Reserved
} B;
} hw_sdmaarm_sdma_chnprin_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_SDMA_CHNPRIn register
*/
//@{
//! @brief Number of instances of the SDMAARM_SDMA_CHNPRIn register.
#define HW_SDMAARM_SDMA_CHNPRIn_COUNT (32)
#define HW_SDMAARM_SDMA_CHNPRIn_ADDR(n) (REGS_SDMAARM_BASE + 0x100 + (0x4 * (n)))
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_SDMA_CHNPRIn(n) (*(volatile hw_sdmaarm_sdma_chnprin_t *) HW_SDMAARM_SDMA_CHNPRIn_ADDR(n))
#define HW_SDMAARM_SDMA_CHNPRIn_RD(n) (HW_SDMAARM_SDMA_CHNPRIn(n).U)
#define HW_SDMAARM_SDMA_CHNPRIn_WR(n, v) (HW_SDMAARM_SDMA_CHNPRIn(n).U = (v))
#define HW_SDMAARM_SDMA_CHNPRIn_SET(n, v) (HW_SDMAARM_SDMA_CHNPRIn_WR(n, HW_SDMAARM_SDMA_CHNPRIn_RD(n) | (v)))
#define HW_SDMAARM_SDMA_CHNPRIn_CLR(n, v) (HW_SDMAARM_SDMA_CHNPRIn_WR(n, HW_SDMAARM_SDMA_CHNPRIn_RD(n) & ~(v)))
#define HW_SDMAARM_SDMA_CHNPRIn_TOG(n, v) (HW_SDMAARM_SDMA_CHNPRIn_WR(n, HW_SDMAARM_SDMA_CHNPRIn_RD(n) ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_SDMA_CHNPRIn bitfields
*/
/*! @name Register SDMAARM_SDMA_CHNPRIn, field CHNPRIN[2:0] (RW)
*
* This contains the priority of channel number n . Useful values are between 1 and 7; 0 is reserved
* by the SDMA hardware to determine when there is no pending channel. Reset value is 0, which
* prevents the channels from starting.
*/
//@{
#define BP_SDMAARM_SDMA_CHNPRIn_CHNPRIN (0) //!< Bit position for SDMAARM_SDMA_CHNPRIn_CHNPRIN.
#define BM_SDMAARM_SDMA_CHNPRIn_CHNPRIN (0x00000007) //!< Bit mask for SDMAARM_SDMA_CHNPRIn_CHNPRIN.
//! @brief Get value of SDMAARM_SDMA_CHNPRIn_CHNPRIN from a register value.
#define BG_SDMAARM_SDMA_CHNPRIn_CHNPRIN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_SDMA_CHNPRIn_CHNPRIN) >> BP_SDMAARM_SDMA_CHNPRIn_CHNPRIN)
//! @brief Format value for bitfield SDMAARM_SDMA_CHNPRIn_CHNPRIN.
#define BF_SDMAARM_SDMA_CHNPRIn_CHNPRIN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_SDMA_CHNPRIn_CHNPRIN) & BM_SDMAARM_SDMA_CHNPRIn_CHNPRIN)
#ifndef __LANGUAGE_ASM__
//! @brief Set the CHNPRIN field to a new value.
#define BW_SDMAARM_SDMA_CHNPRIn_CHNPRIN(n, v) (HW_SDMAARM_SDMA_CHNPRIn_WR(n, (HW_SDMAARM_SDMA_CHNPRIn_RD(n) & ~BM_SDMAARM_SDMA_CHNPRIn_CHNPRIN) | BF_SDMAARM_SDMA_CHNPRIn_CHNPRIN(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// HW_SDMAARM_CHNENBLn - Channel Enable RAM
//-------------------------------------------------------------------------------------------
#ifndef __LANGUAGE_ASM__
/*!
* @brief HW_SDMAARM_CHNENBLn - Channel Enable RAM (RW)
*
* Reset value: 0x00000000
*/
typedef union _hw_sdmaarm_chnenbln
{
reg32_t U;
struct _hw_sdmaarm_chnenbln_bitfields
{
unsigned ENBLN : 32; //!< [31:0] This 32-bit value selects the channels that are triggered by the DMA request number n .
} B;
} hw_sdmaarm_chnenbln_t;
#endif
/*!
* @name Constants and macros for entire SDMAARM_CHNENBLn register
*/
//@{
//! @brief Number of instances of the SDMAARM_CHNENBLn register.
#define HW_SDMAARM_CHNENBLn_COUNT (48)
#define HW_SDMAARM_CHNENBLn_ADDR(n) (REGS_SDMAARM_BASE + 0x200 + (0x4 * (n)))
#ifndef __LANGUAGE_ASM__
#define HW_SDMAARM_CHNENBLn(n) (*(volatile hw_sdmaarm_chnenbln_t *) HW_SDMAARM_CHNENBLn_ADDR(n))
#define HW_SDMAARM_CHNENBLn_RD(n) (HW_SDMAARM_CHNENBLn(n).U)
#define HW_SDMAARM_CHNENBLn_WR(n, v) (HW_SDMAARM_CHNENBLn(n).U = (v))
#define HW_SDMAARM_CHNENBLn_SET(n, v) (HW_SDMAARM_CHNENBLn_WR(n, HW_SDMAARM_CHNENBLn_RD(n) | (v)))
#define HW_SDMAARM_CHNENBLn_CLR(n, v) (HW_SDMAARM_CHNENBLn_WR(n, HW_SDMAARM_CHNENBLn_RD(n) & ~(v)))
#define HW_SDMAARM_CHNENBLn_TOG(n, v) (HW_SDMAARM_CHNENBLn_WR(n, HW_SDMAARM_CHNENBLn_RD(n) ^ (v)))
#endif
//@}
/*
* constants & macros for individual SDMAARM_CHNENBLn bitfields
*/
/*! @name Register SDMAARM_CHNENBLn, field ENBLN[31:0] (RW)
*
* This 32-bit value selects the channels that are triggered by the DMA request number n . If
* ENBLn[i] is set to 1, bit EP[i] will be set when the DMA request n is received. These 48 32-bit
* registers are physically located in a RAM, with no known reset value. It is thus essential for
* the ARM platform to program them before any DMA request is triggered to the SDMA, otherwise an
* unpredictable combination of channels may be started.
*/
//@{
#define BP_SDMAARM_CHNENBLn_ENBLN (0) //!< Bit position for SDMAARM_CHNENBLn_ENBLN.
#define BM_SDMAARM_CHNENBLn_ENBLN (0xffffffff) //!< Bit mask for SDMAARM_CHNENBLn_ENBLN.
//! @brief Get value of SDMAARM_CHNENBLn_ENBLN from a register value.
#define BG_SDMAARM_CHNENBLn_ENBLN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SDMAARM_CHNENBLn_ENBLN) >> BP_SDMAARM_CHNENBLn_ENBLN)
//! @brief Format value for bitfield SDMAARM_CHNENBLn_ENBLN.
#define BF_SDMAARM_CHNENBLn_ENBLN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SDMAARM_CHNENBLn_ENBLN) & BM_SDMAARM_CHNENBLn_ENBLN)
#ifndef __LANGUAGE_ASM__
//! @brief Set the ENBLN field to a new value.
#define BW_SDMAARM_CHNENBLn_ENBLN(n, v) (HW_SDMAARM_CHNENBLn_WR(n, (HW_SDMAARM_CHNENBLn_RD(n) & ~BM_SDMAARM_CHNENBLn_ENBLN) | BF_SDMAARM_CHNENBLn_ENBLN(v)))
#endif
//@}
//-------------------------------------------------------------------------------------------
// hw_sdmaarm_t - module struct
//-------------------------------------------------------------------------------------------
/*!
* @brief All SDMAARM module registers.
*/
#ifndef __LANGUAGE_ASM__
#pragma pack(1)
typedef struct _hw_sdmaarm
{
volatile hw_sdmaarm_mc0ptr_t MC0PTR; //!< ARM platform Channel 0 Pointer
volatile hw_sdmaarm_intr_t INTR; //!< Channel Interrupts
volatile hw_sdmaarm_stop_stat_t STOP_STAT; //!< Channel Stop/Channel Status
volatile hw_sdmaarm_hstart_t HSTART; //!< Channel Start
volatile hw_sdmaarm_evtovr_t EVTOVR; //!< Channel Event Override
volatile hw_sdmaarm_dspovr_t DSPOVR; //!< Channel BP Override
volatile hw_sdmaarm_hostovr_t HOSTOVR; //!< Channel ARM platform Override
volatile hw_sdmaarm_evtpend_t EVTPEND; //!< Channel Event Pending
reg32_t _reserved0;
volatile hw_sdmaarm_reset_t RESET; //!< Reset Register
volatile hw_sdmaarm_evterr_t EVTERR; //!< DMA Request Error Register
volatile hw_sdmaarm_intrmask_t INTRMASK; //!< Channel ARM platform Interrupt Mask
volatile hw_sdmaarm_psw_t PSW; //!< Schedule Status
volatile hw_sdmaarm_evterrdbg_t EVTERRDBG; //!< DMA Request Error Register
volatile hw_sdmaarm_config_t CONFIG; //!< Configuration Register
volatile hw_sdmaarm_sdma_lock_t SDMA_LOCK; //!< SDMA LOCK
volatile hw_sdmaarm_once_enb_t ONCE_ENB; //!< OnCE Enable
volatile hw_sdmaarm_once_data_t ONCE_DATA; //!< OnCE Data Register
volatile hw_sdmaarm_once_instr_t ONCE_INSTR; //!< OnCE Instruction Register
volatile hw_sdmaarm_once_stat_t ONCE_STAT; //!< OnCE Status Register
volatile hw_sdmaarm_once_cmd_t ONCE_CMD; //!< OnCE Command Register
reg32_t _reserved1;
volatile hw_sdmaarm_illinstaddr_t ILLINSTADDR; //!< Illegal Instruction Trap Address
volatile hw_sdmaarm_chn0addr_t CHN0ADDR; //!< Channel 0 Boot Address
volatile hw_sdmaarm_evt_mirror_t EVT_MIRROR; //!< DMA Requests
volatile hw_sdmaarm_evt_mirror2_t EVT_MIRROR2; //!< DMA Requests 2
reg32_t _reserved2[2];
volatile hw_sdmaarm_xtrig_conf1_t XTRIG_CONF1; //!< Cross-Trigger Events Configuration Register 1
volatile hw_sdmaarm_xtrig_conf2_t XTRIG_CONF2; //!< Cross-Trigger Events Configuration Register 2
reg32_t _reserved3[34];
volatile hw_sdmaarm_sdma_chnprin_t SDMA_CHNPRIn[32]; //!< Channel Priority Registers
reg32_t _reserved4[32];
volatile hw_sdmaarm_chnenbln_t CHNENBLn[48]; //!< Channel Enable RAM
} hw_sdmaarm_t;
#pragma pack()
//! @brief Macro to access all SDMAARM registers.
//! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct,
//! use the '&' operator, like <code>&HW_SDMAARM</code>.
#define HW_SDMAARM (*(hw_sdmaarm_t *) REGS_SDMAARM_BASE)
#endif
#endif // __HW_SDMAARM_REGISTERS_H__
// v18/121106/1.2.2
// EOF
| 46,780 |
1,428 | <gh_stars>1000+
class A
{
public static void main(String arg[])
{
System.out.println("Class A");
}
}
class B
{
void display()
{System.out.println("HELOO B");
}
}
class C
{
void display()
{System.out.println("c class");
System.out.println("HELOO C");
}
}
| 105 |
823 | /*
* $Id$
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor <NAME>
* Copyright (c) 2010-2011, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <limits.h>
#include "dec_clientmsg_handler.h"
#include "ihdrbox_manager.h"
#include "jpipstream_manager.h"
#include "jp2k_encoder.h"
#include "opj_inttypes.h"
void handle_JPIPstreamMSG(SOCKET connected_socket, cachelist_param_t *cachelist,
Byte_t **jpipstream, OPJ_SIZE_T *streamlen, msgqueue_param_t *msgqueue)
{
Byte_t *newjpipstream;
OPJ_SIZE_T newstreamlen = 0;
cache_param_t *cache;
char *target, *tid, *cid;
metadatalist_param_t *metadatalist;
newjpipstream = receive_JPIPstream(connected_socket, &target, &tid, &cid,
&newstreamlen);
fprintf(stderr, "newjpipstream length: %" PRIu64 "\n", newstreamlen);
parse_JPIPstream(newjpipstream, newstreamlen, (OPJ_OFF_T)*streamlen, msgqueue);
*jpipstream = update_JPIPstream(newjpipstream, newstreamlen, *jpipstream,
streamlen);
opj_free(newjpipstream);
metadatalist = gene_metadatalist();
parse_metamsg(msgqueue, *jpipstream, *streamlen, metadatalist);
assert(msgqueue->last);
assert(msgqueue->last->csn < INT_MAX);
/* cid registration*/
if (target != NULL) {
if ((cache = search_cache(target, cachelist))) {
if (tid != NULL) {
update_cachetid(tid, cache);
}
if (cid != NULL) {
add_cachecid(cid, cache);
}
} else {
cache = gene_cache(target, (int)msgqueue->last->csn, tid, cid);
insert_cache_into_list(cache, cachelist);
}
} else {
cache = search_cacheBycsn((int)msgqueue->last->csn, cachelist);
}
if (cache->metadatalist) {
delete_metadatalist(&cache->metadatalist);
}
cache->metadatalist = metadatalist;
if (target) {
opj_free(target);
}
if (tid) {
opj_free(tid);
}
if (cid) {
opj_free(cid);
}
response_signal(connected_socket, OPJ_TRUE);
}
void handle_PNMreqMSG(SOCKET connected_socket, Byte_t *jpipstream,
msgqueue_param_t *msgqueue, cachelist_param_t *cachelist)
{
Byte_t *pnmstream;
ihdrbox_param_t *ihdrbox;
char *CIDorTID, tmp[10];
cache_param_t *cache;
int fw, fh;
int maxval;
CIDorTID = receive_string(connected_socket);
if (!(cache = search_cacheBycid(CIDorTID, cachelist)))
if (!(cache = search_cacheBytid(CIDorTID, cachelist))) {
opj_free(CIDorTID);
return;
}
opj_free(CIDorTID);
receive_line(connected_socket, tmp);
fw = atoi(tmp);
receive_line(connected_socket, tmp);
fh = atoi(tmp);
ihdrbox = NULL;
assert(cache->csn >= 0);
pnmstream = jpipstream_to_pnm(jpipstream, msgqueue, (Byte8_t)cache->csn, fw, fh,
&ihdrbox);
maxval = ihdrbox->bpc > 8 ? 255 : (1 << ihdrbox->bpc) - 1;
send_PNMstream(connected_socket, pnmstream, ihdrbox->width, ihdrbox->height,
ihdrbox->nc, (Byte_t)maxval);
opj_free(ihdrbox);
opj_free(pnmstream);
}
void handle_XMLreqMSG(SOCKET connected_socket, Byte_t *jpipstream,
cachelist_param_t *cachelist)
{
char *cid;
cache_param_t *cache;
boxcontents_param_t *boxcontents;
Byte_t *xmlstream;
cid = receive_string(connected_socket);
if (!(cache = search_cacheBycid(cid, cachelist))) {
opj_free(cid);
return;
}
opj_free(cid);
boxcontents = cache->metadatalist->last->boxcontents;
xmlstream = (Byte_t *)opj_malloc(boxcontents->length);
memcpy(xmlstream, jpipstream + boxcontents->offset, boxcontents->length);
send_XMLstream(connected_socket, xmlstream, boxcontents->length);
opj_free(xmlstream);
}
void handle_TIDreqMSG(SOCKET connected_socket, cachelist_param_t *cachelist)
{
char *target, *tid = NULL;
cache_param_t *cache;
OPJ_SIZE_T tidlen = 0;
target = receive_string(connected_socket);
cache = search_cache(target, cachelist);
opj_free(target);
if (cache) {
tid = cache->tid;
tidlen = strlen(tid);
}
send_TIDstream(connected_socket, tid, tidlen);
}
void handle_CIDreqMSG(SOCKET connected_socket, cachelist_param_t *cachelist)
{
char *target, *cid = NULL;
cache_param_t *cache;
OPJ_SIZE_T cidlen = 0;
target = receive_string(connected_socket);
cache = search_cache(target, cachelist);
opj_free(target);
if (cache) {
if (cache->numOfcid > 0) {
cid = cache->cid[ cache->numOfcid - 1];
cidlen = strlen(cid);
}
}
send_CIDstream(connected_socket, cid, cidlen);
}
void handle_dstCIDreqMSG(SOCKET connected_socket, cachelist_param_t *cachelist)
{
char *cid;
cid = receive_string(connected_socket);
remove_cachecid(cid, cachelist);
response_signal(connected_socket, OPJ_TRUE);
opj_free(cid);
}
void handle_SIZreqMSG(SOCKET connected_socket, Byte_t *jpipstream,
msgqueue_param_t *msgqueue, cachelist_param_t *cachelist)
{
char *tid, *cid;
cache_param_t *cache;
Byte4_t width, height;
tid = receive_string(connected_socket);
cid = receive_string(connected_socket);
cache = NULL;
if (tid[0] != '0') {
cache = search_cacheBytid(tid, cachelist);
}
if (!cache && cid[0] != '0') {
cache = search_cacheBycid(cid, cachelist);
}
opj_free(tid);
opj_free(cid);
width = height = 0;
if (cache) {
assert(cache->csn >= 0);
if (!cache->ihdrbox) {
cache->ihdrbox = get_SIZ_from_jpipstream(jpipstream, msgqueue,
(Byte8_t)cache->csn);
}
width = cache->ihdrbox->width;
height = cache->ihdrbox->height;
}
send_SIZstream(connected_socket, width, height);
}
void handle_JP2saveMSG(SOCKET connected_socket, cachelist_param_t *cachelist,
msgqueue_param_t *msgqueue, Byte_t *jpipstream)
{
char *cid;
cache_param_t *cache;
Byte_t *jp2stream;
Byte8_t jp2len;
cid = receive_string(connected_socket);
if (!(cache = search_cacheBycid(cid, cachelist))) {
opj_free(cid);
return;
}
opj_free(cid);
assert(cache->csn >= 0);
jp2stream = recons_jp2(msgqueue, jpipstream, (Byte8_t)cache->csn, &jp2len);
if (jp2stream) {
save_codestream(jp2stream, jp2len, "jp2");
opj_free(jp2stream);
}
}
| 3,620 |
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.j2ee.deployment.impl.bridge;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.event.ChangeListener;
import org.netbeans.api.server.ServerInstance;
import org.netbeans.modules.j2ee.deployment.devmodules.spi.InstanceListener;
import org.netbeans.modules.j2ee.deployment.impl.Server;
import org.netbeans.modules.j2ee.deployment.impl.ServerRegistry;
import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
import org.openide.util.ChangeSupport;
/**
*
* @author <NAME>
*/
public class BridgingServerInstanceProvider implements org.netbeans.spi.server.ServerInstanceProvider, InstanceListener {
private final ChangeSupport changeSupport = new ChangeSupport(this);
private final Server server;
private Map<org.netbeans.modules.j2ee.deployment.impl.ServerInstance, BridgingServerInstance> instances =
new HashMap<org.netbeans.modules.j2ee.deployment.impl.ServerInstance, BridgingServerInstance>();
public BridgingServerInstanceProvider(Server server) {
assert server != null : "Server must not be null"; // NOI18N
this.server = server;
}
public final void addInstanceListener() {
ServerRegistry.getInstance().addInstanceListener(this);
}
public final void removeInstanceListener() {
ServerRegistry.getInstance().removeInstanceListener(this);
}
public void addChangeListener(ChangeListener listener) {
changeSupport.addChangeListener(listener);
}
public void removeChangeListener(ChangeListener listener) {
changeSupport.removeChangeListener(listener);
}
public void changeDefaultInstance(String oldServerInstanceID, String newServerInstanceID) {
}
public void instanceAdded(String serverInstanceID) {
if (server.handlesUri(serverInstanceID)) {
changeSupport.fireChange();
}
}
public void instanceRemoved(String serverInstanceID) {
InstanceProperties props = InstanceProperties.getInstanceProperties(serverInstanceID);
if (server.handlesUri(serverInstanceID) && (props == null || isRegisteredWithUI(props))) {
changeSupport.fireChange();
}
}
// TODO we could slightly optimize this by cacheing
public synchronized List<ServerInstance> getInstances() {
refreshCache();
List<ServerInstance> instancesList = new ArrayList<ServerInstance>(instances.size());
for (BridgingServerInstance instance : instances.values()) {
instancesList.add(instance.getCommonInstance());
}
return instancesList;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BridgingServerInstanceProvider other = (BridgingServerInstanceProvider) obj;
if (this.server != other.server && (this.server == null || !this.server.equals(other.server))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 67 * hash + (this.server != null ? this.server.hashCode() : 0);
return hash;
}
public synchronized ServerInstance getBridge(org.netbeans.modules.j2ee.deployment.impl.ServerInstance instance) {
refreshCache();
BridgingServerInstance bridgingInstance = instances.get(instance);
return bridgingInstance == null ? null : bridgingInstance.getCommonInstance();
}
private synchronized void refreshCache() {
List<org.netbeans.modules.j2ee.deployment.impl.ServerInstance> toRemove = new ArrayList<org.netbeans.modules.j2ee.deployment.impl.ServerInstance>(instances.keySet());
for (org.netbeans.modules.j2ee.deployment.impl.ServerInstance instance : ServerRegistry.getInstance().getServerInstances()) {
if (instance.getServer().equals(server) && isRegisteredWithUI(instance.getInstanceProperties())) {
if (!instances.containsKey(instance)) {
instances.put(instance, BridgingServerInstance.createInstance(instance));
} else {
toRemove.remove(instance);
}
}
}
instances.keySet().removeAll(toRemove);
}
private boolean isRegisteredWithUI(InstanceProperties props) {
String withoutUI = props.getProperty(InstanceProperties.REGISTERED_WITHOUT_UI);
if (withoutUI == null) {
return true;
}
return !Boolean.valueOf(withoutUI);
}
}
| 1,922 |
3,603 | /*
* 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 io.trino.sql.planner.iterative.rule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.trino.sql.planner.PartitioningScheme;
import io.trino.sql.planner.Symbol;
import io.trino.sql.planner.plan.ExchangeNode;
import io.trino.sql.planner.plan.PlanNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static io.trino.sql.planner.plan.Patterns.exchange;
/**
* This rule restricts the outputs of ExchangeNode based on which
* ExchangeNode's output symbols are either referenced by the
* parent node or used for partitioning, ordering or as a hash
* symbol by the ExchangeNode.
* <p>
* For each symbol removed from the output symbols list, the corresponding
* input symbols are removed from ExchangeNode's inputs lists.
* <p>
* Transforms:
* <pre>
* - Project (o1)
* - Exchange:
* outputs [o1, o2, o3, h]
* partitioning by (o2)
* hash h
* inputs [[a1, a2, a3, h1], [b1, b2, b3, h2]]
* - source [a1, a2, a3, h1]
* - source [b1, b2, b3, h2]
* </pre>
* Into:
* <pre>
* - Project (o1)
* - Exchange:
* outputs [o1, o2, h]
* partitioning by (o2)
* hash h
* inputs [[a1, a2, h1], [b1, b2, h2]]
* - source [a1, a2, a3, h1]
* - source [b1, b2, b3, h2]
* </pre>
*/
public class PruneExchangeColumns
extends ProjectOffPushDownRule<ExchangeNode>
{
public PruneExchangeColumns()
{
super(exchange());
}
@Override
protected Optional<PlanNode> pushDownProjectOff(Context context, ExchangeNode exchangeNode, Set<Symbol> referencedOutputs)
{
// Extract output symbols referenced by parent node or used for partitioning, ordering or as a hash symbol of the Exchange
ImmutableSet.Builder<Symbol> builder = ImmutableSet.builder();
builder.addAll(referencedOutputs);
builder.addAll(exchangeNode.getPartitioningScheme().getPartitioning().getColumns());
exchangeNode.getPartitioningScheme().getHashColumn().ifPresent(builder::add);
exchangeNode.getOrderingScheme().ifPresent(orderingScheme -> builder.addAll(orderingScheme.getOrderBy()));
Set<Symbol> outputsToRetain = builder.build();
if (outputsToRetain.size() == exchangeNode.getOutputSymbols().size()) {
return Optional.empty();
}
ImmutableList.Builder<Symbol> newOutputs = ImmutableList.builder();
List<List<Symbol>> newInputs = new ArrayList<>(exchangeNode.getInputs().size());
for (int i = 0; i < exchangeNode.getInputs().size(); i++) {
newInputs.add(new ArrayList<>());
}
// Retain used symbols from output list and corresponding symbols from all input lists
for (int i = 0; i < exchangeNode.getOutputSymbols().size(); i++) {
Symbol output = exchangeNode.getOutputSymbols().get(i);
if (outputsToRetain.contains(output)) {
newOutputs.add(output);
for (int source = 0; source < exchangeNode.getInputs().size(); source++) {
newInputs.get(source).add(exchangeNode.getInputs().get(source).get(i));
}
}
}
// newOutputs contains all partition, sort and hash symbols so simply swap the output layout
PartitioningScheme newPartitioningScheme = new PartitioningScheme(
exchangeNode.getPartitioningScheme().getPartitioning(),
newOutputs.build(),
exchangeNode.getPartitioningScheme().getHashColumn(),
exchangeNode.getPartitioningScheme().isReplicateNullsAndAny(),
exchangeNode.getPartitioningScheme().getBucketToPartition());
return Optional.of(new ExchangeNode(
exchangeNode.getId(),
exchangeNode.getType(),
exchangeNode.getScope(),
newPartitioningScheme,
exchangeNode.getSources(),
newInputs,
exchangeNode.getOrderingScheme()));
}
}
| 1,857 |
335 | <filename>E/Egalitarian_noun.json
{
"word": "Egalitarian",
"definitions": [
"A person who advocates or supports the principle of equality for all people."
],
"parts-of-speech": "Noun"
} | 79 |
2,151 | <gh_stars>1000+
// Copyright 2018 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 "services/audio/test/fake_group_member.h"
#include <algorithm>
#include <cmath>
#include "base/numerics/math_constants.h"
#include "media/base/audio_bus.h"
namespace audio {
FakeGroupMember::FakeGroupMember(const base::UnguessableToken& group_id,
const media::AudioParameters& params)
: group_id_(group_id),
params_(params),
audio_bus_(media::AudioBus::Create(params_)),
frequency_by_channel_(params_.channels(), 0.0) {
CHECK(params_.IsValid());
}
FakeGroupMember::~FakeGroupMember() = default;
void FakeGroupMember::SetChannelTone(int ch, double frequency) {
frequency_by_channel_[ch] = frequency;
}
void FakeGroupMember::SetVolume(double volume) {
CHECK_GE(volume, 0.0);
CHECK_LE(volume, 1.0);
volume_ = volume;
}
void FakeGroupMember::RenderMoreAudio(base::TimeTicks output_timestamp) {
if (snooper_) {
for (int ch = 0; ch < params_.channels(); ++ch) {
const double step = 2.0 * base::kPiDouble * frequency_by_channel_[ch] /
params_.sample_rate();
float* const samples = audio_bus_->channel(ch);
for (int frame = 0; frame < params_.frames_per_buffer(); ++frame) {
samples[frame] = std::sin((at_frame_ + frame) * step);
}
}
snooper_->OnData(*audio_bus_, output_timestamp, volume_);
}
at_frame_ += params_.frames_per_buffer();
}
const base::UnguessableToken& FakeGroupMember::GetGroupId() {
return group_id_;
}
const media::AudioParameters& FakeGroupMember::GetAudioParameters() {
return params_;
}
void FakeGroupMember::StartSnooping(Snooper* snooper) {
CHECK(!snooper_);
snooper_ = snooper;
}
void FakeGroupMember::StopSnooping(Snooper* snooper) {
snooper_ = nullptr;
}
void FakeGroupMember::StartMuting() {
// No effect for this fake implementation.
}
void FakeGroupMember::StopMuting() {
// No effect for this fake implementation.
}
} // namespace audio
| 797 |
1,076 | <filename>d912pxy/d912pxy_trimmed_pso.cpp
/*
MIT License
Copyright(c) 2018-2020 megai2
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "stdafx.h"
D3D12_GRAPHICS_PIPELINE_STATE_DESC d912pxy_trimmed_pso_desc::singleFullPSO = { 0 };
d912pxy_trimmed_pso_desc::d912pxy_trimmed_pso_desc() :
val(),
ref()
{
}
d912pxy_trimmed_pso_desc::~d912pxy_trimmed_pso_desc()
{
}
const d912pxy_trimmed_pso_desc::ValuePart& d912pxy_trimmed_pso_desc::GetValuePart()
{
val.vdeclHash = ref.InputLayout->GetHash();
return val;
}
D3D12_GRAPHICS_PIPELINE_STATE_DESC* d912pxy_trimmed_pso_desc::GetPSODesc()
{
singleFullPSO.VS = { 0 };
singleFullPSO.PS = { 0 };
singleFullPSO.InputLayout = *ref.InputLayout->GetD12IA_InputElementFmt();
singleFullPSO.NumRenderTargets = val.NumRenderTargets;
//TODO: check about blend states for different RTs in DX9
for (int i = 0; i<val.NumRenderTargets;++i)
{
singleFullPSO.BlendState.RenderTarget[i].SrcBlend = (D3D12_BLEND)val.blend.src;
singleFullPSO.BlendState.RenderTarget[i].SrcBlendAlpha = (D3D12_BLEND)val.blend.srcAlpha;
singleFullPSO.BlendState.RenderTarget[i].DestBlend = (D3D12_BLEND)val.blend.dest;
singleFullPSO.BlendState.RenderTarget[i].DestBlendAlpha = (D3D12_BLEND)val.blend.destAlpha;
singleFullPSO.BlendState.RenderTarget[i].BlendEnable = val.blend.enable;
singleFullPSO.BlendState.RenderTarget[i].RenderTargetWriteMask = val.rt[i].writeMask;
singleFullPSO.BlendState.RenderTarget[i].BlendOp = (D3D12_BLEND_OP)val.blend.op;
singleFullPSO.BlendState.RenderTarget[i].BlendOpAlpha = (D3D12_BLEND_OP)val.blend.opAlpha;
}
for (int i = val.NumRenderTargets; i < PXY_INNER_MAX_RENDER_TARGETS; ++i)
singleFullPSO.BlendState.RenderTarget[i] = { 0 };
for (int i = 0; i < PXY_INNER_MAX_RENDER_TARGETS; ++i)
singleFullPSO.RTVFormats[i] = (DXGI_FORMAT)val.rt[i].format;
singleFullPSO.RasterizerState.FillMode = (D3D12_FILL_MODE)val.rast.fillMode;
singleFullPSO.RasterizerState.FrontCounterClockwise = val.rast.cullMode == D3DCULL_CW;
singleFullPSO.RasterizerState.CullMode = val.rast.cullMode != D3DCULL_NONE ? D3D12_CULL_MODE_BACK : D3D12_CULL_MODE_NONE;
singleFullPSO.RasterizerState.SlopeScaledDepthBias = val.rast.slopeScaledDepthBias;
singleFullPSO.RasterizerState.AntialiasedLineEnable = val.rast.antialiasedLineEnable;
singleFullPSO.RasterizerState.DepthBias = val.rast.depthBias;
//singleFullPSO.DepthStencilState = desc->DepthStencilState;
singleFullPSO.DepthStencilState.DepthEnable = val.ds.enable;
singleFullPSO.DepthStencilState.DepthWriteMask = (D3D12_DEPTH_WRITE_MASK)val.ds.writeMask;
singleFullPSO.DepthStencilState.DepthFunc = (D3D12_COMPARISON_FUNC)val.ds.func;
singleFullPSO.DepthStencilState.StencilEnable = val.ds.stencilEnable;
singleFullPSO.DepthStencilState.FrontFace.StencilFailOp = (D3D12_STENCIL_OP)val.ds.frontFace.failOp;
singleFullPSO.DepthStencilState.FrontFace.StencilPassOp = (D3D12_STENCIL_OP)val.ds.frontFace.passOp;
singleFullPSO.DepthStencilState.FrontFace.StencilDepthFailOp = (D3D12_STENCIL_OP)val.ds.frontFace.depthFailOp;
singleFullPSO.DepthStencilState.FrontFace.StencilFunc = (D3D12_COMPARISON_FUNC)val.ds.frontFace.func;
singleFullPSO.DepthStencilState.BackFace.StencilFailOp = (D3D12_STENCIL_OP)val.ds.backFace.failOp;
singleFullPSO.DepthStencilState.BackFace.StencilPassOp = (D3D12_STENCIL_OP)val.ds.backFace.passOp;
singleFullPSO.DepthStencilState.BackFace.StencilDepthFailOp = (D3D12_STENCIL_OP)val.ds.backFace.depthFailOp;
singleFullPSO.DepthStencilState.BackFace.StencilFunc = (D3D12_COMPARISON_FUNC)val.ds.backFace.func;
singleFullPSO.DepthStencilState.StencilReadMask = val.ds.stencilReadMask;
singleFullPSO.DepthStencilState.StencilWriteMask = val.ds.stencilWriteMask;
singleFullPSO.DSVFormat = (DXGI_FORMAT)val.ds.format;
return &singleFullPSO;
}
d912pxy_shader_pair_hash_type d912pxy_trimmed_pso_desc::GetShaderPairUID()
{
return d912pxy_s.render.db.shader.GetPairUID(ref.VS, ref.PS);
}
void d912pxy_trimmed_pso_desc::HoldRefs(const bool yes)
{
const INT refd = yes ? 1 : -1;
ref.InputLayout->ThreadRef(refd);
ref.PS->ThreadRef(refd);
ref.VS->ThreadRef(refd);
}
bool d912pxy_trimmed_pso_desc::haveValidRefs()
{
return (ref.PS != nullptr) && (ref.VS != nullptr) && (ref.InputLayout != nullptr);
}
d912pxy_mem_block d912pxy_trimmed_pso_desc::Serialize()
{
serialized_data* output;
auto mem = d912pxy_mem_block::alloc(&output);
output->val = val;
UINT unused;
memcpy(output->declData, ref.InputLayout->GetDeclarationPtr(&unused), sizeof(D3DVERTEXELEMENT9) * PXY_INNER_MAX_VDECL_LEN);
return mem;
}
bool d912pxy_trimmed_pso_desc::DeSerialize(d912pxy_mem_block data)
{
if (data.size() != sizeof(serialized_data))
return false;
serialized_data* input = data.c_arr<serialized_data>();
val = input->val;
ref.InputLayout = d912pxy_vdecl::d912pxy_vdecl_com(input->declData);
return true;
}
void d912pxy_trimmed_pso_desc::SetupBaseFullPSO(ID3D12RootSignature* defaultRootSignature)
{
singleFullPSO.SampleDesc.Count = 1;
singleFullPSO.SampleDesc.Quality = 0;
singleFullPSO.SampleMask = 0xFFFFFFFF;
singleFullPSO.RasterizerState.DepthBiasClamp = 0;
singleFullPSO.RasterizerState.DepthClipEnable = 1;
singleFullPSO.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
singleFullPSO.pRootSignature = defaultRootSignature;
} | 2,518 |
348 | {"nom":"Replonges","circ":"4ème circonscription","dpt":"Ain","inscrits":2688,"abs":1507,"votants":1181,"blancs":50,"nuls":21,"exp":1110,"res":[{"nuance":"REM","nom":"<NAME>","voix":740},{"nuance":"FN","nom":"<NAME>","voix":370}]} | 92 |
634 | /*
* Copyright 2004-2005 <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.intellij.openapi.roots.ui.configuration;
import com.intellij.ProjectTopics;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.ModuleRootEvent;
import com.intellij.openapi.roots.ModuleRootListener;
import com.intellij.openapi.roots.OrderEntry;
import com.intellij.openapi.roots.ui.configuration.classpath.ClasspathPanelImpl;
import consulo.disposer.Disposable;
import consulo.ui.annotation.RequiredUIAccess;
import javax.annotation.Nonnull;
import javax.swing.*;
/**
* @author <NAME>
* Date: Oct 4, 2003
* Time: 6:54:57 PM
*/
public class ClasspathEditor extends ModuleElementsEditor implements ModuleRootListener {
private ClasspathPanelImpl myPanel;
public ClasspathEditor(final ModuleConfigurationState state) {
super(state);
final Disposable disposable = Disposable.newDisposable();
state.getProject().getMessageBus().connect(disposable).subscribe(ProjectTopics.PROJECT_ROOTS, this);
registerDisposable(disposable);
}
@Override
public String getHelpTopic() {
return "projectStructure.modules.dependencies";
}
@Override
public String getDisplayName() {
return ProjectBundle.message("modules.classpath.title");
}
@Override
public void saveData() {
myPanel.stopEditing();
}
@RequiredUIAccess
@Nonnull
@Override
public JComponent createComponentImpl(Disposable parentUIDisposable) {
return myPanel = new ClasspathPanelImpl(getState());
}
public void selectOrderEntry(@Nonnull final OrderEntry entry) {
myPanel.selectOrderEntry(entry);
}
@Override
public void moduleStateChanged() {
if (myPanel != null) {
myPanel.initFromModel();
}
}
@Override
public void rootsChanged(ModuleRootEvent event) {
if (myPanel != null) {
myPanel.rootsChanged();
}
}
}
| 762 |
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.
*/
package org.apache.drill.yarn.zk;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.work.foreman.DrillbitStatusListener;
import org.apache.drill.yarn.appMaster.AMRegistrar;
/**
* Driver class for the ZooKeeper cluster coordinator. Provides defaults for
* most options, but allows customizing each. Provides a {@link #build()} method
* to create <i>and start</i> the ZK service. Obtains the initial set of
* Drillbits (which should be empty for a YARN-defined cluster) which can be
* retrieved after building.
* <p>
* Maintains the ZK connection and monitors for disconnect. This class simply
* detects a disconnect timeout, it does not send a disconnect event itself to
* avoid creating a timer thread just for this purpose. Instead, the caller can
* poll {@link #hasFailed()}.
* <p>
* Defaults match those in Drill. (Actual Drill defaults are not yet used due to
* code incompatibility issues.)
*/
public class ZKClusterCoordinatorDriver implements AMRegistrar {
private static final Pattern ZK_COMPLEX_STRING = Pattern
.compile("(^.*?)/(.*)/([^/]*)$");
// Defaults are taken from java-exec's drill-module.conf
private String connect = "localhost:2181";
private String clusterId = "drillbits1";
private String zkRoot = "drill";
private int retryCount = 7200;
private int connectTimeoutMs = 5_000;
private int retryDelayMs = 500;
// Default timeout before we declare that ZK is down: 2 minutes.
private int failureTimeoutMs = 120_000;
// Maximum ZK startup wait defaults to 30 seconds. It is only 10 seconds
// in the Drill implementation.
private int maxStartWaitMs = 30_000;
// Expected ports used to match ZK registries with
// containers. ZK lists the ports as part of its key, we have to anticipate
// these values in order to match.
private int userPort = 31010;
private int controlPort = 31011;
private int dataPort = 31012;
private List<DrillbitEndpoint> initialEndpoints;
private ConnectionStateListener stateListener = new ConnectionStateListener() {
@Override
public void stateChanged(CuratorFramework client,
ConnectionState newState) {
ZKClusterCoordinatorDriver.this.stateChanged(newState);
}
};
private ZKClusterCoordinator zkCoord;
private long connectionLostTime;
private AMRegistry amRegistry;
public ZKClusterCoordinatorDriver() {
}
/**
* Specify connect string in the form: host:/zkRoot/clusterId
*
* @param connect
* @return This {@link ZKClusterCoordinatorDriver}.
* @throws ZKConfigException
*/
public ZKClusterCoordinatorDriver setConnect(String connect)
throws ZKConfigException {
// check if this is a complex zk string. If so, parse into components.
Matcher m = ZK_COMPLEX_STRING.matcher(connect);
if (!m.matches()) {
throw new ZKConfigException("Bad connect string: " + connect);
}
this.connect = m.group(1);
zkRoot = m.group(2);
clusterId = m.group(3);
return this;
}
public ZKClusterCoordinatorDriver setConnect(String connect, String zkRoot,
String clusterId) {
this.connect = connect;
this.zkRoot = zkRoot;
this.clusterId = clusterId;
return this;
}
public ZKClusterCoordinatorDriver setRetryCount(int n) {
retryCount = n;
return this;
}
public ZKClusterCoordinatorDriver setConnectTimeoutMs(int ms) {
connectTimeoutMs = ms;
return this;
}
public ZKClusterCoordinatorDriver setRetryDelayMs(int ms) {
retryDelayMs = ms;
return this;
}
public ZKClusterCoordinatorDriver setMaxStartWaitMs(int ms) {
maxStartWaitMs = ms;
return this;
}
public ZKClusterCoordinatorDriver setFailureTimoutMs(int ms) {
failureTimeoutMs = ms;
return this;
}
public ZKClusterCoordinatorDriver setPorts(int userPort, int controlPort,
int dataPort) {
this.userPort = userPort;
this.controlPort = controlPort;
this.dataPort = dataPort;
return this;
}
/**
* Builds and starts the ZooKeeper cluster coordinator, translating any errors
* that occur. After this call, the listener will start receiving messages.
*
* @return This {@link ZKClusterCoordinatorDriver}.
* @throws ZKRuntimeException
* if ZK startup fails
*/
public ZKClusterCoordinatorDriver build() throws ZKRuntimeException {
try {
zkCoord = new ZKClusterCoordinator(connect, zkRoot, clusterId, retryCount,
retryDelayMs, connectTimeoutMs);
} catch (IOException e) {
throw new ZKRuntimeException(
"Failed to initialize the ZooKeeper cluster coordination", e);
}
try {
zkCoord.start(maxStartWaitMs);
} catch (Exception e) {
throw new ZKRuntimeException(
"Failed to start the ZooKeeper cluster coordination after "
+ maxStartWaitMs + " ms.",
e);
}
initialEndpoints = new ArrayList<>(zkCoord.getAvailableEndpoints());
zkCoord.getCurator().getConnectionStateListenable()
.addListener(stateListener);
amRegistry = new AMRegistry(zkCoord);
amRegistry.useLocalRegistry(zkRoot, clusterId);
return this;
}
public void addDrillbitListener(DrillbitStatusListener listener) {
zkCoord.addDrillbitStatusListener(listener);
}
public void removeDrillbitListener(DrillbitStatusListener listener) {
zkCoord.removeDrillbitStatusListener(listener);
}
/**
* Returns the set of Drillbits registered at the time of the {@link #build()}
* call. Should be empty for a cluster managed by YARN.
*
* @return The set of Drillbits registered at the time of the {@link #build()}
* call.
*/
public List<DrillbitEndpoint> getInitialEndpoints() {
return initialEndpoints;
}
/**
* Convenience method to convert a Drillbit to a string. Note that ZK does not
* advertise the HTTP port, so it does not appear in the generated string.
*
* @param bit
* @return A string representation of a Drillbit.
*/
public static String asString(DrillbitEndpoint bit) {
return formatKey(bit.getAddress(), bit.getUserPort(), bit.getControlPort(),
bit.getDataPort());
}
public String toKey(String host) {
return formatKey(host, userPort, controlPort, dataPort);
}
public static String formatKey(String host, int userPort, int controlPort,
int dataPort) {
StringBuilder buf = new StringBuilder();
buf.append(host).append(":").append(userPort).append(':')
.append(controlPort).append(':').append(dataPort);
return buf.toString();
}
/**
* Translate ZK connection events into a connected/disconnected state along
* with the time of the first disconnect not followed by a connect.
*
* @param newState
*/
protected void stateChanged(ConnectionState newState) {
switch (newState) {
case CONNECTED:
case READ_ONLY:
case RECONNECTED:
if (connectionLostTime != 0) {
ZKClusterCoordinator.logger.info("ZK connection regained");
}
connectionLostTime = 0;
break;
case LOST:
case SUSPENDED:
if (connectionLostTime == 0) {
ZKClusterCoordinator.logger.info("ZK connection lost");
connectionLostTime = System.currentTimeMillis();
}
break;
}
}
/**
* Reports our best guess as to whether ZK has failed. We assume ZK has failed
* if we received a connection lost notification without a subsequent connect
* notification, and we received the disconnect notification log enough ago
* that we assume that a timeout has occurred.
*
* @return True if we think zookeeper has failed. False otherwise.
*/
public boolean hasFailed() {
if (connectionLostTime == 0) {
return false;
}
return System.currentTimeMillis() - connectionLostTime > failureTimeoutMs;
}
public long getLostConnectionDurationMs() {
if (connectionLostTime == 0) {
return 0;
}
return System.currentTimeMillis() - connectionLostTime;
}
public void close() {
if (zkCoord == null) {
return;
}
zkCoord.getCurator().getConnectionStateListenable()
.removeListener(stateListener);
try {
zkCoord.close();
} catch (Exception e) {
ZKClusterCoordinator.logger.error("Error occurred on ZK close, ignored",
e);
}
zkCoord = null;
}
@Override
public void register(String amHost, int amPort, String appId)
throws AMRegistrationException {
try {
amRegistry.register(amHost, amPort, appId);
} catch (ZKRuntimeException e) {
throw new AMRegistrationException(e);
}
}
@Override
public void deregister() {
// Nothing to do: ZK does it for us.
}
}
| 3,271 |
997 | <reponame>mkannwischer/PQClean
#ifndef PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_PARAMS_H
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_PARAMS_H
/* Hash output length in bytes. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N 32
/* Height of the hypertree. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FULL_HEIGHT 68
/* Number of subtree layer. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_D 17
/* FORS tree dimensions. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_HEIGHT 9
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_TREES 35
/* Winternitz parameter, */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_W 16
/* The hash function is defined by linking a different hash.c file, as opposed
to setting a #define constant. */
/* For clarity */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_ADDR_BYTES 32
/* WOTS parameters. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LOGW 4
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LEN1 (8 * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N / PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LOGW)
/* PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LEN2 is floor(log(len_1 * (w - 1)) / log(w)) + 1; we precompute */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LEN2 3
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LEN (PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LEN1 + PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LEN2)
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_BYTES (PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_LEN * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N)
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_PK_BYTES PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_BYTES
/* Subtree size. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_TREE_HEIGHT (PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FULL_HEIGHT / PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_D)
/* FORS parameters. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_MSG_BYTES ((PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_HEIGHT * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_TREES + 7) / 8)
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_BYTES ((PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_HEIGHT + 1) * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_TREES * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N)
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_PK_BYTES PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N
/* Resulting SPX sizes. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_BYTES (PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N + PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FORS_BYTES + PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_D * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_WOTS_BYTES +\
PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_FULL_HEIGHT * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N)
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_PK_BYTES (2 * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N)
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_SK_BYTES (2 * PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_N + PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_PK_BYTES)
/* Optionally, signing can be made non-deterministic using optrand.
This can help counter side-channel attacks that would benefit from
getting a large number of traces when the signer uses the same nodes. */
#define PQCLEAN_SPHINCSSHA256256FROBUST_CLEAN_OPTRAND_BYTES 32
#endif
| 1,477 |
14,668 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/web_applications/draggable_region_host_impl.h"
#include "base/feature_list.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "chrome/common/chrome_features.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
DraggableRegionsHostImpl::DraggableRegionsHostImpl(
content::RenderFrameHost* render_frame_host,
mojo::PendingReceiver<chrome::mojom::DraggableRegions> receiver)
: DocumentService(render_frame_host, std::move(receiver)) {}
DraggableRegionsHostImpl::~DraggableRegionsHostImpl() = default;
// static
void DraggableRegionsHostImpl::CreateIfAllowed(
content::RenderFrameHost* render_frame_host,
mojo::PendingReceiver<chrome::mojom::DraggableRegions> receiver) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* browser = chrome::FindBrowserWithWebContents(web_contents);
// We only want to bind the receiver for PWAs.
if (!web_app::AppBrowserController::IsWebApp(browser))
return;
// The object is bound to the lifetime of |render_frame_host| and the mojo
// connection. See DocumentService for details.
new DraggableRegionsHostImpl(render_frame_host, std::move(receiver));
}
void DraggableRegionsHostImpl::UpdateDraggableRegions(
std::vector<chrome::mojom::DraggableRegionPtr> draggable_region) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host());
auto* browser = chrome::FindBrowserWithWebContents(web_contents);
// When a WebApp browser's WebContents is reparented to a tabbed browser, a
// draggable regions update may race with the reparenting logic.
if (!web_app::AppBrowserController::IsWebApp(browser))
return;
SkRegion sk_region;
for (const chrome::mojom::DraggableRegionPtr& region : draggable_region) {
sk_region.op(
SkIRect::MakeLTRB(region->bounds.x(), region->bounds.y(),
region->bounds.x() + region->bounds.width(),
region->bounds.y() + region->bounds.height()),
region->draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
}
auto* app_browser_controller = browser->app_controller();
app_browser_controller->UpdateDraggableRegion(sk_region);
}
| 873 |
1,825 | package com.github.unidbg.ios.struct.kernel;
import com.github.unidbg.pointer.UnidbgStructure;
import com.sun.jna.Pointer;
import java.util.Arrays;
import java.util.List;
public class AslServerMessageRequest extends UnidbgStructure {
public AslServerMessageRequest(Pointer p) {
super(p);
}
public int pad;
public int message;
public int messageCnt;
public int flags;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("pad", "message", "messageCnt", "flags");
}
}
| 204 |
419 | #include "Ammo.h"
//-------------------------------------------------------------------------
#include "Engine/Physics/PhysicsLayers.h"
#include "Engine/Physics/PhysicsQuery.h"
#include "Engine/Physics/PhysicsScene.h"
#include "System/Core/Types/Color.h"
//-------------------------------------------------------------------------
using namespace KRG::Weapon;
// define a context for ammo : physics world + delta time + debug stuff
bool Ammo::Shoot(AmmoContext const& ctx, RangedWeaponInfo weaponDamage, Vector origin, Vector target)
{
// adjust accuracy
// weaponDamage.m_baseAccuracy* m_dmgModifiers.m_accuracyModifier;
// check if we have a valid target
Vector const directionToTarget = (target - origin).GetNormalized3();
// check if dir is valid
Vector const traceEnd = origin + directionToTarget * m_range;
ctx.m_pPhysicsScene->AcquireReadLock();
Physics::QueryFilter filter;
filter.SetLayerMask(Physics::CreateLayerMask(Physics::Layers::Environment));
Physics::RayCastResults outTraceResults;
bool const bHasValidHit = ctx.m_pPhysicsScene->RayCast(origin, traceEnd, filter, outTraceResults);
#if KRG_DEVELOPMENT_TOOLS
// debug draw for now
auto drawingCtx = ctx.m_pEntityWorldUpdateContext->GetDrawingContext();
KRG::Float4 DrawingColor = bHasValidHit ? Colors::HotPink : Colors::Green;
drawingCtx.DrawLine(origin, traceEnd, DrawingColor, 2.f, KRG::Drawing::DisableDepthTest, 2.f);
#endif
ctx.m_pPhysicsScene->ReleaseReadLock();
if (!bHasValidHit || !outTraceResults.hasBlock)
{
return false;
}
Vector const HitLocation = origin + directionToTarget * outTraceResults.block.distance;
#if KRG_DEVELOPMENT_TOOLS
drawingCtx.DrawSphere(HitLocation, KRG::Float3(0.5f), DrawingColor, 2.f, KRG::Drawing::DisableDepthTest, 2.f);
#endif
// Calculate damage with ammo mods
DamageDealtInfo damageToDeal;
damageToDeal.m_damageType = m_dmgModifiers.m_damageType;
damageToDeal.m_damageValue = weaponDamage.m_damageValue * m_dmgModifiers.m_damageModifier;
damageToDeal.m_hitLocation = HitLocation;
// request damage on hit to damage system with damageToDeal info + actor hit info
return true;
} | 670 |
765 | // To avoid linking MSVC specific libs, we don't test virtual/override methods
// that needs vftable support in this file.
// Enum.
enum Enum { RED, GREEN, BLUE };
Enum EnumVar;
// Union.
union Union {
short Row;
unsigned short Col;
int Line : 16; // Test named bitfield.
short : 8; // Unnamed bitfield symbol won't be generated in PDB.
long Table;
};
Union UnionVar;
// Struct.
struct Struct;
typedef Struct StructTypedef;
struct Struct {
bool A;
unsigned char UCharVar;
unsigned int UIntVar;
long long LongLongVar;
Enum EnumVar; // Test struct has UDT member.
int array[10];
};
struct Struct StructVar;
struct _List; // Forward declaration.
struct Complex {
struct _List *array[90];
struct { // Test unnamed struct. MSVC treats it as `int x`
int x;
};
union { // Test unnamed union. MSVC treats it as `int a; float b;`
int a;
float b;
};
};
struct Complex c;
struct _List { // Test doubly linked list.
struct _List *current;
struct _List *previous;
struct _List *next;
};
struct _List ListVar;
typedef struct {
int a;
} UnnamedStruct; // Test unnamed typedef-ed struct.
UnnamedStruct UnnanmedVar;
// Class.
namespace MemberTest {
class Base {
public:
Base() {}
~Base() {}
public:
int Get() { return 0; }
protected:
int a;
};
class Friend {
public:
int f() { return 3; }
};
class Class : public Base { // Test base class.
friend Friend;
static int m_static; // Test static member variable.
public:
Class() : m_public(), m_private(), m_protected() {}
explicit Class(int a) { m_public = a; } // Test first reference of m_public.
~Class() {}
static int StaticMemberFunc(int a, ...) {
return 1;
} // Test static member function.
int Get() { return 1; }
int f(Friend c) { return c.f(); }
inline bool operator==(const Class &rhs) const // Test operator.
{
return (m_public == rhs.m_public);
}
public:
int m_public;
struct Struct m_struct;
private:
Union m_union;
int m_private;
protected:
friend class Friend;
int m_protected;
};
} // namespace MemberTest
int main() {
MemberTest::Base B1;
B1.Get();
MemberTest::Class::StaticMemberFunc(1, 10, 2);
return 0;
}
| 753 |
4,262 | <filename>components/camel-salesforce/camel-salesforce-component/src/test/resources/globalObjects.json
{"encoding":"UTF-8","maxBatchSize":200,"sobjects":[{"activateable":false,"createable":false,"custom":false,"customSetting":false,"deletable":false,"deprecatedAndHidden":false,"feedEnabled":false,"keyPrefix":null,"label":"Accepted Event Relation","labelPlural":"Accepted Event Relations","layoutable":false,"mergeable":false,"name":"AcceptedEventRelation","queryable":true,"replicateable":false,"retrieveable":true,"searchable":false,"triggerable":false,"undeletable":false,"updateable":false,"urls":{"rowTemplate":"/services/data/v34.0/sobjects/AcceptedEventRelation/{ID}","describe":"/services/data/v34.0/sobjects/AcceptedEventRelation/describe","sobject":"/services/data/v34.0/sobjects/AcceptedEventRelation"}},{"activateable":false,"createable":true,"custom":false,"customSetting":false,"deletable":true,"deprecatedAndHidden":false,"feedEnabled":true,"keyPrefix":"001","label":"Account","labelPlural":"Accounts","layoutable":true,"mergeable":true,"name":"Account","queryable":true,"replicateable":true,"retrieveable":true,"searchable":true,"triggerable":true,"undeletable":true,"updateable":true,"urls":{"compactLayouts":"/services/data/v34.0/sobjects/Account/describe/compactLayouts","rowTemplate":"/services/data/v34.0/sobjects/Account/{ID}","approvalLayouts":"/services/data/v34.0/sobjects/Account/describe/approvalLayouts","listviews":"/services/data/v34.0/sobjects/Account/listviews","describe":"/services/data/v34.0/sobjects/Account/describe","quickActions":"/services/data/v34.0/sobjects/Account/quickActions","layouts":"/services/data/v34.0/sobjects/Account/describe/layouts","sobject":"/services/data/v34.0/sobjects/Account"}},{"activateable":false,"createable":false,"custom":false,"customSetting":false,"deletable":false,"deprecatedAndHidden":false,"feedEnabled":false,"keyPrefix":"1CA","label":"Account Clean Info","labelPlural":"Account Clean Info","layoutable":false,"mergeable":false,"name":"AccountCleanInfo","queryable":true,"replicateable":true,"retrieveable":true,"searchable":false,"triggerable":false,"undeletable":false,"updateable":true,"urls":{"rowTemplate":"/services/data/v34.0/sobjects/AccountCleanInfo/{ID}","describe":"/services/data/v34.0/sobjects/AccountCleanInfo/describe","sobject":"/services/data/v34.0/sobjects/AccountCleanInfo"}},{"activateable":false,"createable":true,"custom":false,"customSetting":false,"deletable":true,"deprecatedAndHidden":false,"feedEnabled":false,"keyPrefix":"02Z","label":"Account Contact Role","labelPlural":"Account Contact Roles","layoutable":false,"mergeable":false,"name":"AccountContactRole","queryable":true,"replicateable":true,"retrieveable":true,"searchable":false,"triggerable":false,"undeletable":false,"updateable":true,"urls":{"rowTemplate":"/services/data/v34.0/sobjects/AccountContactRole/{ID}","describe":"/services/data/v34.0/sobjects/AccountContactRole/describe","sobject":"/services/data/v34.0/sobjects/AccountContactRole"}}]}
| 940 |
945 | /*
* 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.iotdb.db.integration;
import org.apache.iotdb.db.utils.EnvironmentUtils;
import org.apache.iotdb.itbase.category.LocalStandaloneTest;
import org.apache.iotdb.jdbc.Config;
import org.apache.iotdb.jdbc.IoTDBSQLException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Notice that, all test begins with "IoTDB" is integration test. All test which will start the
* IoTDB server should be defined as integration test.
*/
@Category({LocalStandaloneTest.class})
public class IoTDBCreateAlignedTimeseriesIT {
private Statement statement;
private Connection connection;
@Before
public void setUp() throws Exception {
EnvironmentUtils.envSetUp();
Class.forName(Config.JDBC_DRIVER_NAME);
connection = DriverManager.getConnection("jdbc:iotdb://127.0.0.1:6667/", "root", "root");
statement = connection.createStatement();
}
@After
public void tearDown() throws Exception {
statement.close();
connection.close();
EnvironmentUtils.cleanEnv();
}
@Test
public void testCreateAlignedTimeseries() throws Exception {
String[] timeSeriesArray =
new String[] {
"root.sg1.d1.vector1.s1,FLOAT,PLAIN,UNCOMPRESSED",
"root.sg1.d1.vector1.s2,INT64,RLE,SNAPPY"
};
statement.execute("SET STORAGE GROUP TO root.sg1");
try {
statement.execute(
"CREATE ALIGNED TIMESERIES root.sg1.d1.vector1(s1 FLOAT encoding=PLAIN compressor=UNCOMPRESSED,s2 INT64 encoding=RLE)");
} catch (IoTDBSQLException ignored) {
}
// ensure that current storage group in cache is right.
assertTimeseriesEquals(timeSeriesArray);
statement.close();
connection.close();
EnvironmentUtils.stopDaemon();
setUp();
// ensure storage group in cache is right after recovering.
assertTimeseriesEquals(timeSeriesArray);
}
@Test
public void testCreateAlignedTimeseriesWithDeletion() throws Exception {
String[] timeSeriesArray =
new String[] {
"root.sg1.d1.vector1.s1,DOUBLE,PLAIN,SNAPPY", "root.sg1.d1.vector1.s2,INT64,RLE,SNAPPY"
};
statement.execute("SET STORAGE GROUP TO root.sg1");
try {
statement.execute(
"CREATE ALIGNED TIMESERIES root.sg1.d1.vector1(s1 FLOAT encoding=PLAIN compressor=UNCOMPRESSED,s2 INT64 encoding=RLE)");
statement.execute("DELETE TIMESERIES root.sg1.d1.vector1.s1");
statement.execute(
"CREATE ALIGNED TIMESERIES root.sg1.d1.vector1(s1 DOUBLE encoding=PLAIN compressor=SNAPPY)");
} catch (IoTDBSQLException e) {
e.printStackTrace();
}
// ensure that current storage group in cache is right.
assertTimeseriesEquals(timeSeriesArray);
statement.close();
connection.close();
EnvironmentUtils.stopDaemon();
setUp();
// ensure storage group in cache is right after recovering.
assertTimeseriesEquals(timeSeriesArray);
}
private void assertTimeseriesEquals(String[] timeSeriesArray) throws SQLException {
boolean hasResult = statement.execute("SHOW TIMESERIES");
Assert.assertTrue(hasResult);
int count = 0;
try (ResultSet resultSet = statement.getResultSet()) {
while (resultSet.next()) {
String ActualResult =
resultSet.getString("timeseries")
+ ","
+ resultSet.getString("dataType")
+ ","
+ resultSet.getString("encoding")
+ ","
+ resultSet.getString("compression");
Assert.assertEquals(timeSeriesArray[count], ActualResult);
count++;
}
}
Assert.assertEquals(timeSeriesArray.length, count);
}
}
| 1,697 |
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.htmlui;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import org.netbeans.api.htmlui.HTMLDialog.OnSubmit;
import org.netbeans.spi.htmlui.HTMLViewerSpi;
import org.openide.util.Lookup;
public abstract class ContextAccessor {
private static ContextAccessor DEFAULT;
protected ContextAccessor() {
synchronized (ContextAccessor.class) {
if (DEFAULT != null) {
throw new IllegalStateException();
}
DEFAULT = this;
}
}
public static ContextAccessor getDefault() {
if (DEFAULT == null) {
try {
final Class<HTMLViewerSpi.Context> clazz = HTMLViewerSpi.Context.class;
Class.forName(clazz.getName(), true, clazz.getClassLoader());
} catch (ClassNotFoundException ex) {
throw new IllegalStateException(ex);
}
}
return DEFAULT;
}
public abstract HTMLViewerSpi.Context newContext(
ClassLoader loader, URL url, String[] techIds,
OnSubmit onSubmit, Consumer<String> lifeCycleCallback, Callable<Lookup> onPageLoad,
Class<?> component
);
}
| 717 |
480 | <reponame>christoph-heiss/mlibc
#include <bits/ensure.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <hel.h>
#include <hel-syscalls.h>
#include <mlibc/debug.hpp>
#include <mlibc/allocator.hpp>
#include <mlibc/posix-pipe.hpp>
#include <mlibc/all-sysdeps.hpp>
#include <posix.frigg_bragi.hpp>
#include <bragi/helpers-frigg.hpp>
#include <helix/ipc-structs.hpp>
extern "C" void __mlibc_signal_restore();
namespace mlibc {
int sys_sigprocmask(int how, const sigset_t *set, sigset_t *retrieve) {
// This implementation is inherently signal-safe.
uint64_t former, unused;
if(set) {
HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + 7, how, *set, &former, &unused));
}else{
HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + 7, 0, 0, &former, &unused));
}
if(retrieve)
*retrieve = former;
return 0;
}
int sys_sigaction(int number, const struct sigaction *__restrict action,
struct sigaction *__restrict saved_action) {
SignalGuard sguard;
// TODO: Respect restorer. __ensure(!(action->sa_flags & SA_RESTORER));
HelAction actions[3];
globalQueue.trim();
managarm::posix::CntRequest<MemoryAllocator> req(getSysdepsAllocator());
req.set_request_type(managarm::posix::CntReqType::SIG_ACTION);
if(action) {
req.set_mode(1);
req.set_flags(action->sa_flags);
req.set_sig_number(number);
req.set_sig_mask(action->sa_mask);
if(action->sa_flags & SA_SIGINFO) {
req.set_sig_handler(reinterpret_cast<uintptr_t>(action->sa_sigaction));
}else{
req.set_sig_handler(reinterpret_cast<uintptr_t>(action->sa_handler));
}
req.set_sig_restorer(reinterpret_cast<uintptr_t>(&__mlibc_signal_restore));
}
frg::string<MemoryAllocator> ser(getSysdepsAllocator());
req.SerializeToString(&ser);
actions[0].type = kHelActionOffer;
actions[0].flags = kHelItemAncillary;
actions[1].type = kHelActionSendFromBuffer;
actions[1].flags = kHelItemChain;
actions[1].buffer = ser.data();
actions[1].length = ser.size();
actions[2].type = kHelActionRecvInline;
actions[2].flags = 0;
HEL_CHECK(helSubmitAsync(getPosixLane(), actions, 3,
globalQueue.getQueue(), 0, 0));
auto element = globalQueue.dequeueSingle();
auto offer = parseHandle(element);
auto send_req = parseSimple(element);
auto recv_resp = parseInline(element);
HEL_CHECK(offer->error);
HEL_CHECK(send_req->error);
HEL_CHECK(recv_resp->error);
managarm::posix::SvrResponse<MemoryAllocator> resp(getSysdepsAllocator());
resp.ParseFromArray(recv_resp->data, recv_resp->length);
if(resp.error() == managarm::posix::Errors::ILLEGAL_REQUEST) {
// This is only returned for servers, not for normal userspace.
return ENOSYS;
}else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) {
return EINVAL;
}
__ensure(resp.error() == managarm::posix::Errors::SUCCESS);
if(saved_action) {
saved_action->sa_flags = resp.flags();
saved_action->sa_mask = resp.sig_mask();
if(resp.flags() & SA_SIGINFO) {
saved_action->sa_sigaction =
reinterpret_cast<void (*)(int, siginfo_t *, void *)>(resp.sig_handler());
}else{
saved_action->sa_handler = reinterpret_cast<void (*)(int)>(resp.sig_handler());
}
// TODO: saved_action->sa_restorer = resp.sig_restorer;
}
return 0;
}
int sys_kill(int pid, int number) {
// This implementation is inherently signal-safe.
HEL_CHECK(helSyscall2(kHelObserveSuperCall + 5, pid, number));
return 0;
}
int sys_tgkill(int, int tid, int number) {
return sys_kill(tid, number);
}
int sys_sigaltstack(const stack_t *ss, stack_t *oss) {
HelWord out;
// This implementation is inherently signal-safe.
HEL_CHECK(helSyscall2_1(kHelObserveSuperCall + 12,
reinterpret_cast<HelWord>(ss),
reinterpret_cast<HelWord>(oss),
&out));
return out;
}
int sys_sigsuspend(const sigset_t *set) {
//SignalGuard sguard;
uint64_t former, seq, unused;
HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + 7, SIG_SETMASK, *set, &former, &seq));
HEL_CHECK(helSyscall1(kHelObserveSuperCall + 13, seq));
HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + 7, SIG_SETMASK, former, &unused, &unused));
return EINTR;
}
} //namespace mlibc
| 1,696 |
1,037 | <filename>fancycoverflow-demo/src/com/mingy/fancycoverflow/base/FancyCoverFlowBaseAdapter.java
package com.mingy.fancycoverflow.base;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import at.technikum.mti.fancycoverflow.FancyCoverFlow;
import at.technikum.mti.fancycoverflow.FancyCoverFlow.LayoutParams;
import at.technikum.mti.fancycoverflow.FancyCoverFlowAdapter;
public class FancyCoverFlowBaseAdapter extends FancyCoverFlowAdapter {
public FancyCoverFlowBaseAdapter( Context context, Integer[] dataList ){
mDataList = dataList;
}
@Override
public int getCount() {
return mDataList.length;
}
@Override
public Object getItem(int position) {
return mDataList[ position ];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getCoverFlowItem(int position, View reusableView, ViewGroup parent) {
ImageView imageView = null;
if (reusableView != null) {
imageView = (ImageView) reusableView;
} else {
imageView = new ImageView(parent.getContext());
imageView.setLayoutParams(new FancyCoverFlow.LayoutParams(LayoutParams.WRAP_CONTENT,256));
}
imageView.setBackgroundResource( mDataList[ position ] );
return imageView;
}
private Integer[] mDataList = null;
}
| 495 |
4,816 | <reponame>mehrdad-shokri/retdec<gh_stars>1000+
/**
* @file include/retdec/llvmir2hll/ir/ufor_loop_stmt.h
* @brief A universal for loop statement.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_LLVMIR2HLL_IR_UFOR_LOOP_STMT_H
#define RETDEC_LLVMIR2HLL_IR_UFOR_LOOP_STMT_H
#include "retdec/llvmir2hll/ir/statement.h"
#include "retdec/llvmir2hll/support/smart_ptr.h"
namespace retdec {
namespace llvmir2hll {
class Expression;
class Value;
/**
* @brief A universal for loop statement.
*
* It differs from ForLoopStmt in the following way. In UForLoopStmt, the
* declaration, condition, and increment parts can contain an arbitrary
* expression. In contrast, in ForLoopStmt, the content of these parts is rather
* limited.
*
* Use create() to create instances. Instances of this class have reference
* object semantics. This class is not meant to be subclassed.
*/
class UForLoopStmt final: public Statement {
public:
static ShPtr<UForLoopStmt> create(
ShPtr<Expression> init,
ShPtr<Expression> cond,
ShPtr<Expression> step,
ShPtr<Statement> body,
ShPtr<Statement> succ = nullptr,
Address a = Address::Undefined
);
virtual ShPtr<Value> clone() override;
virtual bool isEqualTo(ShPtr<Value> otherValue) const override;
virtual bool isCompound() override { return true; }
virtual void replace(ShPtr<Expression> oldExpr, ShPtr<Expression> newExpr) override;
virtual ShPtr<Expression> asExpression() const override;
ShPtr<Expression> getInit() const;
ShPtr<Expression> getCond() const;
ShPtr<Expression> getStep() const;
ShPtr<Statement> getBody() const;
void setInit(ShPtr<Expression> newInit);
void setCond(ShPtr<Expression> newCond);
void setStep(ShPtr<Expression> newStep);
void setBody(ShPtr<Statement> newBody);
bool isInitDefinition() const;
void markInitAsDefinition();
/// @name Observer Interface
/// @{
virtual void update(ShPtr<Value> subject, ShPtr<Value> arg = nullptr) override;
/// @}
/// @name Visitor Interface
/// @{
virtual void accept(Visitor *v) override;
/// @}
private:
// Since instances are created by calling the static function create(), the
// constructor can be private.
UForLoopStmt(
ShPtr<Expression> init,
ShPtr<Expression> cond,
ShPtr<Expression> step,
ShPtr<Statement> body,
Address a = Address::Undefined
);
/// Initialization part.
ShPtr<Expression> init;
/// Is the initialization part a definition?
bool initIsDefinition;
/// Conditional part.
ShPtr<Expression> cond;
/// Step part.
ShPtr<Expression> step;
/// Body.
ShPtr<Statement> body;
};
} // namespace llvmir2hll
} // namespace retdec
#endif
| 899 |
647 | <reponame>gilbertguoze/trick
#include <string.h>
#include "DPM_outputs.hh"
// MEMBER FUNCTION
int DPM_outputs::Initialize( xmlNode *base_node) {
int n_measurements;
if (base_node == NULL) {
std::cerr << "ERROR: DPM_outputs::Initialize: Bad parameters." << std::endl;
return -1;
}
if ( strcmp( (char *)base_node->name, "outputs") != 0) {
std::cerr << "ERROR: Expected <outputs> specification but alas, is wasn\'t found." << std::endl;
return -1;
}
/* Process children */
xmlNode *current_node = base_node->children;
while (current_node != NULL) {
if (current_node->type == XML_ELEMENT_NODE) {
DPM_measurement *measurement;
if ( strcmp( (const char *)current_node->name, "measurement") == 0) {
try {
measurement = new DPM_measurement(this, current_node);
} catch (std::invalid_argument) {
measurement = NULL;
std::cerr << "ERROR: <measurement> is invalid." << std::endl;
}
if (measurement != NULL) {
measurement_list.push_back(measurement);
}
} else {
std::cerr << "WARNING: <outputs> specification contains an unknown element \"<" << current_node->name << ">\". Skipping." << std::endl;
}
}
current_node = current_node->next;
}
// Validation
// 1. Outputs must have at least one valid measurement.
n_measurements = (int)measurement_list.size();
if ( n_measurements < 1) {
std::cerr << "ERROR: <outputs> specification requires at least one valid <measurement> specification." << std::endl;
return -1;
}
return 0;
}
// CONSTRUCTOR
DPM_outputs::DPM_outputs(DPM_component *Parent, xmlNode *Base_node)
: DPM_component (Parent, Base_node) {
Initialize( Base_node);
}
// DESTRUCTOR
DPM_outputs::~DPM_outputs() {
int i,n;
n = (int)measurement_list.size();
for (i = 0; i < n ; i ++) {
DPM_measurement *measurement;
measurement = measurement_list[i];
if (measurement) { delete measurement; }
}
}
// MEMBER FUNCTION
int DPM_outputs::NumberOfOutputs() {
return( (int)measurement_list.size());
}
// MEMBER FUNCTION
const char *DPM_outputs::getVarName( unsigned int index) {
if (index < measurement_list.size( )) {
return ( measurement_list[index]->getVarName() );
} else {
return NULL;
}
}
// MEMBER FUNCTION
const char *DPM_outputs::getUnits( unsigned int index) {
if (index < measurement_list.size( )) {
return ( measurement_list[index]->getUnits() );
} else {
return NULL;
}
}
// MEMBER FUNCTION
std::ostream& operator<< (std::ostream& s, const DPM_outputs *outputs) {
int i;
int n_attrs = (int)outputs->attribute_list.size();
int n_measurements = (int)outputs->measurement_list.size();
s << "<outputs";
for (i=0 ; i<n_attrs ; i++) {
s << " " << outputs->attribute_list[i];
}
s << ">" << std::endl;
for (i=0 ; i<n_measurements ; i++) {
s << outputs->measurement_list[i];
}
s << "</inputs>" << std::endl;
return s;
}
| 1,386 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.